xref: /titanic_52/usr/src/uts/common/io/sata/impl/sata.c (revision 88e8a7f2124e61277dc5f6bf9718881bfb8b724e)
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 VPD Pages Page Code */
3515 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3516 #define	INQUIRY_BDC_PAGE	0xB1	/* Block Device Characteristics Page */
3517 					/* Code */
3518 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3519 
3520 static int
3521 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3522 {
3523 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3524 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3525 	sata_drive_info_t *sdinfo;
3526 	struct scsi_extended_sense *sense;
3527 	int count;
3528 	uint8_t *p;
3529 	int i, j;
3530 	uint8_t page_buf[0xff]; /* Max length */
3531 	int rval, reason;
3532 	ushort_t rate;
3533 
3534 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3535 
3536 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3537 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3538 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3539 		return (rval);
3540 	}
3541 
3542 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3543 	    &spx->txlt_sata_pkt->satapkt_device);
3544 
3545 	ASSERT(sdinfo != NULL);
3546 
3547 	scsipkt->pkt_reason = CMD_CMPLT;
3548 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3549 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3550 
3551 	/* Reject not supported request */
3552 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3553 		*scsipkt->pkt_scbp = STATUS_CHECK;
3554 		sense = sata_arq_sense(spx);
3555 		sense->es_key = KEY_ILLEGAL_REQUEST;
3556 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3557 		goto done;
3558 	}
3559 
3560 	/* Valid Inquiry request */
3561 	*scsipkt->pkt_scbp = STATUS_GOOD;
3562 
3563 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3564 
3565 		/*
3566 		 * Because it is fully emulated command storing data
3567 		 * programatically in the specified buffer, release
3568 		 * preallocated DMA resources before storing data in the buffer,
3569 		 * so no unwanted DMA sync would take place.
3570 		 */
3571 		sata_scsi_dmafree(NULL, scsipkt);
3572 
3573 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3574 			/* Standard Inquiry Data request */
3575 			struct scsi_inquiry inq;
3576 			unsigned int bufsize;
3577 
3578 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3579 			    sdinfo, (uint8_t *)&inq);
3580 			/* Copy no more than requested */
3581 			count = MIN(bp->b_bcount,
3582 			    sizeof (struct scsi_inquiry));
3583 			bufsize = scsipkt->pkt_cdbp[4];
3584 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3585 			count = MIN(count, bufsize);
3586 			bcopy(&inq, bp->b_un.b_addr, count);
3587 
3588 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3589 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3590 			    bufsize - count : 0;
3591 		} else {
3592 			/*
3593 			 * peripheral_qualifier = 0;
3594 			 *
3595 			 * We are dealing only with HD and will be
3596 			 * dealing with CD/DVD devices soon
3597 			 */
3598 			uint8_t peripheral_device_type =
3599 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3600 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3601 
3602 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3603 			case INQUIRY_SUP_VPD_PAGE:
3604 				/*
3605 				 * Request for suported Vital Product Data
3606 				 * pages - assuming only 2 page codes
3607 				 * supported.
3608 				 */
3609 				page_buf[0] = peripheral_device_type;
3610 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3611 				page_buf[2] = 0;
3612 				page_buf[3] = 3; /* page length */
3613 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3614 				page_buf[5] = INQUIRY_USN_PAGE;
3615 				page_buf[6] = INQUIRY_BDC_PAGE;
3616 				/* Copy no more than requested */
3617 				count = MIN(bp->b_bcount, 7);
3618 				bcopy(page_buf, bp->b_un.b_addr, count);
3619 				break;
3620 
3621 			case INQUIRY_USN_PAGE:
3622 				/*
3623 				 * Request for Unit Serial Number page.
3624 				 * Set-up the page.
3625 				 */
3626 				page_buf[0] = peripheral_device_type;
3627 				page_buf[1] = INQUIRY_USN_PAGE;
3628 				page_buf[2] = 0;
3629 				/* remaining page length */
3630 				page_buf[3] = SATA_ID_SERIAL_LEN;
3631 
3632 				/*
3633 				 * Copy serial number from Identify Device data
3634 				 * words into the inquiry page and swap bytes
3635 				 * when necessary.
3636 				 */
3637 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3638 #ifdef	_LITTLE_ENDIAN
3639 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3640 #else
3641 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3642 #endif
3643 				/*
3644 				 * Least significant character of the serial
3645 				 * number shall appear as the last byte,
3646 				 * according to SBC-3 spec.
3647 				 * Count trailing spaces to determine the
3648 				 * necessary shift length.
3649 				 */
3650 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3651 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3652 					if (*(p - j) != '\0' &&
3653 					    *(p - j) != '\040')
3654 						break;
3655 				}
3656 
3657 				/*
3658 				 * Shift SN string right, so that the last
3659 				 * non-blank character would appear in last
3660 				 * byte of SN field in the page.
3661 				 * 'j' is the shift length.
3662 				 */
3663 				for (i = 0;
3664 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3665 				    i++, p--)
3666 					*p = *(p - j);
3667 
3668 				/*
3669 				 * Add leading spaces - same number as the
3670 				 * shift size
3671 				 */
3672 				for (; j > 0; j--)
3673 					page_buf[4 + j - 1] = '\040';
3674 
3675 				count = MIN(bp->b_bcount,
3676 				    SATA_ID_SERIAL_LEN + 4);
3677 				bcopy(page_buf, bp->b_un.b_addr, count);
3678 				break;
3679 
3680 			case INQUIRY_BDC_PAGE:
3681 				/*
3682 				 * Request for Block Device Characteristics
3683 				 * page.  Set-up the page.
3684 				 */
3685 				page_buf[0] = peripheral_device_type;
3686 				page_buf[1] = INQUIRY_BDC_PAGE;
3687 				page_buf[2] = 0;
3688 				/* remaining page length */
3689 				page_buf[3] = SATA_ID_BDC_LEN;
3690 
3691 				rate = sdinfo->satadrv_id.ai_medrotrate;
3692 				page_buf[4] = (rate >> 8) & 0xff;
3693 				page_buf[5] = rate & 0xff;
3694 				page_buf[6] = 0;
3695 				page_buf[7] = sdinfo->satadrv_id.
3696 				    ai_nomformfactor & 0xf;
3697 
3698 				count = MIN(bp->b_bcount,
3699 				    SATA_ID_BDC_LEN + 4);
3700 				bcopy(page_buf, bp->b_un.b_addr, count);
3701 				break;
3702 
3703 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3704 				/*
3705 				 * We may want to implement this page, when
3706 				 * identifiers are common for SATA devices
3707 				 * But not now.
3708 				 */
3709 				/*FALLTHROUGH*/
3710 
3711 			default:
3712 				/* Request for unsupported VPD page */
3713 				*scsipkt->pkt_scbp = STATUS_CHECK;
3714 				sense = sata_arq_sense(spx);
3715 				sense->es_key = KEY_ILLEGAL_REQUEST;
3716 				sense->es_add_code =
3717 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3718 				goto done;
3719 			}
3720 		}
3721 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3722 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3723 		    scsipkt->pkt_cdbp[4] - count : 0;
3724 	}
3725 done:
3726 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3727 
3728 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3729 	    "Scsi_pkt completion reason %x\n",
3730 	    scsipkt->pkt_reason);
3731 
3732 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3733 	    scsipkt->pkt_comp != NULL) {
3734 		/* scsi callback required */
3735 		if (servicing_interrupt()) {
3736 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3737 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3738 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3739 				return (TRAN_BUSY);
3740 			}
3741 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3742 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3743 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3744 			/* Scheduling the callback failed */
3745 			return (TRAN_BUSY);
3746 		}
3747 	}
3748 	return (TRAN_ACCEPT);
3749 }
3750 
3751 /*
3752  * SATA translate command: Request Sense.
3753  *
3754  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3755  * At the moment this is an emulated command (ATA version for SATA hard disks).
3756  * May be translated into Check Power Mode command in the future.
3757  *
3758  * Note: There is a mismatch between already implemented Informational
3759  * Exception Mode Select page 0x1C and this function.
3760  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3761  * NO SENSE and set additional sense code to the exception code - this is not
3762  * implemented here.
3763  */
3764 static int
3765 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3766 {
3767 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3768 	struct scsi_extended_sense sense;
3769 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3770 	sata_drive_info_t *sdinfo;
3771 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3772 	int rval, reason, power_state = 0;
3773 
3774 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3775 
3776 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3777 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3778 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3779 		return (rval);
3780 	}
3781 
3782 	scsipkt->pkt_reason = CMD_CMPLT;
3783 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3784 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3785 	*scsipkt->pkt_scbp = STATUS_GOOD;
3786 
3787 	/*
3788 	 * when CONTROL field's NACA bit == 1
3789 	 * return ILLEGAL_REQUEST
3790 	 */
3791 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3792 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3793 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3794 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3795 	}
3796 
3797 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3798 	    &spx->txlt_sata_pkt->satapkt_device);
3799 	ASSERT(sdinfo != NULL);
3800 
3801 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3802 
3803 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3804 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3805 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3806 	if (sata_hba_start(spx, &rval) != 0) {
3807 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3808 		return (rval);
3809 	} else {
3810 		if (scmd->satacmd_error_reg != 0) {
3811 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3812 			return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3813 			    SD_SCSI_ASC_NO_ADD_SENSE));
3814 		}
3815 	}
3816 
3817 	switch (scmd->satacmd_sec_count_lsb) {
3818 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3819 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3820 			power_state = SATA_POWER_STOPPED;
3821 		else {
3822 			power_state = SATA_POWER_STANDBY;
3823 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
3824 		}
3825 		break;
3826 	case SATA_PWRMODE_IDLE: /* device in idle mode */
3827 		power_state = SATA_POWER_IDLE;
3828 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3829 		break;
3830 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
3831 	default:		  /* 0x40, 0x41 active mode */
3832 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
3833 			power_state = SATA_POWER_IDLE;
3834 		else {
3835 			power_state = SATA_POWER_ACTIVE;
3836 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3837 		}
3838 		break;
3839 	}
3840 
3841 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3842 
3843 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3844 		/*
3845 		 * Because it is fully emulated command storing data
3846 		 * programatically in the specified buffer, release
3847 		 * preallocated DMA resources before storing data in the buffer,
3848 		 * so no unwanted DMA sync would take place.
3849 		 */
3850 		int count = MIN(bp->b_bcount,
3851 		    sizeof (struct scsi_extended_sense));
3852 		sata_scsi_dmafree(NULL, scsipkt);
3853 		bzero(&sense, sizeof (struct scsi_extended_sense));
3854 		sense.es_valid = 0;	/* Valid LBA */
3855 		sense.es_class = 7;	/* Response code 0x70 - current err */
3856 		sense.es_key = KEY_NO_SENSE;
3857 		sense.es_add_len = 6;	/* Additional length */
3858 		/* Copy no more than requested */
3859 		bcopy(&sense, bp->b_un.b_addr, count);
3860 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3861 		scsipkt->pkt_resid = 0;
3862 		switch (power_state) {
3863 		case SATA_POWER_IDLE:
3864 		case SATA_POWER_STANDBY:
3865 			sense.es_add_code =
3866 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
3867 			break;
3868 		case SATA_POWER_STOPPED:
3869 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
3870 			break;
3871 		case SATA_POWER_ACTIVE:
3872 		default:
3873 			break;
3874 		}
3875 	}
3876 
3877 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3878 	    "Scsi_pkt completion reason %x\n",
3879 	    scsipkt->pkt_reason);
3880 
3881 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3882 	    scsipkt->pkt_comp != NULL) {
3883 		/* scsi callback required */
3884 		if (servicing_interrupt()) {
3885 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3886 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3887 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3888 				return (TRAN_BUSY);
3889 			}
3890 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3891 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3892 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3893 			/* Scheduling the callback failed */
3894 			return (TRAN_BUSY);
3895 		}
3896 	}
3897 	return (TRAN_ACCEPT);
3898 }
3899 
3900 /*
3901  * SATA translate command: Test Unit Ready
3902  * (ATA version for SATA hard disks).
3903  * It is translated into the Check Power Mode command.
3904  *
3905  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3906  */
3907 static int
3908 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3909 {
3910 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3911 	struct scsi_extended_sense *sense;
3912 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3913 	sata_drive_info_t *sdinfo;
3914 	int power_state;
3915 	int rval, reason;
3916 
3917 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3918 
3919 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3920 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3921 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3922 		return (rval);
3923 	}
3924 
3925 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3926 	    &spx->txlt_sata_pkt->satapkt_device);
3927 	ASSERT(sdinfo != NULL);
3928 
3929 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3930 
3931 	/* send CHECK POWER MODE command */
3932 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3933 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3934 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3935 	if (sata_hba_start(spx, &rval) != 0) {
3936 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3937 		return (rval);
3938 	} else {
3939 		if (scmd->satacmd_error_reg != 0) {
3940 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3941 			return (sata_txlt_check_condition(spx, KEY_NOT_READY,
3942 			    SD_SCSI_ASC_LU_NOT_RESPONSE));
3943 		}
3944 	}
3945 
3946 	power_state = scmd->satacmd_sec_count_lsb;
3947 
3948 	/*
3949 	 * return NOT READY when device in STOPPED mode
3950 	 */
3951 	if (power_state == SATA_PWRMODE_STANDBY &&
3952 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
3953 		*scsipkt->pkt_scbp = STATUS_CHECK;
3954 		sense = sata_arq_sense(spx);
3955 		sense->es_key = KEY_NOT_READY;
3956 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3957 	} else {
3958 		/*
3959 		 * For other power mode, return GOOD status
3960 		 */
3961 		*scsipkt->pkt_scbp = STATUS_GOOD;
3962 	}
3963 
3964 	scsipkt->pkt_reason = CMD_CMPLT;
3965 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3966 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3967 
3968 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3969 
3970 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3971 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3972 
3973 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3974 	    scsipkt->pkt_comp != NULL) {
3975 		/* scsi callback required */
3976 		if (servicing_interrupt()) {
3977 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3978 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3979 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3980 				return (TRAN_BUSY);
3981 			}
3982 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3983 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3984 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3985 			/* Scheduling the callback failed */
3986 			return (TRAN_BUSY);
3987 		}
3988 	}
3989 
3990 	return (TRAN_ACCEPT);
3991 }
3992 
3993 /*
3994  * SATA translate command: Start Stop Unit
3995  * Translation depends on a command:
3996  *
3997  * Power condition bits will be supported
3998  * and the power level should be maintained by SATL,
3999  * When SATL received a command, it will check the
4000  * power level firstly, and return the status according
4001  * to SAT2 v2.6 and SAT-2 Standby Modifications
4002  *
4003  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
4004  * -----------------------------------------------------------------------
4005  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
4006  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
4007  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
4008  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
4009  *
4010  *	Unload Media / NOT SUPPORTED YET
4011  *	Load Media / NOT SUPPROTED YET
4012  *	Immediate bit / NOT SUPPORTED YET (deferred error)
4013  *
4014  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4015  * appropriate values in scsi_pkt fields.
4016  */
4017 static int
4018 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
4019 {
4020 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4021 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4022 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4023 	int cport = SATA_TXLT_CPORT(spx);
4024 	int rval, reason;
4025 	sata_drive_info_t *sdinfo;
4026 	sata_id_t *sata_id;
4027 
4028 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4029 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
4030 
4031 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
4032 
4033 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4034 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4035 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4036 		return (rval);
4037 	}
4038 
4039 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
4040 		/* IMMED bit - not supported */
4041 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4042 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4043 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4044 	}
4045 
4046 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
4047 	spx->txlt_sata_pkt->satapkt_comp = NULL;
4048 
4049 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4050 	    &spx->txlt_sata_pkt->satapkt_device);
4051 	ASSERT(sdinfo != NULL);
4052 	sata_id = &sdinfo->satadrv_id;
4053 
4054 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
4055 	case 0:
4056 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
4057 			/* Load/Unload Media - invalid request */
4058 			goto err_out;
4059 		}
4060 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
4061 			/* Start Unit */
4062 			sata_build_read_verify_cmd(scmd, 1, 5);
4063 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4064 			/* Transfer command to HBA */
4065 			if (sata_hba_start(spx, &rval) != 0) {
4066 				/* Pkt not accepted for execution */
4067 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4068 				return (rval);
4069 			} else {
4070 				if (scmd->satacmd_error_reg != 0) {
4071 					goto err_out;
4072 				}
4073 			}
4074 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4075 		} else {
4076 			/* Stop Unit */
4077 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4078 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4079 			if (sata_hba_start(spx, &rval) != 0) {
4080 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4081 				return (rval);
4082 			} else {
4083 				if (scmd->satacmd_error_reg != 0) {
4084 					goto err_out;
4085 				}
4086 			}
4087 			/* ata standby immediate command */
4088 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4089 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4090 			if (sata_hba_start(spx, &rval) != 0) {
4091 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4092 				return (rval);
4093 			} else {
4094 				if (scmd->satacmd_error_reg != 0) {
4095 					goto err_out;
4096 				}
4097 			}
4098 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4099 		}
4100 		break;
4101 	case 0x1:
4102 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4103 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4104 		if (sata_hba_start(spx, &rval) != 0) {
4105 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4106 			return (rval);
4107 		} else {
4108 			if (scmd->satacmd_error_reg != 0) {
4109 				goto err_out;
4110 			}
4111 		}
4112 		sata_build_read_verify_cmd(scmd, 1, 5);
4113 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4114 		/* Transfer command to HBA */
4115 		if (sata_hba_start(spx, &rval) != 0) {
4116 			/* Pkt not accepted for execution */
4117 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4118 			return (rval);
4119 		} else {
4120 			if (scmd->satacmd_error_reg != 0) {
4121 				goto err_out;
4122 			}
4123 		}
4124 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4125 		break;
4126 	case 0x2:
4127 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4128 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4129 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4130 			if (sata_hba_start(spx, &rval) != 0) {
4131 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4132 				return (rval);
4133 			} else {
4134 				if (scmd->satacmd_error_reg != 0) {
4135 					goto err_out;
4136 				}
4137 			}
4138 		}
4139 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4140 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4141 		if (sata_hba_start(spx, &rval) != 0) {
4142 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4143 			return (rval);
4144 		} else {
4145 			if (scmd->satacmd_error_reg != 0) {
4146 				goto err_out;
4147 			}
4148 		}
4149 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4150 			/*
4151 			 *  POWER CONDITION MODIFIER bit set
4152 			 *  to 0x1 or larger it will be handled
4153 			 *  on the same way as bit = 0x1
4154 			 */
4155 			if (!(sata_id->ai_cmdset84 &
4156 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4157 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4158 				break;
4159 			}
4160 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4161 			scmd->satacmd_features_reg = 0x44;
4162 			scmd->satacmd_lba_low_lsb = 0x4c;
4163 			scmd->satacmd_lba_mid_lsb = 0x4e;
4164 			scmd->satacmd_lba_high_lsb = 0x55;
4165 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4166 			if (sata_hba_start(spx, &rval) != 0) {
4167 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4168 				return (rval);
4169 			} else {
4170 				if (scmd->satacmd_error_reg != 0) {
4171 					goto err_out;
4172 				}
4173 			}
4174 		}
4175 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4176 		break;
4177 	case 0x3:
4178 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4179 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4180 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4181 			if (sata_hba_start(spx, &rval) != 0) {
4182 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4183 				return (rval);
4184 			} else {
4185 				if (scmd->satacmd_error_reg != 0) {
4186 					goto err_out;
4187 				}
4188 			}
4189 		}
4190 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4191 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4192 		if (sata_hba_start(spx, &rval) != 0) {
4193 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4194 			return (rval);
4195 		} else {
4196 			if (scmd->satacmd_error_reg != 0) {
4197 				goto err_out;
4198 			}
4199 		}
4200 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4201 		break;
4202 	case 0x7:
4203 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4204 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4205 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4206 		if (sata_hba_start(spx, &rval) != 0) {
4207 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4208 			return (rval);
4209 		} else {
4210 			if (scmd->satacmd_error_reg != 0) {
4211 				goto err_out;
4212 			}
4213 		}
4214 		switch (scmd->satacmd_sec_count_lsb) {
4215 		case SATA_PWRMODE_STANDBY:
4216 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4217 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4218 			    sdinfo->satadrv_standby_timer);
4219 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4220 			if (sata_hba_start(spx, &rval) != 0) {
4221 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4222 				return (rval);
4223 			} else {
4224 				if (scmd->satacmd_error_reg != 0) {
4225 					goto err_out;
4226 				}
4227 			}
4228 			break;
4229 		case SATA_PWRMODE_IDLE:
4230 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4231 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4232 			    sdinfo->satadrv_standby_timer);
4233 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4234 			if (sata_hba_start(spx, &rval) != 0) {
4235 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4236 				return (rval);
4237 			} else {
4238 				if (scmd->satacmd_error_reg != 0) {
4239 					goto err_out;
4240 				}
4241 			}
4242 			break;
4243 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4244 		case SATA_PWRMODE_ACTIVE_SPINUP:
4245 		case SATA_PWRMODE_ACTIVE:
4246 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4247 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4248 			    sdinfo->satadrv_standby_timer);
4249 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4250 			if (sata_hba_start(spx, &rval) != 0) {
4251 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4252 				return (rval);
4253 			} else {
4254 				if (scmd->satacmd_error_reg != 0) {
4255 					goto err_out;
4256 				}
4257 			}
4258 			sata_build_read_verify_cmd(scmd, 1, 5);
4259 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4260 			if (sata_hba_start(spx, &rval) != 0) {
4261 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4262 				return (rval);
4263 			} else {
4264 				if (scmd->satacmd_error_reg != 0) {
4265 					goto err_out;
4266 				}
4267 			}
4268 			break;
4269 		default:
4270 			goto err_out;
4271 		}
4272 		break;
4273 	case 0xb:
4274 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4275 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4276 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4277 			return (sata_txlt_check_condition(spx,
4278 			    KEY_ILLEGAL_REQUEST,
4279 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4280 		}
4281 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4282 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4283 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4284 			if (sata_hba_start(spx, &rval) != 0) {
4285 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4286 				return (rval);
4287 			} else {
4288 				if (scmd->satacmd_error_reg != 0) {
4289 					goto err_out;
4290 				}
4291 			}
4292 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4293 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4294 			if (sata_hba_start(spx, &rval) != 0) {
4295 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4296 				return (rval);
4297 			} else {
4298 				if (scmd->satacmd_error_reg != 0) {
4299 					goto err_out;
4300 				}
4301 			}
4302 		}
4303 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4304 		break;
4305 	default:
4306 err_out:
4307 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4308 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4309 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4310 	}
4311 
4312 	/*
4313 	 * Since it was a synchronous command,
4314 	 * a callback function will be called directly.
4315 	 */
4316 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4317 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4318 	    "synchronous execution status %x\n",
4319 	    spx->txlt_sata_pkt->satapkt_reason);
4320 
4321 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4322 	    scsipkt->pkt_comp != NULL) {
4323 		sata_set_arq_data(spx->txlt_sata_pkt);
4324 		if (servicing_interrupt()) {
4325 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4326 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4327 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4328 				return (TRAN_BUSY);
4329 			}
4330 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4331 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4332 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4333 			/* Scheduling the callback failed */
4334 			return (TRAN_BUSY);
4335 		}
4336 	}
4337 	else
4338 
4339 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4340 
4341 	return (TRAN_ACCEPT);
4342 
4343 }
4344 
4345 /*
4346  * SATA translate command:  Read Capacity.
4347  * Emulated command for SATA disks.
4348  * Capacity is retrieved from cached Idenifty Device data.
4349  * Identify Device data shows effective disk capacity, not the native
4350  * capacity, which may be limitted by Set Max Address command.
4351  * This is ATA version for SATA hard disks.
4352  *
4353  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4354  */
4355 static int
4356 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4357 {
4358 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4359 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4360 	sata_drive_info_t *sdinfo;
4361 	uint64_t val;
4362 	uchar_t *rbuf;
4363 	int rval, reason;
4364 
4365 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4366 	    "sata_txlt_read_capacity: ", NULL);
4367 
4368 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4369 
4370 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4371 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4372 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4373 		return (rval);
4374 	}
4375 
4376 	scsipkt->pkt_reason = CMD_CMPLT;
4377 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4378 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4379 	*scsipkt->pkt_scbp = STATUS_GOOD;
4380 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4381 		/*
4382 		 * Because it is fully emulated command storing data
4383 		 * programatically in the specified buffer, release
4384 		 * preallocated DMA resources before storing data in the buffer,
4385 		 * so no unwanted DMA sync would take place.
4386 		 */
4387 		sata_scsi_dmafree(NULL, scsipkt);
4388 
4389 		sdinfo = sata_get_device_info(
4390 		    spx->txlt_sata_hba_inst,
4391 		    &spx->txlt_sata_pkt->satapkt_device);
4392 		/* Last logical block address */
4393 		val = sdinfo->satadrv_capacity - 1;
4394 		rbuf = (uchar_t *)bp->b_un.b_addr;
4395 		/* Need to swap endians to match scsi format */
4396 		rbuf[0] = (val >> 24) & 0xff;
4397 		rbuf[1] = (val >> 16) & 0xff;
4398 		rbuf[2] = (val >> 8) & 0xff;
4399 		rbuf[3] = val & 0xff;
4400 		/* block size - always 512 bytes, for now */
4401 		rbuf[4] = 0;
4402 		rbuf[5] = 0;
4403 		rbuf[6] = 0x02;
4404 		rbuf[7] = 0;
4405 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4406 		scsipkt->pkt_resid = 0;
4407 
4408 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4409 		    sdinfo->satadrv_capacity -1);
4410 	}
4411 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4412 	/*
4413 	 * If a callback was requested, do it now.
4414 	 */
4415 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4416 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4417 
4418 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4419 	    scsipkt->pkt_comp != NULL) {
4420 		/* scsi callback required */
4421 		if (servicing_interrupt()) {
4422 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4423 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4424 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4425 				return (TRAN_BUSY);
4426 			}
4427 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4428 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4429 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4430 			/* Scheduling the callback failed */
4431 			return (TRAN_BUSY);
4432 		}
4433 	}
4434 
4435 	return (TRAN_ACCEPT);
4436 }
4437 
4438 /*
4439  * SATA translate command: Mode Sense.
4440  * Translated into appropriate SATA command or emulated.
4441  * Saved Values Page Control (03) are not supported.
4442  *
4443  * NOTE: only caching mode sense page is currently implemented.
4444  *
4445  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4446  */
4447 
4448 #define	LLBAA	0x10	/* Long LBA Accepted */
4449 
4450 static int
4451 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4452 {
4453 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4454 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4455 	sata_drive_info_t *sdinfo;
4456 	sata_id_t *sata_id;
4457 	struct scsi_extended_sense *sense;
4458 	int 		len, bdlen, count, alc_len;
4459 	int		pc;	/* Page Control code */
4460 	uint8_t		*buf;	/* mode sense buffer */
4461 	int		rval, reason;
4462 
4463 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4464 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4465 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4466 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4467 
4468 	if (servicing_interrupt()) {
4469 		buf = kmem_zalloc(1024, KM_NOSLEEP);
4470 		if (buf == NULL) {
4471 			return (TRAN_BUSY);
4472 		}
4473 	} else {
4474 		buf = kmem_zalloc(1024, KM_SLEEP);
4475 	}
4476 
4477 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4478 
4479 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4480 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4481 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4482 		kmem_free(buf, 1024);
4483 		return (rval);
4484 	}
4485 
4486 	scsipkt->pkt_reason = CMD_CMPLT;
4487 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4488 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4489 
4490 	pc = scsipkt->pkt_cdbp[2] >> 6;
4491 
4492 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4493 		/*
4494 		 * Because it is fully emulated command storing data
4495 		 * programatically in the specified buffer, release
4496 		 * preallocated DMA resources before storing data in the buffer,
4497 		 * so no unwanted DMA sync would take place.
4498 		 */
4499 		sata_scsi_dmafree(NULL, scsipkt);
4500 
4501 		len = 0;
4502 		bdlen = 0;
4503 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4504 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4505 			    (scsipkt->pkt_cdbp[1] & LLBAA))
4506 				bdlen = 16;
4507 			else
4508 				bdlen = 8;
4509 		}
4510 		/* Build mode parameter header */
4511 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4512 			/* 4-byte mode parameter header */
4513 			buf[len++] = 0;		/* mode data length */
4514 			buf[len++] = 0;		/* medium type */
4515 			buf[len++] = 0;		/* dev-specific param */
4516 			buf[len++] = bdlen;	/* Block Descriptor length */
4517 		} else {
4518 			/* 8-byte mode parameter header */
4519 			buf[len++] = 0;		/* mode data length */
4520 			buf[len++] = 0;
4521 			buf[len++] = 0;		/* medium type */
4522 			buf[len++] = 0;		/* dev-specific param */
4523 			if (bdlen == 16)
4524 				buf[len++] = 1;	/* long lba descriptor */
4525 			else
4526 				buf[len++] = 0;
4527 			buf[len++] = 0;
4528 			buf[len++] = 0;		/* Block Descriptor length */
4529 			buf[len++] = bdlen;
4530 		}
4531 
4532 		sdinfo = sata_get_device_info(
4533 		    spx->txlt_sata_hba_inst,
4534 		    &spx->txlt_sata_pkt->satapkt_device);
4535 
4536 		/* Build block descriptor only if not disabled (DBD) */
4537 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4538 			/* Block descriptor - direct-access device format */
4539 			if (bdlen == 8) {
4540 				/* build regular block descriptor */
4541 				buf[len++] =
4542 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4543 				buf[len++] =
4544 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4545 				buf[len++] =
4546 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4547 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4548 				buf[len++] = 0; /* density code */
4549 				buf[len++] = 0;
4550 				if (sdinfo->satadrv_type ==
4551 				    SATA_DTYPE_ATADISK)
4552 					buf[len++] = 2;
4553 				else
4554 					/* ATAPI */
4555 					buf[len++] = 8;
4556 				buf[len++] = 0;
4557 			} else if (bdlen == 16) {
4558 				/* Long LBA Accepted */
4559 				/* build long lba block descriptor */
4560 #ifndef __lock_lint
4561 				buf[len++] =
4562 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4563 				buf[len++] =
4564 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4565 				buf[len++] =
4566 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4567 				buf[len++] =
4568 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4569 #endif
4570 				buf[len++] =
4571 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4572 				buf[len++] =
4573 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4574 				buf[len++] =
4575 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4576 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4577 				buf[len++] = 0;
4578 				buf[len++] = 0; /* density code */
4579 				buf[len++] = 0;
4580 				buf[len++] = 0;
4581 				if (sdinfo->satadrv_type ==
4582 				    SATA_DTYPE_ATADISK)
4583 					buf[len++] = 2;
4584 				else
4585 					/* ATAPI */
4586 					buf[len++] = 8;
4587 				buf[len++] = 0;
4588 			}
4589 		}
4590 
4591 		sata_id = &sdinfo->satadrv_id;
4592 
4593 		/*
4594 		 * Add requested pages.
4595 		 * Page 3 and 4 are obsolete and we are not supporting them.
4596 		 * We deal now with:
4597 		 * caching (read/write cache control).
4598 		 * We should eventually deal with following mode pages:
4599 		 * error recovery  (0x01),
4600 		 * power condition (0x1a),
4601 		 * exception control page (enables SMART) (0x1c),
4602 		 * enclosure management (ses),
4603 		 * protocol-specific port mode (port control).
4604 		 */
4605 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4606 		case MODEPAGE_RW_ERRRECOV:
4607 			/* DAD_MODE_ERR_RECOV */
4608 			/* R/W recovery */
4609 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4610 			break;
4611 		case MODEPAGE_CACHING:
4612 			/* DAD_MODE_CACHE */
4613 			/* Reject not supported request for saved parameters */
4614 			if (pc == 3) {
4615 				*scsipkt->pkt_scbp = STATUS_CHECK;
4616 				sense = sata_arq_sense(spx);
4617 				sense->es_key = KEY_ILLEGAL_REQUEST;
4618 				sense->es_add_code =
4619 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
4620 				goto done;
4621 			}
4622 
4623 			/* caching */
4624 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4625 			break;
4626 		case MODEPAGE_INFO_EXCPT:
4627 			/* exception cntrl */
4628 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4629 				len += sata_build_msense_page_1c(sdinfo, pc,
4630 				    buf+len);
4631 			}
4632 			else
4633 				goto err;
4634 			break;
4635 		case MODEPAGE_POWER_COND:
4636 			/* DAD_MODE_POWER_COND */
4637 			/* power condition */
4638 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4639 			break;
4640 
4641 		case MODEPAGE_ACOUSTIC_MANAG:
4642 			/* acoustic management */
4643 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4644 			break;
4645 		case MODEPAGE_ALLPAGES:
4646 			/* all pages */
4647 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4648 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4649 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4650 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4651 				len += sata_build_msense_page_1c(sdinfo, pc,
4652 				    buf+len);
4653 			}
4654 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4655 			break;
4656 		default:
4657 		err:
4658 			/* Invalid request */
4659 			*scsipkt->pkt_scbp = STATUS_CHECK;
4660 			sense = sata_arq_sense(spx);
4661 			sense->es_key = KEY_ILLEGAL_REQUEST;
4662 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4663 			goto done;
4664 		}
4665 
4666 		/* fix total mode data length */
4667 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4668 			/* 4-byte mode parameter header */
4669 			buf[0] = len - 1;	/* mode data length */
4670 		} else {
4671 			buf[0] = (len -2) >> 8;
4672 			buf[1] = (len -2) & 0xff;
4673 		}
4674 
4675 
4676 		/* Check allocation length */
4677 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4678 			alc_len = scsipkt->pkt_cdbp[4];
4679 		} else {
4680 			alc_len = scsipkt->pkt_cdbp[7];
4681 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4682 		}
4683 		/*
4684 		 * We do not check for possible parameters truncation
4685 		 * (alc_len < len) assuming that the target driver works
4686 		 * correctly. Just avoiding overrun.
4687 		 * Copy no more than requested and possible, buffer-wise.
4688 		 */
4689 		count = MIN(alc_len, len);
4690 		count = MIN(bp->b_bcount, count);
4691 		bcopy(buf, bp->b_un.b_addr, count);
4692 
4693 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4694 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4695 	}
4696 	*scsipkt->pkt_scbp = STATUS_GOOD;
4697 done:
4698 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4699 	(void) kmem_free(buf, 1024);
4700 
4701 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4702 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4703 
4704 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4705 	    scsipkt->pkt_comp != NULL) {
4706 		/* scsi callback required */
4707 		if (servicing_interrupt()) {
4708 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4709 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4710 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4711 				return (TRAN_BUSY);
4712 			}
4713 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4714 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4715 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4716 			/* Scheduling the callback failed */
4717 			return (TRAN_BUSY);
4718 		}
4719 	}
4720 
4721 	return (TRAN_ACCEPT);
4722 }
4723 
4724 
4725 /*
4726  * SATA translate command: Mode Select.
4727  * Translated into appropriate SATA command or emulated.
4728  * Saving parameters is not supported.
4729  * Changing device capacity is not supported (although theoretically
4730  * possible by executing SET FEATURES/SET MAX ADDRESS)
4731  *
4732  * Assumption is that the target driver is working correctly.
4733  *
4734  * More than one SATA command may be executed to perform operations specified
4735  * by mode select pages. The first error terminates further execution.
4736  * Operations performed successully are not backed-up in such case.
4737  *
4738  * NOTE: Implemented pages:
4739  * - caching page
4740  * - informational exception page
4741  * - acoustic management page
4742  * - power condition page
4743  * Caching setup is remembered so it could be re-stored in case of
4744  * an unexpected device reset.
4745  *
4746  * Returns TRAN_XXXX.
4747  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
4748  */
4749 
4750 static int
4751 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4752 {
4753 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4754 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4755 	struct scsi_extended_sense *sense;
4756 	int len, pagelen, count, pllen;
4757 	uint8_t *buf;	/* mode select buffer */
4758 	int rval, stat, reason;
4759 	uint_t nointr_flag;
4760 	int dmod = 0;
4761 
4762 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4763 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4764 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4765 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4766 
4767 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4768 
4769 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4770 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4771 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4772 		return (rval);
4773 	}
4774 
4775 	rval = TRAN_ACCEPT;
4776 
4777 	scsipkt->pkt_reason = CMD_CMPLT;
4778 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4779 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4780 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4781 
4782 	/* Reject not supported request */
4783 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4784 		*scsipkt->pkt_scbp = STATUS_CHECK;
4785 		sense = sata_arq_sense(spx);
4786 		sense->es_key = KEY_ILLEGAL_REQUEST;
4787 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4788 		goto done;
4789 	}
4790 
4791 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4792 		pllen = scsipkt->pkt_cdbp[4];
4793 	} else {
4794 		pllen = scsipkt->pkt_cdbp[7];
4795 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4796 	}
4797 
4798 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4799 
4800 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4801 		buf = (uint8_t *)bp->b_un.b_addr;
4802 		count = MIN(bp->b_bcount, pllen);
4803 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4804 		scsipkt->pkt_resid = 0;
4805 		pllen = count;
4806 
4807 		/*
4808 		 * Check the header to skip the block descriptor(s) - we
4809 		 * do not support setting device capacity.
4810 		 * Existing macros do not recognize long LBA dscriptor,
4811 		 * hence manual calculation.
4812 		 */
4813 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4814 			/* 6-bytes CMD, 4 bytes header */
4815 			if (count <= 4)
4816 				goto done;		/* header only */
4817 			len = buf[3] + 4;
4818 		} else {
4819 			/* 10-bytes CMD, 8 bytes header */
4820 			if (count <= 8)
4821 				goto done;		/* header only */
4822 			len = buf[6];
4823 			len = (len << 8) + buf[7] + 8;
4824 		}
4825 		if (len >= count)
4826 			goto done;	/* header + descriptor(s) only */
4827 
4828 		pllen -= len;		/* remaining data length */
4829 
4830 		/*
4831 		 * We may be executing SATA command and want to execute it
4832 		 * in SYNCH mode, regardless of scsi_pkt setting.
4833 		 * Save scsi_pkt setting and indicate SYNCH mode
4834 		 */
4835 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4836 		    scsipkt->pkt_comp != NULL) {
4837 			scsipkt->pkt_flags |= FLAG_NOINTR;
4838 		}
4839 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
4840 
4841 		/*
4842 		 * len is now the offset to a first mode select page
4843 		 * Process all pages
4844 		 */
4845 		while (pllen > 0) {
4846 			switch ((int)buf[len]) {
4847 			case MODEPAGE_CACHING:
4848 				/* No support for SP (saving) */
4849 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4850 					*scsipkt->pkt_scbp = STATUS_CHECK;
4851 					sense = sata_arq_sense(spx);
4852 					sense->es_key = KEY_ILLEGAL_REQUEST;
4853 					sense->es_add_code =
4854 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4855 					goto done;
4856 				}
4857 				stat = sata_mode_select_page_8(spx,
4858 				    (struct mode_cache_scsi3 *)&buf[len],
4859 				    pllen, &pagelen, &rval, &dmod);
4860 				/*
4861 				 * The pagelen value indicates the number of
4862 				 * parameter bytes already processed.
4863 				 * The rval is the return value from
4864 				 * sata_tran_start().
4865 				 * The stat indicates the overall status of
4866 				 * the operation(s).
4867 				 */
4868 				if (stat != SATA_SUCCESS)
4869 					/*
4870 					 * Page processing did not succeed -
4871 					 * all error info is already set-up,
4872 					 * just return
4873 					 */
4874 					pllen = 0; /* this breaks the loop */
4875 				else {
4876 					len += pagelen;
4877 					pllen -= pagelen;
4878 				}
4879 				break;
4880 
4881 			case MODEPAGE_INFO_EXCPT:
4882 				stat = sata_mode_select_page_1c(spx,
4883 				    (struct mode_info_excpt_page *)&buf[len],
4884 				    pllen, &pagelen, &rval, &dmod);
4885 				/*
4886 				 * The pagelen value indicates the number of
4887 				 * parameter bytes already processed.
4888 				 * The rval is the return value from
4889 				 * sata_tran_start().
4890 				 * The stat indicates the overall status of
4891 				 * the operation(s).
4892 				 */
4893 				if (stat != SATA_SUCCESS)
4894 					/*
4895 					 * Page processing did not succeed -
4896 					 * all error info is already set-up,
4897 					 * just return
4898 					 */
4899 					pllen = 0; /* this breaks the loop */
4900 				else {
4901 					len += pagelen;
4902 					pllen -= pagelen;
4903 				}
4904 				break;
4905 
4906 			case MODEPAGE_ACOUSTIC_MANAG:
4907 				stat = sata_mode_select_page_30(spx,
4908 				    (struct mode_acoustic_management *)
4909 				    &buf[len], pllen, &pagelen, &rval, &dmod);
4910 				/*
4911 				 * The pagelen value indicates the number of
4912 				 * parameter bytes already processed.
4913 				 * The rval is the return value from
4914 				 * sata_tran_start().
4915 				 * The stat indicates the overall status of
4916 				 * the operation(s).
4917 				 */
4918 				if (stat != SATA_SUCCESS)
4919 					/*
4920 					 * Page processing did not succeed -
4921 					 * all error info is already set-up,
4922 					 * just return
4923 					 */
4924 					pllen = 0; /* this breaks the loop */
4925 				else {
4926 					len += pagelen;
4927 					pllen -= pagelen;
4928 				}
4929 
4930 				break;
4931 			case MODEPAGE_POWER_COND:
4932 				stat = sata_mode_select_page_1a(spx,
4933 				    (struct mode_info_power_cond *)&buf[len],
4934 				    pllen, &pagelen, &rval, &dmod);
4935 				/*
4936 				 * The pagelen value indicates the number of
4937 				 * parameter bytes already processed.
4938 				 * The rval is the return value from
4939 				 * sata_tran_start().
4940 				 * The stat indicates the overall status of
4941 				 * the operation(s).
4942 				 */
4943 				if (stat != SATA_SUCCESS)
4944 					/*
4945 					 * Page processing did not succeed -
4946 					 * all error info is already set-up,
4947 					 * just return
4948 					 */
4949 					pllen = 0; /* this breaks the loop */
4950 				else {
4951 					len += pagelen;
4952 					pllen -= pagelen;
4953 				}
4954 				break;
4955 			default:
4956 				*scsipkt->pkt_scbp = STATUS_CHECK;
4957 				sense = sata_arq_sense(spx);
4958 				sense->es_key = KEY_ILLEGAL_REQUEST;
4959 				sense->es_add_code =
4960 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
4961 				goto done;
4962 			}
4963 		}
4964 	}
4965 done:
4966 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4967 	/*
4968 	 * If device parameters were modified, fetch and store the new
4969 	 * Identify Device data. Since port mutex could have been released
4970 	 * for accessing HBA driver, we need to re-check device existence.
4971 	 */
4972 	if (dmod != 0) {
4973 		sata_drive_info_t new_sdinfo, *sdinfo;
4974 		int rv = 0;
4975 
4976 		/*
4977 		 * Following statement has to be changed if this function is
4978 		 * used for devices other than SATA hard disks.
4979 		 */
4980 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4981 
4982 		new_sdinfo.satadrv_addr =
4983 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4984 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4985 		    &new_sdinfo);
4986 
4987 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4988 		/*
4989 		 * Since port mutex could have been released when
4990 		 * accessing HBA driver, we need to re-check that the
4991 		 * framework still holds the device info structure.
4992 		 */
4993 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4994 		    &spx->txlt_sata_pkt->satapkt_device);
4995 		if (sdinfo != NULL) {
4996 			/*
4997 			 * Device still has info structure in the
4998 			 * sata framework. Copy newly fetched info
4999 			 */
5000 			if (rv == 0) {
5001 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
5002 				sata_save_drive_settings(sdinfo);
5003 			} else {
5004 				/*
5005 				 * Could not fetch new data - invalidate
5006 				 * sata_drive_info. That makes device
5007 				 * unusable.
5008 				 */
5009 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
5010 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
5011 			}
5012 		}
5013 		if (rv != 0 || sdinfo == NULL) {
5014 			/*
5015 			 * This changes the overall mode select completion
5016 			 * reason to a failed one !!!!!
5017 			 */
5018 			*scsipkt->pkt_scbp = STATUS_CHECK;
5019 			sense = sata_arq_sense(spx);
5020 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5021 			rval = TRAN_ACCEPT;
5022 		}
5023 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5024 	}
5025 	/* Restore the scsi pkt flags */
5026 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
5027 	scsipkt->pkt_flags |= nointr_flag;
5028 
5029 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5030 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5031 
5032 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5033 	    scsipkt->pkt_comp != NULL) {
5034 		/* scsi callback required */
5035 		if (servicing_interrupt()) {
5036 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5037 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5038 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5039 				return (TRAN_BUSY);
5040 			}
5041 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5042 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5043 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5044 			/* Scheduling the callback failed */
5045 			return (TRAN_BUSY);
5046 		}
5047 	}
5048 
5049 	return (rval);
5050 }
5051 
5052 /*
5053  * Translate command: ATA Pass Through
5054  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
5055  * PIO Data-Out protocols.  Also supports CK_COND bit.
5056  *
5057  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
5058  * described in Table 111 of SAT-2 (Draft 9).
5059  */
5060 static  int
5061 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
5062 {
5063 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5064 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5065 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5066 	int extend;
5067 	uint64_t lba;
5068 	uint16_t feature, sec_count;
5069 	int t_len, synch;
5070 	int rval, reason;
5071 
5072 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5073 
5074 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
5075 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5076 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5077 		return (rval);
5078 	}
5079 
5080 	/* T_DIR bit */
5081 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
5082 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5083 	else
5084 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5085 
5086 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
5087 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
5088 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5089 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5090 	}
5091 
5092 	/* OFFLINE field. If non-zero, invalid command (for now). */
5093 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
5094 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5095 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5096 	}
5097 
5098 	/* PROTOCOL field */
5099 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
5100 	case SATL_APT_P_HW_RESET:
5101 	case SATL_APT_P_SRST:
5102 	case SATL_APT_P_DMA:
5103 	case SATL_APT_P_DMA_QUEUED:
5104 	case SATL_APT_P_DEV_DIAG:
5105 	case SATL_APT_P_DEV_RESET:
5106 	case SATL_APT_P_UDMA_IN:
5107 	case SATL_APT_P_UDMA_OUT:
5108 	case SATL_APT_P_FPDMA:
5109 	case SATL_APT_P_RET_RESP:
5110 		/* Not yet implemented */
5111 	default:
5112 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5113 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5114 
5115 	case SATL_APT_P_NON_DATA:
5116 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
5117 		break;
5118 
5119 	case SATL_APT_P_PIO_DATA_IN:
5120 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5121 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
5122 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5123 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5124 		}
5125 
5126 		/* if there is a buffer, release its DMA resources */
5127 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5128 			sata_scsi_dmafree(NULL, scsipkt);
5129 		} else {
5130 			/* if there is no buffer, how do you PIO in? */
5131 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5132 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5133 		}
5134 
5135 		break;
5136 
5137 	case SATL_APT_P_PIO_DATA_OUT:
5138 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5139 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5140 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5141 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5142 		}
5143 
5144 		/* if there is a buffer, release its DMA resources */
5145 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5146 			sata_scsi_dmafree(NULL, scsipkt);
5147 		} else {
5148 			/* if there is no buffer, how do you PIO out? */
5149 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5150 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5151 		}
5152 
5153 		break;
5154 	}
5155 
5156 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5157 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5158 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5159 		feature = scsipkt->pkt_cdbp[3];
5160 
5161 		sec_count = scsipkt->pkt_cdbp[4];
5162 
5163 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5164 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5165 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5166 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5167 
5168 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5169 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5170 
5171 		break;
5172 
5173 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5174 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5175 			extend = 1;
5176 
5177 			feature = scsipkt->pkt_cdbp[3];
5178 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5179 
5180 			sec_count = scsipkt->pkt_cdbp[5];
5181 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5182 
5183 			lba = scsipkt->pkt_cdbp[11];
5184 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5185 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5186 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5187 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5188 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5189 
5190 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5191 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5192 		} else {
5193 			feature = scsipkt->pkt_cdbp[3];
5194 
5195 			sec_count = scsipkt->pkt_cdbp[5];
5196 
5197 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5198 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5199 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5200 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5201 
5202 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5203 			    0xf0;
5204 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5205 		}
5206 
5207 		break;
5208 	}
5209 
5210 	/* CK_COND bit */
5211 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5212 		if (extend) {
5213 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5214 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5215 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5216 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5217 		}
5218 
5219 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5220 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5221 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5222 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5223 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5224 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5225 	}
5226 
5227 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5228 	if (extend) {
5229 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5230 
5231 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5232 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5233 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5234 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5235 		scmd->satacmd_lba_high_msb = lba >> 40;
5236 	} else {
5237 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5238 
5239 		scmd->satacmd_features_reg_ext = 0;
5240 		scmd->satacmd_sec_count_msb = 0;
5241 		scmd->satacmd_lba_low_msb = 0;
5242 		scmd->satacmd_lba_mid_msb = 0;
5243 		scmd->satacmd_lba_high_msb = 0;
5244 	}
5245 
5246 	scmd->satacmd_features_reg = feature & 0xff;
5247 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5248 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5249 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5250 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5251 
5252 	/* Determine transfer length */
5253 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5254 	case 1:
5255 		t_len = feature;
5256 		break;
5257 	case 2:
5258 		t_len = sec_count;
5259 		break;
5260 	default:
5261 		t_len = 0;
5262 		break;
5263 	}
5264 
5265 	/* Adjust transfer length for the Byte Block bit */
5266 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5267 		t_len *= SATA_DISK_SECTOR_SIZE;
5268 
5269 	/* Start processing command */
5270 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5271 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5272 		synch = FALSE;
5273 	} else {
5274 		synch = TRUE;
5275 	}
5276 
5277 	if (sata_hba_start(spx, &rval) != 0) {
5278 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5279 		return (rval);
5280 	}
5281 
5282 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5283 
5284 	if (synch) {
5285 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5286 	}
5287 
5288 	return (TRAN_ACCEPT);
5289 }
5290 
5291 /*
5292  * Translate command: Log Sense
5293  */
5294 static 	int
5295 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5296 {
5297 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5298 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5299 	sata_drive_info_t *sdinfo;
5300 	struct scsi_extended_sense *sense;
5301 	int 		len, count, alc_len;
5302 	int		pc;	/* Page Control code */
5303 	int		page_code;	/* Page code */
5304 	uint8_t		*buf;	/* log sense buffer */
5305 	int		rval, reason;
5306 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5307 
5308 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5309 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5310 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5311 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5312 
5313 	if (servicing_interrupt()) {
5314 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_NOSLEEP);
5315 		if (buf == NULL) {
5316 			return (TRAN_BUSY);
5317 		}
5318 	} else {
5319 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5320 	}
5321 
5322 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5323 
5324 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5325 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5326 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5327 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5328 		return (rval);
5329 	}
5330 
5331 	scsipkt->pkt_reason = CMD_CMPLT;
5332 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5333 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5334 
5335 	pc = scsipkt->pkt_cdbp[2] >> 6;
5336 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5337 
5338 	/* Reject not supported request for all but cumulative values */
5339 	switch (pc) {
5340 	case PC_CUMULATIVE_VALUES:
5341 		break;
5342 	default:
5343 		*scsipkt->pkt_scbp = STATUS_CHECK;
5344 		sense = sata_arq_sense(spx);
5345 		sense->es_key = KEY_ILLEGAL_REQUEST;
5346 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5347 		goto done;
5348 	}
5349 
5350 	switch (page_code) {
5351 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5352 	case PAGE_CODE_SELF_TEST_RESULTS:
5353 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5354 	case PAGE_CODE_SMART_READ_DATA:
5355 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5356 		break;
5357 	default:
5358 		*scsipkt->pkt_scbp = STATUS_CHECK;
5359 		sense = sata_arq_sense(spx);
5360 		sense->es_key = KEY_ILLEGAL_REQUEST;
5361 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5362 		goto done;
5363 	}
5364 
5365 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5366 		/*
5367 		 * Because log sense uses local buffers for data retrieval from
5368 		 * the devices and sets the data programatically in the
5369 		 * original specified buffer, release preallocated DMA
5370 		 * resources before storing data in the original buffer,
5371 		 * so no unwanted DMA sync would take place.
5372 		 */
5373 		sata_id_t *sata_id;
5374 
5375 		sata_scsi_dmafree(NULL, scsipkt);
5376 
5377 		len = 0;
5378 
5379 		/* Build log parameter header */
5380 		buf[len++] = page_code;	/* page code as in the CDB */
5381 		buf[len++] = 0;		/* reserved */
5382 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5383 		buf[len++] = 0;		/* (LSB) */
5384 
5385 		sdinfo = sata_get_device_info(
5386 		    spx->txlt_sata_hba_inst,
5387 		    &spx->txlt_sata_pkt->satapkt_device);
5388 
5389 		/*
5390 		 * Add requested pages.
5391 		 */
5392 		switch (page_code) {
5393 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5394 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5395 			break;
5396 		case PAGE_CODE_SELF_TEST_RESULTS:
5397 			sata_id = &sdinfo->satadrv_id;
5398 			if ((! (sata_id->ai_cmdset84 &
5399 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5400 			    (! (sata_id->ai_features87 &
5401 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5402 				*scsipkt->pkt_scbp = STATUS_CHECK;
5403 				sense = sata_arq_sense(spx);
5404 				sense->es_key = KEY_ILLEGAL_REQUEST;
5405 				sense->es_add_code =
5406 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5407 
5408 				goto done;
5409 			}
5410 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5411 			    spx->txlt_sata_hba_inst);
5412 			break;
5413 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5414 			sata_id = &sdinfo->satadrv_id;
5415 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5416 				*scsipkt->pkt_scbp = STATUS_CHECK;
5417 				sense = sata_arq_sense(spx);
5418 				sense->es_key = KEY_ILLEGAL_REQUEST;
5419 				sense->es_add_code =
5420 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5421 
5422 				goto done;
5423 			}
5424 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5425 				*scsipkt->pkt_scbp = STATUS_CHECK;
5426 				sense = sata_arq_sense(spx);
5427 				sense->es_key = KEY_ABORTED_COMMAND;
5428 				sense->es_add_code =
5429 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5430 				sense->es_qual_code =
5431 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5432 
5433 				goto done;
5434 			}
5435 
5436 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5437 			    spx->txlt_sata_hba_inst);
5438 			break;
5439 		case PAGE_CODE_SMART_READ_DATA:
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 
5462 			/* This page doesn't include a page header */
5463 			len = sata_build_lsense_page_30(sdinfo, buf,
5464 			    spx->txlt_sata_hba_inst);
5465 			goto no_header;
5466 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5467 			sata_id = &sdinfo->satadrv_id;
5468 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5469 				*scsipkt->pkt_scbp = STATUS_CHECK;
5470 				sense = sata_arq_sense(spx);
5471 				sense->es_key = KEY_ILLEGAL_REQUEST;
5472 				sense->es_add_code =
5473 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5474 
5475 				goto done;
5476 			}
5477 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5478 				*scsipkt->pkt_scbp = STATUS_CHECK;
5479 				sense = sata_arq_sense(spx);
5480 				sense->es_key = KEY_ABORTED_COMMAND;
5481 				sense->es_add_code =
5482 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5483 				sense->es_qual_code =
5484 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5485 
5486 				goto done;
5487 			}
5488 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
5489 			goto no_header;
5490 		default:
5491 			/* Invalid request */
5492 			*scsipkt->pkt_scbp = STATUS_CHECK;
5493 			sense = sata_arq_sense(spx);
5494 			sense->es_key = KEY_ILLEGAL_REQUEST;
5495 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5496 			goto done;
5497 		}
5498 
5499 		/* set parameter log sense data length */
5500 		buf[2] = len >> 8;	/* log sense length (MSB) */
5501 		buf[3] = len & 0xff;	/* log sense length (LSB) */
5502 
5503 		len += SCSI_LOG_PAGE_HDR_LEN;
5504 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
5505 
5506 no_header:
5507 		/* Check allocation length */
5508 		alc_len = scsipkt->pkt_cdbp[7];
5509 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5510 
5511 		/*
5512 		 * We do not check for possible parameters truncation
5513 		 * (alc_len < len) assuming that the target driver works
5514 		 * correctly. Just avoiding overrun.
5515 		 * Copy no more than requested and possible, buffer-wise.
5516 		 */
5517 		count = MIN(alc_len, len);
5518 		count = MIN(bp->b_bcount, count);
5519 		bcopy(buf, bp->b_un.b_addr, count);
5520 
5521 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5522 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5523 	}
5524 	*scsipkt->pkt_scbp = STATUS_GOOD;
5525 done:
5526 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5527 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5528 
5529 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5530 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5531 
5532 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5533 	    scsipkt->pkt_comp != NULL) {
5534 		/* scsi callback required */
5535 		if (servicing_interrupt()) {
5536 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5537 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5538 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5539 				return (TRAN_BUSY);
5540 			}
5541 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5542 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5543 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5544 			/* Scheduling the callback failed */
5545 			return (TRAN_BUSY);
5546 		}
5547 	}
5548 
5549 	return (TRAN_ACCEPT);
5550 }
5551 
5552 /*
5553  * Translate command: Log Select
5554  * Not implemented at this time - returns invalid command response.
5555  */
5556 static	int
5557 sata_txlt_log_select(sata_pkt_txlate_t *spx)
5558 {
5559 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5560 	    "sata_txlt_log_select\n", NULL);
5561 
5562 	return (sata_txlt_invalid_command(spx));
5563 }
5564 
5565 
5566 /*
5567  * Translate command: Read (various types).
5568  * Translated into appropriate type of ATA READ command
5569  * for SATA hard disks.
5570  * Both the device capabilities and requested operation mode are
5571  * considered.
5572  *
5573  * Following scsi cdb fields are ignored:
5574  * rdprotect, dpo, fua, fua_nv, group_number.
5575  *
5576  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5577  * enable variable sata_func_enable), the capability of the controller and
5578  * capability of a device are checked and if both support queueing, read
5579  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
5580  * command rather than plain READ_XXX command.
5581  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5582  * both the controller and device suport such functionality, the read
5583  * request will be translated to READ_FPDMA_QUEUED command.
5584  * In both cases the maximum queue depth is derived as minimum of:
5585  * HBA capability,device capability and sata_max_queue_depth variable setting.
5586  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5587  * used to pass max queue depth value, and the maximum possible queue depth
5588  * is 32.
5589  *
5590  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5591  * appropriate values in scsi_pkt fields.
5592  */
5593 static int
5594 sata_txlt_read(sata_pkt_txlate_t *spx)
5595 {
5596 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5597 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5598 	sata_drive_info_t *sdinfo;
5599 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5600 	int cport = SATA_TXLT_CPORT(spx);
5601 	uint16_t sec_count;
5602 	uint64_t lba;
5603 	int rval, reason;
5604 	int synch;
5605 
5606 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5607 
5608 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5609 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5610 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5611 		return (rval);
5612 	}
5613 
5614 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5615 	    &spx->txlt_sata_pkt->satapkt_device);
5616 
5617 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5618 	/*
5619 	 * Extract LBA and sector count from scsi CDB.
5620 	 */
5621 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5622 	case SCMD_READ:
5623 		/* 6-byte scsi read cmd : 0x08 */
5624 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5625 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5626 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5627 		sec_count = scsipkt->pkt_cdbp[4];
5628 		/* sec_count 0 will be interpreted as 256 by a device */
5629 		break;
5630 	case SCMD_READ_G1:
5631 		/* 10-bytes scsi read command : 0x28 */
5632 		lba = scsipkt->pkt_cdbp[2];
5633 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5634 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5635 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5636 		sec_count = scsipkt->pkt_cdbp[7];
5637 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5638 		break;
5639 	case SCMD_READ_G5:
5640 		/* 12-bytes scsi read command : 0xA8 */
5641 		lba = scsipkt->pkt_cdbp[2];
5642 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5643 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5644 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5645 		sec_count = scsipkt->pkt_cdbp[6];
5646 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5647 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5648 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5649 		break;
5650 	case SCMD_READ_G4:
5651 		/* 16-bytes scsi read command : 0x88 */
5652 		lba = scsipkt->pkt_cdbp[2];
5653 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5654 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5655 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5656 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5657 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5658 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5659 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5660 		sec_count = scsipkt->pkt_cdbp[10];
5661 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5662 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5663 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5664 		break;
5665 	default:
5666 		/* Unsupported command */
5667 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5668 		return (sata_txlt_invalid_command(spx));
5669 	}
5670 
5671 	/*
5672 	 * Check if specified address exceeds device capacity
5673 	 */
5674 	if ((lba >= sdinfo->satadrv_capacity) ||
5675 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5676 		/* LBA out of range */
5677 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5678 		return (sata_txlt_lba_out_of_range(spx));
5679 	}
5680 
5681 	/*
5682 	 * For zero-length transfer, emulate good completion of the command
5683 	 * (reasons for rejecting the command were already checked).
5684 	 * No DMA resources were allocated.
5685 	 */
5686 	if (spx->txlt_dma_cookie_list == NULL) {
5687 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5688 		return (sata_emul_rw_completion(spx));
5689 	}
5690 
5691 	/*
5692 	 * Build cmd block depending on the device capability and
5693 	 * requested operation mode.
5694 	 * Do not bother with non-dma mode - we are working only with
5695 	 * devices supporting DMA.
5696 	 */
5697 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5698 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5699 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
5700 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5701 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5702 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
5703 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5704 #ifndef __lock_lint
5705 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5706 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5707 		scmd->satacmd_lba_high_msb = lba >> 40;
5708 #endif
5709 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5710 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5711 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5712 	}
5713 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5714 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5715 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5716 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5717 	scmd->satacmd_features_reg = 0;
5718 	scmd->satacmd_status_reg = 0;
5719 	scmd->satacmd_error_reg = 0;
5720 
5721 	/*
5722 	 * Check if queueing commands should be used and switch
5723 	 * to appropriate command if possible
5724 	 */
5725 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5726 		boolean_t using_queuing;
5727 
5728 		/* Queuing supported by controller and device? */
5729 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5730 		    (sdinfo->satadrv_features_support &
5731 		    SATA_DEV_F_NCQ) &&
5732 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5733 		    SATA_CTLF_NCQ)) {
5734 			using_queuing = B_TRUE;
5735 
5736 			/* NCQ supported - use FPDMA READ */
5737 			scmd->satacmd_cmd_reg =
5738 			    SATAC_READ_FPDMA_QUEUED;
5739 			scmd->satacmd_features_reg_ext =
5740 			    scmd->satacmd_sec_count_msb;
5741 			scmd->satacmd_sec_count_msb = 0;
5742 		} else if ((sdinfo->satadrv_features_support &
5743 		    SATA_DEV_F_TCQ) &&
5744 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5745 		    SATA_CTLF_QCMD)) {
5746 			using_queuing = B_TRUE;
5747 
5748 			/* Legacy queueing */
5749 			if (sdinfo->satadrv_features_support &
5750 			    SATA_DEV_F_LBA48) {
5751 				scmd->satacmd_cmd_reg =
5752 				    SATAC_READ_DMA_QUEUED_EXT;
5753 				scmd->satacmd_features_reg_ext =
5754 				    scmd->satacmd_sec_count_msb;
5755 				scmd->satacmd_sec_count_msb = 0;
5756 			} else {
5757 				scmd->satacmd_cmd_reg =
5758 				    SATAC_READ_DMA_QUEUED;
5759 			}
5760 		} else	/* NCQ nor legacy queuing not supported */
5761 			using_queuing = B_FALSE;
5762 
5763 		/*
5764 		 * If queuing, the sector count goes in the features register
5765 		 * and the secount count will contain the tag.
5766 		 */
5767 		if (using_queuing) {
5768 			scmd->satacmd_features_reg =
5769 			    scmd->satacmd_sec_count_lsb;
5770 			scmd->satacmd_sec_count_lsb = 0;
5771 			scmd->satacmd_flags.sata_queued = B_TRUE;
5772 
5773 			/* Set-up maximum queue depth */
5774 			scmd->satacmd_flags.sata_max_queue_depth =
5775 			    sdinfo->satadrv_max_queue_depth - 1;
5776 		} else if (sdinfo->satadrv_features_enabled &
5777 		    SATA_DEV_F_E_UNTAGGED_QING) {
5778 			/*
5779 			 * Although NCQ/TCQ is not enabled, untagged queuing
5780 			 * may be still used.
5781 			 * Set-up the maximum untagged queue depth.
5782 			 * Use controller's queue depth from sata_hba_tran.
5783 			 * SATA HBA drivers may ignore this value and rely on
5784 			 * the internal limits.For drivers that do not
5785 			 * ignore untaged queue depth, limit the value to
5786 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5787 			 * largest value that can be passed via
5788 			 * satacmd_flags.sata_max_queue_depth.
5789 			 */
5790 			scmd->satacmd_flags.sata_max_queue_depth =
5791 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5792 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5793 
5794 		} else {
5795 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5796 		}
5797 	} else
5798 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5799 
5800 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
5801 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
5802 	    scmd->satacmd_cmd_reg, lba, sec_count);
5803 
5804 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5805 		/* Need callback function */
5806 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5807 		synch = FALSE;
5808 	} else
5809 		synch = TRUE;
5810 
5811 	/* Transfer command to HBA */
5812 	if (sata_hba_start(spx, &rval) != 0) {
5813 		/* Pkt not accepted for execution */
5814 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5815 		return (rval);
5816 	}
5817 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5818 	/*
5819 	 * If execution is non-synchronous,
5820 	 * a callback function will handle potential errors, translate
5821 	 * the response and will do a callback to a target driver.
5822 	 * If it was synchronous, check execution status using the same
5823 	 * framework callback.
5824 	 */
5825 	if (synch) {
5826 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5827 		    "synchronous execution status %x\n",
5828 		    spx->txlt_sata_pkt->satapkt_reason);
5829 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5830 	}
5831 	return (TRAN_ACCEPT);
5832 }
5833 
5834 
5835 /*
5836  * SATA translate command: Write (various types)
5837  * Translated into appropriate type of ATA WRITE command
5838  * for SATA hard disks.
5839  * Both the device capabilities and requested operation mode are
5840  * considered.
5841  *
5842  * Following scsi cdb fields are ignored:
5843  * rwprotect, dpo, fua, fua_nv, group_number.
5844  *
5845  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5846  * enable variable sata_func_enable), the capability of the controller and
5847  * capability of a device are checked and if both support queueing, write
5848  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
5849  * command rather than plain WRITE_XXX command.
5850  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5851  * both the controller and device suport such functionality, the write
5852  * request will be translated to WRITE_FPDMA_QUEUED command.
5853  * In both cases the maximum queue depth is derived as minimum of:
5854  * HBA capability,device capability and sata_max_queue_depth variable setting.
5855  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5856  * used to pass max queue depth value, and the maximum possible queue depth
5857  * is 32.
5858  *
5859  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5860  * appropriate values in scsi_pkt fields.
5861  */
5862 static int
5863 sata_txlt_write(sata_pkt_txlate_t *spx)
5864 {
5865 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5866 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5867 	sata_drive_info_t *sdinfo;
5868 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5869 	int cport = SATA_TXLT_CPORT(spx);
5870 	uint16_t sec_count;
5871 	uint64_t lba;
5872 	int rval, reason;
5873 	int synch;
5874 
5875 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5876 
5877 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5878 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5879 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5880 		return (rval);
5881 	}
5882 
5883 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5884 	    &spx->txlt_sata_pkt->satapkt_device);
5885 
5886 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5887 	/*
5888 	 * Extract LBA and sector count from scsi CDB
5889 	 */
5890 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5891 	case SCMD_WRITE:
5892 		/* 6-byte scsi read cmd : 0x0A */
5893 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5894 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5895 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5896 		sec_count = scsipkt->pkt_cdbp[4];
5897 		/* sec_count 0 will be interpreted as 256 by a device */
5898 		break;
5899 	case SCMD_WRITE_G1:
5900 		/* 10-bytes scsi write command : 0x2A */
5901 		lba = scsipkt->pkt_cdbp[2];
5902 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5903 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5904 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5905 		sec_count = scsipkt->pkt_cdbp[7];
5906 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5907 		break;
5908 	case SCMD_WRITE_G5:
5909 		/* 12-bytes scsi read command : 0xAA */
5910 		lba = scsipkt->pkt_cdbp[2];
5911 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5912 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5913 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5914 		sec_count = scsipkt->pkt_cdbp[6];
5915 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5916 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5917 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5918 		break;
5919 	case SCMD_WRITE_G4:
5920 		/* 16-bytes scsi write command : 0x8A */
5921 		lba = scsipkt->pkt_cdbp[2];
5922 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5923 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5924 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5925 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5926 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5927 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5928 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5929 		sec_count = scsipkt->pkt_cdbp[10];
5930 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5931 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5932 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5933 		break;
5934 	default:
5935 		/* Unsupported command */
5936 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5937 		return (sata_txlt_invalid_command(spx));
5938 	}
5939 
5940 	/*
5941 	 * Check if specified address and length exceeds device capacity
5942 	 */
5943 	if ((lba >= sdinfo->satadrv_capacity) ||
5944 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5945 		/* LBA out of range */
5946 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5947 		return (sata_txlt_lba_out_of_range(spx));
5948 	}
5949 
5950 	/*
5951 	 * For zero-length transfer, emulate good completion of the command
5952 	 * (reasons for rejecting the command were already checked).
5953 	 * No DMA resources were allocated.
5954 	 */
5955 	if (spx->txlt_dma_cookie_list == NULL) {
5956 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5957 		return (sata_emul_rw_completion(spx));
5958 	}
5959 
5960 	/*
5961 	 * Build cmd block depending on the device capability and
5962 	 * requested operation mode.
5963 	 * Do not bother with non-dma mode- we are working only with
5964 	 * devices supporting DMA.
5965 	 */
5966 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5967 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5968 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
5969 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5970 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5971 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
5972 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5973 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5974 #ifndef __lock_lint
5975 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5976 		scmd->satacmd_lba_high_msb = lba >> 40;
5977 #endif
5978 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5979 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5980 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5981 	}
5982 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5983 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5984 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5985 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5986 	scmd->satacmd_features_reg = 0;
5987 	scmd->satacmd_status_reg = 0;
5988 	scmd->satacmd_error_reg = 0;
5989 
5990 	/*
5991 	 * Check if queueing commands should be used and switch
5992 	 * to appropriate command if possible
5993 	 */
5994 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5995 		boolean_t using_queuing;
5996 
5997 		/* Queuing supported by controller and device? */
5998 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5999 		    (sdinfo->satadrv_features_support &
6000 		    SATA_DEV_F_NCQ) &&
6001 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6002 		    SATA_CTLF_NCQ)) {
6003 			using_queuing = B_TRUE;
6004 
6005 			/* NCQ supported - use FPDMA WRITE */
6006 			scmd->satacmd_cmd_reg =
6007 			    SATAC_WRITE_FPDMA_QUEUED;
6008 			scmd->satacmd_features_reg_ext =
6009 			    scmd->satacmd_sec_count_msb;
6010 			scmd->satacmd_sec_count_msb = 0;
6011 		} else if ((sdinfo->satadrv_features_support &
6012 		    SATA_DEV_F_TCQ) &&
6013 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6014 		    SATA_CTLF_QCMD)) {
6015 			using_queuing = B_TRUE;
6016 
6017 			/* Legacy queueing */
6018 			if (sdinfo->satadrv_features_support &
6019 			    SATA_DEV_F_LBA48) {
6020 				scmd->satacmd_cmd_reg =
6021 				    SATAC_WRITE_DMA_QUEUED_EXT;
6022 				scmd->satacmd_features_reg_ext =
6023 				    scmd->satacmd_sec_count_msb;
6024 				scmd->satacmd_sec_count_msb = 0;
6025 			} else {
6026 				scmd->satacmd_cmd_reg =
6027 				    SATAC_WRITE_DMA_QUEUED;
6028 			}
6029 		} else	/*  NCQ nor legacy queuing not supported */
6030 			using_queuing = B_FALSE;
6031 
6032 		if (using_queuing) {
6033 			scmd->satacmd_features_reg =
6034 			    scmd->satacmd_sec_count_lsb;
6035 			scmd->satacmd_sec_count_lsb = 0;
6036 			scmd->satacmd_flags.sata_queued = B_TRUE;
6037 			/* Set-up maximum queue depth */
6038 			scmd->satacmd_flags.sata_max_queue_depth =
6039 			    sdinfo->satadrv_max_queue_depth - 1;
6040 		} else if (sdinfo->satadrv_features_enabled &
6041 		    SATA_DEV_F_E_UNTAGGED_QING) {
6042 			/*
6043 			 * Although NCQ/TCQ is not enabled, untagged queuing
6044 			 * may be still used.
6045 			 * Set-up the maximum untagged queue depth.
6046 			 * Use controller's queue depth from sata_hba_tran.
6047 			 * SATA HBA drivers may ignore this value and rely on
6048 			 * the internal limits. For drivera that do not
6049 			 * ignore untaged queue depth, limit the value to
6050 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
6051 			 * largest value that can be passed via
6052 			 * satacmd_flags.sata_max_queue_depth.
6053 			 */
6054 			scmd->satacmd_flags.sata_max_queue_depth =
6055 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
6056 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
6057 
6058 		} else {
6059 			scmd->satacmd_flags.sata_max_queue_depth = 0;
6060 		}
6061 	} else
6062 		scmd->satacmd_flags.sata_max_queue_depth = 0;
6063 
6064 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6065 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
6066 	    scmd->satacmd_cmd_reg, lba, sec_count);
6067 
6068 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6069 		/* Need callback function */
6070 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
6071 		synch = FALSE;
6072 	} else
6073 		synch = TRUE;
6074 
6075 	/* Transfer command to HBA */
6076 	if (sata_hba_start(spx, &rval) != 0) {
6077 		/* Pkt not accepted for execution */
6078 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6079 		return (rval);
6080 	}
6081 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6082 
6083 	/*
6084 	 * If execution is non-synchronous,
6085 	 * a callback function will handle potential errors, translate
6086 	 * the response and will do a callback to a target driver.
6087 	 * If it was synchronous, check execution status using the same
6088 	 * framework callback.
6089 	 */
6090 	if (synch) {
6091 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6092 		    "synchronous execution status %x\n",
6093 		    spx->txlt_sata_pkt->satapkt_reason);
6094 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6095 	}
6096 	return (TRAN_ACCEPT);
6097 }
6098 
6099 
6100 /*
6101  * Implements SCSI SBC WRITE BUFFER command download microcode option
6102  */
6103 static int
6104 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
6105 {
6106 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
6107 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
6108 
6109 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
6110 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6111 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
6112 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6113 
6114 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6115 	struct scsi_extended_sense *sense;
6116 	int rval, mode, sector_count, reason;
6117 	int cport = SATA_TXLT_CPORT(spx);
6118 
6119 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
6120 
6121 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6122 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
6123 
6124 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6125 
6126 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6127 	    TRAN_ACCEPT) {
6128 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6129 		return (rval);
6130 	}
6131 
6132 	/* Use synchronous mode */
6133 	spx->txlt_sata_pkt->satapkt_op_mode
6134 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
6135 
6136 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6137 
6138 	scsipkt->pkt_reason = CMD_CMPLT;
6139 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6140 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6141 
6142 	/*
6143 	 * The SCSI to ATA translation specification only calls
6144 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6145 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6146 	 * ATA 8 (draft) got rid of download microcode for temp
6147 	 * and it is even optional for ATA 7, so it may be aborted.
6148 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6149 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6150 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6151 	 * sectors.  Thus the offset really doesn't buy us anything.
6152 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6153 	 * is revised, this can be revisisted.
6154 	 */
6155 	/* Reject not supported request */
6156 	switch (mode) {
6157 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6158 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6159 		break;
6160 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6161 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6162 		break;
6163 	default:
6164 		goto bad_param;
6165 	}
6166 
6167 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6168 
6169 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6170 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6171 		goto bad_param;
6172 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6173 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6174 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6175 	scmd->satacmd_lba_mid_lsb = 0;
6176 	scmd->satacmd_lba_high_lsb = 0;
6177 	scmd->satacmd_device_reg = 0;
6178 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6179 	scmd->satacmd_addr_type = 0;
6180 
6181 	/* Transfer command to HBA */
6182 	if (sata_hba_start(spx, &rval) != 0) {
6183 		/* Pkt not accepted for execution */
6184 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6185 		return (rval);
6186 	}
6187 
6188 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6189 
6190 	/* Then we need synchronous check the status of the disk */
6191 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6192 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6193 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6194 		scsipkt->pkt_reason = CMD_CMPLT;
6195 
6196 		/* Download commmand succeed, so probe and identify device */
6197 		sata_reidentify_device(spx);
6198 	} else {
6199 		/* Something went wrong, microcode download command failed */
6200 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6201 		*scsipkt->pkt_scbp = STATUS_CHECK;
6202 		sense = sata_arq_sense(spx);
6203 		switch (sata_pkt->satapkt_reason) {
6204 		case SATA_PKT_PORT_ERROR:
6205 			/*
6206 			 * We have no device data. Assume no data transfered.
6207 			 */
6208 			sense->es_key = KEY_HARDWARE_ERROR;
6209 			break;
6210 
6211 		case SATA_PKT_DEV_ERROR:
6212 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6213 			    SATA_STATUS_ERR) {
6214 				/*
6215 				 * determine dev error reason from error
6216 				 * reg content
6217 				 */
6218 				sata_decode_device_error(spx, sense);
6219 				break;
6220 			}
6221 			/* No extended sense key - no info available */
6222 			break;
6223 
6224 		case SATA_PKT_TIMEOUT:
6225 			scsipkt->pkt_reason = CMD_TIMEOUT;
6226 			scsipkt->pkt_statistics |=
6227 			    STAT_TIMEOUT | STAT_DEV_RESET;
6228 			/* No extended sense key ? */
6229 			break;
6230 
6231 		case SATA_PKT_ABORTED:
6232 			scsipkt->pkt_reason = CMD_ABORTED;
6233 			scsipkt->pkt_statistics |= STAT_ABORTED;
6234 			/* No extended sense key ? */
6235 			break;
6236 
6237 		case SATA_PKT_RESET:
6238 			/* pkt aborted by an explicit reset from a host */
6239 			scsipkt->pkt_reason = CMD_RESET;
6240 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6241 			break;
6242 
6243 		default:
6244 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6245 			    "sata_txlt_nodata_cmd_completion: "
6246 			    "invalid packet completion reason %d",
6247 			    sata_pkt->satapkt_reason));
6248 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6249 			break;
6250 		}
6251 
6252 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6253 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6254 
6255 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6256 			/* scsi callback required */
6257 			scsi_hba_pkt_comp(scsipkt);
6258 	}
6259 	return (TRAN_ACCEPT);
6260 
6261 bad_param:
6262 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6263 	*scsipkt->pkt_scbp = STATUS_CHECK;
6264 	sense = sata_arq_sense(spx);
6265 	sense->es_key = KEY_ILLEGAL_REQUEST;
6266 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6267 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6268 	    scsipkt->pkt_comp != NULL) {
6269 		/* scsi callback required */
6270 		if (servicing_interrupt()) {
6271 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6272 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6273 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6274 				return (TRAN_BUSY);
6275 			}
6276 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6277 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6278 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6279 			/* Scheduling the callback failed */
6280 			return (TRAN_BUSY);
6281 		}
6282 	}
6283 	return (rval);
6284 }
6285 
6286 /*
6287  * Re-identify device after doing a firmware download.
6288  */
6289 static void
6290 sata_reidentify_device(sata_pkt_txlate_t *spx)
6291 {
6292 #define	DOWNLOAD_WAIT_TIME_SECS	60
6293 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6294 	int rval;
6295 	int retry_cnt;
6296 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6297 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6298 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6299 	sata_drive_info_t *sdinfo;
6300 
6301 	/*
6302 	 * Before returning good status, probe device.
6303 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6304 	 * The assumption is that the new microcode is applied by the
6305 	 * device. It is a caller responsibility to verify this.
6306 	 */
6307 	for (retry_cnt = 0;
6308 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6309 	    retry_cnt++) {
6310 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6311 
6312 		if (rval == SATA_SUCCESS) { /* Set default features */
6313 			sdinfo = sata_get_device_info(sata_hba_inst,
6314 			    &sata_device);
6315 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6316 			    SATA_SUCCESS) {
6317 				/* retry */
6318 				rval = sata_initialize_device(sata_hba_inst,
6319 				    sdinfo);
6320 				if (rval == SATA_RETRY)
6321 					sata_log(sata_hba_inst, CE_WARN,
6322 					    "SATA device at port %d pmport %d -"
6323 					    " default device features could not"
6324 					    " be set. Device may not operate "
6325 					    "as expected.",
6326 					    sata_device.satadev_addr.cport,
6327 					    sata_device.satadev_addr.pmport);
6328 			}
6329 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6330 				scsi_hba_pkt_comp(scsipkt);
6331 			return;
6332 		} else if (rval == SATA_RETRY) {
6333 			delay(drv_usectohz(1000000 *
6334 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6335 			continue;
6336 		} else	/* failed - no reason to retry */
6337 			break;
6338 	}
6339 
6340 	/*
6341 	 * Something went wrong, device probing failed.
6342 	 */
6343 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6344 	    "Cannot probe device after downloading microcode\n"));
6345 
6346 	/* Reset device to force retrying the probe. */
6347 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6348 	    (SATA_DIP(sata_hba_inst), &sata_device);
6349 
6350 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6351 		scsi_hba_pkt_comp(scsipkt);
6352 }
6353 
6354 
6355 /*
6356  * Translate command: Synchronize Cache.
6357  * Translates into Flush Cache command for SATA hard disks.
6358  *
6359  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6360  * appropriate values in scsi_pkt fields.
6361  */
6362 static 	int
6363 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6364 {
6365 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6366 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6367 	int cport = SATA_TXLT_CPORT(spx);
6368 	int rval, reason;
6369 	int synch;
6370 
6371 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6372 
6373 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6374 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6375 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6376 		return (rval);
6377 	}
6378 
6379 	scmd->satacmd_addr_type = 0;
6380 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6381 	scmd->satacmd_device_reg = 0;
6382 	scmd->satacmd_sec_count_lsb = 0;
6383 	scmd->satacmd_lba_low_lsb = 0;
6384 	scmd->satacmd_lba_mid_lsb = 0;
6385 	scmd->satacmd_lba_high_lsb = 0;
6386 	scmd->satacmd_features_reg = 0;
6387 	scmd->satacmd_status_reg = 0;
6388 	scmd->satacmd_error_reg = 0;
6389 
6390 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6391 	    "sata_txlt_synchronize_cache\n", NULL);
6392 
6393 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6394 		/* Need to set-up a callback function */
6395 		spx->txlt_sata_pkt->satapkt_comp =
6396 		    sata_txlt_nodata_cmd_completion;
6397 		synch = FALSE;
6398 	} else
6399 		synch = TRUE;
6400 
6401 	/* Transfer command to HBA */
6402 	if (sata_hba_start(spx, &rval) != 0) {
6403 		/* Pkt not accepted for execution */
6404 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6405 		return (rval);
6406 	}
6407 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6408 
6409 	/*
6410 	 * If execution non-synchronous, it had to be completed
6411 	 * a callback function will handle potential errors, translate
6412 	 * the response and will do a callback to a target driver.
6413 	 * If it was synchronous, check status, using the same
6414 	 * framework callback.
6415 	 */
6416 	if (synch) {
6417 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6418 		    "synchronous execution status %x\n",
6419 		    spx->txlt_sata_pkt->satapkt_reason);
6420 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6421 	}
6422 	return (TRAN_ACCEPT);
6423 }
6424 
6425 
6426 /*
6427  * Send pkt to SATA HBA driver
6428  *
6429  * This function may be called only if the operation is requested by scsi_pkt,
6430  * i.e. scsi_pkt is not NULL.
6431  *
6432  * This function has to be called with cport mutex held. It does release
6433  * the mutex when it calls HBA driver sata_tran_start function and
6434  * re-acquires it afterwards.
6435  *
6436  * If return value is 0, pkt was accepted, -1 otherwise
6437  * rval is set to appropriate sata_scsi_start return value.
6438  *
6439  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6440  * have called the sata_pkt callback function for this packet.
6441  *
6442  * The scsi callback has to be performed by the caller of this routine.
6443  */
6444 static int
6445 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6446 {
6447 	int stat;
6448 	uint8_t cport = SATA_TXLT_CPORT(spx);
6449 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6450 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6451 	sata_drive_info_t *sdinfo;
6452 	sata_pmult_info_t *pminfo;
6453 	sata_pmport_info_t *pmportinfo = NULL;
6454 	sata_device_t *sata_device = NULL;
6455 	uint8_t cmd;
6456 	struct sata_cmd_flags cmd_flags;
6457 
6458 	ASSERT(spx->txlt_sata_pkt != NULL);
6459 
6460 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6461 
6462 	sdinfo = sata_get_device_info(sata_hba_inst,
6463 	    &spx->txlt_sata_pkt->satapkt_device);
6464 	ASSERT(sdinfo != NULL);
6465 
6466 	/* Clear device reset state? */
6467 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6468 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6469 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6470 
6471 		/*
6472 		 * Get the pmult_info of the its parent port multiplier, all
6473 		 * sub-devices share a common device reset flags on in
6474 		 * pmult_info.
6475 		 */
6476 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
6477 		pmportinfo = pminfo->pmult_dev_port[pmport];
6478 		ASSERT(pminfo != NULL);
6479 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
6480 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6481 			    sata_clear_dev_reset = B_TRUE;
6482 			pminfo->pmult_event_flags &=
6483 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6484 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6485 			    "sata_hba_start: clearing device reset state"
6486 			    "on pmult.\n", NULL);
6487 		}
6488 	} else {
6489 		if (sdinfo->satadrv_event_flags &
6490 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
6491 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6492 			    sata_clear_dev_reset = B_TRUE;
6493 			sdinfo->satadrv_event_flags &=
6494 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6495 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6496 			    "sata_hba_start: clearing device reset state\n",
6497 			    NULL);
6498 		}
6499 	}
6500 
6501 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
6502 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
6503 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
6504 
6505 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6506 
6507 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6508 	    "Sata cmd 0x%2x\n", cmd);
6509 
6510 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
6511 	    spx->txlt_sata_pkt);
6512 
6513 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6514 	/*
6515 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
6516 	 * with the sata callback, the sata_pkt could be already destroyed
6517 	 * by the time we check ther return status from the hba_start()
6518 	 * function, because sata_scsi_destroy_pkt() could have been already
6519 	 * called (perhaps in the interrupt context). So, in such case, there
6520 	 * should be no references to it. In other cases, sata_pkt still
6521 	 * exists.
6522 	 */
6523 	if (stat == SATA_TRAN_ACCEPTED) {
6524 		/*
6525 		 * pkt accepted for execution.
6526 		 * If it was executed synchronously, it is already completed
6527 		 * and pkt completion_reason indicates completion status.
6528 		 */
6529 		*rval = TRAN_ACCEPT;
6530 		return (0);
6531 	}
6532 
6533 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6534 	switch (stat) {
6535 	case SATA_TRAN_QUEUE_FULL:
6536 		/*
6537 		 * Controller detected queue full condition.
6538 		 */
6539 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
6540 		    "sata_hba_start: queue full\n", NULL);
6541 
6542 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6543 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
6544 
6545 		*rval = TRAN_BUSY;
6546 		break;
6547 
6548 	case SATA_TRAN_PORT_ERROR:
6549 		/*
6550 		 * Communication/link with device or general port error
6551 		 * detected before pkt execution begun.
6552 		 */
6553 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6554 		    SATA_ADDR_CPORT ||
6555 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6556 		    SATA_ADDR_DCPORT)
6557 			sata_log(sata_hba_inst, CE_CONT,
6558 			    "SATA port %d error",
6559 			    sata_device->satadev_addr.cport);
6560 		else
6561 			sata_log(sata_hba_inst, CE_CONT,
6562 			    "SATA port %d:%d error\n",
6563 			    sata_device->satadev_addr.cport,
6564 			    sata_device->satadev_addr.pmport);
6565 
6566 		/*
6567 		 * Update the port/device structure.
6568 		 * sata_pkt should be still valid. Since port error is
6569 		 * returned, sata_device content should reflect port
6570 		 * state - it means, that sata address have been changed,
6571 		 * because original packet's sata address refered to a device
6572 		 * attached to some port.
6573 		 */
6574 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
6575 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
6576 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6577 			mutex_enter(&pmportinfo->pmport_mutex);
6578 			sata_update_pmport_info(sata_hba_inst, sata_device);
6579 			mutex_exit(&pmportinfo->pmport_mutex);
6580 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6581 		} else {
6582 			sata_update_port_info(sata_hba_inst, sata_device);
6583 		}
6584 
6585 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6586 		*rval = TRAN_FATAL_ERROR;
6587 		break;
6588 
6589 	case SATA_TRAN_CMD_UNSUPPORTED:
6590 		/*
6591 		 * Command rejected by HBA as unsupported. It was HBA driver
6592 		 * that rejected the command, command was not sent to
6593 		 * an attached device.
6594 		 */
6595 		if ((sdinfo != NULL) &&
6596 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
6597 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6598 			    "sat_hba_start: cmd 0x%2x rejected "
6599 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
6600 
6601 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6602 		(void) sata_txlt_invalid_command(spx);
6603 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6604 
6605 		*rval = TRAN_ACCEPT;
6606 		break;
6607 
6608 	case SATA_TRAN_BUSY:
6609 		/*
6610 		 * Command rejected by HBA because other operation prevents
6611 		 * accepting the packet, or device is in RESET condition.
6612 		 */
6613 		if (sdinfo != NULL) {
6614 			sdinfo->satadrv_state =
6615 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
6616 
6617 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
6618 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6619 				    "sata_hba_start: cmd 0x%2x rejected "
6620 				    "because of device reset condition\n",
6621 				    cmd);
6622 			} else {
6623 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6624 				    "sata_hba_start: cmd 0x%2x rejected "
6625 				    "with SATA_TRAN_BUSY status\n",
6626 				    cmd);
6627 			}
6628 		}
6629 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6630 		*rval = TRAN_BUSY;
6631 		break;
6632 
6633 	default:
6634 		/* Unrecognized HBA response */
6635 		SATA_LOG_D((sata_hba_inst, CE_WARN,
6636 		    "sata_hba_start: unrecognized HBA response "
6637 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
6638 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6639 		*rval = TRAN_FATAL_ERROR;
6640 		break;
6641 	}
6642 
6643 	/*
6644 	 * If we got here, the packet was rejected.
6645 	 * Check if we need to remember reset state clearing request
6646 	 */
6647 	if (cmd_flags.sata_clear_dev_reset) {
6648 		/*
6649 		 * Check if device is still configured - it may have
6650 		 * disapeared from the configuration
6651 		 */
6652 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6653 		if (sdinfo != NULL) {
6654 			/*
6655 			 * Restore the flag that requests clearing of
6656 			 * the device reset state,
6657 			 * so the next sata packet may carry it to HBA.
6658 			 */
6659 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
6660 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
6661 				pminfo->pmult_event_flags |=
6662 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6663 			} else {
6664 				sdinfo->satadrv_event_flags |=
6665 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6666 			}
6667 		}
6668 	}
6669 	return (-1);
6670 }
6671 
6672 /*
6673  * Scsi response setup for invalid LBA
6674  *
6675  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
6676  */
6677 static int
6678 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
6679 {
6680 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6681 	struct scsi_extended_sense *sense;
6682 
6683 	scsipkt->pkt_reason = CMD_CMPLT;
6684 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6685 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6686 	*scsipkt->pkt_scbp = STATUS_CHECK;
6687 
6688 	*scsipkt->pkt_scbp = STATUS_CHECK;
6689 	sense = sata_arq_sense(spx);
6690 	sense->es_key = KEY_ILLEGAL_REQUEST;
6691 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6692 
6693 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6694 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6695 
6696 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6697 	    scsipkt->pkt_comp != NULL) {
6698 		/* scsi callback required */
6699 		if (servicing_interrupt()) {
6700 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6701 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6702 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6703 				return (TRAN_BUSY);
6704 			}
6705 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6706 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6707 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6708 			/* Scheduling the callback failed */
6709 			return (TRAN_BUSY);
6710 		}
6711 	}
6712 	return (TRAN_ACCEPT);
6713 }
6714 
6715 
6716 /*
6717  * Analyze device status and error registers and translate them into
6718  * appropriate scsi sense codes.
6719  * NOTE: non-packet commands only for now
6720  */
6721 static void
6722 sata_decode_device_error(sata_pkt_txlate_t *spx,
6723     struct scsi_extended_sense *sense)
6724 {
6725 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
6726 
6727 	ASSERT(sense != NULL);
6728 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
6729 	    SATA_STATUS_ERR);
6730 
6731 
6732 	if (err_reg & SATA_ERROR_ICRC) {
6733 		sense->es_key = KEY_ABORTED_COMMAND;
6734 		sense->es_add_code = 0x08; /* Communication failure */
6735 		return;
6736 	}
6737 
6738 	if (err_reg & SATA_ERROR_UNC) {
6739 		sense->es_key = KEY_MEDIUM_ERROR;
6740 		/* Information bytes (LBA) need to be set by a caller */
6741 		return;
6742 	}
6743 
6744 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
6745 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
6746 		sense->es_key = KEY_UNIT_ATTENTION;
6747 		sense->es_add_code = 0x3a; /* No media present */
6748 		return;
6749 	}
6750 
6751 	if (err_reg & SATA_ERROR_IDNF) {
6752 		if (err_reg & SATA_ERROR_ABORT) {
6753 			sense->es_key = KEY_ABORTED_COMMAND;
6754 		} else {
6755 			sense->es_key = KEY_ILLEGAL_REQUEST;
6756 			sense->es_add_code = 0x21; /* LBA out of range */
6757 		}
6758 		return;
6759 	}
6760 
6761 	if (err_reg & SATA_ERROR_ABORT) {
6762 		ASSERT(spx->txlt_sata_pkt != NULL);
6763 		sense->es_key = KEY_ABORTED_COMMAND;
6764 		return;
6765 	}
6766 }
6767 
6768 /*
6769  * Extract error LBA from sata_pkt.satapkt_cmd register fields
6770  */
6771 static void
6772 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
6773 {
6774 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
6775 
6776 	*lba = 0;
6777 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
6778 		*lba = sata_cmd->satacmd_lba_high_msb;
6779 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
6780 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
6781 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
6782 		*lba = sata_cmd->satacmd_device_reg & 0xf;
6783 	}
6784 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
6785 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
6786 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
6787 }
6788 
6789 /*
6790  * This is fixed sense format - if LBA exceeds the info field size,
6791  * no valid info will be returned (valid bit in extended sense will
6792  * be set to 0).
6793  */
6794 static struct scsi_extended_sense *
6795 sata_arq_sense(sata_pkt_txlate_t *spx)
6796 {
6797 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6798 	struct scsi_arq_status *arqs;
6799 	struct scsi_extended_sense *sense;
6800 
6801 	/* Fill ARQ sense data */
6802 	scsipkt->pkt_state |= STATE_ARQ_DONE;
6803 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
6804 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
6805 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
6806 	arqs->sts_rqpkt_reason = CMD_CMPLT;
6807 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6808 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
6809 	arqs->sts_rqpkt_resid = 0;
6810 	sense = &arqs->sts_sensedata;
6811 	bzero(sense, sizeof (struct scsi_extended_sense));
6812 	sata_fixed_sense_data_preset(sense);
6813 	return (sense);
6814 }
6815 
6816 /*
6817  * ATA Pass Through support
6818  * Sets flags indicating that an invalid value was found in some
6819  * field in the command.  It could be something illegal according to
6820  * the SAT-2 spec or it could be a feature that is not (yet?)
6821  * supported.
6822  */
6823 static int
6824 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
6825 {
6826 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6827 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
6828 
6829 	scsipkt->pkt_reason = CMD_CMPLT;
6830 	*scsipkt->pkt_scbp = STATUS_CHECK;
6831 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6832 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6833 
6834 	sense = sata_arq_sense(spx);
6835 	sense->es_key = KEY_ILLEGAL_REQUEST;
6836 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6837 
6838 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6839 	    scsipkt->pkt_comp != NULL) {
6840 		/* scsi callback required */
6841 		if (servicing_interrupt()) {
6842 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6843 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6844 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6845 				return (TRAN_BUSY);
6846 			}
6847 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6848 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6849 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6850 			/* Scheduling the callback failed */
6851 			return (TRAN_BUSY);
6852 		}
6853 	}
6854 
6855 	return (TRAN_ACCEPT);
6856 }
6857 
6858 /*
6859  * Emulated SATA Read/Write command completion for zero-length requests.
6860  * This request always succedes, so in synchronous mode it always returns
6861  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
6862  * callback cannot be scheduled.
6863  */
6864 static int
6865 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
6866 {
6867 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6868 
6869 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6870 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6871 	scsipkt->pkt_reason = CMD_CMPLT;
6872 	*scsipkt->pkt_scbp = STATUS_GOOD;
6873 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6874 		/* scsi callback required - have to schedule it */
6875 		if (servicing_interrupt()) {
6876 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6877 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6878 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6879 				return (TRAN_BUSY);
6880 			}
6881 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6882 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6883 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6884 			/* Scheduling the callback failed */
6885 			return (TRAN_BUSY);
6886 		}
6887 	}
6888 	return (TRAN_ACCEPT);
6889 }
6890 
6891 
6892 /*
6893  * Translate completion status of SATA read/write commands into scsi response.
6894  * pkt completion_reason is checked to determine the completion status.
6895  * Do scsi callback if necessary.
6896  *
6897  * Note: this function may be called also for synchronously executed
6898  * commands.
6899  * This function may be used only if scsi_pkt is non-NULL.
6900  */
6901 static void
6902 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
6903 {
6904 	sata_pkt_txlate_t *spx =
6905 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6906 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6907 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6908 	struct scsi_extended_sense *sense;
6909 	uint64_t lba;
6910 	struct buf *bp;
6911 	int rval;
6912 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6913 		/* Normal completion */
6914 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6915 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6916 		scsipkt->pkt_reason = CMD_CMPLT;
6917 		*scsipkt->pkt_scbp = STATUS_GOOD;
6918 		if (spx->txlt_tmp_buf != NULL) {
6919 			/* Temporary buffer was used */
6920 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6921 			if (bp->b_flags & B_READ) {
6922 				rval = ddi_dma_sync(
6923 				    spx->txlt_buf_dma_handle, 0, 0,
6924 				    DDI_DMA_SYNC_FORCPU);
6925 				ASSERT(rval == DDI_SUCCESS);
6926 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6927 				    bp->b_bcount);
6928 			}
6929 		}
6930 	} else {
6931 		/*
6932 		 * Something went wrong - analyze return
6933 		 */
6934 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6935 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6936 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6937 		*scsipkt->pkt_scbp = STATUS_CHECK;
6938 		sense = sata_arq_sense(spx);
6939 		ASSERT(sense != NULL);
6940 
6941 		/*
6942 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
6943 		 * extract from device registers the failing LBA.
6944 		 */
6945 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
6946 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
6947 			    (scmd->satacmd_lba_mid_msb != 0 ||
6948 			    scmd->satacmd_lba_high_msb != 0)) {
6949 				/*
6950 				 * We have problem reporting this cmd LBA
6951 				 * in fixed sense data format, because of
6952 				 * the size of the scsi LBA fields.
6953 				 */
6954 				sense->es_valid = 0;
6955 			} else {
6956 				sata_extract_error_lba(spx, &lba);
6957 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
6958 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
6959 				sense->es_info_3 = (lba & 0xFF00) >> 8;
6960 				sense->es_info_4 = lba & 0xFF;
6961 			}
6962 		} else {
6963 			/* Invalid extended sense info */
6964 			sense->es_valid = 0;
6965 		}
6966 
6967 		switch (sata_pkt->satapkt_reason) {
6968 		case SATA_PKT_PORT_ERROR:
6969 			/* We may want to handle DEV GONE state as well */
6970 			/*
6971 			 * We have no device data. Assume no data transfered.
6972 			 */
6973 			sense->es_key = KEY_HARDWARE_ERROR;
6974 			break;
6975 
6976 		case SATA_PKT_DEV_ERROR:
6977 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6978 			    SATA_STATUS_ERR) {
6979 				/*
6980 				 * determine dev error reason from error
6981 				 * reg content
6982 				 */
6983 				sata_decode_device_error(spx, sense);
6984 				if (sense->es_key == KEY_MEDIUM_ERROR) {
6985 					switch (scmd->satacmd_cmd_reg) {
6986 					case SATAC_READ_DMA:
6987 					case SATAC_READ_DMA_EXT:
6988 					case SATAC_READ_DMA_QUEUED:
6989 					case SATAC_READ_DMA_QUEUED_EXT:
6990 					case SATAC_READ_FPDMA_QUEUED:
6991 						/* Unrecovered read error */
6992 						sense->es_add_code =
6993 						    SD_SCSI_ASC_UNREC_READ_ERR;
6994 						break;
6995 					case SATAC_WRITE_DMA:
6996 					case SATAC_WRITE_DMA_EXT:
6997 					case SATAC_WRITE_DMA_QUEUED:
6998 					case SATAC_WRITE_DMA_QUEUED_EXT:
6999 					case SATAC_WRITE_FPDMA_QUEUED:
7000 						/* Write error */
7001 						sense->es_add_code =
7002 						    SD_SCSI_ASC_WRITE_ERR;
7003 						break;
7004 					default:
7005 						/* Internal error */
7006 						SATA_LOG_D((
7007 						    spx->txlt_sata_hba_inst,
7008 						    CE_WARN,
7009 						    "sata_txlt_rw_completion :"
7010 						    "internal error - invalid "
7011 						    "command 0x%2x",
7012 						    scmd->satacmd_cmd_reg));
7013 						break;
7014 					}
7015 				}
7016 				break;
7017 			}
7018 			/* No extended sense key - no info available */
7019 			scsipkt->pkt_reason = CMD_INCOMPLETE;
7020 			break;
7021 
7022 		case SATA_PKT_TIMEOUT:
7023 			scsipkt->pkt_reason = CMD_TIMEOUT;
7024 			scsipkt->pkt_statistics |=
7025 			    STAT_TIMEOUT | STAT_DEV_RESET;
7026 			sense->es_key = KEY_ABORTED_COMMAND;
7027 			break;
7028 
7029 		case SATA_PKT_ABORTED:
7030 			scsipkt->pkt_reason = CMD_ABORTED;
7031 			scsipkt->pkt_statistics |= STAT_ABORTED;
7032 			sense->es_key = KEY_ABORTED_COMMAND;
7033 			break;
7034 
7035 		case SATA_PKT_RESET:
7036 			scsipkt->pkt_reason = CMD_RESET;
7037 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7038 			sense->es_key = KEY_ABORTED_COMMAND;
7039 			break;
7040 
7041 		default:
7042 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7043 			    "sata_txlt_rw_completion: "
7044 			    "invalid packet completion reason"));
7045 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7046 			break;
7047 		}
7048 	}
7049 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7050 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7051 
7052 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7053 		/* scsi callback required */
7054 		scsi_hba_pkt_comp(scsipkt);
7055 }
7056 
7057 
7058 /*
7059  * Translate completion status of non-data commands (i.e. commands returning
7060  * no data).
7061  * pkt completion_reason is checked to determine the completion status.
7062  * Do scsi callback if necessary (FLAG_NOINTR == 0)
7063  *
7064  * Note: this function may be called also for synchronously executed
7065  * commands.
7066  * This function may be used only if scsi_pkt is non-NULL.
7067  */
7068 
7069 static	void
7070 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
7071 {
7072 	sata_pkt_txlate_t *spx =
7073 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7074 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7075 
7076 	sata_set_arq_data(sata_pkt);
7077 
7078 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7079 		/* scsi callback required */
7080 		scsi_hba_pkt_comp(scsipkt);
7081 }
7082 
7083 /*
7084  * Completion handler for ATA Pass Through command
7085  */
7086 static void
7087 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
7088 {
7089 	sata_pkt_txlate_t *spx =
7090 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7091 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7092 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7093 	struct buf *bp;
7094 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
7095 
7096 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7097 		/* Normal completion */
7098 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7099 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7100 		scsipkt->pkt_reason = CMD_CMPLT;
7101 		*scsipkt->pkt_scbp = STATUS_GOOD;
7102 
7103 		/*
7104 		 * If the command has CK_COND set
7105 		 */
7106 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
7107 			*scsipkt->pkt_scbp = STATUS_CHECK;
7108 			sata_fill_ata_return_desc(sata_pkt,
7109 			    KEY_RECOVERABLE_ERROR,
7110 			    SD_SCSI_ASC_ATP_INFO_AVAIL, 0);
7111 		}
7112 
7113 		if (spx->txlt_tmp_buf != NULL) {
7114 			/* Temporary buffer was used */
7115 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7116 			if (bp->b_flags & B_READ) {
7117 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7118 				    bp->b_bcount);
7119 			}
7120 		}
7121 	} else {
7122 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7123 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7124 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7125 		*scsipkt->pkt_scbp = STATUS_CHECK;
7126 
7127 		/*
7128 		 * If DF or ERR was set, the HBA should have copied out the
7129 		 * status and error registers to the satacmd structure.
7130 		 */
7131 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
7132 			sense_key = KEY_HARDWARE_ERROR;
7133 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
7134 			addl_sense_qual = 0;
7135 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
7136 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
7137 				sense_key = KEY_NOT_READY;
7138 				addl_sense_code =
7139 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
7140 				addl_sense_qual = 0;
7141 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
7142 				sense_key = KEY_MEDIUM_ERROR;
7143 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
7144 				addl_sense_qual = 0;
7145 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7146 				sense_key = KEY_DATA_PROTECT;
7147 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7148 				addl_sense_qual = 0;
7149 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7150 				sense_key = KEY_ILLEGAL_REQUEST;
7151 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7152 				addl_sense_qual = 0;
7153 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7154 				sense_key = KEY_ABORTED_COMMAND;
7155 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7156 				addl_sense_qual = 0;
7157 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7158 				sense_key = KEY_UNIT_ATTENTION;
7159 				addl_sense_code =
7160 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7161 				addl_sense_qual = 0;
7162 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7163 				sense_key = KEY_UNIT_ATTENTION;
7164 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7165 				addl_sense_qual = 0;
7166 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7167 				sense_key = KEY_ABORTED_COMMAND;
7168 				addl_sense_code =
7169 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7170 				addl_sense_qual = 0;
7171 			}
7172 		}
7173 
7174 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7175 		    addl_sense_qual);
7176 	}
7177 
7178 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7179 		/* scsi callback required */
7180 		scsi_hba_pkt_comp(scsipkt);
7181 }
7182 
7183 /*
7184  * j
7185  */
7186 static void
7187 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7188     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7189 {
7190 	sata_pkt_txlate_t *spx =
7191 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7192 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7193 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7194 	struct sata_apt_sense_data *apt_sd =
7195 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7196 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7197 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7198 	    &(apt_sd->apt_sd_sense);
7199 	int extend = 0;
7200 
7201 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7202 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7203 		extend = 1;
7204 
7205 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7206 
7207 	/* update the residual count */
7208 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7209 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7210 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7211 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7212 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7213 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7214 	    sizeof (struct sata_apt_sense_data);
7215 
7216 	/*
7217 	 * Fill in the Descriptor sense header
7218 	 */
7219 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7220 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7221 	sds->ds_class = CLASS_EXTENDED_SENSE;
7222 	sds->ds_key = sense_key & 0xf;
7223 	sds->ds_add_code = addl_sense_code;
7224 	sds->ds_qual_code = addl_sense_qual;
7225 	sds->ds_addl_sense_length =
7226 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7227 
7228 	/*
7229 	 * Fill in the ATA Return descriptor sense data
7230 	 */
7231 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7232 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7233 	ata_ret_desc->ars_addl_length = 0xc;
7234 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7235 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7236 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7237 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7238 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7239 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7240 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7241 
7242 	if (extend == 1) {
7243 		ata_ret_desc->ars_extend = 1;
7244 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7245 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7246 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7247 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7248 	} else {
7249 		ata_ret_desc->ars_extend = 0;
7250 		ata_ret_desc->ars_sec_count_msb = 0;
7251 		ata_ret_desc->ars_lba_low_msb = 0;
7252 		ata_ret_desc->ars_lba_mid_msb = 0;
7253 		ata_ret_desc->ars_lba_high_msb = 0;
7254 	}
7255 }
7256 
7257 static	void
7258 sata_set_arq_data(sata_pkt_t *sata_pkt)
7259 {
7260 	sata_pkt_txlate_t *spx =
7261 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7262 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7263 	struct scsi_extended_sense *sense;
7264 
7265 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7266 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7267 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7268 		/* Normal completion */
7269 		scsipkt->pkt_reason = CMD_CMPLT;
7270 		*scsipkt->pkt_scbp = STATUS_GOOD;
7271 	} else {
7272 		/* Something went wrong */
7273 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7274 		*scsipkt->pkt_scbp = STATUS_CHECK;
7275 		sense = sata_arq_sense(spx);
7276 		switch (sata_pkt->satapkt_reason) {
7277 		case SATA_PKT_PORT_ERROR:
7278 			/*
7279 			 * We have no device data. Assume no data transfered.
7280 			 */
7281 			sense->es_key = KEY_HARDWARE_ERROR;
7282 			break;
7283 
7284 		case SATA_PKT_DEV_ERROR:
7285 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7286 			    SATA_STATUS_ERR) {
7287 				/*
7288 				 * determine dev error reason from error
7289 				 * reg content
7290 				 */
7291 				sata_decode_device_error(spx, sense);
7292 				break;
7293 			}
7294 			/* No extended sense key - no info available */
7295 			break;
7296 
7297 		case SATA_PKT_TIMEOUT:
7298 			scsipkt->pkt_reason = CMD_TIMEOUT;
7299 			scsipkt->pkt_statistics |=
7300 			    STAT_TIMEOUT | STAT_DEV_RESET;
7301 			/* No extended sense key ? */
7302 			break;
7303 
7304 		case SATA_PKT_ABORTED:
7305 			scsipkt->pkt_reason = CMD_ABORTED;
7306 			scsipkt->pkt_statistics |= STAT_ABORTED;
7307 			/* No extended sense key ? */
7308 			break;
7309 
7310 		case SATA_PKT_RESET:
7311 			/* pkt aborted by an explicit reset from a host */
7312 			scsipkt->pkt_reason = CMD_RESET;
7313 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7314 			break;
7315 
7316 		default:
7317 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7318 			    "sata_txlt_nodata_cmd_completion: "
7319 			    "invalid packet completion reason %d",
7320 			    sata_pkt->satapkt_reason));
7321 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7322 			break;
7323 		}
7324 
7325 	}
7326 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7327 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7328 }
7329 
7330 
7331 /*
7332  * Build Mode sense R/W recovery page
7333  * NOT IMPLEMENTED
7334  */
7335 
7336 static int
7337 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7338 {
7339 #ifndef __lock_lint
7340 	_NOTE(ARGUNUSED(sdinfo))
7341 	_NOTE(ARGUNUSED(pcntrl))
7342 	_NOTE(ARGUNUSED(buf))
7343 #endif
7344 	return (0);
7345 }
7346 
7347 /*
7348  * Build Mode sense caching page  -  scsi-3 implementation.
7349  * Page length distinguishes previous format from scsi-3 format.
7350  * buf must have space for 0x12 bytes.
7351  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
7352  *
7353  */
7354 static int
7355 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7356 {
7357 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
7358 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7359 
7360 	/*
7361 	 * Most of the fields are set to 0, being not supported and/or disabled
7362 	 */
7363 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
7364 
7365 	/* Saved paramters not supported */
7366 	if (pcntrl == 3)
7367 		return (0);
7368 	if (pcntrl == 0 || pcntrl == 2) {
7369 		/*
7370 		 * For now treat current and default parameters as same
7371 		 * That may have to change, if target driver will complain
7372 		 */
7373 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
7374 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7375 
7376 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
7377 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
7378 			page->dra = 1;		/* Read Ahead disabled */
7379 			page->rcd = 1;		/* Read Cache disabled */
7380 		}
7381 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
7382 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
7383 			page->wce = 1;		/* Write Cache enabled */
7384 	} else {
7385 		/* Changeable parameters */
7386 		page->mode_page.code = MODEPAGE_CACHING;
7387 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7388 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7389 			page->dra = 1;
7390 			page->rcd = 1;
7391 		}
7392 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
7393 			page->wce = 1;
7394 	}
7395 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7396 	    sizeof (struct mode_page));
7397 }
7398 
7399 /*
7400  * Build Mode sense exception cntrl page
7401  */
7402 static int
7403 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7404 {
7405 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
7406 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7407 
7408 	/*
7409 	 * Most of the fields are set to 0, being not supported and/or disabled
7410 	 */
7411 	bzero(buf, PAGELENGTH_INFO_EXCPT);
7412 
7413 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
7414 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
7415 
7416 	/* Indicate that this is page is saveable */
7417 	page->mode_page.ps = 1;
7418 
7419 	/*
7420 	 * We will return the same data for default, current and saved page.
7421 	 * The only changeable bit is dexcpt and that bit is required
7422 	 * by the ATA specification to be preserved across power cycles.
7423 	 */
7424 	if (pcntrl != 1) {
7425 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
7426 		page->mrie = MRIE_ONLY_ON_REQUEST;
7427 	}
7428 	else
7429 		page->dexcpt = 1;	/* Only changeable parameter */
7430 
7431 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
7432 }
7433 
7434 
7435 static int
7436 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7437 {
7438 	struct mode_acoustic_management *page =
7439 	    (struct mode_acoustic_management *)buf;
7440 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7441 
7442 	/*
7443 	 * Most of the fields are set to 0, being not supported and/or disabled
7444 	 */
7445 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
7446 
7447 	switch (pcntrl) {
7448 	case P_CNTRL_DEFAULT:
7449 		/*  default paramters not supported */
7450 		return (0);
7451 
7452 	case P_CNTRL_CURRENT:
7453 	case P_CNTRL_SAVED:
7454 		/* Saved and current are supported and are identical */
7455 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7456 		page->mode_page.length =
7457 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7458 		page->mode_page.ps = 1;
7459 
7460 		/* Word 83 indicates if feature is supported */
7461 		/* If feature is not supported */
7462 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
7463 			page->acoustic_manag_enable =
7464 			    ACOUSTIC_DISABLED;
7465 		} else {
7466 			page->acoustic_manag_enable =
7467 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
7468 			    != 0);
7469 			/* Word 94 inidicates the value */
7470 #ifdef	_LITTLE_ENDIAN
7471 			page->acoustic_manag_level =
7472 			    (uchar_t)sata_id->ai_acoustic;
7473 			page->vendor_recommended_value =
7474 			    sata_id->ai_acoustic >> 8;
7475 #else
7476 			page->acoustic_manag_level =
7477 			    sata_id->ai_acoustic >> 8;
7478 			page->vendor_recommended_value =
7479 			    (uchar_t)sata_id->ai_acoustic;
7480 #endif
7481 		}
7482 		break;
7483 
7484 	case P_CNTRL_CHANGEABLE:
7485 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7486 		page->mode_page.length =
7487 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7488 		page->mode_page.ps = 1;
7489 
7490 		/* Word 83 indicates if the feature is supported */
7491 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
7492 			page->acoustic_manag_enable =
7493 			    ACOUSTIC_ENABLED;
7494 			page->acoustic_manag_level = 0xff;
7495 		}
7496 		break;
7497 	}
7498 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7499 	    sizeof (struct mode_page));
7500 }
7501 
7502 
7503 /*
7504  * Build Mode sense power condition page.
7505  */
7506 static int
7507 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7508 {
7509 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
7510 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7511 
7512 	/*
7513 	 * Most of the fields are set to 0, being not supported and/or disabled
7514 	 * power condition page length was 0x0a
7515 	 */
7516 	bzero(buf, sizeof (struct mode_info_power_cond));
7517 
7518 	if (pcntrl == P_CNTRL_DEFAULT) {
7519 		/*  default paramters not supported */
7520 		return (0);
7521 	}
7522 
7523 	page->mode_page.code = MODEPAGE_POWER_COND;
7524 	page->mode_page.length = sizeof (struct mode_info_power_cond);
7525 
7526 	if (sata_id->ai_cap && SATA_STANDBYTIMER) {
7527 		page->standby = 1;
7528 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
7529 		    sizeof (uchar_t) * 4);
7530 	}
7531 
7532 	return (sizeof (struct mode_info_power_cond));
7533 }
7534 
7535 /*
7536  * Process mode select caching page 8 (scsi3 format only).
7537  * Read Ahead (same as read cache) and Write Cache may be turned on and off
7538  * if these features are supported by the device. If these features are not
7539  * supported, the command will be terminated with STATUS_CHECK.
7540  * This function fails only if the SET FEATURE command sent to
7541  * the device fails. The page format is not varified, assuming that the
7542  * target driver operates correctly - if parameters length is too short,
7543  * we just drop the page.
7544  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
7545  * setting have to be changed.
7546  * SET FEATURE command is executed synchronously, i.e. we wait here until
7547  * it is completed, regardless of the scsi pkt directives.
7548  *
7549  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
7550  * changing DRA will change RCD.
7551  *
7552  * More than one SATA command may be executed to perform operations specified
7553  * by mode select pages. The first error terminates further execution.
7554  * Operations performed successully are not backed-up in such case.
7555  *
7556  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7557  * If operation resulted in changing device setup, dmod flag should be set to
7558  * one (1). If parameters were not changed, dmod flag should be set to 0.
7559  * Upon return, if operation required sending command to the device, the rval
7560  * should be set to the value returned by sata_hba_start. If operation
7561  * did not require device access, rval should be set to TRAN_ACCEPT.
7562  * The pagelen should be set to the length of the page.
7563  *
7564  * This function has to be called with a port mutex held.
7565  *
7566  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7567  */
7568 int
7569 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
7570     int parmlen, int *pagelen, int *rval, int *dmod)
7571 {
7572 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7573 	sata_drive_info_t *sdinfo;
7574 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7575 	sata_id_t *sata_id;
7576 	struct scsi_extended_sense *sense;
7577 	int wce, dra;	/* Current settings */
7578 
7579 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7580 	    &spx->txlt_sata_pkt->satapkt_device);
7581 	sata_id = &sdinfo->satadrv_id;
7582 	*dmod = 0;
7583 
7584 	/* Verify parameters length. If too short, drop it */
7585 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7586 	    sizeof (struct mode_page)) > parmlen) {
7587 		*scsipkt->pkt_scbp = STATUS_CHECK;
7588 		sense = sata_arq_sense(spx);
7589 		sense->es_key = KEY_ILLEGAL_REQUEST;
7590 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7591 		*pagelen = parmlen;
7592 		*rval = TRAN_ACCEPT;
7593 		return (SATA_FAILURE);
7594 	}
7595 
7596 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
7597 
7598 	/* Current setting of Read Ahead (and Read Cache) */
7599 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
7600 		dra = 0;	/* 0 == not disabled */
7601 	else
7602 		dra = 1;
7603 	/* Current setting of Write Cache */
7604 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
7605 		wce = 1;
7606 	else
7607 		wce = 0;
7608 
7609 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
7610 		/* nothing to do */
7611 		*rval = TRAN_ACCEPT;
7612 		return (SATA_SUCCESS);
7613 	}
7614 
7615 	/*
7616 	 * Need to flip some setting
7617 	 * Set-up Internal SET FEATURES command(s)
7618 	 */
7619 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7620 	scmd->satacmd_addr_type = 0;
7621 	scmd->satacmd_device_reg = 0;
7622 	scmd->satacmd_status_reg = 0;
7623 	scmd->satacmd_error_reg = 0;
7624 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7625 	if (page->dra != dra || page->rcd != dra) {
7626 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7627 			/* Need to flip read ahead setting */
7628 			if (dra == 0)
7629 				/* Disable read ahead / read cache */
7630 				scmd->satacmd_features_reg =
7631 				    SATAC_SF_DISABLE_READ_AHEAD;
7632 			else
7633 				/* Enable read ahead  / read cache */
7634 				scmd->satacmd_features_reg =
7635 				    SATAC_SF_ENABLE_READ_AHEAD;
7636 
7637 			/* Transfer command to HBA */
7638 			if (sata_hba_start(spx, rval) != 0)
7639 				/*
7640 				 * Pkt not accepted for execution.
7641 				 */
7642 				return (SATA_FAILURE);
7643 
7644 			*dmod = 1;
7645 
7646 			/* Now process return */
7647 			if (spx->txlt_sata_pkt->satapkt_reason !=
7648 			    SATA_PKT_COMPLETED) {
7649 				goto failure;	/* Terminate */
7650 			}
7651 		} else {
7652 			*scsipkt->pkt_scbp = STATUS_CHECK;
7653 			sense = sata_arq_sense(spx);
7654 			sense->es_key = KEY_ILLEGAL_REQUEST;
7655 			sense->es_add_code =
7656 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7657 			*pagelen = parmlen;
7658 			*rval = TRAN_ACCEPT;
7659 			return (SATA_FAILURE);
7660 		}
7661 	}
7662 
7663 	/* Note that the packet is not removed, so it could be re-used */
7664 	if (page->wce != wce) {
7665 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
7666 			/* Need to flip Write Cache setting */
7667 			if (page->wce == 1)
7668 				/* Enable write cache */
7669 				scmd->satacmd_features_reg =
7670 				    SATAC_SF_ENABLE_WRITE_CACHE;
7671 			else
7672 				/* Disable write cache */
7673 				scmd->satacmd_features_reg =
7674 				    SATAC_SF_DISABLE_WRITE_CACHE;
7675 
7676 			/* Transfer command to HBA */
7677 			if (sata_hba_start(spx, rval) != 0)
7678 				/*
7679 				 * Pkt not accepted for execution.
7680 				 */
7681 				return (SATA_FAILURE);
7682 
7683 			*dmod = 1;
7684 
7685 			/* Now process return */
7686 			if (spx->txlt_sata_pkt->satapkt_reason !=
7687 			    SATA_PKT_COMPLETED) {
7688 				goto failure;
7689 			}
7690 		} else {
7691 			*scsipkt->pkt_scbp = STATUS_CHECK;
7692 			sense = sata_arq_sense(spx);
7693 			sense->es_key = KEY_ILLEGAL_REQUEST;
7694 			sense->es_add_code =
7695 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7696 			*pagelen = parmlen;
7697 			*rval = TRAN_ACCEPT;
7698 			return (SATA_FAILURE);
7699 		}
7700 	}
7701 	return (SATA_SUCCESS);
7702 
7703 failure:
7704 	sata_xlate_errors(spx);
7705 
7706 	return (SATA_FAILURE);
7707 }
7708 
7709 /*
7710  * Process mode select informational exceptions control page 0x1c
7711  *
7712  * The only changeable bit is dexcpt (disable exceptions).
7713  * MRIE (method of reporting informational exceptions) must be
7714  * "only on request".
7715  * This page applies to informational exceptions that report
7716  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
7717  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
7718  * Informational exception conditions occur as the result of background scan
7719  * errors, background self-test errors, or vendor specific events within a
7720  * logical unit. An informational exception condition may occur asynchronous
7721  * to any commands.
7722  *
7723  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7724  * If operation resulted in changing device setup, dmod flag should be set to
7725  * one (1). If parameters were not changed, dmod flag should be set to 0.
7726  * Upon return, if operation required sending command to the device, the rval
7727  * should be set to the value returned by sata_hba_start. If operation
7728  * did not require device access, rval should be set to TRAN_ACCEPT.
7729  * The pagelen should be set to the length of the page.
7730  *
7731  * This function has to be called with a port mutex held.
7732  *
7733  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7734  *
7735  * Cannot be called in the interrupt context.
7736  */
7737 static	int
7738 sata_mode_select_page_1c(
7739 	sata_pkt_txlate_t *spx,
7740 	struct mode_info_excpt_page *page,
7741 	int parmlen,
7742 	int *pagelen,
7743 	int *rval,
7744 	int *dmod)
7745 {
7746 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7747 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7748 	sata_drive_info_t *sdinfo;
7749 	sata_id_t *sata_id;
7750 	struct scsi_extended_sense *sense;
7751 
7752 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7753 	    &spx->txlt_sata_pkt->satapkt_device);
7754 	sata_id = &sdinfo->satadrv_id;
7755 
7756 	*dmod = 0;
7757 
7758 	/* Verify parameters length. If too short, drop it */
7759 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
7760 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
7761 		*scsipkt->pkt_scbp = STATUS_CHECK;
7762 		sense = sata_arq_sense(spx);
7763 		sense->es_key = KEY_ILLEGAL_REQUEST;
7764 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7765 		*pagelen = parmlen;
7766 		*rval = TRAN_ACCEPT;
7767 		return (SATA_FAILURE);
7768 	}
7769 
7770 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
7771 
7772 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
7773 		*scsipkt->pkt_scbp = STATUS_CHECK;
7774 		sense = sata_arq_sense(spx);
7775 		sense->es_key = KEY_ILLEGAL_REQUEST;
7776 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7777 		*pagelen = parmlen;
7778 		*rval = TRAN_ACCEPT;
7779 		return (SATA_FAILURE);
7780 	}
7781 
7782 	/* If already in the state requested, we are done */
7783 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
7784 		/* nothing to do */
7785 		*rval = TRAN_ACCEPT;
7786 		return (SATA_SUCCESS);
7787 	}
7788 
7789 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7790 
7791 	/* Build SMART_ENABLE or SMART_DISABLE command */
7792 	scmd->satacmd_addr_type = 0;		/* N/A */
7793 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
7794 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
7795 	scmd->satacmd_features_reg = page->dexcpt ?
7796 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
7797 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
7798 	scmd->satacmd_cmd_reg = SATAC_SMART;
7799 
7800 	/* Transfer command to HBA */
7801 	if (sata_hba_start(spx, rval) != 0)
7802 		/*
7803 		 * Pkt not accepted for execution.
7804 		 */
7805 		return (SATA_FAILURE);
7806 
7807 	*dmod = 1;	/* At least may have been modified */
7808 
7809 	/* Now process return */
7810 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
7811 		return (SATA_SUCCESS);
7812 
7813 	/* Packet did not complete successfully */
7814 	sata_xlate_errors(spx);
7815 
7816 	return (SATA_FAILURE);
7817 }
7818 
7819 /*
7820  * Process mode select acoustic management control page 0x30
7821  *
7822  *
7823  * This function has to be called with a port mutex held.
7824  *
7825  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7826  *
7827  * Cannot be called in the interrupt context.
7828  */
7829 int
7830 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
7831     mode_acoustic_management *page, int parmlen, int *pagelen,
7832     int *rval, int *dmod)
7833 {
7834 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7835 	sata_drive_info_t *sdinfo;
7836 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7837 	sata_id_t *sata_id;
7838 	struct scsi_extended_sense *sense;
7839 
7840 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7841 	    &spx->txlt_sata_pkt->satapkt_device);
7842 	sata_id = &sdinfo->satadrv_id;
7843 	*dmod = 0;
7844 
7845 	/* If parmlen is too short or the feature is not supported, drop it */
7846 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7847 	    sizeof (struct mode_page)) > parmlen) ||
7848 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
7849 		*scsipkt->pkt_scbp = STATUS_CHECK;
7850 		sense = sata_arq_sense(spx);
7851 		sense->es_key = KEY_ILLEGAL_REQUEST;
7852 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7853 		*pagelen = parmlen;
7854 		*rval = TRAN_ACCEPT;
7855 		return (SATA_FAILURE);
7856 	}
7857 
7858 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7859 	    sizeof (struct mode_page);
7860 
7861 	/*
7862 	 * We can enable and disable acoustice management and
7863 	 * set the acoustic management level.
7864 	 */
7865 
7866 	/*
7867 	 * Set-up Internal SET FEATURES command(s)
7868 	 */
7869 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7870 	scmd->satacmd_addr_type = 0;
7871 	scmd->satacmd_device_reg = 0;
7872 	scmd->satacmd_status_reg = 0;
7873 	scmd->satacmd_error_reg = 0;
7874 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7875 	if (page->acoustic_manag_enable) {
7876 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
7877 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
7878 	} else {	/* disabling acoustic management */
7879 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
7880 	}
7881 
7882 	/* Transfer command to HBA */
7883 	if (sata_hba_start(spx, rval) != 0)
7884 		/*
7885 		 * Pkt not accepted for execution.
7886 		 */
7887 		return (SATA_FAILURE);
7888 
7889 	/* Now process return */
7890 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
7891 		sata_xlate_errors(spx);
7892 		return (SATA_FAILURE);
7893 	}
7894 
7895 	*dmod = 1;
7896 
7897 	return (SATA_SUCCESS);
7898 }
7899 
7900 /*
7901  * Process mode select power condition page 0x1a
7902  *
7903  * This function has to be called with a port mutex held.
7904  *
7905  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7906  *
7907  * Cannot be called in the interrupt context.
7908  */
7909 int
7910 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
7911     mode_info_power_cond *page, int parmlen, int *pagelen,
7912     int *rval, int *dmod)
7913 {
7914 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7915 	sata_drive_info_t *sdinfo;
7916 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7917 	sata_id_t *sata_id;
7918 	struct scsi_extended_sense *sense;
7919 	uint8_t ata_count;
7920 	int i, len;
7921 
7922 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7923 	    &spx->txlt_sata_pkt->satapkt_device);
7924 	sata_id = &sdinfo->satadrv_id;
7925 	*dmod = 0;
7926 
7927 	len = sizeof (struct mode_info_power_cond);
7928 	len += sizeof (struct mode_page);
7929 
7930 	/* If parmlen is too short or the feature is not supported, drop it */
7931 	if ((len < parmlen) || (page->idle == 1) ||
7932 	    (!(sata_id->ai_cap && SATA_STANDBYTIMER) && page->standby == 1)) {
7933 		*scsipkt->pkt_scbp = STATUS_CHECK;
7934 		sense = sata_arq_sense(spx);
7935 		sense->es_key = KEY_ILLEGAL_REQUEST;
7936 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7937 		*pagelen = parmlen;
7938 		*rval = TRAN_ACCEPT;
7939 		return (SATA_FAILURE);
7940 	}
7941 
7942 	*pagelen = len;
7943 
7944 	/*
7945 	 * Set-up Internal STANDBY command(s)
7946 	 */
7947 	if (page->standby == 0)
7948 		goto out;
7949 
7950 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
7951 
7952 	scmd->satacmd_addr_type = 0;
7953 	scmd->satacmd_sec_count_lsb = ata_count;
7954 	scmd->satacmd_lba_low_lsb = 0;
7955 	scmd->satacmd_lba_mid_lsb = 0;
7956 	scmd->satacmd_lba_high_lsb = 0;
7957 	scmd->satacmd_features_reg = 0;
7958 	scmd->satacmd_device_reg = 0;
7959 	scmd->satacmd_status_reg = 0;
7960 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
7961 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
7962 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
7963 
7964 	/* Transfer command to HBA */
7965 	if (sata_hba_start(spx, rval) != 0) {
7966 		return (SATA_FAILURE);
7967 	} else {
7968 		if ((scmd->satacmd_error_reg != 0) ||
7969 		    (spx->txlt_sata_pkt->satapkt_reason !=
7970 		    SATA_PKT_COMPLETED)) {
7971 			sata_xlate_errors(spx);
7972 			return (SATA_FAILURE);
7973 		}
7974 	}
7975 
7976 	for (i = 0; i < 4; i++) {
7977 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
7978 	}
7979 out:
7980 	*dmod = 1;
7981 	return (SATA_SUCCESS);
7982 }
7983 
7984 /*
7985  * sata_build_lsense_page0() is used to create the
7986  * SCSI LOG SENSE page 0 (supported log pages)
7987  *
7988  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
7989  * (supported log pages, self-test results, informational exceptions
7990  * Sun vendor specific ATA SMART data, and start stop cycle counter).
7991  *
7992  * Takes a sata_drive_info t * and the address of a buffer
7993  * in which to create the page information.
7994  *
7995  * Returns the number of bytes valid in the buffer.
7996  */
7997 static	int
7998 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
7999 {
8000 	struct log_parameter *lpp = (struct log_parameter *)buf;
8001 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
8002 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
8003 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8004 
8005 	lpp->param_code[0] = 0;
8006 	lpp->param_code[1] = 0;
8007 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8008 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
8009 
8010 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
8011 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
8012 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
8013 			++num_pages_supported;
8014 		}
8015 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
8016 		++num_pages_supported;
8017 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
8018 		++num_pages_supported;
8019 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
8020 		++num_pages_supported;
8021 	}
8022 
8023 	lpp->param_len = num_pages_supported;
8024 
8025 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
8026 	    num_pages_supported);
8027 }
8028 
8029 /*
8030  * sata_build_lsense_page_10() is used to create the
8031  * SCSI LOG SENSE page 0x10 (self-test results)
8032  *
8033  * Takes a sata_drive_info t * and the address of a buffer
8034  * in which to create the page information as well as a sata_hba_inst_t *.
8035  *
8036  * Returns the number of bytes valid in the buffer.
8037  *
8038  * Note: Self test and SMART data is accessible in device log pages.
8039  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
8040  * of data can be transferred by a single command), or by the General Purpose
8041  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
8042  * - approximately 33MB - can be transferred by a single command.
8043  * The SCT Command response (either error or command) is the same for both
8044  * the SMART and GPL methods of issuing commands.
8045  * This function uses READ LOG EXT command when drive supports LBA48, and
8046  * SMART READ command otherwise.
8047  *
8048  * Since above commands are executed in a synchronous mode, this function
8049  * should not be called in an interrupt context.
8050  */
8051 static	int
8052 sata_build_lsense_page_10(
8053 	sata_drive_info_t *sdinfo,
8054 	uint8_t *buf,
8055 	sata_hba_inst_t *sata_hba_inst)
8056 {
8057 	struct log_parameter *lpp = (struct log_parameter *)buf;
8058 	int rval;
8059 
8060 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
8061 		struct smart_ext_selftest_log *ext_selftest_log;
8062 
8063 		ext_selftest_log = kmem_zalloc(
8064 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
8065 
8066 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
8067 		    ext_selftest_log, 0);
8068 		if (rval == 0) {
8069 			int index, start_index;
8070 			struct smart_ext_selftest_log_entry *entry;
8071 			static const struct smart_ext_selftest_log_entry empty =
8072 			    {0};
8073 			uint16_t block_num;
8074 			int count;
8075 			boolean_t only_one_block = B_FALSE;
8076 
8077 			index = ext_selftest_log->
8078 			    smart_ext_selftest_log_index[0];
8079 			index |= ext_selftest_log->
8080 			    smart_ext_selftest_log_index[1] << 8;
8081 			if (index == 0)
8082 				goto out;
8083 
8084 			--index;	/* Correct for 0 origin */
8085 			start_index = index;	/* remember where we started */
8086 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8087 			if (block_num != 0) {
8088 				rval = sata_ext_smart_selftest_read_log(
8089 				    sata_hba_inst, sdinfo, ext_selftest_log,
8090 				    block_num);
8091 				if (rval != 0)
8092 					goto out;
8093 			}
8094 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8095 			entry =
8096 			    &ext_selftest_log->
8097 			    smart_ext_selftest_log_entries[index];
8098 
8099 			for (count = 1;
8100 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8101 			    ++count) {
8102 				uint8_t status;
8103 				uint8_t code;
8104 				uint8_t sense_key;
8105 				uint8_t add_sense_code;
8106 				uint8_t add_sense_code_qual;
8107 
8108 				/* If this is an unused entry, we are done */
8109 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
8110 					/* Broken firmware on some disks */
8111 					if (index + 1 ==
8112 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
8113 						--entry;
8114 						--index;
8115 						if (bcmp(entry, &empty,
8116 						    sizeof (empty)) == 0)
8117 							goto out;
8118 					} else
8119 						goto out;
8120 				}
8121 
8122 				if (only_one_block &&
8123 				    start_index == index)
8124 					goto out;
8125 
8126 				lpp->param_code[0] = 0;
8127 				lpp->param_code[1] = count;
8128 				lpp->param_ctrl_flags =
8129 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8130 				lpp->param_len =
8131 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8132 
8133 				status = entry->smart_ext_selftest_log_status;
8134 				status >>= 4;
8135 				switch (status) {
8136 				case 0:
8137 				default:
8138 					sense_key = KEY_NO_SENSE;
8139 					add_sense_code =
8140 					    SD_SCSI_ASC_NO_ADD_SENSE;
8141 					add_sense_code_qual = 0;
8142 					break;
8143 				case 1:
8144 					sense_key = KEY_ABORTED_COMMAND;
8145 					add_sense_code =
8146 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8147 					add_sense_code_qual = SCSI_COMPONENT_81;
8148 					break;
8149 				case 2:
8150 					sense_key = KEY_ABORTED_COMMAND;
8151 					add_sense_code =
8152 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8153 					add_sense_code_qual = SCSI_COMPONENT_82;
8154 					break;
8155 				case 3:
8156 					sense_key = KEY_ABORTED_COMMAND;
8157 					add_sense_code =
8158 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8159 					add_sense_code_qual = SCSI_COMPONENT_83;
8160 					break;
8161 				case 4:
8162 					sense_key = KEY_HARDWARE_ERROR;
8163 					add_sense_code =
8164 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8165 					add_sense_code_qual = SCSI_COMPONENT_84;
8166 					break;
8167 				case 5:
8168 					sense_key = KEY_HARDWARE_ERROR;
8169 					add_sense_code =
8170 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8171 					add_sense_code_qual = SCSI_COMPONENT_85;
8172 					break;
8173 				case 6:
8174 					sense_key = KEY_HARDWARE_ERROR;
8175 					add_sense_code =
8176 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8177 					add_sense_code_qual = SCSI_COMPONENT_86;
8178 					break;
8179 				case 7:
8180 					sense_key = KEY_MEDIUM_ERROR;
8181 					add_sense_code =
8182 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8183 					add_sense_code_qual = SCSI_COMPONENT_87;
8184 					break;
8185 				case 8:
8186 					sense_key = KEY_HARDWARE_ERROR;
8187 					add_sense_code =
8188 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8189 					add_sense_code_qual = SCSI_COMPONENT_88;
8190 					break;
8191 				}
8192 				code = 0;	/* unspecified */
8193 				status |= (code << 4);
8194 				lpp->param_values[0] = status;
8195 				lpp->param_values[1] = 0; /* unspecified */
8196 				lpp->param_values[2] = entry->
8197 				    smart_ext_selftest_log_timestamp[1];
8198 				lpp->param_values[3] = entry->
8199 				    smart_ext_selftest_log_timestamp[0];
8200 				if (status != 0) {
8201 					lpp->param_values[4] = 0;
8202 					lpp->param_values[5] = 0;
8203 					lpp->param_values[6] = entry->
8204 					    smart_ext_selftest_log_failing_lba
8205 					    [5];
8206 					lpp->param_values[7] = entry->
8207 					    smart_ext_selftest_log_failing_lba
8208 					    [4];
8209 					lpp->param_values[8] = entry->
8210 					    smart_ext_selftest_log_failing_lba
8211 					    [3];
8212 					lpp->param_values[9] = entry->
8213 					    smart_ext_selftest_log_failing_lba
8214 					    [2];
8215 					lpp->param_values[10] = entry->
8216 					    smart_ext_selftest_log_failing_lba
8217 					    [1];
8218 					lpp->param_values[11] = entry->
8219 					    smart_ext_selftest_log_failing_lba
8220 					    [0];
8221 				} else {	/* No bad block address */
8222 					lpp->param_values[4] = 0xff;
8223 					lpp->param_values[5] = 0xff;
8224 					lpp->param_values[6] = 0xff;
8225 					lpp->param_values[7] = 0xff;
8226 					lpp->param_values[8] = 0xff;
8227 					lpp->param_values[9] = 0xff;
8228 					lpp->param_values[10] = 0xff;
8229 					lpp->param_values[11] = 0xff;
8230 				}
8231 
8232 				lpp->param_values[12] = sense_key;
8233 				lpp->param_values[13] = add_sense_code;
8234 				lpp->param_values[14] = add_sense_code_qual;
8235 				lpp->param_values[15] = 0; /* undefined */
8236 
8237 				lpp = (struct log_parameter *)
8238 				    (((uint8_t *)lpp) +
8239 				    SCSI_LOG_PARAM_HDR_LEN +
8240 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8241 
8242 				--index;	/* Back up to previous entry */
8243 				if (index < 0) {
8244 					if (block_num > 0) {
8245 						--block_num;
8246 					} else {
8247 						struct read_log_ext_directory
8248 						    logdir;
8249 
8250 						rval =
8251 						    sata_read_log_ext_directory(
8252 						    sata_hba_inst, sdinfo,
8253 						    &logdir);
8254 						if (rval == -1)
8255 							goto out;
8256 						if ((logdir.read_log_ext_vers
8257 						    [0] == 0) &&
8258 						    (logdir.read_log_ext_vers
8259 						    [1] == 0))
8260 							goto out;
8261 						block_num =
8262 						    logdir.read_log_ext_nblks
8263 						    [EXT_SMART_SELFTEST_LOG_PAGE
8264 						    - 1][0];
8265 						block_num |= logdir.
8266 						    read_log_ext_nblks
8267 						    [EXT_SMART_SELFTEST_LOG_PAGE
8268 						    - 1][1] << 8;
8269 						--block_num;
8270 						only_one_block =
8271 						    (block_num == 0);
8272 					}
8273 					rval = sata_ext_smart_selftest_read_log(
8274 					    sata_hba_inst, sdinfo,
8275 					    ext_selftest_log, block_num);
8276 					if (rval != 0)
8277 						goto out;
8278 
8279 					index =
8280 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8281 					    1;
8282 				}
8283 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8284 				entry = &ext_selftest_log->
8285 				    smart_ext_selftest_log_entries[index];
8286 			}
8287 		}
8288 out:
8289 		kmem_free(ext_selftest_log,
8290 		    sizeof (struct smart_ext_selftest_log));
8291 	} else {
8292 		struct smart_selftest_log *selftest_log;
8293 
8294 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8295 		    KM_SLEEP);
8296 
8297 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8298 		    selftest_log);
8299 
8300 		if (rval == 0) {
8301 			int index;
8302 			int count;
8303 			struct smart_selftest_log_entry *entry;
8304 			static const struct smart_selftest_log_entry empty =
8305 			    { 0 };
8306 
8307 			index = selftest_log->smart_selftest_log_index;
8308 			if (index == 0)
8309 				goto done;
8310 			--index;	/* Correct for 0 origin */
8311 			entry = &selftest_log->
8312 			    smart_selftest_log_entries[index];
8313 			for (count = 1;
8314 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8315 			    ++count) {
8316 				uint8_t status;
8317 				uint8_t code;
8318 				uint8_t sense_key;
8319 				uint8_t add_sense_code;
8320 				uint8_t add_sense_code_qual;
8321 
8322 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8323 					goto done;
8324 
8325 				lpp->param_code[0] = 0;
8326 				lpp->param_code[1] = count;
8327 				lpp->param_ctrl_flags =
8328 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8329 				lpp->param_len =
8330 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8331 
8332 				status = entry->smart_selftest_log_status;
8333 				status >>= 4;
8334 				switch (status) {
8335 				case 0:
8336 				default:
8337 					sense_key = KEY_NO_SENSE;
8338 					add_sense_code =
8339 					    SD_SCSI_ASC_NO_ADD_SENSE;
8340 					break;
8341 				case 1:
8342 					sense_key = KEY_ABORTED_COMMAND;
8343 					add_sense_code =
8344 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8345 					add_sense_code_qual = SCSI_COMPONENT_81;
8346 					break;
8347 				case 2:
8348 					sense_key = KEY_ABORTED_COMMAND;
8349 					add_sense_code =
8350 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8351 					add_sense_code_qual = SCSI_COMPONENT_82;
8352 					break;
8353 				case 3:
8354 					sense_key = KEY_ABORTED_COMMAND;
8355 					add_sense_code =
8356 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8357 					add_sense_code_qual = SCSI_COMPONENT_83;
8358 					break;
8359 				case 4:
8360 					sense_key = KEY_HARDWARE_ERROR;
8361 					add_sense_code =
8362 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8363 					add_sense_code_qual = SCSI_COMPONENT_84;
8364 					break;
8365 				case 5:
8366 					sense_key = KEY_HARDWARE_ERROR;
8367 					add_sense_code =
8368 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8369 					add_sense_code_qual = SCSI_COMPONENT_85;
8370 					break;
8371 				case 6:
8372 					sense_key = KEY_HARDWARE_ERROR;
8373 					add_sense_code =
8374 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8375 					add_sense_code_qual = SCSI_COMPONENT_86;
8376 					break;
8377 				case 7:
8378 					sense_key = KEY_MEDIUM_ERROR;
8379 					add_sense_code =
8380 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8381 					add_sense_code_qual = SCSI_COMPONENT_87;
8382 					break;
8383 				case 8:
8384 					sense_key = KEY_HARDWARE_ERROR;
8385 					add_sense_code =
8386 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8387 					add_sense_code_qual = SCSI_COMPONENT_88;
8388 					break;
8389 				}
8390 				code = 0;	/* unspecified */
8391 				status |= (code << 4);
8392 				lpp->param_values[0] = status;
8393 				lpp->param_values[1] = 0; /* unspecified */
8394 				lpp->param_values[2] = entry->
8395 				    smart_selftest_log_timestamp[1];
8396 				lpp->param_values[3] = entry->
8397 				    smart_selftest_log_timestamp[0];
8398 				if (status != 0) {
8399 					lpp->param_values[4] = 0;
8400 					lpp->param_values[5] = 0;
8401 					lpp->param_values[6] = 0;
8402 					lpp->param_values[7] = 0;
8403 					lpp->param_values[8] = entry->
8404 					    smart_selftest_log_failing_lba[3];
8405 					lpp->param_values[9] = entry->
8406 					    smart_selftest_log_failing_lba[2];
8407 					lpp->param_values[10] = entry->
8408 					    smart_selftest_log_failing_lba[1];
8409 					lpp->param_values[11] = entry->
8410 					    smart_selftest_log_failing_lba[0];
8411 				} else {	/* No block address */
8412 					lpp->param_values[4] = 0xff;
8413 					lpp->param_values[5] = 0xff;
8414 					lpp->param_values[6] = 0xff;
8415 					lpp->param_values[7] = 0xff;
8416 					lpp->param_values[8] = 0xff;
8417 					lpp->param_values[9] = 0xff;
8418 					lpp->param_values[10] = 0xff;
8419 					lpp->param_values[11] = 0xff;
8420 				}
8421 				lpp->param_values[12] = sense_key;
8422 				lpp->param_values[13] = add_sense_code;
8423 				lpp->param_values[14] = add_sense_code_qual;
8424 				lpp->param_values[15] = 0; /* undefined */
8425 
8426 				lpp = (struct log_parameter *)
8427 				    (((uint8_t *)lpp) +
8428 				    SCSI_LOG_PARAM_HDR_LEN +
8429 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8430 				--index;	/* back up to previous entry */
8431 				if (index < 0) {
8432 					index =
8433 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
8434 				}
8435 				entry = &selftest_log->
8436 				    smart_selftest_log_entries[index];
8437 			}
8438 		}
8439 done:
8440 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
8441 	}
8442 
8443 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
8444 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
8445 }
8446 
8447 /*
8448  * sata_build_lsense_page_2f() is used to create the
8449  * SCSI LOG SENSE page 0x2f (informational exceptions)
8450  *
8451  * Takes a sata_drive_info t * and the address of a buffer
8452  * in which to create the page information as well as a sata_hba_inst_t *.
8453  *
8454  * Returns the number of bytes valid in the buffer.
8455  *
8456  * Because it invokes function(s) that send synchronously executed command
8457  * to the HBA, it cannot be called in the interrupt context.
8458  */
8459 static	int
8460 sata_build_lsense_page_2f(
8461 	sata_drive_info_t *sdinfo,
8462 	uint8_t *buf,
8463 	sata_hba_inst_t *sata_hba_inst)
8464 {
8465 	struct log_parameter *lpp = (struct log_parameter *)buf;
8466 	int rval;
8467 	uint8_t *smart_data;
8468 	uint8_t temp;
8469 	sata_id_t *sata_id;
8470 #define	SMART_NO_TEMP	0xff
8471 
8472 	lpp->param_code[0] = 0;
8473 	lpp->param_code[1] = 0;
8474 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8475 
8476 	/* Now get the SMART status w.r.t. threshold exceeded */
8477 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
8478 	switch (rval) {
8479 	case 1:
8480 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
8481 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
8482 		break;
8483 	case 0:
8484 	case -1:	/* failed to get data */
8485 		lpp->param_values[0] = 0;	/* No failure predicted */
8486 		lpp->param_values[1] = 0;
8487 		break;
8488 #if defined(SATA_DEBUG)
8489 	default:
8490 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
8491 		/* NOTREACHED */
8492 #endif
8493 	}
8494 
8495 	sata_id = &sdinfo->satadrv_id;
8496 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
8497 		temp = SMART_NO_TEMP;
8498 	else {
8499 		/* Now get the temperature */
8500 		smart_data = kmem_zalloc(512, KM_SLEEP);
8501 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
8502 		    SCT_STATUS_LOG_PAGE, 1);
8503 		if (rval == -1)
8504 			temp = SMART_NO_TEMP;
8505 		else {
8506 			temp = smart_data[200];
8507 			if (temp & 0x80) {
8508 				if (temp & 0x7f)
8509 					temp = 0;
8510 				else
8511 					temp = SMART_NO_TEMP;
8512 			}
8513 		}
8514 		kmem_free(smart_data, 512);
8515 	}
8516 
8517 	lpp->param_values[2] = temp;	/* most recent temperature */
8518 	lpp->param_values[3] = 0;	/* required vendor specific byte */
8519 
8520 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
8521 
8522 
8523 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
8524 }
8525 
8526 /*
8527  * sata_build_lsense_page_30() is used to create the
8528  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
8529  *
8530  * Takes a sata_drive_info t * and the address of a buffer
8531  * in which to create the page information as well as a sata_hba_inst_t *.
8532  *
8533  * Returns the number of bytes valid in the buffer.
8534  */
8535 static int
8536 sata_build_lsense_page_30(
8537 	sata_drive_info_t *sdinfo,
8538 	uint8_t *buf,
8539 	sata_hba_inst_t *sata_hba_inst)
8540 {
8541 	struct smart_data *smart_data = (struct smart_data *)buf;
8542 	int rval;
8543 
8544 	/* Now do the SMART READ DATA */
8545 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
8546 	if (rval == -1)
8547 		return (0);
8548 
8549 	return (sizeof (struct smart_data));
8550 }
8551 
8552 /*
8553  * sata_build_lsense_page_0e() is used to create the
8554  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
8555  *
8556  * Date of Manufacture (0x0001)
8557  *	YEAR = "0000"
8558  *	WEEK = "00"
8559  * Accounting Date (0x0002)
8560  *	6 ASCII space character(20h)
8561  * Specified cycle count over device lifetime
8562  *	VALUE - THRESH - the delta between max and min;
8563  * Accumulated start-stop cycles
8564  *	VALUE - WORST - the accumulated cycles;
8565  *
8566  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
8567  *
8568  * Takes a sata_drive_info t * and the address of a buffer
8569  * in which to create the page information as well as a sata_hba_inst_t *.
8570  *
8571  * Returns the number of bytes valid in the buffer.
8572  */
8573 static	int
8574 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
8575 	sata_pkt_txlate_t *spx)
8576 {
8577 	struct start_stop_cycle_counter_log *log_page;
8578 	int i, rval, index;
8579 	uint8_t smart_data[512], id, value, worst, thresh;
8580 	uint32_t max_count, cycles;
8581 
8582 	/* Now do the SMART READ DATA */
8583 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
8584 	    (struct smart_data *)smart_data);
8585 	if (rval == -1)
8586 		return (0);
8587 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
8588 		index = (i * 12) + 2;
8589 		id = smart_data[index];
8590 		if (id != SMART_START_STOP_COUNT_ID)
8591 			continue;
8592 		else {
8593 			thresh = smart_data[index + 2];
8594 			value = smart_data[index + 3];
8595 			worst = smart_data[index + 4];
8596 			break;
8597 		}
8598 	}
8599 	if (id != SMART_START_STOP_COUNT_ID)
8600 		return (0);
8601 	max_count = value - thresh;
8602 	cycles = value - worst;
8603 
8604 	log_page = (struct start_stop_cycle_counter_log *)buf;
8605 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
8606 	log_page->code = 0x0e;
8607 	log_page->page_len_low = 0x24;
8608 
8609 	log_page->manufactor_date_low = 0x1;
8610 	log_page->param_1.fmt_link = 0x1; /* 01b */
8611 	log_page->param_len_1 = 0x06;
8612 	for (i = 0; i < 4; i++) {
8613 		log_page->year_manu[i] = 0x30;
8614 		if (i < 2)
8615 			log_page->week_manu[i] = 0x30;
8616 	}
8617 
8618 	log_page->account_date_low = 0x02;
8619 	log_page->param_2.fmt_link = 0x01; /* 01b */
8620 	log_page->param_len_2 = 0x06;
8621 	for (i = 0; i < 4; i++) {
8622 		log_page->year_account[i] = 0x20;
8623 		if (i < 2)
8624 			log_page->week_account[i] = 0x20;
8625 	}
8626 
8627 	log_page->lifetime_code_low = 0x03;
8628 	log_page->param_3.fmt_link = 0x03; /* 11b */
8629 	log_page->param_len_3 = 0x04;
8630 	/* VALUE - THRESH - the delta between max and min */
8631 	log_page->cycle_code_low = 0x04;
8632 	log_page->param_4.fmt_link = 0x03; /* 11b */
8633 	log_page->param_len_4 = 0x04;
8634 	/* WORST - THRESH - the distance from 'now' to min */
8635 
8636 	for (i = 0; i < 4; i++) {
8637 		log_page->cycle_lifetime[i] =
8638 		    (max_count >> (8 * (3 - i))) & 0xff;
8639 		log_page->cycle_accumulated[i] =
8640 		    (cycles >> (8 * (3 - i))) & 0xff;
8641 	}
8642 
8643 	return (sizeof (struct start_stop_cycle_counter_log));
8644 }
8645 
8646 /*
8647  * This function was used for build a ATA read verify sector command
8648  */
8649 static void
8650 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
8651 {
8652 	scmd->satacmd_cmd_reg = SATAC_RDVER;
8653 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
8654 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8655 
8656 	scmd->satacmd_sec_count_lsb = sec & 0xff;
8657 	scmd->satacmd_lba_low_lsb = lba & 0xff;
8658 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
8659 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
8660 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
8661 	scmd->satacmd_features_reg = 0;
8662 	scmd->satacmd_status_reg = 0;
8663 	scmd->satacmd_error_reg = 0;
8664 }
8665 
8666 /*
8667  * This function was used for building an ATA
8668  * command, and only command register need to
8669  * be defined, other register will be zero or na.
8670  */
8671 static void
8672 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
8673 {
8674 	scmd->satacmd_addr_type = 0;
8675 	scmd->satacmd_cmd_reg = cmd;
8676 	scmd->satacmd_device_reg = 0;
8677 	scmd->satacmd_sec_count_lsb = 0;
8678 	scmd->satacmd_lba_low_lsb = 0;
8679 	scmd->satacmd_lba_mid_lsb = 0;
8680 	scmd->satacmd_lba_high_lsb = 0;
8681 	scmd->satacmd_features_reg = 0;
8682 	scmd->satacmd_status_reg = 0;
8683 	scmd->satacmd_error_reg = 0;
8684 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8685 }
8686 
8687 /*
8688  * This function was used for changing the standby
8689  * timer format from SCSI to ATA.
8690  */
8691 static uint8_t
8692 sata_get_standby_timer(uint8_t *timer)
8693 {
8694 	uint32_t i = 0, count = 0;
8695 	uint8_t ata_count;
8696 
8697 	for (i = 0; i < 4; i++) {
8698 		count = count << 8 | timer[i];
8699 	}
8700 
8701 	if (count == 0)
8702 		return (0);
8703 
8704 	if (count >= 1 && count <= 12000)
8705 		ata_count = (count -1) / 50 + 1;
8706 	else if (count > 12000 && count <= 12600)
8707 		ata_count = 0xfc;
8708 	else if (count > 12601 && count <= 12750)
8709 		ata_count = 0xff;
8710 	else if (count > 12750 && count <= 17999)
8711 		ata_count = 0xf1;
8712 	else if (count > 18000 && count <= 198000)
8713 		ata_count = count / 18000 + 240;
8714 	else
8715 		ata_count = 0xfd;
8716 	return (ata_count);
8717 }
8718 
8719 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
8720 
8721 /*
8722  * Start command for ATAPI device.
8723  * This function processes scsi_pkt requests.
8724  * Now CD/DVD, tape and ATAPI disk devices are supported.
8725  * Most commands are packet without any translation into Packet Command.
8726  * Some may be trapped and executed as SATA commands (not clear which one).
8727  *
8728  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
8729  * execution).
8730  * Returns other TRAN_XXXX codes if command is not accepted or completed
8731  * (see return values for sata_hba_start()).
8732  *
8733  * Note:
8734  * Inquiry cdb format differs between transport version 2 and 3.
8735  * However, the transport version 3 devices that were checked did not adhere
8736  * to the specification (ignored MSB of the allocation length). Therefore,
8737  * the transport version is not checked, but Inquiry allocation length is
8738  * truncated to 255 bytes if the original allocation length set-up by the
8739  * target driver is greater than 255 bytes.
8740  */
8741 static int
8742 sata_txlt_atapi(sata_pkt_txlate_t *spx)
8743 {
8744 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8745 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8746 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8747 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
8748 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
8749 	    &spx->txlt_sata_pkt->satapkt_device);
8750 	int cport = SATA_TXLT_CPORT(spx);
8751 	int cdblen;
8752 	int rval, reason;
8753 	int synch;
8754 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
8755 
8756 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8757 
8758 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
8759 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
8760 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8761 		return (rval);
8762 	}
8763 
8764 	/*
8765 	 * ATAPI device executes some ATA commands in addition to those
8766 	 * commands sent via PACKET command. These ATA commands may be
8767 	 * executed by the regular SATA translation functions. None needs
8768 	 * to be captured now.
8769 	 *
8770 	 * Commands sent via PACKET command include:
8771 	 *	MMC command set for ATAPI CD/DVD device
8772 	 *	SSC command set for ATAPI TAPE device
8773 	 *	SBC command set for ATAPI disk device
8774 	 *
8775 	 */
8776 
8777 	/* Check the size of cdb */
8778 
8779 	switch (GETGROUP(cdbp)) {
8780 	case CDB_GROUPID_3:   /* Reserved, per SPC-4 */
8781 		/*
8782 		 * opcodes 0x7e and 0x7f identify variable-length CDBs and
8783 		 * therefore require special handling.  Return failure, for now.
8784 		 */
8785 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8786 		return (TRAN_BADPKT);
8787 
8788 	case CDB_GROUPID_6:   /* Vendor-specific, per SPC-4 */
8789 	case CDB_GROUPID_7:   /* Vendor-specific, per SPC-4 */
8790 		/* obtain length from the scsi_pkt */
8791 		cdblen = scsipkt->pkt_cdblen;
8792 		break;
8793 
8794 	default:
8795 		/* CDB's length is statically known, per SPC-4 */
8796 		cdblen = scsi_cdb_size[GETGROUP(cdbp)];
8797 		break;
8798 	}
8799 
8800 	if (cdblen <= 0 || cdblen > sdinfo->satadrv_atapi_cdb_len) {
8801 		sata_log(NULL, CE_WARN,
8802 		    "sata: invalid ATAPI cdb length %d",
8803 		    cdblen);
8804 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8805 		return (TRAN_BADPKT);
8806 	}
8807 
8808 	SATAATAPITRACE(spx, cdblen);
8809 
8810 	/*
8811 	 * For non-read/write commands we need to
8812 	 * map buffer
8813 	 */
8814 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
8815 	case SCMD_READ:
8816 	case SCMD_READ_G1:
8817 	case SCMD_READ_G5:
8818 	case SCMD_READ_G4:
8819 	case SCMD_WRITE:
8820 	case SCMD_WRITE_G1:
8821 	case SCMD_WRITE_G5:
8822 	case SCMD_WRITE_G4:
8823 		break;
8824 	default:
8825 		if (bp != NULL) {
8826 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
8827 				bp_mapin(bp);
8828 		}
8829 		break;
8830 	}
8831 	/*
8832 	 * scmd->satacmd_flags.sata_data_direction default -
8833 	 * SATA_DIR_NODATA_XFER - is set by
8834 	 * sata_txlt_generic_pkt_info().
8835 	 */
8836 	if (scmd->satacmd_bp) {
8837 		if (scmd->satacmd_bp->b_flags & B_READ) {
8838 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8839 		} else {
8840 			scmd->satacmd_flags.sata_data_direction =
8841 			    SATA_DIR_WRITE;
8842 		}
8843 	}
8844 
8845 	/*
8846 	 * Set up ATAPI packet command.
8847 	 */
8848 
8849 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8850 
8851 	/* Copy cdb into sata_cmd */
8852 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8853 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
8854 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
8855 
8856 	/* See note in the command header */
8857 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
8858 		if (scmd->satacmd_acdb[3] != 0)
8859 			scmd->satacmd_acdb[4] = 255;
8860 	}
8861 
8862 #ifdef SATA_DEBUG
8863 	if (sata_debug_flags & SATA_DBG_ATAPI) {
8864 		uint8_t *p = scmd->satacmd_acdb;
8865 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
8866 
8867 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
8868 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
8869 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
8870 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
8871 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
8872 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
8873 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
8874 	}
8875 #endif
8876 
8877 	/*
8878 	 * Preset request sense data to NO SENSE.
8879 	 * If there is no way to get error information via Request Sense,
8880 	 * the packet request sense data would not have to be modified by HBA,
8881 	 * but it could be returned as is.
8882 	 */
8883 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8884 	sata_fixed_sense_data_preset(
8885 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8886 
8887 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
8888 		/* Need callback function */
8889 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
8890 		synch = FALSE;
8891 	} else
8892 		synch = TRUE;
8893 
8894 	/* Transfer command to HBA */
8895 	if (sata_hba_start(spx, &rval) != 0) {
8896 		/* Pkt not accepted for execution */
8897 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8898 		return (rval);
8899 	}
8900 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8901 	/*
8902 	 * If execution is non-synchronous,
8903 	 * a callback function will handle potential errors, translate
8904 	 * the response and will do a callback to a target driver.
8905 	 * If it was synchronous, use the same framework callback to check
8906 	 * an execution status.
8907 	 */
8908 	if (synch) {
8909 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
8910 		    "synchronous execution status %x\n",
8911 		    spx->txlt_sata_pkt->satapkt_reason);
8912 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
8913 	}
8914 	return (TRAN_ACCEPT);
8915 }
8916 
8917 
8918 /*
8919  * ATAPI Packet command completion.
8920  *
8921  * Failure of the command passed via Packet command are considered device
8922  * error. SATA HBA driver would have to retrieve error data (via Request
8923  * Sense command delivered via error retrieval sata packet) and copy it
8924  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
8925  */
8926 static void
8927 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
8928 {
8929 	sata_pkt_txlate_t *spx =
8930 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
8931 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8932 	struct scsi_extended_sense *sense;
8933 	struct buf *bp;
8934 	int rval;
8935 
8936 #ifdef SATA_DEBUG
8937 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
8938 #endif
8939 
8940 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
8941 	    STATE_SENT_CMD | STATE_GOT_STATUS;
8942 
8943 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
8944 		/* Normal completion */
8945 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
8946 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
8947 		scsipkt->pkt_reason = CMD_CMPLT;
8948 		*scsipkt->pkt_scbp = STATUS_GOOD;
8949 		if (spx->txlt_tmp_buf != NULL) {
8950 			/* Temporary buffer was used */
8951 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8952 			if (bp->b_flags & B_READ) {
8953 				rval = ddi_dma_sync(
8954 				    spx->txlt_buf_dma_handle, 0, 0,
8955 				    DDI_DMA_SYNC_FORCPU);
8956 				ASSERT(rval == DDI_SUCCESS);
8957 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
8958 				    bp->b_bcount);
8959 			}
8960 		}
8961 	} else {
8962 		/*
8963 		 * Something went wrong - analyze return
8964 		 */
8965 		*scsipkt->pkt_scbp = STATUS_CHECK;
8966 		sense = sata_arq_sense(spx);
8967 
8968 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
8969 			/*
8970 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
8971 			 * Under this condition ERR bit is set for ATA command,
8972 			 * and CHK bit set for ATAPI command.
8973 			 *
8974 			 * Please check st_intr & sdintr about how pkt_reason
8975 			 * is used.
8976 			 */
8977 			scsipkt->pkt_reason = CMD_CMPLT;
8978 
8979 			/*
8980 			 * We may not have ARQ data if there was a double
8981 			 * error. But sense data in sata packet was pre-set
8982 			 * with NO SENSE so it is valid even if HBA could
8983 			 * not retrieve a real sense data.
8984 			 * Just copy this sense data into scsi pkt sense area.
8985 			 */
8986 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
8987 			    SATA_ATAPI_MIN_RQSENSE_LEN);
8988 #ifdef SATA_DEBUG
8989 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
8990 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
8991 				    "sata_txlt_atapi_completion: %02x\n"
8992 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
8993 				    "          %02x %02x %02x %02x %02x %02x "
8994 				    "          %02x %02x %02x %02x %02x %02x\n",
8995 				    scsipkt->pkt_reason,
8996 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
8997 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
8998 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
8999 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9000 				    rqsp[16], rqsp[17]);
9001 			}
9002 #endif
9003 		} else {
9004 			switch (sata_pkt->satapkt_reason) {
9005 			case SATA_PKT_PORT_ERROR:
9006 				/*
9007 				 * We have no device data.
9008 				 */
9009 				scsipkt->pkt_reason = CMD_INCOMPLETE;
9010 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9011 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9012 				    STATE_GOT_STATUS);
9013 				sense->es_key = KEY_HARDWARE_ERROR;
9014 				break;
9015 
9016 			case SATA_PKT_TIMEOUT:
9017 				scsipkt->pkt_reason = CMD_TIMEOUT;
9018 				scsipkt->pkt_statistics |=
9019 				    STAT_TIMEOUT | STAT_DEV_RESET;
9020 				/*
9021 				 * Need to check if HARDWARE_ERROR/
9022 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
9023 				 * appropriate.
9024 				 */
9025 				break;
9026 
9027 			case SATA_PKT_ABORTED:
9028 				scsipkt->pkt_reason = CMD_ABORTED;
9029 				scsipkt->pkt_statistics |= STAT_ABORTED;
9030 				/* Should we set key COMMAND_ABPRTED? */
9031 				break;
9032 
9033 			case SATA_PKT_RESET:
9034 				scsipkt->pkt_reason = CMD_RESET;
9035 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
9036 				/*
9037 				 * May be we should set Unit Attention /
9038 				 * Reset. Perhaps the same should be
9039 				 * returned for disks....
9040 				 */
9041 				sense->es_key = KEY_UNIT_ATTENTION;
9042 				sense->es_add_code = SD_SCSI_ASC_RESET;
9043 				break;
9044 
9045 			default:
9046 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9047 				    "sata_txlt_atapi_completion: "
9048 				    "invalid packet completion reason"));
9049 				scsipkt->pkt_reason = CMD_TRAN_ERR;
9050 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9051 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9052 				    STATE_GOT_STATUS);
9053 				break;
9054 			}
9055 		}
9056 	}
9057 
9058 	SATAATAPITRACE(spx, 0);
9059 
9060 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
9061 	    scsipkt->pkt_comp != NULL) {
9062 		/* scsi callback required */
9063 		(*scsipkt->pkt_comp)(scsipkt);
9064 	}
9065 }
9066 
9067 /*
9068  * Set up error retrieval sata command for ATAPI Packet Command error data
9069  * recovery.
9070  *
9071  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
9072  * returns SATA_FAILURE otherwise.
9073  */
9074 
9075 static int
9076 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
9077 {
9078 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
9079 	sata_cmd_t *scmd;
9080 	struct buf *bp;
9081 
9082 	/*
9083 	 * Allocate dma-able buffer error data.
9084 	 * Buffer allocation will take care of buffer alignment and other DMA
9085 	 * attributes.
9086 	 */
9087 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
9088 	if (bp == NULL) {
9089 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
9090 		    "sata_get_err_retrieval_pkt: "
9091 		    "cannot allocate buffer for error data", NULL);
9092 		return (SATA_FAILURE);
9093 	}
9094 	bp_mapin(bp); /* make data buffer accessible */
9095 
9096 	/* Operation modes are up to the caller */
9097 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9098 
9099 	/* Synchronous mode, no callback - may be changed by the caller */
9100 	spkt->satapkt_comp = NULL;
9101 	spkt->satapkt_time = sata_default_pkt_time;
9102 
9103 	scmd = &spkt->satapkt_cmd;
9104 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9105 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9106 
9107 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9108 
9109 	/*
9110 	 * Set-up acdb. Request Sense CDB (packet command content) is
9111 	 * not in DMA-able buffer. Its handling is HBA-specific (how
9112 	 * it is transfered into packet FIS).
9113 	 */
9114 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9115 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
9116 	/* Following zeroing of pad bytes may not be necessary */
9117 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
9118 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
9119 
9120 	/*
9121 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
9122 	 * before accessing it. Handle is in usual place in translate struct.
9123 	 */
9124 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
9125 
9126 	/*
9127 	 * Preset request sense data to NO SENSE.
9128 	 * Here it is redundant, only for a symetry with scsi-originated
9129 	 * packets. It should not be used for anything but debugging.
9130 	 */
9131 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9132 	sata_fixed_sense_data_preset(
9133 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9134 
9135 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9136 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9137 
9138 	return (SATA_SUCCESS);
9139 }
9140 
9141 /*
9142  * Set-up ATAPI packet command.
9143  * Data transfer direction has to be set-up in sata_cmd structure prior to
9144  * calling this function.
9145  *
9146  * Returns void
9147  */
9148 
9149 static void
9150 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
9151 {
9152 	scmd->satacmd_addr_type = 0;		/* N/A */
9153 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
9154 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
9155 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
9156 	scmd->satacmd_lba_high_lsb =
9157 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
9158 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
9159 
9160 	/*
9161 	 * We want all data to be transfered via DMA.
9162 	 * But specify it only if drive supports DMA and DMA mode is
9163 	 * selected - some drives are sensitive about it.
9164 	 * Hopefully it wil work for all drives....
9165 	 */
9166 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
9167 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
9168 
9169 	/*
9170 	 * Features register requires special care for devices that use
9171 	 * Serial ATA bridge - they need an explicit specification of
9172 	 * the data transfer direction for Packet DMA commands.
9173 	 * Setting this bit is harmless if DMA is not used.
9174 	 *
9175 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
9176 	 * spec they follow.
9177 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
9178 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
9179 	 * ATA/ATAPI-7 support is explicitly indicated.
9180 	 */
9181 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9182 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
9183 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
9184 		/*
9185 		 * Specification of major version is valid and version 7
9186 		 * is supported. It does automatically imply that all
9187 		 * spec features are supported. For now, we assume that
9188 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
9189 		 */
9190 		if ((sdinfo->satadrv_id.ai_dirdma &
9191 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
9192 			if (scmd->satacmd_flags.sata_data_direction ==
9193 			    SATA_DIR_READ)
9194 			scmd->satacmd_features_reg |=
9195 			    SATA_ATAPI_F_DATA_DIR_READ;
9196 		}
9197 	}
9198 }
9199 
9200 
9201 #ifdef SATA_DEBUG
9202 
9203 /* Display 18 bytes of Inquiry data */
9204 static void
9205 sata_show_inqry_data(uint8_t *buf)
9206 {
9207 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9208 	uint8_t *p;
9209 
9210 	cmn_err(CE_NOTE, "Inquiry data:");
9211 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9212 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9213 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9214 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9215 	    SATA_ATAPI_TRANS_VERSION(inq));
9216 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9217 	    inq->inq_rdf, inq->inq_aenc);
9218 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9219 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9220 	p = (uint8_t *)inq->inq_vid;
9221 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9222 	    "%02x %02x %02x %02x",
9223 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9224 	p = (uint8_t *)inq->inq_vid;
9225 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9226 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9227 
9228 	p = (uint8_t *)inq->inq_pid;
9229 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9230 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9231 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9232 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9233 	p = (uint8_t *)inq->inq_pid;
9234 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9235 	    "%c %c %c %c %c %c %c %c",
9236 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9237 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9238 
9239 	p = (uint8_t *)inq->inq_revision;
9240 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9241 	    p[0], p[1], p[2], p[3]);
9242 	p = (uint8_t *)inq->inq_revision;
9243 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9244 	    p[0], p[1], p[2], p[3]);
9245 
9246 }
9247 
9248 
9249 static void
9250 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9251 {
9252 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9253 
9254 	if (scsi_pkt == NULL)
9255 		return;
9256 	if (count != 0) {
9257 		/* saving cdb */
9258 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9259 		    SATA_ATAPI_MAX_CDB_LEN);
9260 		bcopy(scsi_pkt->pkt_cdbp,
9261 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9262 	} else {
9263 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9264 		    sts_sensedata,
9265 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9266 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9267 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9268 		    scsi_pkt->pkt_reason;
9269 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9270 		    spx->txlt_sata_pkt->satapkt_reason;
9271 
9272 		if (++sata_atapi_trace_index >= 64)
9273 			sata_atapi_trace_index = 0;
9274 	}
9275 }
9276 
9277 #endif
9278 
9279 /*
9280  * Fetch inquiry data from ATAPI device
9281  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
9282  *
9283  * Note:
9284  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9285  * where the caller expects to see the inquiry data.
9286  *
9287  */
9288 
9289 static int
9290 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9291     sata_address_t *saddr, struct scsi_inquiry *inq)
9292 {
9293 	sata_pkt_txlate_t *spx;
9294 	sata_pkt_t *spkt;
9295 	struct buf *bp;
9296 	sata_drive_info_t *sdinfo;
9297 	sata_cmd_t *scmd;
9298 	int rval;
9299 	uint8_t *rqsp;
9300 #ifdef SATA_DEBUG
9301 	char msg_buf[MAXPATHLEN];
9302 #endif
9303 
9304 	ASSERT(sata_hba != NULL);
9305 
9306 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9307 	spx->txlt_sata_hba_inst = sata_hba;
9308 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9309 	spkt = sata_pkt_alloc(spx, NULL);
9310 	if (spkt == NULL) {
9311 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9312 		return (SATA_FAILURE);
9313 	}
9314 	/* address is needed now */
9315 	spkt->satapkt_device.satadev_addr = *saddr;
9316 
9317 	/* scsi_inquiry size buffer */
9318 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9319 	if (bp == NULL) {
9320 		sata_pkt_free(spx);
9321 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9322 		SATA_LOG_D((sata_hba, CE_WARN,
9323 		    "sata_get_atapi_inquiry_data: "
9324 		    "cannot allocate data buffer"));
9325 		return (SATA_FAILURE);
9326 	}
9327 	bp_mapin(bp); /* make data buffer accessible */
9328 
9329 	scmd = &spkt->satapkt_cmd;
9330 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9331 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9332 
9333 	/* Use synchronous mode */
9334 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9335 	spkt->satapkt_comp = NULL;
9336 	spkt->satapkt_time = sata_default_pkt_time;
9337 
9338 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9339 
9340 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9341 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9342 
9343 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
9344 	sdinfo = sata_get_device_info(sata_hba,
9345 	    &spx->txlt_sata_pkt->satapkt_device);
9346 	if (sdinfo == NULL) {
9347 		/* we have to be carefull about the disapearing device */
9348 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9349 		rval = SATA_FAILURE;
9350 		goto cleanup;
9351 	}
9352 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9353 
9354 	/*
9355 	 * Set-up acdb. This works for atapi transport version 2 and later.
9356 	 */
9357 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9358 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9359 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9360 	scmd->satacmd_acdb[1] = 0x00;
9361 	scmd->satacmd_acdb[2] = 0x00;
9362 	scmd->satacmd_acdb[3] = 0x00;
9363 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9364 	scmd->satacmd_acdb[5] = 0x00;
9365 
9366 	sata_fixed_sense_data_preset(
9367 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9368 
9369 	/* Transfer command to HBA */
9370 	if (sata_hba_start(spx, &rval) != 0) {
9371 		/* Pkt not accepted for execution */
9372 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9373 		    "sata_get_atapi_inquiry_data: "
9374 		    "Packet not accepted for execution - ret: %02x", rval);
9375 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9376 		rval = SATA_FAILURE;
9377 		goto cleanup;
9378 	}
9379 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9380 
9381 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9382 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9383 		    "sata_get_atapi_inquiry_data: "
9384 		    "Packet completed successfully - ret: %02x", rval);
9385 		if (spx->txlt_buf_dma_handle != NULL) {
9386 			/*
9387 			 * Sync buffer. Handle is in usual place in translate
9388 			 * struct.
9389 			 */
9390 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9391 			    DDI_DMA_SYNC_FORCPU);
9392 			ASSERT(rval == DDI_SUCCESS);
9393 		}
9394 		/*
9395 		 * Normal completion - copy data into caller's buffer
9396 		 */
9397 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
9398 		    sizeof (struct scsi_inquiry));
9399 #ifdef SATA_DEBUG
9400 		if (sata_debug_flags & SATA_DBG_ATAPI) {
9401 			sata_show_inqry_data((uint8_t *)inq);
9402 		}
9403 #endif
9404 		rval = SATA_SUCCESS;
9405 	} else {
9406 		/*
9407 		 * Something went wrong - analyze return - check rqsense data
9408 		 */
9409 		rval = SATA_FAILURE;
9410 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9411 			/*
9412 			 * ARQ data hopefull show something other than NO SENSE
9413 			 */
9414 			rqsp = scmd->satacmd_rqsense;
9415 #ifdef SATA_DEBUG
9416 			if (sata_debug_flags & SATA_DBG_ATAPI) {
9417 				msg_buf[0] = '\0';
9418 				(void) snprintf(msg_buf, MAXPATHLEN,
9419 				    "ATAPI packet completion reason: %02x\n"
9420 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
9421 				    "          %02x %02x %02x %02x %02x %02x\n"
9422 				    "          %02x %02x %02x %02x %02x %02x",
9423 				    spkt->satapkt_reason,
9424 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9425 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9426 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9427 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9428 				    rqsp[16], rqsp[17]);
9429 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9430 				    "%s", msg_buf);
9431 			}
9432 #endif
9433 		} else {
9434 			switch (spkt->satapkt_reason) {
9435 			case SATA_PKT_PORT_ERROR:
9436 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9437 				    "sata_get_atapi_inquiry_data: "
9438 				    "packet reason: port error", NULL);
9439 				break;
9440 
9441 			case SATA_PKT_TIMEOUT:
9442 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9443 				    "sata_get_atapi_inquiry_data: "
9444 				    "packet reason: timeout", NULL);
9445 				break;
9446 
9447 			case SATA_PKT_ABORTED:
9448 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9449 				    "sata_get_atapi_inquiry_data: "
9450 				    "packet reason: aborted", NULL);
9451 				break;
9452 
9453 			case SATA_PKT_RESET:
9454 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9455 				    "sata_get_atapi_inquiry_data: "
9456 				    "packet reason: reset\n", NULL);
9457 				break;
9458 			default:
9459 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9460 				    "sata_get_atapi_inquiry_data: "
9461 				    "invalid packet reason: %02x\n",
9462 				    spkt->satapkt_reason);
9463 				break;
9464 			}
9465 		}
9466 	}
9467 cleanup:
9468 	sata_free_local_buffer(spx);
9469 	sata_pkt_free(spx);
9470 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9471 	return (rval);
9472 }
9473 
9474 
9475 
9476 
9477 
9478 #if 0
9479 #ifdef SATA_DEBUG
9480 
9481 /*
9482  * Test ATAPI packet command.
9483  * Single threaded test: send packet command in synch mode, process completion
9484  *
9485  */
9486 static void
9487 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
9488 {
9489 	sata_pkt_txlate_t *spx;
9490 	sata_pkt_t *spkt;
9491 	struct buf *bp;
9492 	sata_device_t sata_device;
9493 	sata_drive_info_t *sdinfo;
9494 	sata_cmd_t *scmd;
9495 	int rval;
9496 	uint8_t *rqsp;
9497 
9498 	ASSERT(sata_hba_inst != NULL);
9499 	sata_device.satadev_addr.cport = cport;
9500 	sata_device.satadev_addr.pmport = 0;
9501 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
9502 	sata_device.satadev_rev = SATA_DEVICE_REV;
9503 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9504 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
9505 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9506 	if (sdinfo == NULL) {
9507 		sata_log(sata_hba_inst, CE_WARN,
9508 		    "sata_test_atapi_packet_command: "
9509 		    "no device info for cport %d",
9510 		    sata_device.satadev_addr.cport);
9511 		return;
9512 	}
9513 
9514 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9515 	spx->txlt_sata_hba_inst = sata_hba_inst;
9516 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9517 	spkt = sata_pkt_alloc(spx, NULL);
9518 	if (spkt == NULL) {
9519 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9520 		return;
9521 	}
9522 	/* address is needed now */
9523 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
9524 
9525 	/* 1024k buffer */
9526 	bp = sata_alloc_local_buffer(spx, 1024);
9527 	if (bp == NULL) {
9528 		sata_pkt_free(spx);
9529 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9530 		sata_log(sata_hba_inst, CE_WARN,
9531 		    "sata_test_atapi_packet_command: "
9532 		    "cannot allocate data buffer");
9533 		return;
9534 	}
9535 	bp_mapin(bp); /* make data buffer accessible */
9536 
9537 	scmd = &spkt->satapkt_cmd;
9538 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9539 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9540 
9541 	/* Use synchronous mode */
9542 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9543 
9544 	/* Synchronous mode, no callback - may be changed by the caller */
9545 	spkt->satapkt_comp = NULL;
9546 	spkt->satapkt_time = sata_default_pkt_time;
9547 
9548 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9549 
9550 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9551 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9552 
9553 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9554 
9555 	/* Set-up acdb. */
9556 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9557 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9558 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9559 	scmd->satacmd_acdb[1] = 0x00;
9560 	scmd->satacmd_acdb[2] = 0x00;
9561 	scmd->satacmd_acdb[3] = 0x00;
9562 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9563 	scmd->satacmd_acdb[5] = 0x00;
9564 
9565 	sata_fixed_sense_data_preset(
9566 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9567 
9568 	/* Transfer command to HBA */
9569 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9570 	if (sata_hba_start(spx, &rval) != 0) {
9571 		/* Pkt not accepted for execution */
9572 		sata_log(sata_hba_inst, CE_WARN,
9573 		    "sata_test_atapi_packet_command: "
9574 		    "Packet not accepted for execution - ret: %02x", rval);
9575 		mutex_exit(
9576 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9577 		goto cleanup;
9578 	}
9579 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9580 
9581 	if (spx->txlt_buf_dma_handle != NULL) {
9582 		/*
9583 		 * Sync buffer. Handle is in usual place in translate struct.
9584 		 */
9585 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9586 		    DDI_DMA_SYNC_FORCPU);
9587 		ASSERT(rval == DDI_SUCCESS);
9588 	}
9589 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9590 		sata_log(sata_hba_inst, CE_WARN,
9591 		    "sata_test_atapi_packet_command: "
9592 		    "Packet completed successfully");
9593 		/*
9594 		 * Normal completion - show inquiry data
9595 		 */
9596 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
9597 	} else {
9598 		/*
9599 		 * Something went wrong - analyze return - check rqsense data
9600 		 */
9601 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9602 			/*
9603 			 * ARQ data hopefull show something other than NO SENSE
9604 			 */
9605 			rqsp = scmd->satacmd_rqsense;
9606 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9607 			    "ATAPI packet completion reason: %02x\n"
9608 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9609 			    "          %02x %02x %02x %02x %02x %02x "
9610 			    "          %02x %02x %02x %02x %02x %02x\n",
9611 			    spkt->satapkt_reason,
9612 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9613 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9614 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9615 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9616 			    rqsp[16], rqsp[17]);
9617 		} else {
9618 			switch (spkt->satapkt_reason) {
9619 			case SATA_PKT_PORT_ERROR:
9620 				sata_log(sata_hba_inst, CE_WARN,
9621 				    "sata_test_atapi_packet_command: "
9622 				    "packet reason: port error\n");
9623 				break;
9624 
9625 			case SATA_PKT_TIMEOUT:
9626 				sata_log(sata_hba_inst, CE_WARN,
9627 				    "sata_test_atapi_packet_command: "
9628 				    "packet reason: timeout\n");
9629 				break;
9630 
9631 			case SATA_PKT_ABORTED:
9632 				sata_log(sata_hba_inst, CE_WARN,
9633 				    "sata_test_atapi_packet_command: "
9634 				    "packet reason: aborted\n");
9635 				break;
9636 
9637 			case SATA_PKT_RESET:
9638 				sata_log(sata_hba_inst, CE_WARN,
9639 				    "sata_test_atapi_packet_command: "
9640 				    "packet reason: reset\n");
9641 				break;
9642 			default:
9643 				sata_log(sata_hba_inst, CE_WARN,
9644 				    "sata_test_atapi_packet_command: "
9645 				    "invalid packet reason: %02x\n",
9646 				    spkt->satapkt_reason);
9647 				break;
9648 			}
9649 		}
9650 	}
9651 cleanup:
9652 	sata_free_local_buffer(spx);
9653 	sata_pkt_free(spx);
9654 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9655 }
9656 
9657 #endif /* SATA_DEBUG */
9658 #endif /* 1 */
9659 
9660 
9661 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
9662 
9663 /*
9664  * Validate sata_tran info
9665  * SATA_FAILURE returns if structure is inconsistent or structure revision
9666  * does not match one used by the framework.
9667  *
9668  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
9669  * required function pointers.
9670  * Returns SATA_FAILURE otherwise.
9671  */
9672 static int
9673 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
9674 {
9675 	/*
9676 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
9677 	 * of the SATA interface.
9678 	 */
9679 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
9680 		sata_log(NULL, CE_WARN,
9681 		    "sata: invalid sata_hba_tran version %d for driver %s",
9682 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
9683 		return (SATA_FAILURE);
9684 	}
9685 
9686 	if (dip != sata_tran->sata_tran_hba_dip) {
9687 		SATA_LOG_D((NULL, CE_WARN,
9688 		    "sata: inconsistent sata_tran_hba_dip "
9689 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
9690 		return (SATA_FAILURE);
9691 	}
9692 
9693 	if (sata_tran->sata_tran_probe_port == NULL ||
9694 	    sata_tran->sata_tran_start == NULL ||
9695 	    sata_tran->sata_tran_abort == NULL ||
9696 	    sata_tran->sata_tran_reset_dport == NULL ||
9697 	    sata_tran->sata_tran_hotplug_ops == NULL ||
9698 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
9699 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
9700 	    NULL) {
9701 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
9702 		    "required functions"));
9703 	}
9704 	return (SATA_SUCCESS);
9705 }
9706 
9707 /*
9708  * Remove HBA instance from sata_hba_list.
9709  */
9710 static void
9711 sata_remove_hba_instance(dev_info_t *dip)
9712 {
9713 	sata_hba_inst_t	*sata_hba_inst;
9714 
9715 	mutex_enter(&sata_mutex);
9716 	for (sata_hba_inst = sata_hba_list;
9717 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
9718 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9719 		if (sata_hba_inst->satahba_dip == dip)
9720 			break;
9721 	}
9722 
9723 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
9724 #ifdef SATA_DEBUG
9725 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
9726 		    "unknown HBA instance\n");
9727 #endif
9728 		ASSERT(FALSE);
9729 	}
9730 	if (sata_hba_inst == sata_hba_list) {
9731 		sata_hba_list = sata_hba_inst->satahba_next;
9732 		if (sata_hba_list) {
9733 			sata_hba_list->satahba_prev =
9734 			    (struct sata_hba_inst *)NULL;
9735 		}
9736 		if (sata_hba_inst == sata_hba_list_tail) {
9737 			sata_hba_list_tail = NULL;
9738 		}
9739 	} else if (sata_hba_inst == sata_hba_list_tail) {
9740 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
9741 		if (sata_hba_list_tail) {
9742 			sata_hba_list_tail->satahba_next =
9743 			    (struct sata_hba_inst *)NULL;
9744 		}
9745 	} else {
9746 		sata_hba_inst->satahba_prev->satahba_next =
9747 		    sata_hba_inst->satahba_next;
9748 		sata_hba_inst->satahba_next->satahba_prev =
9749 		    sata_hba_inst->satahba_prev;
9750 	}
9751 	mutex_exit(&sata_mutex);
9752 }
9753 
9754 /*
9755  * Probe all SATA ports of the specified HBA instance.
9756  * The assumption is that there are no target and attachment point minor nodes
9757  * created by the boot subsystems, so we do not need to prune device tree.
9758  *
9759  * This function is called only from sata_hba_attach(). It does not have to
9760  * be protected by controller mutex, because the hba_attached flag is not set
9761  * yet and no one would be touching this HBA instance other than this thread.
9762  * Determines if port is active and what type of the device is attached
9763  * (if any). Allocates necessary structures for each port.
9764  *
9765  * An AP (Attachement Point) node is created for each SATA device port even
9766  * when there is no device attached.
9767  */
9768 
9769 static 	void
9770 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
9771 {
9772 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9773 	int			ncport;
9774 	sata_cport_info_t 	*cportinfo;
9775 	sata_drive_info_t	*drive;
9776 	sata_device_t		sata_device;
9777 	int			rval;
9778 	dev_t			minor_number;
9779 	char			name[16];
9780 	clock_t			start_time, cur_time;
9781 
9782 	/*
9783 	 * Probe controller ports first, to find port status and
9784 	 * any port multiplier attached.
9785 	 */
9786 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
9787 		/* allocate cport structure */
9788 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
9789 		ASSERT(cportinfo != NULL);
9790 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
9791 
9792 		mutex_enter(&cportinfo->cport_mutex);
9793 
9794 		cportinfo->cport_addr.cport = ncport;
9795 		cportinfo->cport_addr.pmport = 0;
9796 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
9797 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
9798 		cportinfo->cport_state |= SATA_STATE_PROBING;
9799 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
9800 
9801 		/*
9802 		 * Regardless if a port is usable or not, create
9803 		 * an attachment point
9804 		 */
9805 		mutex_exit(&cportinfo->cport_mutex);
9806 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
9807 		    ncport, 0, SATA_ADDR_CPORT);
9808 		(void) sprintf(name, "%d", ncport);
9809 		if (ddi_create_minor_node(dip, name, S_IFCHR,
9810 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
9811 		    DDI_SUCCESS) {
9812 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
9813 			    "cannot create SATA attachment point for port %d",
9814 			    ncport);
9815 		}
9816 
9817 		/* Probe port */
9818 		start_time = ddi_get_lbolt();
9819 	reprobe_cport:
9820 		sata_device.satadev_addr.cport = ncport;
9821 		sata_device.satadev_addr.pmport = 0;
9822 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
9823 		sata_device.satadev_rev = SATA_DEVICE_REV;
9824 
9825 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9826 		    (dip, &sata_device);
9827 
9828 		mutex_enter(&cportinfo->cport_mutex);
9829 		cportinfo->cport_scr = sata_device.satadev_scr;
9830 		if (rval != SATA_SUCCESS) {
9831 			/* Something went wrong? Fail the port */
9832 			cportinfo->cport_state = SATA_PSTATE_FAILED;
9833 			mutex_exit(&cportinfo->cport_mutex);
9834 			continue;
9835 		}
9836 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
9837 		cportinfo->cport_state |= SATA_STATE_PROBED;
9838 		cportinfo->cport_dev_type = sata_device.satadev_type;
9839 
9840 		cportinfo->cport_state |= SATA_STATE_READY;
9841 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
9842 			mutex_exit(&cportinfo->cport_mutex);
9843 			continue;
9844 		}
9845 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
9846 			/*
9847 			 * There is some device attached.
9848 			 * Allocate device info structure
9849 			 */
9850 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
9851 				mutex_exit(&cportinfo->cport_mutex);
9852 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
9853 				    kmem_zalloc(sizeof (sata_drive_info_t),
9854 				    KM_SLEEP);
9855 				mutex_enter(&cportinfo->cport_mutex);
9856 			}
9857 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
9858 			drive->satadrv_addr = cportinfo->cport_addr;
9859 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
9860 			drive->satadrv_type = cportinfo->cport_dev_type;
9861 			drive->satadrv_state = SATA_STATE_UNKNOWN;
9862 
9863 			mutex_exit(&cportinfo->cport_mutex);
9864 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
9865 			    SATA_SUCCESS) {
9866 				/*
9867 				 * Plugged device was not correctly identified.
9868 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
9869 				 */
9870 				cur_time = ddi_get_lbolt();
9871 				if ((cur_time - start_time) <
9872 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
9873 					/* sleep for a while */
9874 					delay(drv_usectohz(
9875 					    SATA_DEV_RETRY_DLY));
9876 					goto reprobe_cport;
9877 				}
9878 			}
9879 		} else { /* SATA_DTYPE_PMULT */
9880 			mutex_exit(&cportinfo->cport_mutex);
9881 
9882 			/* Allocate sata_pmult_info and sata_pmport_info */
9883 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
9884 			    SATA_SUCCESS)
9885 				continue;
9886 
9887 			/* Log the information of the port multiplier */
9888 			sata_show_pmult_info(sata_hba_inst, &sata_device);
9889 
9890 			/* Probe its pmports */
9891 			sata_probe_pmports(sata_hba_inst, ncport);
9892 		}
9893 	}
9894 }
9895 
9896 /*
9897  * Probe all device ports behind a port multiplier.
9898  *
9899  * PMult-related structure should be allocated before by sata_alloc_pmult().
9900  *
9901  * NOTE1: Only called from sata_probe_ports()
9902  * NOTE2: No mutex should be hold.
9903  */
9904 static void
9905 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
9906 {
9907 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9908 	sata_pmult_info_t	*pmultinfo = NULL;
9909 	sata_pmport_info_t 	*pmportinfo = NULL;
9910 	sata_drive_info_t	*drive = NULL;
9911 	sata_device_t		sata_device;
9912 
9913 	clock_t			start_time, cur_time;
9914 	int			npmport;
9915 	int			rval;
9916 
9917 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
9918 
9919 	/* Probe Port Multiplier ports */
9920 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
9921 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
9922 		start_time = ddi_get_lbolt();
9923 reprobe_pmport:
9924 		sata_device.satadev_addr.cport = ncport;
9925 		sata_device.satadev_addr.pmport = npmport;
9926 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
9927 		sata_device.satadev_rev = SATA_DEVICE_REV;
9928 
9929 		/* Let HBA driver probe it. */
9930 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9931 		    (dip, &sata_device);
9932 		mutex_enter(&pmportinfo->pmport_mutex);
9933 
9934 		pmportinfo->pmport_scr = sata_device.satadev_scr;
9935 
9936 		if (rval != SATA_SUCCESS) {
9937 			pmportinfo->pmport_state =
9938 			    SATA_PSTATE_FAILED;
9939 			mutex_exit(&pmportinfo->pmport_mutex);
9940 			continue;
9941 		}
9942 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
9943 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
9944 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
9945 
9946 		pmportinfo->pmport_state |= SATA_STATE_READY;
9947 		if (pmportinfo->pmport_dev_type ==
9948 		    SATA_DTYPE_NONE) {
9949 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
9950 			    "no device found at port %d:%d", ncport, npmport);
9951 			mutex_exit(&pmportinfo->pmport_mutex);
9952 			continue;
9953 		}
9954 		/* Port multipliers cannot be chained */
9955 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
9956 		/*
9957 		 * There is something attached to Port
9958 		 * Multiplier device port
9959 		 * Allocate device info structure
9960 		 */
9961 		if (pmportinfo->pmport_sata_drive == NULL) {
9962 			mutex_exit(&pmportinfo->pmport_mutex);
9963 			pmportinfo->pmport_sata_drive =
9964 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
9965 			mutex_enter(&pmportinfo->pmport_mutex);
9966 		}
9967 		drive = pmportinfo->pmport_sata_drive;
9968 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
9969 		drive->satadrv_addr.pmport = npmport;
9970 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
9971 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
9972 		drive->satadrv_state = SATA_STATE_UNKNOWN;
9973 
9974 		mutex_exit(&pmportinfo->pmport_mutex);
9975 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
9976 
9977 		if (rval != SATA_SUCCESS) {
9978 			/*
9979 			 * Plugged device was not correctly identified.
9980 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
9981 			 */
9982 			cur_time = ddi_get_lbolt();
9983 			if ((cur_time - start_time) < drv_usectohz(
9984 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
9985 				/* sleep for a while */
9986 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
9987 				goto reprobe_pmport;
9988 			}
9989 		}
9990 	}
9991 }
9992 
9993 /*
9994  * Add SATA device for specified HBA instance & port (SCSI target
9995  * device nodes).
9996  * This function is called (indirectly) only from sata_hba_attach().
9997  * A target node is created when there is a supported type device attached,
9998  * but may be removed if it cannot be put online.
9999  *
10000  * This function cannot be called from an interrupt context.
10001  *
10002  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
10003  *
10004  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
10005  * device identification failed - adding a device could be retried.
10006  *
10007  */
10008 static 	int
10009 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
10010     sata_device_t *sata_device)
10011 {
10012 	sata_cport_info_t 	*cportinfo;
10013 	sata_pmult_info_t	*pminfo;
10014 	sata_pmport_info_t	*pmportinfo;
10015 	dev_info_t		*cdip;		/* child dip */
10016 	sata_address_t		*saddr = &sata_device->satadev_addr;
10017 	uint8_t			cport, pmport;
10018 	int			rval;
10019 
10020 	cport = saddr->cport;
10021 	pmport = saddr->pmport;
10022 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10023 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
10024 
10025 	/*
10026 	 * Some device is attached to a controller port.
10027 	 * We rely on controllers distinquishing between no-device,
10028 	 * attached port multiplier and other kind of attached device.
10029 	 * We need to get Identify Device data and determine
10030 	 * positively the dev type before trying to attach
10031 	 * the target driver.
10032 	 */
10033 	sata_device->satadev_rev = SATA_DEVICE_REV;
10034 	switch (saddr->qual) {
10035 	case SATA_ADDR_CPORT:
10036 		/*
10037 		 * Add a non-port-multiplier device at controller port.
10038 		 */
10039 		saddr->qual = SATA_ADDR_DCPORT;
10040 
10041 		rval = sata_probe_device(sata_hba_inst, sata_device);
10042 		if (rval != SATA_SUCCESS ||
10043 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
10044 			return (SATA_FAILURE);
10045 
10046 		mutex_enter(&cportinfo->cport_mutex);
10047 		sata_show_drive_info(sata_hba_inst,
10048 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
10049 
10050 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10051 			/*
10052 			 * Could not determine device type or
10053 			 * a device is not supported.
10054 			 * Degrade this device to unknown.
10055 			 */
10056 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10057 			mutex_exit(&cportinfo->cport_mutex);
10058 			return (SATA_SUCCESS);
10059 		}
10060 		cportinfo->cport_dev_type = sata_device->satadev_type;
10061 		cportinfo->cport_tgtnode_clean = B_TRUE;
10062 		mutex_exit(&cportinfo->cport_mutex);
10063 
10064 		/*
10065 		 * Initialize device to the desired state. Even if it
10066 		 * fails, the device will still attach but syslog
10067 		 * will show the warning.
10068 		 */
10069 		if (sata_initialize_device(sata_hba_inst,
10070 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
10071 			/* Retry */
10072 			rval = sata_initialize_device(sata_hba_inst,
10073 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
10074 
10075 			if (rval == SATA_RETRY)
10076 				sata_log(sata_hba_inst, CE_WARN,
10077 				    "SATA device at port %d - "
10078 				    "default device features could not be set."
10079 				    " Device may not operate as expected.",
10080 				    cport);
10081 		}
10082 
10083 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10084 		if (cdip == NULL) {
10085 			/*
10086 			 * Attaching target node failed.
10087 			 * We retain sata_drive_info structure...
10088 			 */
10089 			return (SATA_SUCCESS);
10090 		}
10091 
10092 		mutex_enter(&cportinfo->cport_mutex);
10093 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
10094 		    satadrv_state = SATA_STATE_READY;
10095 		mutex_exit(&cportinfo->cport_mutex);
10096 
10097 		break;
10098 
10099 	case SATA_ADDR_PMPORT:
10100 		saddr->qual = SATA_ADDR_DPMPORT;
10101 
10102 		mutex_enter(&cportinfo->cport_mutex);
10103 		/* It must be a Port Multiplier at the controller port */
10104 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
10105 
10106 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
10107 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
10108 		mutex_exit(&cportinfo->cport_mutex);
10109 
10110 		rval = sata_probe_device(sata_hba_inst, sata_device);
10111 		if (rval != SATA_SUCCESS ||
10112 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
10113 			return (SATA_FAILURE);
10114 		}
10115 
10116 		mutex_enter(&pmportinfo->pmport_mutex);
10117 		sata_show_drive_info(sata_hba_inst,
10118 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
10119 
10120 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10121 			/*
10122 			 * Could not determine device type.
10123 			 * Degrade this device to unknown.
10124 			 */
10125 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10126 			mutex_exit(&pmportinfo->pmport_mutex);
10127 			return (SATA_SUCCESS);
10128 		}
10129 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
10130 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
10131 		mutex_exit(&pmportinfo->pmport_mutex);
10132 
10133 		/*
10134 		 * Initialize device to the desired state.
10135 		 * Even if it fails, the device will still
10136 		 * attach but syslog will show the warning.
10137 		 */
10138 		if (sata_initialize_device(sata_hba_inst,
10139 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
10140 			/* Retry */
10141 			rval = sata_initialize_device(sata_hba_inst,
10142 			    pmportinfo->pmport_sata_drive);
10143 
10144 			if (rval == SATA_RETRY)
10145 				sata_log(sata_hba_inst, CE_WARN,
10146 				    "SATA device at port %d:%d - "
10147 				    "default device features could not be set."
10148 				    " Device may not operate as expected.",
10149 				    cport, pmport);
10150 		}
10151 
10152 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10153 		if (cdip == NULL) {
10154 			/*
10155 			 * Attaching target node failed.
10156 			 * We retain sata_drive_info structure...
10157 			 */
10158 			return (SATA_SUCCESS);
10159 		}
10160 		mutex_enter(&pmportinfo->pmport_mutex);
10161 		pmportinfo->pmport_sata_drive->satadrv_state |=
10162 		    SATA_STATE_READY;
10163 		mutex_exit(&pmportinfo->pmport_mutex);
10164 
10165 		break;
10166 
10167 	default:
10168 		return (SATA_FAILURE);
10169 	}
10170 
10171 	return (SATA_SUCCESS);
10172 }
10173 
10174 /*
10175  * Clean up target node at specific address.
10176  *
10177  * NOTE: No Mutex should be hold.
10178  */
10179 static int
10180 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
10181     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
10182 {
10183 	uint8_t cport, pmport, qual;
10184 	dev_info_t *tdip;
10185 
10186 	cport = sata_device->satadev_addr.cport;
10187 	pmport = sata_device->satadev_addr.pmport;
10188 	qual = sata_device->satadev_addr.qual;
10189 
10190 	if (qual == SATA_ADDR_DCPORT) {
10191 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10192 		    "sata_hba_ioctl: disconnect device at port %d", cport));
10193 	} else {
10194 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10195 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10196 		    cport, pmport));
10197 	}
10198 
10199 	/* We are addressing attached device, not a port */
10200 	sata_device->satadev_addr.qual =
10201 	    sdinfo->satadrv_addr.qual;
10202 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10203 	    &sata_device->satadev_addr);
10204 	if (tdip != NULL && ndi_devi_offline(tdip,
10205 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10206 		/*
10207 		 * Problem :
10208 		 * The target node remained attached.
10209 		 * This happens when the device file was open
10210 		 * or a node was waiting for resources.
10211 		 * Cannot do anything about it.
10212 		 */
10213 		if (qual == SATA_ADDR_DCPORT) {
10214 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10215 			    "sata_hba_ioctl: disconnect: could "
10216 			    "not unconfigure device before "
10217 			    "disconnecting the SATA port %d",
10218 			    cport));
10219 		} else {
10220 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10221 			    "sata_hba_ioctl: disconnect: could "
10222 			    "not unconfigure device before "
10223 			    "disconnecting the SATA port %d:%d",
10224 			    cport, pmport));
10225 		}
10226 		/*
10227 		 * Set DEVICE REMOVED state in the target
10228 		 * node. It will prevent access to the device
10229 		 * even when a new device is attached, until
10230 		 * the old target node is released, removed and
10231 		 * recreated for a new  device.
10232 		 */
10233 		sata_set_device_removed(tdip);
10234 
10235 		/*
10236 		 * Instruct event daemon to try the target
10237 		 * node cleanup later.
10238 		 */
10239 		sata_set_target_node_cleanup(
10240 		    sata_hba_inst, &sata_device->satadev_addr);
10241 	}
10242 
10243 
10244 	return (SATA_SUCCESS);
10245 }
10246 
10247 
10248 /*
10249  * Create scsi target node for attached device, create node properties and
10250  * attach the node.
10251  * The node could be removed if the device onlining fails.
10252  *
10253  * A dev_info_t pointer is returned if operation is successful, NULL is
10254  * returned otherwise.
10255  */
10256 
10257 static dev_info_t *
10258 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10259 			sata_address_t *sata_addr)
10260 {
10261 	dev_info_t *cdip = NULL;
10262 	int rval;
10263 	char *nname = NULL;
10264 	char **compatible = NULL;
10265 	int ncompatible;
10266 	struct scsi_inquiry inq;
10267 	sata_device_t sata_device;
10268 	sata_drive_info_t *sdinfo;
10269 	int target;
10270 	int i;
10271 
10272 	sata_device.satadev_rev = SATA_DEVICE_REV;
10273 	sata_device.satadev_addr = *sata_addr;
10274 
10275 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10276 
10277 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10278 
10279 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10280 	    sata_addr->pmport, sata_addr->qual);
10281 
10282 	if (sdinfo == NULL) {
10283 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10284 		    sata_addr->cport)));
10285 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10286 		    "sata_create_target_node: no sdinfo for target %x",
10287 		    target));
10288 		return (NULL);
10289 	}
10290 
10291 	/*
10292 	 * create or get scsi inquiry data, expected by
10293 	 * scsi_hba_nodename_compatible_get()
10294 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10295 	 * ATAPI devices respond directly to Inquiry request.
10296 	 */
10297 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10298 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10299 		    (uint8_t *)&inq);
10300 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10301 		    sata_addr->cport)));
10302 	} else { /* Assume supported ATAPI device */
10303 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10304 		    sata_addr->cport)));
10305 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10306 		    &inq) == SATA_FAILURE)
10307 			return (NULL);
10308 		/*
10309 		 * Save supported ATAPI transport version
10310 		 */
10311 		sdinfo->satadrv_atapi_trans_ver =
10312 		    SATA_ATAPI_TRANS_VERSION(&inq);
10313 	}
10314 
10315 	/* determine the node name and compatible */
10316 	scsi_hba_nodename_compatible_get(&inq, NULL,
10317 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10318 
10319 #ifdef SATA_DEBUG
10320 	if (sata_debug_flags & SATA_DBG_NODES) {
10321 		if (nname == NULL) {
10322 			cmn_err(CE_NOTE, "sata_create_target_node: "
10323 			    "cannot determine nodename for target %d\n",
10324 			    target);
10325 		} else {
10326 			cmn_err(CE_WARN, "sata_create_target_node: "
10327 			    "target %d nodename: %s\n", target, nname);
10328 		}
10329 		if (compatible == NULL) {
10330 			cmn_err(CE_WARN,
10331 			    "sata_create_target_node: no compatible name\n");
10332 		} else {
10333 			for (i = 0; i < ncompatible; i++) {
10334 				cmn_err(CE_WARN, "sata_create_target_node: "
10335 				    "compatible name: %s\n", compatible[i]);
10336 			}
10337 		}
10338 	}
10339 #endif
10340 
10341 	/* if nodename can't be determined, log error and exit */
10342 	if (nname == NULL) {
10343 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10344 		    "sata_create_target_node: cannot determine nodename "
10345 		    "for target %d\n", target));
10346 		scsi_hba_nodename_compatible_free(nname, compatible);
10347 		return (NULL);
10348 	}
10349 	/*
10350 	 * Create scsi target node
10351 	 */
10352 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
10353 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10354 	    "device-type", "scsi");
10355 
10356 	if (rval != DDI_PROP_SUCCESS) {
10357 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10358 		    "updating device_type prop failed %d", rval));
10359 		goto fail;
10360 	}
10361 
10362 	/*
10363 	 * Create target node properties: target & lun
10364 	 */
10365 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
10366 	if (rval != DDI_PROP_SUCCESS) {
10367 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10368 		    "updating target prop failed %d", rval));
10369 		goto fail;
10370 	}
10371 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
10372 	if (rval != DDI_PROP_SUCCESS) {
10373 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10374 		    "updating target prop failed %d", rval));
10375 		goto fail;
10376 	}
10377 
10378 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10379 		/*
10380 		 * Add "variant" property
10381 		 */
10382 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10383 		    "variant", "atapi");
10384 		if (rval != DDI_PROP_SUCCESS) {
10385 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10386 			    "sata_create_target_node: variant atapi "
10387 			    "property could not be created: %d", rval));
10388 			goto fail;
10389 		}
10390 	}
10391 	/* decorate the node with compatible */
10392 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
10393 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
10394 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10395 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
10396 		    (void *)cdip));
10397 		goto fail;
10398 	}
10399 
10400 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10401 		/*
10402 		 * Add "sata-phy" property
10403 		 */
10404 		if (ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "sata-phy",
10405 		    (int)sata_addr->cport) != DDI_PROP_SUCCESS) {
10406 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10407 			    "sata_create_target_node: failed to create "
10408 			    "\"sata-phy\" property: port %d",
10409 			    sata_addr->cport));
10410 		}
10411 	}
10412 
10413 
10414 	/*
10415 	 * Now, try to attach the driver. If probing of the device fails,
10416 	 * the target node may be removed
10417 	 */
10418 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
10419 
10420 	scsi_hba_nodename_compatible_free(nname, compatible);
10421 
10422 	if (rval == NDI_SUCCESS)
10423 		return (cdip);
10424 
10425 	/* target node was removed - are we sure? */
10426 	return (NULL);
10427 
10428 fail:
10429 	scsi_hba_nodename_compatible_free(nname, compatible);
10430 	ddi_prop_remove_all(cdip);
10431 	rval = ndi_devi_free(cdip);
10432 	if (rval != NDI_SUCCESS) {
10433 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10434 		    "node removal failed %d", rval));
10435 	}
10436 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
10437 	    "cannot create target node for SATA device at port %d",
10438 	    sata_addr->cport);
10439 	return (NULL);
10440 }
10441 
10442 /*
10443  * Remove a target node.
10444  */
10445 static void
10446 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
10447 			sata_address_t *sata_addr)
10448 {
10449 	dev_info_t *tdip;
10450 	uint8_t cport = sata_addr->cport;
10451 	uint8_t pmport = sata_addr->pmport;
10452 	uint8_t qual = sata_addr->qual;
10453 
10454 	/* Note the sata daemon uses the address of the port/pmport */
10455 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10456 
10457 	/* Remove target node */
10458 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
10459 	if (tdip != NULL) {
10460 		/*
10461 		 * Target node exists.  Unconfigure device
10462 		 * then remove the target node (one ndi
10463 		 * operation).
10464 		 */
10465 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10466 			/*
10467 			 * PROBLEM - no device, but target node remained. This
10468 			 * happens when the file was open or node was waiting
10469 			 * for resources.
10470 			 */
10471 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10472 			    "sata_remove_target_node: "
10473 			    "Failed to remove target node for "
10474 			    "detached SATA device."));
10475 			/*
10476 			 * Set target node state to DEVI_DEVICE_REMOVED. But
10477 			 * re-check first that the node still exists.
10478 			 */
10479 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
10480 			    cport, pmport);
10481 			if (tdip != NULL) {
10482 				sata_set_device_removed(tdip);
10483 				/*
10484 				 * Instruct event daemon to retry the cleanup
10485 				 * later.
10486 				 */
10487 				sata_set_target_node_cleanup(sata_hba_inst,
10488 				    sata_addr);
10489 			}
10490 		}
10491 
10492 		if (qual == SATA_ADDR_CPORT)
10493 			sata_log(sata_hba_inst, CE_WARN,
10494 			    "SATA device detached at port %d", cport);
10495 		else
10496 			sata_log(sata_hba_inst, CE_WARN,
10497 			    "SATA device detached at port %d:%d",
10498 			    cport, pmport);
10499 	}
10500 #ifdef SATA_DEBUG
10501 	else {
10502 		if (qual == SATA_ADDR_CPORT)
10503 			sata_log(sata_hba_inst, CE_WARN,
10504 			    "target node not found at port %d", cport);
10505 		else
10506 			sata_log(sata_hba_inst, CE_WARN,
10507 			    "target node not found at port %d:%d",
10508 			    cport, pmport);
10509 	}
10510 #endif
10511 }
10512 
10513 
10514 /*
10515  * Re-probe sata port, check for a device and attach info
10516  * structures when necessary. Identify Device data is fetched, if possible.
10517  * Assumption: sata address is already validated.
10518  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10519  * the presence of a device and its type.
10520  *
10521  * flag arg specifies that the function should try multiple times to identify
10522  * device type and to initialize it, or it should return immediately on failure.
10523  * SATA_DEV_IDENTIFY_RETRY - retry
10524  * SATA_DEV_IDENTIFY_NORETRY - no retry
10525  *
10526  * SATA_FAILURE is returned if one of the operations failed.
10527  *
10528  * This function cannot be called in interrupt context - it may sleep.
10529  *
10530  * Note: Port multiplier is supported.
10531  */
10532 static int
10533 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10534     int flag)
10535 {
10536 	sata_cport_info_t *cportinfo;
10537 	sata_pmult_info_t *pmultinfo;
10538 	sata_drive_info_t *sdinfo, *osdinfo;
10539 	boolean_t init_device = B_FALSE;
10540 	int prev_device_type = SATA_DTYPE_NONE;
10541 	int prev_device_settings = 0;
10542 	int prev_device_state = 0;
10543 	clock_t start_time;
10544 	int retry = B_FALSE;
10545 	uint8_t cport = sata_device->satadev_addr.cport;
10546 	int rval_probe, rval_init;
10547 
10548 	/*
10549 	 * If target is pmport, sata_reprobe_pmport() will handle it.
10550 	 */
10551 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
10552 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
10553 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
10554 
10555 	/* We only care about host sata cport for now */
10556 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10557 	    sata_device->satadev_addr.cport);
10558 
10559 	/*
10560 	 * If a port multiplier was previously attached (we have no idea it
10561 	 * still there or not), sata_reprobe_pmult() will handle it.
10562 	 */
10563 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
10564 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
10565 
10566 	/* Store sata_drive_info when a non-pmult device was attached. */
10567 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10568 	if (osdinfo != NULL) {
10569 		/*
10570 		 * We are re-probing port with a previously attached device.
10571 		 * Save previous device type and settings.
10572 		 */
10573 		prev_device_type = cportinfo->cport_dev_type;
10574 		prev_device_settings = osdinfo->satadrv_settings;
10575 		prev_device_state = osdinfo->satadrv_state;
10576 	}
10577 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
10578 		start_time = ddi_get_lbolt();
10579 		retry = B_TRUE;
10580 	}
10581 retry_probe:
10582 
10583 	/* probe port */
10584 	mutex_enter(&cportinfo->cport_mutex);
10585 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10586 	cportinfo->cport_state |= SATA_STATE_PROBING;
10587 	mutex_exit(&cportinfo->cport_mutex);
10588 
10589 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10590 	    (SATA_DIP(sata_hba_inst), sata_device);
10591 
10592 	mutex_enter(&cportinfo->cport_mutex);
10593 	if (rval_probe != SATA_SUCCESS) {
10594 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10595 		mutex_exit(&cportinfo->cport_mutex);
10596 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
10597 		    "SATA port %d probing failed",
10598 		    cportinfo->cport_addr.cport));
10599 		return (SATA_FAILURE);
10600 	}
10601 
10602 	/*
10603 	 * update sata port state and set device type
10604 	 */
10605 	sata_update_port_info(sata_hba_inst, sata_device);
10606 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10607 
10608 	/*
10609 	 * Sanity check - Port is active? Is the link active?
10610 	 * Is there any device attached?
10611 	 */
10612 	if ((cportinfo->cport_state &
10613 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10614 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10615 	    SATA_PORT_DEVLINK_UP) {
10616 		/*
10617 		 * Port in non-usable state or no link active/no device.
10618 		 * Free info structure if necessary (direct attached drive
10619 		 * only, for now!
10620 		 */
10621 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10622 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10623 		/* Add here differentiation for device attached or not */
10624 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10625 		mutex_exit(&cportinfo->cport_mutex);
10626 		if (sdinfo != NULL)
10627 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10628 		return (SATA_SUCCESS);
10629 	}
10630 
10631 	cportinfo->cport_state |= SATA_STATE_READY;
10632 	cportinfo->cport_state |= SATA_STATE_PROBED;
10633 
10634 	cportinfo->cport_dev_type = sata_device->satadev_type;
10635 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10636 
10637 	/*
10638 	 * If we are re-probing the port, there may be
10639 	 * sata_drive_info structure attached
10640 	 */
10641 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10642 
10643 		/*
10644 		 * There is no device, so remove device info structure,
10645 		 * if necessary.
10646 		 */
10647 		/* Device change: Drive -> None */
10648 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10649 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10650 		if (sdinfo != NULL) {
10651 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10652 			sata_log(sata_hba_inst, CE_WARN,
10653 			    "SATA device detached "
10654 			    "from port %d", cportinfo->cport_addr.cport);
10655 		}
10656 		mutex_exit(&cportinfo->cport_mutex);
10657 		return (SATA_SUCCESS);
10658 
10659 	}
10660 
10661 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10662 
10663 		/* Device (may) change: Drive -> Drive */
10664 		if (sdinfo == NULL) {
10665 			/*
10666 			 * There is some device attached, but there is
10667 			 * no sata_drive_info structure - allocate one
10668 			 */
10669 			mutex_exit(&cportinfo->cport_mutex);
10670 			sdinfo = kmem_zalloc(
10671 			    sizeof (sata_drive_info_t), KM_SLEEP);
10672 			mutex_enter(&cportinfo->cport_mutex);
10673 			/*
10674 			 * Recheck, that the port state did not change when we
10675 			 * released mutex.
10676 			 */
10677 			if (cportinfo->cport_state & SATA_STATE_READY) {
10678 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
10679 				sdinfo->satadrv_addr = cportinfo->cport_addr;
10680 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
10681 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10682 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10683 			} else {
10684 				/*
10685 				 * Port is not in ready state, we
10686 				 * cannot attach a device.
10687 				 */
10688 				mutex_exit(&cportinfo->cport_mutex);
10689 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
10690 				return (SATA_SUCCESS);
10691 			}
10692 			/*
10693 			 * Since we are adding device, presumably new one,
10694 			 * indicate that it  should be initalized,
10695 			 * as well as some internal framework states).
10696 			 */
10697 			init_device = B_TRUE;
10698 		}
10699 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10700 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10701 	} else {
10702 		/* Device change: Drive -> PMult */
10703 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10704 		if (sdinfo != NULL) {
10705 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10706 			sata_log(sata_hba_inst, CE_WARN,
10707 			    "SATA device detached "
10708 			    "from port %d", cportinfo->cport_addr.cport);
10709 		}
10710 
10711 		sata_log(sata_hba_inst, CE_WARN,
10712 		    "SATA port multiplier detected at port %d",
10713 		    cportinfo->cport_addr.cport);
10714 
10715 		mutex_exit(&cportinfo->cport_mutex);
10716 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
10717 		    SATA_SUCCESS)
10718 			return (SATA_FAILURE);
10719 		sata_show_pmult_info(sata_hba_inst, sata_device);
10720 		mutex_enter(&cportinfo->cport_mutex);
10721 
10722 		/*
10723 		 * Mark all the port multiplier port behind the port
10724 		 * multiplier behind with link events, so that the sata daemon
10725 		 * will update their status.
10726 		 */
10727 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10728 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10729 		mutex_exit(&cportinfo->cport_mutex);
10730 		return (SATA_SUCCESS);
10731 	}
10732 	mutex_exit(&cportinfo->cport_mutex);
10733 
10734 	/*
10735 	 * Figure out what kind of device we are really
10736 	 * dealing with. Failure of identifying device does not fail this
10737 	 * function.
10738 	 */
10739 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
10740 	rval_init = SATA_FAILURE;
10741 	mutex_enter(&cportinfo->cport_mutex);
10742 	if (rval_probe == SATA_SUCCESS) {
10743 		/*
10744 		 * If we are dealing with the same type of a device as before,
10745 		 * restore its settings flags.
10746 		 */
10747 		if (osdinfo != NULL &&
10748 		    sata_device->satadev_type == prev_device_type)
10749 			sdinfo->satadrv_settings = prev_device_settings;
10750 
10751 		mutex_exit(&cportinfo->cport_mutex);
10752 		rval_init = SATA_SUCCESS;
10753 		/* Set initial device features, if necessary */
10754 		if (init_device == B_TRUE) {
10755 			rval_init = sata_initialize_device(sata_hba_inst,
10756 			    sdinfo);
10757 		}
10758 		if (rval_init == SATA_SUCCESS)
10759 			return (rval_init);
10760 		/* else we will retry if retry was asked for */
10761 
10762 	} else {
10763 		/*
10764 		 * If there was some device info before we probe the device,
10765 		 * restore previous device setting, so we can retry from scratch
10766 		 * later. Providing, of course, that device has not disapear
10767 		 * during probing process.
10768 		 */
10769 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10770 			if (osdinfo != NULL) {
10771 				cportinfo->cport_dev_type = prev_device_type;
10772 				sdinfo->satadrv_type = prev_device_type;
10773 				sdinfo->satadrv_state = prev_device_state;
10774 			}
10775 		} else {
10776 			/* device is gone */
10777 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10778 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10779 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10780 			mutex_exit(&cportinfo->cport_mutex);
10781 			return (SATA_SUCCESS);
10782 		}
10783 		mutex_exit(&cportinfo->cport_mutex);
10784 	}
10785 
10786 	if (retry) {
10787 		clock_t cur_time = ddi_get_lbolt();
10788 		/*
10789 		 * A device was not successfully identified or initialized.
10790 		 * Track retry time for device identification.
10791 		 */
10792 		if ((cur_time - start_time) <
10793 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10794 			/* sleep for a while */
10795 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10796 			goto retry_probe;
10797 		}
10798 		/* else no more retries */
10799 		mutex_enter(&cportinfo->cport_mutex);
10800 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10801 			if (rval_init == SATA_RETRY) {
10802 				/*
10803 				 * Setting drive features have failed, but
10804 				 * because the drive is still accessible,
10805 				 * keep it and emit a warning message.
10806 				 */
10807 				sata_log(sata_hba_inst, CE_WARN,
10808 				    "SATA device at port %d - desired "
10809 				    "drive features could not be set. "
10810 				    "Device may not operate as expected.",
10811 				    cportinfo->cport_addr.cport);
10812 			} else {
10813 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
10814 				    satadrv_state = SATA_DSTATE_FAILED;
10815 			}
10816 		}
10817 		mutex_exit(&cportinfo->cport_mutex);
10818 	}
10819 	return (SATA_SUCCESS);
10820 }
10821 
10822 /*
10823  * Reprobe a controller port that connected to a port multiplier.
10824  *
10825  * NOTE: No Mutex should be hold.
10826  */
10827 static int
10828 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10829     int flag)
10830 {
10831 	_NOTE(ARGUNUSED(flag))
10832 	sata_cport_info_t *cportinfo;
10833 	sata_pmult_info_t *pmultinfo;
10834 	uint8_t cport = sata_device->satadev_addr.cport;
10835 	int rval_probe;
10836 
10837 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10838 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10839 
10840 	/* probe port */
10841 	mutex_enter(&cportinfo->cport_mutex);
10842 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10843 	cportinfo->cport_state |= SATA_STATE_PROBING;
10844 	mutex_exit(&cportinfo->cport_mutex);
10845 
10846 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10847 	    (SATA_DIP(sata_hba_inst), sata_device);
10848 
10849 	mutex_enter(&cportinfo->cport_mutex);
10850 	if (rval_probe != SATA_SUCCESS) {
10851 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10852 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
10853 		    "SATA port %d probing failed", cport));
10854 		sata_log(sata_hba_inst, CE_WARN,
10855 		    "SATA port multiplier detached at port %d", cport);
10856 		mutex_exit(&cportinfo->cport_mutex);
10857 		sata_free_pmult(sata_hba_inst, sata_device);
10858 		return (SATA_FAILURE);
10859 	}
10860 
10861 	/*
10862 	 * update sata port state and set device type
10863 	 */
10864 	sata_update_port_info(sata_hba_inst, sata_device);
10865 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10866 	cportinfo->cport_state |= SATA_STATE_PROBED;
10867 
10868 	/*
10869 	 * Sanity check - Port is active? Is the link active?
10870 	 * Is there any device attached?
10871 	 */
10872 	if ((cportinfo->cport_state &
10873 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10874 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10875 	    SATA_PORT_DEVLINK_UP ||
10876 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
10877 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10878 		mutex_exit(&cportinfo->cport_mutex);
10879 		sata_free_pmult(sata_hba_inst, sata_device);
10880 		sata_log(sata_hba_inst, CE_WARN,
10881 		    "SATA port multiplier detached at port %d", cport);
10882 		return (SATA_SUCCESS);
10883 	}
10884 
10885 	/*
10886 	 * Device changed: PMult -> Non-PMult
10887 	 *
10888 	 * This situation is uncommon, most possibly being caused by errors
10889 	 * after which the port multiplier is not correct initialized and
10890 	 * recognized. In that case the new device will be marked as unknown
10891 	 * and will not be automatically probed in this routine. Instead
10892 	 * system administrator could manually restart it via cfgadm(1M).
10893 	 */
10894 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10895 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10896 		mutex_exit(&cportinfo->cport_mutex);
10897 		sata_free_pmult(sata_hba_inst, sata_device);
10898 		sata_log(sata_hba_inst, CE_WARN,
10899 		    "SATA port multiplier detached at port %d", cport);
10900 		return (SATA_FAILURE);
10901 	}
10902 
10903 	/*
10904 	 * Now we know it is a port multiplier. However, if this is not the
10905 	 * previously attached port multiplier - they may have different
10906 	 * pmport numbers - we need to re-allocate data structures for every
10907 	 * pmport and drive.
10908 	 *
10909 	 * Port multipliers of the same model have identical values in these
10910 	 * registers, so it is still necessary to update the information of
10911 	 * all drives attached to the previous port multiplier afterwards.
10912 	 */
10913 	/* Device changed: PMult -> another PMult */
10914 	mutex_exit(&cportinfo->cport_mutex);
10915 	sata_free_pmult(sata_hba_inst, sata_device);
10916 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
10917 		return (SATA_FAILURE);
10918 	mutex_enter(&cportinfo->cport_mutex);
10919 
10920 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
10921 	    "SATA port multiplier [changed] at port %d", cport);
10922 	sata_log(sata_hba_inst, CE_WARN,
10923 	    "SATA port multiplier detected at port %d", cport);
10924 
10925 	/*
10926 	 * Mark all the port multiplier port behind the port
10927 	 * multiplier behind with link events, so that the sata daemon
10928 	 * will update their status.
10929 	 */
10930 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10931 	mutex_exit(&cportinfo->cport_mutex);
10932 
10933 	return (SATA_SUCCESS);
10934 }
10935 
10936 /*
10937  * Re-probe a port multiplier port, check for a device and attach info
10938  * structures when necessary. Identify Device data is fetched, if possible.
10939  * Assumption: sata address is already validated as port multiplier port.
10940  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10941  * the presence of a device and its type.
10942  *
10943  * flag arg specifies that the function should try multiple times to identify
10944  * device type and to initialize it, or it should return immediately on failure.
10945  * SATA_DEV_IDENTIFY_RETRY - retry
10946  * SATA_DEV_IDENTIFY_NORETRY - no retry
10947  *
10948  * SATA_FAILURE is returned if one of the operations failed.
10949  *
10950  * This function cannot be called in interrupt context - it may sleep.
10951  *
10952  * NOTE: Should be only called by sata_probe_port() in case target port is a
10953  *       port multiplier port.
10954  * NOTE: No Mutex should be hold.
10955  */
10956 static int
10957 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10958     int flag)
10959 {
10960 	sata_cport_info_t *cportinfo = NULL;
10961 	sata_pmport_info_t *pmportinfo = NULL;
10962 	sata_drive_info_t *sdinfo, *osdinfo;
10963 	sata_device_t sdevice;
10964 	boolean_t init_device = B_FALSE;
10965 	int prev_device_type = SATA_DTYPE_NONE;
10966 	int prev_device_settings = 0;
10967 	int prev_device_state = 0;
10968 	clock_t start_time;
10969 	uint8_t cport = sata_device->satadev_addr.cport;
10970 	uint8_t pmport = sata_device->satadev_addr.pmport;
10971 	int rval;
10972 
10973 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10974 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
10975 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10976 
10977 	if (osdinfo != NULL) {
10978 		/*
10979 		 * We are re-probing port with a previously attached device.
10980 		 * Save previous device type and settings.
10981 		 */
10982 		prev_device_type = pmportinfo->pmport_dev_type;
10983 		prev_device_settings = osdinfo->satadrv_settings;
10984 		prev_device_state = osdinfo->satadrv_state;
10985 	}
10986 
10987 	start_time = ddi_get_lbolt();
10988 
10989 	/* check parent status */
10990 	mutex_enter(&cportinfo->cport_mutex);
10991 	if ((cportinfo->cport_state &
10992 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10993 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10994 	    SATA_PORT_DEVLINK_UP) {
10995 		mutex_exit(&cportinfo->cport_mutex);
10996 		return (SATA_FAILURE);
10997 	}
10998 	mutex_exit(&cportinfo->cport_mutex);
10999 
11000 retry_probe_pmport:
11001 
11002 	/* probe port */
11003 	mutex_enter(&pmportinfo->pmport_mutex);
11004 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11005 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
11006 	mutex_exit(&pmportinfo->pmport_mutex);
11007 
11008 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11009 	    (SATA_DIP(sata_hba_inst), sata_device);
11010 
11011 	/* might need retry because we cannot touch registers. */
11012 	if (rval == SATA_FAILURE) {
11013 		mutex_enter(&pmportinfo->pmport_mutex);
11014 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
11015 		mutex_exit(&pmportinfo->pmport_mutex);
11016 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
11017 		    "SATA port %d:%d probing failed",
11018 		    cport, pmport));
11019 		return (SATA_FAILURE);
11020 	} else if (rval == SATA_RETRY) {
11021 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
11022 		    "SATA port %d:%d probing failed, retrying...",
11023 		    cport, pmport));
11024 		clock_t cur_time = ddi_get_lbolt();
11025 		/*
11026 		 * A device was not successfully identified or initialized.
11027 		 * Track retry time for device identification.
11028 		 */
11029 		if ((cur_time - start_time) <
11030 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11031 			/* sleep for a while */
11032 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11033 			goto retry_probe_pmport;
11034 		} else {
11035 			mutex_enter(&pmportinfo->pmport_mutex);
11036 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11037 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11038 				    satadrv_state = SATA_DSTATE_FAILED;
11039 			mutex_exit(&pmportinfo->pmport_mutex);
11040 			return (SATA_SUCCESS);
11041 		}
11042 	}
11043 
11044 	/*
11045 	 * Sanity check - Controller port is active? Is the link active?
11046 	 * Is it still a port multiplier?
11047 	 */
11048 	if ((cportinfo->cport_state &
11049 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11050 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11051 	    SATA_PORT_DEVLINK_UP ||
11052 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
11053 		/*
11054 		 * Port in non-usable state or no link active/no
11055 		 * device. Free info structure.
11056 		 */
11057 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11058 
11059 		sdevice.satadev_addr.cport = cport;
11060 		sdevice.satadev_addr.pmport = pmport;
11061 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
11062 		mutex_exit(&cportinfo->cport_mutex);
11063 
11064 		sata_free_pmult(sata_hba_inst, &sdevice);
11065 		return (SATA_FAILURE);
11066 	}
11067 
11068 	/* SATA_SUCCESS NOW */
11069 	/*
11070 	 * update sata port state and set device type
11071 	 */
11072 	mutex_enter(&pmportinfo->pmport_mutex);
11073 	sata_update_pmport_info(sata_hba_inst, sata_device);
11074 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
11075 
11076 	/*
11077 	 * Sanity check - Port is active? Is the link active?
11078 	 * Is there any device attached?
11079 	 */
11080 	if ((pmportinfo->pmport_state &
11081 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11082 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11083 	    SATA_PORT_DEVLINK_UP) {
11084 		/*
11085 		 * Port in non-usable state or no link active/no device.
11086 		 * Free info structure if necessary (direct attached drive
11087 		 * only, for now!
11088 		 */
11089 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11090 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11091 		/* Add here differentiation for device attached or not */
11092 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11093 		mutex_exit(&pmportinfo->pmport_mutex);
11094 		if (sdinfo != NULL)
11095 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11096 		return (SATA_SUCCESS);
11097 	}
11098 
11099 	pmportinfo->pmport_state |= SATA_STATE_READY;
11100 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
11101 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11102 
11103 	/*
11104 	 * If we are re-probing the port, there may be
11105 	 * sata_drive_info structure attached
11106 	 * (or sata_pm_info, if PMult is supported).
11107 	 */
11108 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
11109 		/*
11110 		 * There is no device, so remove device info structure,
11111 		 * if necessary.
11112 		 */
11113 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11114 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11115 		if (sdinfo != NULL) {
11116 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11117 			sata_log(sata_hba_inst, CE_WARN,
11118 			    "SATA device detached from port %d:%d",
11119 			    cport, pmport);
11120 		}
11121 		mutex_exit(&pmportinfo->pmport_mutex);
11122 		return (SATA_SUCCESS);
11123 	}
11124 
11125 	/* this should not be a pmult */
11126 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
11127 	if (sdinfo == NULL) {
11128 		/*
11129 		 * There is some device attached, but there is
11130 		 * no sata_drive_info structure - allocate one
11131 		 */
11132 		mutex_exit(&pmportinfo->pmport_mutex);
11133 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
11134 		    KM_SLEEP);
11135 		mutex_enter(&pmportinfo->pmport_mutex);
11136 		/*
11137 		 * Recheck, that the port state did not change when we
11138 		 * released mutex.
11139 		 */
11140 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
11141 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
11142 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
11143 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
11144 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11145 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11146 		} else {
11147 			/*
11148 			 * Port is not in ready state, we
11149 			 * cannot attach a device.
11150 			 */
11151 			mutex_exit(&pmportinfo->pmport_mutex);
11152 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11153 			return (SATA_SUCCESS);
11154 		}
11155 		/*
11156 		 * Since we are adding device, presumably new one,
11157 		 * indicate that it  should be initalized,
11158 		 * as well as some internal framework states).
11159 		 */
11160 		init_device = B_TRUE;
11161 	}
11162 
11163 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
11164 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
11165 
11166 	mutex_exit(&pmportinfo->pmport_mutex);
11167 	/*
11168 	 * Figure out what kind of device we are really
11169 	 * dealing with.
11170 	 */
11171 	rval = sata_probe_device(sata_hba_inst, sata_device);
11172 
11173 	mutex_enter(&pmportinfo->pmport_mutex);
11174 	if (rval == SATA_SUCCESS) {
11175 		/*
11176 		 * If we are dealing with the same type of a device as before,
11177 		 * restore its settings flags.
11178 		 */
11179 		if (osdinfo != NULL &&
11180 		    sata_device->satadev_type == prev_device_type)
11181 			sdinfo->satadrv_settings = prev_device_settings;
11182 
11183 		mutex_exit(&pmportinfo->pmport_mutex);
11184 		/* Set initial device features, if necessary */
11185 		if (init_device == B_TRUE) {
11186 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
11187 		}
11188 		if (rval == SATA_SUCCESS)
11189 			return (rval);
11190 	} else {
11191 		/*
11192 		 * If there was some device info before we probe the device,
11193 		 * restore previous device setting, so we can retry from scratch
11194 		 * later. Providing, of course, that device has not disappeared
11195 		 * during probing process.
11196 		 */
11197 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11198 			if (osdinfo != NULL) {
11199 				pmportinfo->pmport_dev_type = prev_device_type;
11200 				sdinfo->satadrv_type = prev_device_type;
11201 				sdinfo->satadrv_state = prev_device_state;
11202 			}
11203 		} else {
11204 			/* device is gone */
11205 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11206 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11207 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11208 			mutex_exit(&pmportinfo->pmport_mutex);
11209 			return (SATA_SUCCESS);
11210 		}
11211 		mutex_exit(&pmportinfo->pmport_mutex);
11212 	}
11213 
11214 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11215 		clock_t cur_time = ddi_get_lbolt();
11216 		/*
11217 		 * A device was not successfully identified or initialized.
11218 		 * Track retry time for device identification.
11219 		 */
11220 		if ((cur_time - start_time) <
11221 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11222 			/* sleep for a while */
11223 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11224 			goto retry_probe_pmport;
11225 		} else {
11226 			mutex_enter(&pmportinfo->pmport_mutex);
11227 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11228 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11229 				    satadrv_state = SATA_DSTATE_FAILED;
11230 			mutex_exit(&pmportinfo->pmport_mutex);
11231 		}
11232 	}
11233 	return (SATA_SUCCESS);
11234 }
11235 
11236 /*
11237  * Allocated related structure for a port multiplier and its device ports
11238  *
11239  * Port multiplier should be ready and probed, and related information like
11240  * the number of the device ports should be store in sata_device_t.
11241  *
11242  * NOTE: No Mutex should be hold.
11243  */
11244 static int
11245 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11246 {
11247 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11248 	sata_cport_info_t *cportinfo = NULL;
11249 	sata_pmult_info_t *pmultinfo = NULL;
11250 	sata_pmport_info_t *pmportinfo = NULL;
11251 	sata_device_t sd;
11252 	dev_t minor_number;
11253 	char name[16];
11254 	uint8_t cport = sata_device->satadev_addr.cport;
11255 	int rval;
11256 	int npmport;
11257 
11258 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11259 
11260 	/* This function might be called while a port-mult is hot-plugged. */
11261 	mutex_enter(&cportinfo->cport_mutex);
11262 
11263 	/* dev_type's not updated when get called from sata_reprobe_port() */
11264 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11265 		/* Create a pmult_info structure */
11266 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11267 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11268 	}
11269 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11270 
11271 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11272 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11273 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11274 
11275 	/*
11276 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11277 	 * The HBA driver should initialize and register the port multiplier,
11278 	 * sata_register_pmult() will fill following fields,
11279 	 *   + sata_pmult_info.pmult_gscr
11280 	 *   + sata_pmult_info.pmult_num_dev_ports
11281 	 */
11282 	sd.satadev_addr = sata_device->satadev_addr;
11283 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11284 	mutex_exit(&cportinfo->cport_mutex);
11285 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11286 	    (SATA_DIP(sata_hba_inst), &sd);
11287 	mutex_enter(&cportinfo->cport_mutex);
11288 
11289 	if (rval != SATA_SUCCESS ||
11290 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11291 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11292 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11293 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11294 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11295 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11296 		mutex_exit(&cportinfo->cport_mutex);
11297 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11298 		    "sata_alloc_pmult: failed to initialize pmult "
11299 		    "at port %d.", cport)
11300 		return (SATA_FAILURE);
11301 	}
11302 
11303 	/* Initialize pmport_info structure */
11304 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11305 	    npmport++) {
11306 
11307 		/* if everything is allocated, skip */
11308 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11309 			continue;
11310 
11311 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11312 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11313 		mutex_exit(&cportinfo->cport_mutex);
11314 
11315 		mutex_enter(&pmportinfo->pmport_mutex);
11316 		pmportinfo->pmport_addr.cport = cport;
11317 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11318 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11319 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11320 		mutex_exit(&pmportinfo->pmport_mutex);
11321 
11322 		mutex_enter(&cportinfo->cport_mutex);
11323 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11324 
11325 		/* Create an attachment point */
11326 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
11327 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
11328 		(void) sprintf(name, "%d.%d", cport, npmport);
11329 
11330 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
11331 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
11332 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
11333 			    "cannot create SATA attachment point for "
11334 			    "port %d:%d", cport, npmport);
11335 		}
11336 	}
11337 
11338 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
11339 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
11340 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
11341 
11342 	mutex_exit(&cportinfo->cport_mutex);
11343 	return (SATA_SUCCESS);
11344 }
11345 
11346 /*
11347  * Free data structures when a port multiplier is removed.
11348  *
11349  * NOTE: No Mutex should be hold.
11350  */
11351 static void
11352 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11353 {
11354 	sata_cport_info_t *cportinfo;
11355 	sata_pmult_info_t *pmultinfo;
11356 	sata_pmport_info_t *pmportinfo;
11357 	sata_device_t pmport_device;
11358 	sata_drive_info_t *sdinfo;
11359 	dev_info_t *tdip;
11360 	char name[16];
11361 	uint8_t cport = sata_device->satadev_addr.cport;
11362 	int npmport;
11363 
11364 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11365 
11366 	/* This function might be called while port-mult is hot plugged. */
11367 	mutex_enter(&cportinfo->cport_mutex);
11368 
11369 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11370 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11371 	ASSERT(pmultinfo != NULL);
11372 
11373 	/* Free pmport_info structure */
11374 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11375 	    npmport++) {
11376 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
11377 		if (pmportinfo == NULL)
11378 			continue;
11379 		mutex_exit(&cportinfo->cport_mutex);
11380 
11381 		mutex_enter(&pmportinfo->pmport_mutex);
11382 		sdinfo = pmportinfo->pmport_sata_drive;
11383 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11384 		mutex_exit(&pmportinfo->pmport_mutex);
11385 
11386 		/* Remove attachment point. */
11387 		name[0] = '\0';
11388 		(void) sprintf(name, "%d.%d", cport, npmport);
11389 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
11390 		sata_log(sata_hba_inst, CE_NOTE,
11391 		    "Remove attachment point of port %d:%d",
11392 		    cport, npmport);
11393 
11394 		/*
11395 		 * Rumove target node
11396 		 */
11397 		bzero(&pmport_device, sizeof (sata_device_t));
11398 		pmport_device.satadev_rev = SATA_DEVICE_REV;
11399 		pmport_device.satadev_addr.cport = cport;
11400 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
11401 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
11402 
11403 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11404 		    &(pmport_device.satadev_addr));
11405 		if (tdip != NULL && ndi_devi_offline(tdip,
11406 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11407 			/*
11408 			 * Problem :
11409 			 * The target node remained attached.
11410 			 * This happens when the device file was open
11411 			 * or a node was waiting for resources.
11412 			 * Cannot do anything about it.
11413 			 */
11414 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11415 			    "sata_free_pmult: could not unconfigure device "
11416 			    "before disconnecting the SATA port %d:%d",
11417 			    cport, npmport));
11418 
11419 			/*
11420 			 * Set DEVICE REMOVED state in the target
11421 			 * node. It will prevent access to the device
11422 			 * even when a new device is attached, until
11423 			 * the old target node is released, removed and
11424 			 * recreated for a new  device.
11425 			 */
11426 			sata_set_device_removed(tdip);
11427 
11428 			/*
11429 			 * Instruct event daemon to try the target
11430 			 * node cleanup later.
11431 			 */
11432 			sata_set_target_node_cleanup(
11433 			    sata_hba_inst, &(pmport_device.satadev_addr));
11434 
11435 		}
11436 		mutex_enter(&cportinfo->cport_mutex);
11437 
11438 		/*
11439 		 * Add here differentiation for device attached or not
11440 		 */
11441 		if (sdinfo != NULL)  {
11442 			sata_log(sata_hba_inst, CE_WARN,
11443 			    "SATA device detached from port %d:%d",
11444 			    cport, npmport);
11445 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11446 		}
11447 
11448 		mutex_destroy(&pmportinfo->pmport_mutex);
11449 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
11450 	}
11451 
11452 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11453 
11454 	cportinfo->cport_devp.cport_sata_pmult = NULL;
11455 
11456 	sata_log(sata_hba_inst, CE_WARN,
11457 	    "SATA port multiplier detached at port %d", cport);
11458 
11459 	mutex_exit(&cportinfo->cport_mutex);
11460 }
11461 
11462 /*
11463  * Initialize device
11464  * Specified device is initialized to a default state.
11465  *
11466  * Returns SATA_SUCCESS if all device features are set successfully,
11467  * SATA_RETRY if device is accessible but device features were not set
11468  * successfully, and SATA_FAILURE otherwise.
11469  */
11470 static int
11471 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
11472     sata_drive_info_t *sdinfo)
11473 {
11474 	int rval;
11475 
11476 	sata_save_drive_settings(sdinfo);
11477 
11478 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
11479 
11480 	sata_init_write_cache_mode(sdinfo);
11481 
11482 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
11483 
11484 	/* Determine current data transfer mode */
11485 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
11486 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11487 	} else if ((sdinfo->satadrv_id.ai_validinfo &
11488 	    SATA_VALIDINFO_88) != 0 &&
11489 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
11490 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11491 	} else if ((sdinfo->satadrv_id.ai_dworddma &
11492 	    SATA_MDMA_SEL_MASK) != 0) {
11493 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11494 	} else
11495 		/* DMA supported, not no DMA transfer mode is selected !? */
11496 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11497 
11498 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
11499 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
11500 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
11501 	else
11502 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
11503 
11504 	return (rval);
11505 }
11506 
11507 
11508 /*
11509  * Initialize write cache mode.
11510  *
11511  * The default write cache setting for SATA HDD is provided by sata_write_cache
11512  * static variable. ATAPI CD/DVDs devices have write cache default is
11513  * determined by sata_atapicdvd_write_cache static variable.
11514  * ATAPI tape devices have write cache default is determined by
11515  * sata_atapitape_write_cache static variable.
11516  * ATAPI disk devices have write cache default is determined by
11517  * sata_atapidisk_write_cache static variable.
11518  * 1 - enable
11519  * 0 - disable
11520  * any other value - current drive setting
11521  *
11522  * Although there is not reason to disable write cache on CD/DVD devices,
11523  * tape devices and ATAPI disk devices, the default setting control is provided
11524  * for the maximun flexibility.
11525  *
11526  * In the future, it may be overridden by the
11527  * disk-write-cache-enable property setting, if it is defined.
11528  * Returns SATA_SUCCESS if all device features are set successfully,
11529  * SATA_FAILURE otherwise.
11530  */
11531 static void
11532 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
11533 {
11534 	switch (sdinfo->satadrv_type) {
11535 	case SATA_DTYPE_ATADISK:
11536 		if (sata_write_cache == 1)
11537 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11538 		else if (sata_write_cache == 0)
11539 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11540 		/*
11541 		 * When sata_write_cache value is not 0 or 1,
11542 		 * a current setting of the drive's write cache is used.
11543 		 */
11544 		break;
11545 	case SATA_DTYPE_ATAPICD:
11546 		if (sata_atapicdvd_write_cache == 1)
11547 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11548 		else if (sata_atapicdvd_write_cache == 0)
11549 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11550 		/*
11551 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
11552 		 * a current setting of the drive's write cache is used.
11553 		 */
11554 		break;
11555 	case SATA_DTYPE_ATAPITAPE:
11556 		if (sata_atapitape_write_cache == 1)
11557 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11558 		else if (sata_atapitape_write_cache == 0)
11559 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11560 		/*
11561 		 * When sata_atapitape_write_cache value is not 0 or 1,
11562 		 * a current setting of the drive's write cache is used.
11563 		 */
11564 		break;
11565 	case SATA_DTYPE_ATAPIDISK:
11566 		if (sata_atapidisk_write_cache == 1)
11567 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11568 		else if (sata_atapidisk_write_cache == 0)
11569 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11570 		/*
11571 		 * When sata_atapidisk_write_cache value is not 0 or 1,
11572 		 * a current setting of the drive's write cache is used.
11573 		 */
11574 		break;
11575 	}
11576 }
11577 
11578 
11579 /*
11580  * Validate sata address.
11581  * Specified cport, pmport and qualifier has to match
11582  * passed sata_scsi configuration info.
11583  * The presence of an attached device is not verified.
11584  *
11585  * Returns 0 when address is valid, -1 otherwise.
11586  */
11587 static int
11588 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
11589 	int pmport, int qual)
11590 {
11591 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
11592 		goto invalid_address;
11593 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11594 		goto invalid_address;
11595 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
11596 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
11597 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
11598 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
11599 		goto invalid_address;
11600 
11601 	return (0);
11602 
11603 invalid_address:
11604 	return (-1);
11605 
11606 }
11607 
11608 /*
11609  * Validate scsi address
11610  * SCSI target address is translated into SATA cport/pmport and compared
11611  * with a controller port/device configuration. LUN has to be 0.
11612  * Returns 0 if a scsi target refers to an attached device,
11613  * returns 1 if address is valid but no valid device is attached,
11614  * returns 2 if address is valid but device type is unknown (not valid device),
11615  * returns -1 if bad address or device is of an unsupported type.
11616  * Upon return sata_device argument is set.
11617  *
11618  * Port multiplier is supported now.
11619  */
11620 static int
11621 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
11622 	struct scsi_address *ap, sata_device_t *sata_device)
11623 {
11624 	int cport, pmport, qual, rval;
11625 
11626 	rval = -1;	/* Invalid address */
11627 	if (ap->a_lun != 0)
11628 		goto out;
11629 
11630 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
11631 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
11632 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
11633 
11634 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
11635 		goto out;
11636 
11637 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
11638 	    0) {
11639 
11640 		sata_cport_info_t *cportinfo;
11641 		sata_pmult_info_t *pmultinfo;
11642 		sata_drive_info_t *sdinfo = NULL;
11643 
11644 		sata_device->satadev_addr.qual = qual;
11645 		sata_device->satadev_addr.cport = cport;
11646 		sata_device->satadev_addr.pmport = pmport;
11647 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
11648 
11649 		rval = 1;	/* Valid sata address */
11650 
11651 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11652 		if (qual == SATA_ADDR_DCPORT) {
11653 			if (cportinfo == NULL ||
11654 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11655 				goto out;
11656 
11657 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11658 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
11659 			    sdinfo != NULL) {
11660 				rval = 2;
11661 				goto out;
11662 			}
11663 
11664 			if ((cportinfo->cport_dev_type &
11665 			    SATA_VALID_DEV_TYPE) == 0) {
11666 				rval = -1;
11667 				goto out;
11668 			}
11669 
11670 		} else if (qual == SATA_ADDR_DPMPORT) {
11671 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11672 			if (pmultinfo == NULL) {
11673 				rval = -1;
11674 				goto out;
11675 			}
11676 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
11677 			    NULL ||
11678 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11679 			    pmport) == SATA_DTYPE_NONE)
11680 				goto out;
11681 
11682 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
11683 			    pmport);
11684 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11685 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
11686 				rval = 2;
11687 				goto out;
11688 			}
11689 
11690 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11691 			    pmport) && SATA_VALID_DEV_TYPE) == 0) {
11692 				rval = -1;
11693 				goto out;
11694 			}
11695 
11696 		} else {
11697 			rval = -1;
11698 			goto out;
11699 		}
11700 		if ((sdinfo == NULL) ||
11701 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
11702 			goto out;
11703 
11704 		sata_device->satadev_type = sdinfo->satadrv_type;
11705 
11706 		return (0);
11707 	}
11708 out:
11709 	if (rval > 0) {
11710 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
11711 		    "sata_validate_scsi_address: no valid target %x lun %x",
11712 		    ap->a_target, ap->a_lun);
11713 	}
11714 	return (rval);
11715 }
11716 
11717 /*
11718  * Find dip corresponding to passed device number
11719  *
11720  * Returns NULL if invalid device number is passed or device cannot be found,
11721  * Returns dip is device is found.
11722  */
11723 static dev_info_t *
11724 sata_devt_to_devinfo(dev_t dev)
11725 {
11726 	dev_info_t *dip;
11727 #ifndef __lock_lint
11728 	struct devnames *dnp;
11729 	major_t major = getmajor(dev);
11730 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
11731 
11732 	if (major >= devcnt)
11733 		return (NULL);
11734 
11735 	dnp = &devnamesp[major];
11736 	LOCK_DEV_OPS(&(dnp->dn_lock));
11737 	dip = dnp->dn_head;
11738 	while (dip && (ddi_get_instance(dip) != instance)) {
11739 		dip = ddi_get_next(dip);
11740 	}
11741 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
11742 #endif
11743 
11744 	return (dip);
11745 }
11746 
11747 
11748 /*
11749  * Probe device.
11750  * This function issues Identify Device command and initializes local
11751  * sata_drive_info structure if the device can be identified.
11752  * The device type is determined by examining Identify Device
11753  * command response.
11754  * If the sata_hba_inst has linked drive info structure for this
11755  * device address, the Identify Device data is stored into sata_drive_info
11756  * structure linked to the port info structure.
11757  *
11758  * sata_device has to refer to the valid sata port(s) for HBA described
11759  * by sata_hba_inst structure.
11760  *
11761  * Returns:
11762  *	SATA_SUCCESS if device type was successfully probed and port-linked
11763  *		drive info structure was updated;
11764  * 	SATA_FAILURE if there is no device, or device was not probed
11765  *		successully;
11766  *	SATA_RETRY if device probe can be retried later.
11767  * If a device cannot be identified, sata_device's dev_state and dev_type
11768  * fields are set to unknown.
11769  * There are no retries in this function. Any retries should be managed by
11770  * the caller.
11771  */
11772 
11773 
11774 static int
11775 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11776 {
11777 	sata_pmport_info_t *pmportinfo;
11778 	sata_drive_info_t *sdinfo;
11779 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
11780 	int rval;
11781 
11782 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
11783 	    sata_device->satadev_addr.cport) &
11784 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
11785 
11786 	sata_device->satadev_type = SATA_DTYPE_NONE;
11787 
11788 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11789 	    sata_device->satadev_addr.cport)));
11790 
11791 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
11792 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
11793 		    sata_device->satadev_addr.cport,
11794 		    sata_device->satadev_addr.pmport);
11795 		ASSERT(pmportinfo != NULL);
11796 	}
11797 
11798 	/* Get pointer to port-linked sata device info structure */
11799 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11800 	if (sdinfo != NULL) {
11801 		sdinfo->satadrv_state &=
11802 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
11803 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
11804 	} else {
11805 		/* No device to probe */
11806 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11807 		    sata_device->satadev_addr.cport)));
11808 		sata_device->satadev_type = SATA_DTYPE_NONE;
11809 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
11810 		return (SATA_FAILURE);
11811 	}
11812 	/*
11813 	 * Need to issue both types of identify device command and
11814 	 * determine device type by examining retreived data/status.
11815 	 * First, ATA Identify Device.
11816 	 */
11817 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
11818 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
11819 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11820 	    sata_device->satadev_addr.cport)));
11821 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
11822 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11823 	if (rval == SATA_RETRY) {
11824 		/* We may try to check for ATAPI device */
11825 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
11826 			/*
11827 			 * HBA supports ATAPI - try to issue Identify Packet
11828 			 * Device command.
11829 			 */
11830 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
11831 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11832 		}
11833 	}
11834 	if (rval == SATA_SUCCESS) {
11835 		/*
11836 		 * Got something responding positively to ATA Identify Device
11837 		 * or to Identify Packet Device cmd.
11838 		 * Save last used device type.
11839 		 */
11840 		sata_device->satadev_type = new_sdinfo.satadrv_type;
11841 
11842 		/* save device info, if possible */
11843 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11844 		    sata_device->satadev_addr.cport)));
11845 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11846 		if (sdinfo == NULL) {
11847 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11848 			    sata_device->satadev_addr.cport)));
11849 			return (SATA_FAILURE);
11850 		}
11851 		/*
11852 		 * Copy drive info into the port-linked drive info structure.
11853 		 */
11854 		*sdinfo = new_sdinfo;
11855 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11856 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11857 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11858 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11859 			    sata_device->satadev_addr.cport) =
11860 			    sdinfo->satadrv_type;
11861 		else { /* SATA_ADDR_DPMPORT */
11862 			mutex_enter(&pmportinfo->pmport_mutex);
11863 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11864 			    sata_device->satadev_addr.cport,
11865 			    sata_device->satadev_addr.pmport) =
11866 			    sdinfo->satadrv_type;
11867 			mutex_exit(&pmportinfo->pmport_mutex);
11868 		}
11869 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11870 		    sata_device->satadev_addr.cport)));
11871 		return (SATA_SUCCESS);
11872 	}
11873 
11874 	/*
11875 	 * It may be SATA_RETRY or SATA_FAILURE return.
11876 	 * Looks like we cannot determine the device type at this time.
11877 	 */
11878 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11879 	    sata_device->satadev_addr.cport)));
11880 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11881 	if (sdinfo != NULL) {
11882 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
11883 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11884 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11885 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11886 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11887 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11888 			    sata_device->satadev_addr.cport) =
11889 			    SATA_DTYPE_UNKNOWN;
11890 		else {
11891 			/* SATA_ADDR_DPMPORT */
11892 			mutex_enter(&pmportinfo->pmport_mutex);
11893 			if ((SATA_PMULT_INFO(sata_hba_inst,
11894 			    sata_device->satadev_addr.cport) != NULL) &&
11895 			    (SATA_PMPORT_INFO(sata_hba_inst,
11896 			    sata_device->satadev_addr.cport,
11897 			    sata_device->satadev_addr.pmport) != NULL))
11898 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11899 				    sata_device->satadev_addr.cport,
11900 				    sata_device->satadev_addr.pmport) =
11901 				    SATA_DTYPE_UNKNOWN;
11902 			mutex_exit(&pmportinfo->pmport_mutex);
11903 		}
11904 	}
11905 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11906 	    sata_device->satadev_addr.cport)));
11907 	return (rval);
11908 }
11909 
11910 
11911 /*
11912  * Get pointer to sata_drive_info structure.
11913  *
11914  * The sata_device has to contain address (cport, pmport and qualifier) for
11915  * specified sata_scsi structure.
11916  *
11917  * Returns NULL if device address is not valid for this HBA configuration.
11918  * Otherwise, returns a pointer to sata_drive_info structure.
11919  *
11920  * This function should be called with a port mutex held.
11921  */
11922 static sata_drive_info_t *
11923 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
11924     sata_device_t *sata_device)
11925 {
11926 	uint8_t cport = sata_device->satadev_addr.cport;
11927 	uint8_t pmport = sata_device->satadev_addr.pmport;
11928 	uint8_t qual = sata_device->satadev_addr.qual;
11929 
11930 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11931 		return (NULL);
11932 
11933 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
11934 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
11935 		/* Port not probed yet */
11936 		return (NULL);
11937 
11938 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
11939 		return (NULL);
11940 
11941 	if (qual == SATA_ADDR_DCPORT) {
11942 		/* Request for a device on a controller port */
11943 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
11944 		    SATA_DTYPE_PMULT)
11945 			/* Port multiplier attached */
11946 			return (NULL);
11947 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
11948 	}
11949 	if (qual == SATA_ADDR_DPMPORT) {
11950 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
11951 		    SATA_DTYPE_PMULT)
11952 			return (NULL);
11953 
11954 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
11955 			return (NULL);
11956 
11957 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
11958 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
11959 			/* Port multiplier port not probed yet */
11960 			return (NULL);
11961 
11962 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
11963 	}
11964 
11965 	/* we should not get here */
11966 	return (NULL);
11967 }
11968 
11969 
11970 /*
11971  * sata_identify_device.
11972  * Send Identify Device command to SATA HBA driver.
11973  * If command executes successfully, update sata_drive_info structure pointed
11974  * to by sdinfo argument, including Identify Device data.
11975  * If command fails, invalidate data in sata_drive_info.
11976  *
11977  * Cannot be called from interrupt level.
11978  *
11979  * Returns:
11980  * SATA_SUCCESS if the device was identified as a supported device,
11981  * SATA_RETRY if the device was not identified but could be retried,
11982  * SATA_FAILURE if the device was not identified and identify attempt
11983  *	should not be retried.
11984  */
11985 static int
11986 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
11987     sata_drive_info_t *sdinfo)
11988 {
11989 	uint16_t cfg_word;
11990 	int rval;
11991 
11992 	/* fetch device identify data */
11993 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
11994 	    sdinfo)) != SATA_SUCCESS)
11995 		goto fail_unknown;
11996 
11997 	cfg_word = sdinfo->satadrv_id.ai_config;
11998 
11999 	/* Set the correct device type */
12000 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
12001 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
12002 	} else if (cfg_word == SATA_CFA_TYPE) {
12003 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
12004 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
12005 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
12006 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
12007 		case SATA_ATAPI_CDROM_DEV:
12008 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
12009 			break;
12010 		case SATA_ATAPI_SQACC_DEV:
12011 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
12012 			break;
12013 		case SATA_ATAPI_DIRACC_DEV:
12014 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
12015 			break;
12016 		default:
12017 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12018 		}
12019 	} else {
12020 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12021 	}
12022 
12023 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12024 		if (sdinfo->satadrv_capacity == 0) {
12025 			/* Non-LBA disk. Too bad... */
12026 			sata_log(sata_hba_inst, CE_WARN,
12027 			    "SATA disk device at port %d does not support LBA",
12028 			    sdinfo->satadrv_addr.cport);
12029 			rval = SATA_FAILURE;
12030 			goto fail_unknown;
12031 		}
12032 	}
12033 #if 0
12034 	/* Left for historical reason */
12035 	/*
12036 	 * Some initial version of SATA spec indicated that at least
12037 	 * UDMA mode 4 has to be supported. It is not metioned in
12038 	 * SerialATA 2.6, so this restriction is removed.
12039 	 */
12040 	/* Check for Ultra DMA modes 6 through 0 being supported */
12041 	for (i = 6; i >= 0; --i) {
12042 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
12043 			break;
12044 	}
12045 
12046 	/*
12047 	 * At least UDMA 4 mode has to be supported. If mode 4 or
12048 	 * higher are not supported by the device, fail this
12049 	 * device.
12050 	 */
12051 	if (i < 4) {
12052 		/* No required Ultra DMA mode supported */
12053 		sata_log(sata_hba_inst, CE_WARN,
12054 		    "SATA disk device at port %d does not support UDMA "
12055 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
12056 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12057 		    "mode 4 or higher required, %d supported", i));
12058 		rval = SATA_FAILURE;
12059 		goto fail_unknown;
12060 	}
12061 #endif
12062 
12063 	/*
12064 	 * For Disk devices, if it doesn't support UDMA mode, we would
12065 	 * like to return failure directly.
12066 	 */
12067 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
12068 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
12069 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
12070 		sata_log(sata_hba_inst, CE_WARN,
12071 		    "SATA disk device at port %d does not support UDMA",
12072 		    sdinfo->satadrv_addr.cport);
12073 		rval = SATA_FAILURE;
12074 		goto fail_unknown;
12075 	}
12076 
12077 	return (SATA_SUCCESS);
12078 
12079 fail_unknown:
12080 	/* Invalidate sata_drive_info ? */
12081 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12082 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
12083 	return (rval);
12084 }
12085 
12086 /*
12087  * Log/display device information
12088  */
12089 static void
12090 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
12091     sata_drive_info_t *sdinfo)
12092 {
12093 	int valid_version;
12094 	char msg_buf[MAXPATHLEN];
12095 	int i;
12096 
12097 	/* Show HBA path */
12098 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
12099 
12100 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
12101 
12102 	switch (sdinfo->satadrv_type) {
12103 	case SATA_DTYPE_ATADISK:
12104 		(void) sprintf(msg_buf, "SATA disk device at");
12105 		break;
12106 
12107 	case SATA_DTYPE_ATAPICD:
12108 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
12109 		break;
12110 
12111 	case SATA_DTYPE_ATAPITAPE:
12112 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
12113 		break;
12114 
12115 	case SATA_DTYPE_ATAPIDISK:
12116 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
12117 		break;
12118 
12119 	case SATA_DTYPE_UNKNOWN:
12120 		(void) sprintf(msg_buf,
12121 		    "Unsupported SATA device type (cfg 0x%x) at ",
12122 		    sdinfo->satadrv_id.ai_config);
12123 		break;
12124 	}
12125 
12126 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
12127 		cmn_err(CE_CONT, "?\t%s port %d\n",
12128 		    msg_buf, sdinfo->satadrv_addr.cport);
12129 	else
12130 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
12131 		    msg_buf, sdinfo->satadrv_addr.cport,
12132 		    sdinfo->satadrv_addr.pmport);
12133 
12134 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
12135 	    sizeof (sdinfo->satadrv_id.ai_model));
12136 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
12137 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
12138 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
12139 
12140 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
12141 	    sizeof (sdinfo->satadrv_id.ai_fw));
12142 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
12143 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
12144 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
12145 
12146 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
12147 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12148 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
12149 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
12150 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12151 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12152 	} else {
12153 		/*
12154 		 * Some drives do not implement serial number and may
12155 		 * violate the spec by providing spaces rather than zeros
12156 		 * in serial number field. Scan the buffer to detect it.
12157 		 */
12158 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
12159 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
12160 				break;
12161 		}
12162 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
12163 			cmn_err(CE_CONT, "?\tserial number - none\n");
12164 		} else {
12165 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12166 		}
12167 	}
12168 
12169 #ifdef SATA_DEBUG
12170 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
12171 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
12172 		int i;
12173 		for (i = 14; i >= 2; i--) {
12174 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
12175 				valid_version = i;
12176 				break;
12177 			}
12178 		}
12179 		cmn_err(CE_CONT,
12180 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
12181 		    valid_version,
12182 		    sdinfo->satadrv_id.ai_majorversion,
12183 		    sdinfo->satadrv_id.ai_minorversion);
12184 	}
12185 #endif
12186 	/* Log some info */
12187 	cmn_err(CE_CONT, "?\tsupported features:\n");
12188 	msg_buf[0] = '\0';
12189 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12190 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
12191 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
12192 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
12193 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
12194 	}
12195 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
12196 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
12197 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
12198 		(void) strlcat(msg_buf, ", Native Command Queueing",
12199 		    MAXPATHLEN);
12200 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
12201 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
12202 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
12203 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
12204 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
12205 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
12206 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
12207 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12208 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12209 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12210 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12211 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12212 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12213 	if (sdinfo->satadrv_features_support &
12214 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12215 		msg_buf[0] = '\0';
12216 		(void) snprintf(msg_buf, MAXPATHLEN,
12217 		    "Supported queue depth %d",
12218 		    sdinfo->satadrv_queue_depth);
12219 		if (!(sata_func_enable &
12220 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12221 			(void) strlcat(msg_buf,
12222 			    " - queueing disabled globally", MAXPATHLEN);
12223 		else if (sdinfo->satadrv_queue_depth >
12224 		    sdinfo->satadrv_max_queue_depth) {
12225 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12226 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12227 			    (int)sdinfo->satadrv_max_queue_depth);
12228 		}
12229 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12230 	}
12231 
12232 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12233 #ifdef __i386
12234 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12235 		    sdinfo->satadrv_capacity);
12236 #else
12237 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12238 		    sdinfo->satadrv_capacity);
12239 #endif
12240 		cmn_err(CE_CONT, "?%s", msg_buf);
12241 	}
12242 }
12243 
12244 /*
12245  * Log/display port multiplier information
12246  * No Mutex should be hold.
12247  */
12248 static void
12249 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12250     sata_device_t *sata_device)
12251 {
12252 	_NOTE(ARGUNUSED(sata_hba_inst))
12253 
12254 	int cport = sata_device->satadev_addr.cport;
12255 	sata_pmult_info_t *pmultinfo;
12256 	char msg_buf[MAXPATHLEN];
12257 	uint32_t gscr0, gscr1, gscr2, gscr64;
12258 
12259 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12260 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12261 	if (pmultinfo == NULL) {
12262 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12263 		return;
12264 	}
12265 
12266 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12267 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12268 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12269 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12270 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12271 
12272 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12273 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12274 
12275 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12276 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12277 	cmn_err(CE_CONT, "?%s", msg_buf);
12278 
12279 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12280 	if (gscr1 & (1 << 3))
12281 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12282 	else if (gscr1 & (1 << 2))
12283 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12284 	else if (gscr1 & (1 << 1))
12285 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12286 	else
12287 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12288 	cmn_err(CE_CONT, "?%s", msg_buf);
12289 
12290 	(void) strcpy(msg_buf, "\tSupport ");
12291 	if (gscr64 & (1 << 3))
12292 		(void) strlcat(msg_buf, "Asy-Notif, ",
12293 		    MAXPATHLEN);
12294 	if (gscr64 & (1 << 2))
12295 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12296 	if (gscr64 & (1 << 1))
12297 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12298 	if (gscr64 & (1 << 0))
12299 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12300 	if ((gscr64 & 0xf) == 0)
12301 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12302 	cmn_err(CE_CONT, "?%s", msg_buf);
12303 
12304 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12305 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12306 	cmn_err(CE_CONT, "?%s", msg_buf);
12307 }
12308 
12309 /*
12310  * sata_save_drive_settings extracts current setting of the device and stores
12311  * it for future reference, in case the device setup would need to be restored
12312  * after the device reset.
12313  *
12314  * For all devices read ahead and write cache settings are saved, if the
12315  * device supports these features at all.
12316  * For ATAPI devices the Removable Media Status Notification setting is saved.
12317  */
12318 static void
12319 sata_save_drive_settings(sata_drive_info_t *sdinfo)
12320 {
12321 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
12322 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
12323 
12324 		/* Current setting of Read Ahead (and Read Cache) */
12325 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
12326 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12327 		else
12328 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
12329 
12330 		/* Current setting of Write Cache */
12331 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
12332 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12333 		else
12334 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12335 	}
12336 
12337 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
12338 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
12339 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
12340 		else
12341 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
12342 	}
12343 }
12344 
12345 
12346 /*
12347  * sata_check_capacity function determines a disk capacity
12348  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
12349  *
12350  * NOTE: CHS mode is not supported! If a device does not support LBA,
12351  * this function is not called.
12352  *
12353  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
12354  */
12355 static uint64_t
12356 sata_check_capacity(sata_drive_info_t *sdinfo)
12357 {
12358 	uint64_t capacity = 0;
12359 	int i;
12360 
12361 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
12362 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
12363 		/* Capacity valid only for LBA-addressable disk devices */
12364 		return (0);
12365 
12366 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
12367 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
12368 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
12369 		/* LBA48 mode supported and enabled */
12370 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
12371 		    SATA_DEV_F_LBA28;
12372 		for (i = 3;  i >= 0;  --i) {
12373 			capacity <<= 16;
12374 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
12375 		}
12376 	} else {
12377 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
12378 		capacity <<= 16;
12379 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
12380 		if (capacity >= 0x1000000)
12381 			/* LBA28 mode */
12382 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
12383 	}
12384 	return (capacity);
12385 }
12386 
12387 
12388 /*
12389  * Allocate consistent buffer for DMA transfer
12390  *
12391  * Cannot be called from interrupt level or with mutex held - it may sleep.
12392  *
12393  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
12394  */
12395 static struct buf *
12396 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
12397 {
12398 	struct scsi_address ap;
12399 	struct buf *bp;
12400 	ddi_dma_attr_t	cur_dma_attr;
12401 
12402 	ASSERT(spx->txlt_sata_pkt != NULL);
12403 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
12404 	ap.a_target = SATA_TO_SCSI_TARGET(
12405 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
12406 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
12407 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
12408 	ap.a_lun = 0;
12409 
12410 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
12411 	    B_READ, SLEEP_FUNC, NULL);
12412 
12413 	if (bp != NULL) {
12414 		/* Allocate DMA resources for this buffer */
12415 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
12416 		/*
12417 		 * We use a local version of the dma_attr, to account
12418 		 * for a device addressing limitations.
12419 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
12420 		 * will cause dma attributes to be adjusted to a lowest
12421 		 * acceptable level.
12422 		 */
12423 		sata_adjust_dma_attr(NULL,
12424 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
12425 
12426 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
12427 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
12428 			scsi_free_consistent_buf(bp);
12429 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12430 			bp = NULL;
12431 		}
12432 	}
12433 	return (bp);
12434 }
12435 
12436 /*
12437  * Release local buffer (consistent buffer for DMA transfer) allocated
12438  * via sata_alloc_local_buffer().
12439  */
12440 static void
12441 sata_free_local_buffer(sata_pkt_txlate_t *spx)
12442 {
12443 	ASSERT(spx->txlt_sata_pkt != NULL);
12444 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
12445 
12446 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
12447 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
12448 
12449 	sata_common_free_dma_rsrcs(spx);
12450 
12451 	/* Free buffer */
12452 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
12453 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12454 }
12455 
12456 /*
12457  * Allocate sata_pkt
12458  * Pkt structure version and embedded strcutures version are initialized.
12459  * sata_pkt and sata_pkt_txlate structures are cross-linked.
12460  *
12461  * Since this may be called in interrupt context by sata_scsi_init_pkt,
12462  * callback argument determines if it can sleep or not.
12463  * Hence, it should not be called from interrupt context.
12464  *
12465  * If successful, non-NULL pointer to a sata pkt is returned.
12466  * Upon failure, NULL pointer is returned.
12467  */
12468 static sata_pkt_t *
12469 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
12470 {
12471 	sata_pkt_t *spkt;
12472 	int kmsflag;
12473 
12474 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
12475 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
12476 	if (spkt == NULL) {
12477 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12478 		    "sata_pkt_alloc: failed"));
12479 		return (NULL);
12480 	}
12481 	spkt->satapkt_rev = SATA_PKT_REV;
12482 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
12483 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
12484 	spkt->satapkt_framework_private = spx;
12485 	spx->txlt_sata_pkt = spkt;
12486 	return (spkt);
12487 }
12488 
12489 /*
12490  * Free sata pkt allocated via sata_pkt_alloc()
12491  */
12492 static void
12493 sata_pkt_free(sata_pkt_txlate_t *spx)
12494 {
12495 	ASSERT(spx->txlt_sata_pkt != NULL);
12496 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
12497 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
12498 	spx->txlt_sata_pkt = NULL;
12499 }
12500 
12501 
12502 /*
12503  * Adjust DMA attributes.
12504  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
12505  * from 8 bits to 16 bits, depending on a command being used.
12506  * Limiting max block count arbitrarily to 256 for all read/write
12507  * commands may affects performance, so check both the device and
12508  * controller capability before adjusting dma attributes.
12509  */
12510 void
12511 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
12512     ddi_dma_attr_t *adj_dma_attr)
12513 {
12514 	uint32_t count_max;
12515 
12516 	/* Copy original attributes */
12517 	*adj_dma_attr = *dma_attr;
12518 	/*
12519 	 * Things to consider: device addressing capability,
12520 	 * "excessive" controller DMA capabilities.
12521 	 * If a device is being probed/initialized, there are
12522 	 * no device info - use default limits then.
12523 	 */
12524 	if (sdinfo == NULL) {
12525 		count_max = dma_attr->dma_attr_granular * 0x100;
12526 		if (dma_attr->dma_attr_count_max > count_max)
12527 			adj_dma_attr->dma_attr_count_max = count_max;
12528 		if (dma_attr->dma_attr_maxxfer > count_max)
12529 			adj_dma_attr->dma_attr_maxxfer = count_max;
12530 		return;
12531 	}
12532 
12533 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12534 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
12535 			/*
12536 			 * 16-bit sector count may be used - we rely on
12537 			 * the assumption that only read and write cmds
12538 			 * will request more than 256 sectors worth of data
12539 			 */
12540 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
12541 		} else {
12542 			/*
12543 			 * 8-bit sector count will be used - default limits
12544 			 * for dma attributes
12545 			 */
12546 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
12547 		}
12548 		/*
12549 		 * Adjust controler dma attributes, if necessary
12550 		 */
12551 		if (dma_attr->dma_attr_count_max > count_max)
12552 			adj_dma_attr->dma_attr_count_max = count_max;
12553 		if (dma_attr->dma_attr_maxxfer > count_max)
12554 			adj_dma_attr->dma_attr_maxxfer = count_max;
12555 	}
12556 }
12557 
12558 
12559 /*
12560  * Allocate DMA resources for the buffer
12561  * This function handles initial DMA resource allocation as well as
12562  * DMA window shift and may be called repeatedly for the same DMA window
12563  * until all DMA cookies in the DMA window are processed.
12564  * To guarantee that there is always a coherent set of cookies to process
12565  * by SATA HBA driver (observing alignment, device granularity, etc.),
12566  * the number of slots for DMA cookies is equal to lesser of  a number of
12567  * cookies in a DMA window and a max number of scatter/gather entries.
12568  *
12569  * Returns DDI_SUCCESS upon successful operation.
12570  * Return failure code of a failing command or DDI_FAILURE when
12571  * internal cleanup failed.
12572  */
12573 static int
12574 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
12575     int (*callback)(caddr_t), caddr_t arg,
12576     ddi_dma_attr_t *cur_dma_attr)
12577 {
12578 	int	rval;
12579 	off_t	offset;
12580 	size_t	size;
12581 	int	max_sg_len, req_len, i;
12582 	uint_t	dma_flags;
12583 	struct buf	*bp;
12584 	uint64_t	cur_txfer_len;
12585 
12586 
12587 	ASSERT(spx->txlt_sata_pkt != NULL);
12588 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
12589 	ASSERT(bp != NULL);
12590 
12591 
12592 	if (spx->txlt_buf_dma_handle == NULL) {
12593 		/*
12594 		 * No DMA resources allocated so far - this is a first call
12595 		 * for this sata pkt.
12596 		 */
12597 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
12598 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
12599 
12600 		if (rval != DDI_SUCCESS) {
12601 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12602 			    "sata_dma_buf_setup: no buf DMA resources %x",
12603 			    rval));
12604 			return (rval);
12605 		}
12606 
12607 		if (bp->b_flags & B_READ)
12608 			dma_flags = DDI_DMA_READ;
12609 		else
12610 			dma_flags = DDI_DMA_WRITE;
12611 
12612 		if (flags & PKT_CONSISTENT)
12613 			dma_flags |= DDI_DMA_CONSISTENT;
12614 
12615 		if (flags & PKT_DMA_PARTIAL)
12616 			dma_flags |= DDI_DMA_PARTIAL;
12617 
12618 		/*
12619 		 * Check buffer alignment and size against dma attributes
12620 		 * Consider dma_attr_align only. There may be requests
12621 		 * with the size lower than device granularity, but they
12622 		 * will not read/write from/to the device, so no adjustment
12623 		 * is necessary. The dma_attr_minxfer theoretically should
12624 		 * be considered, but no HBA driver is checking it.
12625 		 */
12626 		if (IS_P2ALIGNED(bp->b_un.b_addr,
12627 		    cur_dma_attr->dma_attr_align)) {
12628 			rval = ddi_dma_buf_bind_handle(
12629 			    spx->txlt_buf_dma_handle,
12630 			    bp, dma_flags, callback, arg,
12631 			    &spx->txlt_dma_cookie,
12632 			    &spx->txlt_curwin_num_dma_cookies);
12633 		} else { /* Buffer is not aligned */
12634 
12635 			int	(*ddicallback)(caddr_t);
12636 			size_t	bufsz;
12637 
12638 			/* Check id sleeping is allowed */
12639 			ddicallback = (callback == NULL_FUNC) ?
12640 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
12641 
12642 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12643 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
12644 			    (void *)bp->b_un.b_addr, bp->b_bcount);
12645 
12646 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
12647 				/*
12648 				 * CPU will need to access data in the buffer
12649 				 * (for copying) so map it.
12650 				 */
12651 				bp_mapin(bp);
12652 
12653 			ASSERT(spx->txlt_tmp_buf == NULL);
12654 
12655 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
12656 			rval = ddi_dma_mem_alloc(
12657 			    spx->txlt_buf_dma_handle,
12658 			    bp->b_bcount,
12659 			    &sata_acc_attr,
12660 			    DDI_DMA_STREAMING,
12661 			    ddicallback, NULL,
12662 			    &spx->txlt_tmp_buf,
12663 			    &bufsz,
12664 			    &spx->txlt_tmp_buf_handle);
12665 
12666 			if (rval != DDI_SUCCESS) {
12667 				/* DMA mapping failed */
12668 				(void) ddi_dma_free_handle(
12669 				    &spx->txlt_buf_dma_handle);
12670 				spx->txlt_buf_dma_handle = NULL;
12671 #ifdef SATA_DEBUG
12672 				mbuffail_count++;
12673 #endif
12674 				SATADBG1(SATA_DBG_DMA_SETUP,
12675 				    spx->txlt_sata_hba_inst,
12676 				    "sata_dma_buf_setup: "
12677 				    "buf dma mem alloc failed %x\n", rval);
12678 				return (rval);
12679 			}
12680 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
12681 			    cur_dma_attr->dma_attr_align));
12682 
12683 #ifdef SATA_DEBUG
12684 			mbuf_count++;
12685 
12686 			if (bp->b_bcount != bufsz)
12687 				/*
12688 				 * This will require special handling, because
12689 				 * DMA cookies will be based on the temporary
12690 				 * buffer size, not the original buffer
12691 				 * b_bcount, so the residue may have to
12692 				 * be counted differently.
12693 				 */
12694 				SATADBG2(SATA_DBG_DMA_SETUP,
12695 				    spx->txlt_sata_hba_inst,
12696 				    "sata_dma_buf_setup: bp size %x != "
12697 				    "bufsz %x\n", bp->b_bcount, bufsz);
12698 #endif
12699 			if (dma_flags & DDI_DMA_WRITE) {
12700 				/*
12701 				 * Write operation - copy data into
12702 				 * an aligned temporary buffer. Buffer will be
12703 				 * synced for device by ddi_dma_addr_bind_handle
12704 				 */
12705 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
12706 				    bp->b_bcount);
12707 			}
12708 
12709 			rval = ddi_dma_addr_bind_handle(
12710 			    spx->txlt_buf_dma_handle,
12711 			    NULL,
12712 			    spx->txlt_tmp_buf,
12713 			    bufsz, dma_flags, ddicallback, 0,
12714 			    &spx->txlt_dma_cookie,
12715 			    &spx->txlt_curwin_num_dma_cookies);
12716 		}
12717 
12718 		switch (rval) {
12719 		case DDI_DMA_PARTIAL_MAP:
12720 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12721 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
12722 			/*
12723 			 * Partial DMA mapping.
12724 			 * Retrieve number of DMA windows for this request.
12725 			 */
12726 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
12727 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
12728 				if (spx->txlt_tmp_buf != NULL) {
12729 					ddi_dma_mem_free(
12730 					    &spx->txlt_tmp_buf_handle);
12731 					spx->txlt_tmp_buf = NULL;
12732 				}
12733 				(void) ddi_dma_unbind_handle(
12734 				    spx->txlt_buf_dma_handle);
12735 				(void) ddi_dma_free_handle(
12736 				    &spx->txlt_buf_dma_handle);
12737 				spx->txlt_buf_dma_handle = NULL;
12738 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12739 				    "sata_dma_buf_setup: numwin failed\n"));
12740 				return (DDI_FAILURE);
12741 			}
12742 			SATADBG2(SATA_DBG_DMA_SETUP,
12743 			    spx->txlt_sata_hba_inst,
12744 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
12745 			    spx->txlt_num_dma_win,
12746 			    spx->txlt_curwin_num_dma_cookies);
12747 			spx->txlt_cur_dma_win = 0;
12748 			break;
12749 
12750 		case DDI_DMA_MAPPED:
12751 			/* DMA fully mapped */
12752 			spx->txlt_num_dma_win = 1;
12753 			spx->txlt_cur_dma_win = 0;
12754 			SATADBG1(SATA_DBG_DMA_SETUP,
12755 			    spx->txlt_sata_hba_inst,
12756 			    "sata_dma_buf_setup: windows: 1 "
12757 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
12758 			break;
12759 
12760 		default:
12761 			/* DMA mapping failed */
12762 			if (spx->txlt_tmp_buf != NULL) {
12763 				ddi_dma_mem_free(
12764 				    &spx->txlt_tmp_buf_handle);
12765 				spx->txlt_tmp_buf = NULL;
12766 			}
12767 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12768 			spx->txlt_buf_dma_handle = NULL;
12769 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12770 			    "sata_dma_buf_setup: buf dma handle binding "
12771 			    "failed %x\n", rval));
12772 			return (rval);
12773 		}
12774 		spx->txlt_curwin_processed_dma_cookies = 0;
12775 		spx->txlt_dma_cookie_list = NULL;
12776 	} else {
12777 		/*
12778 		 * DMA setup is reused. Check if we need to process more
12779 		 * cookies in current window, or to get next window, if any.
12780 		 */
12781 
12782 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
12783 		    spx->txlt_curwin_num_dma_cookies);
12784 
12785 		if (spx->txlt_curwin_processed_dma_cookies ==
12786 		    spx->txlt_curwin_num_dma_cookies) {
12787 			/*
12788 			 * All cookies from current DMA window were processed.
12789 			 * Get next DMA window.
12790 			 */
12791 			spx->txlt_cur_dma_win++;
12792 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
12793 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
12794 				    spx->txlt_cur_dma_win, &offset, &size,
12795 				    &spx->txlt_dma_cookie,
12796 				    &spx->txlt_curwin_num_dma_cookies);
12797 				spx->txlt_curwin_processed_dma_cookies = 0;
12798 			} else {
12799 				/* No more windows! End of request! */
12800 				/* What to do? - panic for now */
12801 				ASSERT(spx->txlt_cur_dma_win >=
12802 				    spx->txlt_num_dma_win);
12803 
12804 				spx->txlt_curwin_num_dma_cookies = 0;
12805 				spx->txlt_curwin_processed_dma_cookies = 0;
12806 				spx->txlt_sata_pkt->
12807 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
12808 				return (DDI_SUCCESS);
12809 			}
12810 		}
12811 	}
12812 	/* There better be at least one DMA cookie outstanding */
12813 	ASSERT((spx->txlt_curwin_num_dma_cookies -
12814 	    spx->txlt_curwin_processed_dma_cookies) > 0);
12815 
12816 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
12817 		/* The default cookie slot was used in previous run */
12818 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
12819 		spx->txlt_dma_cookie_list = NULL;
12820 		spx->txlt_dma_cookie_list_len = 0;
12821 	}
12822 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
12823 		/*
12824 		 * Processing a new DMA window - set-up dma cookies list.
12825 		 * We may reuse previously allocated cookie array if it is
12826 		 * possible.
12827 		 */
12828 		if (spx->txlt_dma_cookie_list != NULL &&
12829 		    spx->txlt_dma_cookie_list_len <
12830 		    spx->txlt_curwin_num_dma_cookies) {
12831 			/*
12832 			 * New DMA window contains more cookies than
12833 			 * the previous one. We need larger cookie list - free
12834 			 * the old one.
12835 			 */
12836 			(void) kmem_free(spx->txlt_dma_cookie_list,
12837 			    spx->txlt_dma_cookie_list_len *
12838 			    sizeof (ddi_dma_cookie_t));
12839 			spx->txlt_dma_cookie_list = NULL;
12840 			spx->txlt_dma_cookie_list_len = 0;
12841 		}
12842 		if (spx->txlt_dma_cookie_list == NULL) {
12843 			/*
12844 			 * Calculate lesser of number of cookies in this
12845 			 * DMA window and number of s/g entries.
12846 			 */
12847 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
12848 			req_len = MIN(max_sg_len,
12849 			    spx->txlt_curwin_num_dma_cookies);
12850 
12851 			/* Allocate new dma cookie array if necessary */
12852 			if (req_len == 1) {
12853 				/* Only one cookie - no need for a list */
12854 				spx->txlt_dma_cookie_list =
12855 				    &spx->txlt_dma_cookie;
12856 				spx->txlt_dma_cookie_list_len = 1;
12857 			} else {
12858 				/*
12859 				 * More than one cookie - try to allocate space.
12860 				 */
12861 				spx->txlt_dma_cookie_list = kmem_zalloc(
12862 				    sizeof (ddi_dma_cookie_t) * req_len,
12863 				    callback == NULL_FUNC ? KM_NOSLEEP :
12864 				    KM_SLEEP);
12865 				if (spx->txlt_dma_cookie_list == NULL) {
12866 					SATADBG1(SATA_DBG_DMA_SETUP,
12867 					    spx->txlt_sata_hba_inst,
12868 					    "sata_dma_buf_setup: cookie list "
12869 					    "allocation failed\n", NULL);
12870 					/*
12871 					 * We could not allocate space for
12872 					 * neccessary number of dma cookies in
12873 					 * this window, so we fail this request.
12874 					 * Next invocation would try again to
12875 					 * allocate space for cookie list.
12876 					 * Note:Packet residue was not modified.
12877 					 */
12878 					return (DDI_DMA_NORESOURCES);
12879 				} else {
12880 					spx->txlt_dma_cookie_list_len = req_len;
12881 				}
12882 			}
12883 		}
12884 		/*
12885 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
12886 		 * First cookie was already fetched.
12887 		 */
12888 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
12889 		cur_txfer_len =
12890 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
12891 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
12892 		spx->txlt_curwin_processed_dma_cookies++;
12893 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
12894 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
12895 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12896 			    &spx->txlt_dma_cookie_list[i]);
12897 			cur_txfer_len +=
12898 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12899 			spx->txlt_curwin_processed_dma_cookies++;
12900 			spx->txlt_sata_pkt->
12901 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
12902 		}
12903 	} else {
12904 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12905 		    "sata_dma_buf_setup: sliding within DMA window, "
12906 		    "cur cookie %d, total cookies %d\n",
12907 		    spx->txlt_curwin_processed_dma_cookies,
12908 		    spx->txlt_curwin_num_dma_cookies);
12909 
12910 		/*
12911 		 * Not all cookies from the current dma window were used because
12912 		 * of s/g limitation.
12913 		 * There is no need to re-size the list - it was set at
12914 		 * optimal size, or only default entry is used (s/g = 1).
12915 		 */
12916 		if (spx->txlt_dma_cookie_list == NULL) {
12917 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
12918 			spx->txlt_dma_cookie_list_len = 1;
12919 		}
12920 		/*
12921 		 * Since we are processing remaining cookies in a DMA window,
12922 		 * there may be less of them than the number of entries in the
12923 		 * current dma cookie list.
12924 		 */
12925 		req_len = MIN(spx->txlt_dma_cookie_list_len,
12926 		    (spx->txlt_curwin_num_dma_cookies -
12927 		    spx->txlt_curwin_processed_dma_cookies));
12928 
12929 		/* Fetch the next batch of cookies */
12930 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
12931 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12932 			    &spx->txlt_dma_cookie_list[i]);
12933 			cur_txfer_len +=
12934 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12935 			spx->txlt_sata_pkt->
12936 			    satapkt_cmd.satacmd_num_dma_cookies++;
12937 			spx->txlt_curwin_processed_dma_cookies++;
12938 		}
12939 	}
12940 
12941 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
12942 
12943 	/* Point sata_cmd to the cookie list */
12944 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
12945 	    &spx->txlt_dma_cookie_list[0];
12946 
12947 	/* Remember number of DMA cookies passed in sata packet */
12948 	spx->txlt_num_dma_cookies =
12949 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
12950 
12951 	ASSERT(cur_txfer_len != 0);
12952 	if (cur_txfer_len <= bp->b_bcount)
12953 		spx->txlt_total_residue -= cur_txfer_len;
12954 	else {
12955 		/*
12956 		 * Temporary DMA buffer has been padded by
12957 		 * ddi_dma_mem_alloc()!
12958 		 * This requires special handling, because DMA cookies are
12959 		 * based on the temporary buffer size, not the b_bcount,
12960 		 * and we have extra bytes to transfer - but the packet
12961 		 * residue has to stay correct because we will copy only
12962 		 * the requested number of bytes.
12963 		 */
12964 		spx->txlt_total_residue -= bp->b_bcount;
12965 	}
12966 
12967 	return (DDI_SUCCESS);
12968 }
12969 
12970 /*
12971  * Common routine for releasing DMA resources
12972  */
12973 static void
12974 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
12975 {
12976 	if (spx->txlt_buf_dma_handle != NULL) {
12977 		if (spx->txlt_tmp_buf != NULL)  {
12978 			/*
12979 			 * Intermediate DMA buffer was allocated.
12980 			 * Free allocated buffer and associated access handle.
12981 			 */
12982 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
12983 			spx->txlt_tmp_buf = NULL;
12984 		}
12985 		/*
12986 		 * Free DMA resources - cookies and handles
12987 		 */
12988 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
12989 		if (spx->txlt_dma_cookie_list != NULL) {
12990 			if (spx->txlt_dma_cookie_list !=
12991 			    &spx->txlt_dma_cookie) {
12992 				(void) kmem_free(spx->txlt_dma_cookie_list,
12993 				    spx->txlt_dma_cookie_list_len *
12994 				    sizeof (ddi_dma_cookie_t));
12995 				spx->txlt_dma_cookie_list = NULL;
12996 			}
12997 		}
12998 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
12999 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
13000 		spx->txlt_buf_dma_handle = NULL;
13001 	}
13002 }
13003 
13004 /*
13005  * Free DMA resources
13006  * Used by the HBA driver to release DMA resources that it does not use.
13007  *
13008  * Returns Void
13009  */
13010 void
13011 sata_free_dma_resources(sata_pkt_t *sata_pkt)
13012 {
13013 	sata_pkt_txlate_t *spx;
13014 
13015 	if (sata_pkt == NULL)
13016 		return;
13017 
13018 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
13019 
13020 	sata_common_free_dma_rsrcs(spx);
13021 }
13022 
13023 /*
13024  * Fetch Device Identify data.
13025  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
13026  * command to a device and get the device identify data.
13027  * The device_info structure has to be set to device type (for selecting proper
13028  * device identify command).
13029  *
13030  * Returns:
13031  * SATA_SUCCESS if cmd succeeded
13032  * SATA_RETRY if cmd was rejected and could be retried,
13033  * SATA_FAILURE if cmd failed and should not be retried (port error)
13034  *
13035  * Cannot be called in an interrupt context.
13036  */
13037 
13038 static int
13039 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
13040     sata_drive_info_t *sdinfo)
13041 {
13042 	struct buf *bp;
13043 	sata_pkt_t *spkt;
13044 	sata_cmd_t *scmd;
13045 	sata_pkt_txlate_t *spx;
13046 	int rval;
13047 
13048 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13049 	spx->txlt_sata_hba_inst = sata_hba_inst;
13050 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13051 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13052 	if (spkt == NULL) {
13053 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13054 		return (SATA_RETRY); /* may retry later */
13055 	}
13056 	/* address is needed now */
13057 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13058 
13059 	/*
13060 	 * Allocate buffer for Identify Data return data
13061 	 */
13062 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
13063 	if (bp == NULL) {
13064 		sata_pkt_free(spx);
13065 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13066 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13067 		    "sata_fetch_device_identify_data: "
13068 		    "cannot allocate buffer for ID"));
13069 		return (SATA_RETRY); /* may retry later */
13070 	}
13071 
13072 	/* Fill sata_pkt */
13073 	sdinfo->satadrv_state = SATA_STATE_PROBING;
13074 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13075 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13076 	/* Synchronous mode, no callback */
13077 	spkt->satapkt_comp = NULL;
13078 	/* Timeout 30s */
13079 	spkt->satapkt_time = sata_default_pkt_time;
13080 
13081 	scmd = &spkt->satapkt_cmd;
13082 	scmd->satacmd_bp = bp;
13083 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13084 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13085 
13086 	/* Build Identify Device cmd in the sata_pkt */
13087 	scmd->satacmd_addr_type = 0;		/* N/A */
13088 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13089 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13090 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
13091 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
13092 	scmd->satacmd_features_reg = 0;		/* N/A */
13093 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13094 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
13095 		/* Identify Packet Device cmd */
13096 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
13097 	} else {
13098 		/* Identify Device cmd - mandatory for all other devices */
13099 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
13100 	}
13101 
13102 	/* Send pkt to SATA HBA driver */
13103 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
13104 
13105 #ifdef SATA_INJECT_FAULTS
13106 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13107 #endif
13108 
13109 	if (rval == SATA_TRAN_ACCEPTED &&
13110 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
13111 		if (spx->txlt_buf_dma_handle != NULL) {
13112 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13113 			    DDI_DMA_SYNC_FORKERNEL);
13114 			ASSERT(rval == DDI_SUCCESS);
13115 		}
13116 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
13117 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
13118 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13119 			    "SATA disk device at port %d - "
13120 			    "partial Identify Data",
13121 			    sdinfo->satadrv_addr.cport));
13122 			rval = SATA_RETRY; /* may retry later */
13123 			goto fail;
13124 		}
13125 		/* Update sata_drive_info */
13126 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
13127 		    sizeof (sata_id_t));
13128 
13129 		sdinfo->satadrv_features_support = 0;
13130 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
13131 			/*
13132 			 * Retrieve capacity (disks only) and addressing mode
13133 			 */
13134 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
13135 		} else {
13136 			/*
13137 			 * For ATAPI devices one would have to issue
13138 			 * Get Capacity cmd for media capacity. Not here.
13139 			 */
13140 			sdinfo->satadrv_capacity = 0;
13141 			/*
13142 			 * Check what cdb length is supported
13143 			 */
13144 			if ((sdinfo->satadrv_id.ai_config &
13145 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
13146 				sdinfo->satadrv_atapi_cdb_len = 16;
13147 			else
13148 				sdinfo->satadrv_atapi_cdb_len = 12;
13149 		}
13150 		/* Setup supported features flags */
13151 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
13152 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
13153 
13154 		/* Check for SATA GEN and NCQ support */
13155 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
13156 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
13157 			/* SATA compliance */
13158 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
13159 				sdinfo->satadrv_features_support |=
13160 				    SATA_DEV_F_NCQ;
13161 			if (sdinfo->satadrv_id.ai_satacap &
13162 			    (SATA_1_SPEED | SATA_2_SPEED)) {
13163 				if (sdinfo->satadrv_id.ai_satacap &
13164 				    SATA_2_SPEED)
13165 					sdinfo->satadrv_features_support |=
13166 					    SATA_DEV_F_SATA2;
13167 				if (sdinfo->satadrv_id.ai_satacap &
13168 				    SATA_1_SPEED)
13169 					sdinfo->satadrv_features_support |=
13170 					    SATA_DEV_F_SATA1;
13171 			} else {
13172 				sdinfo->satadrv_features_support |=
13173 				    SATA_DEV_F_SATA1;
13174 			}
13175 		}
13176 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
13177 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
13178 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
13179 
13180 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
13181 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
13182 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
13183 			++sdinfo->satadrv_queue_depth;
13184 			/* Adjust according to controller capabilities */
13185 			sdinfo->satadrv_max_queue_depth = MIN(
13186 			    sdinfo->satadrv_queue_depth,
13187 			    SATA_QDEPTH(sata_hba_inst));
13188 			/* Adjust according to global queue depth limit */
13189 			sdinfo->satadrv_max_queue_depth = MIN(
13190 			    sdinfo->satadrv_max_queue_depth,
13191 			    sata_current_max_qdepth);
13192 			if (sdinfo->satadrv_max_queue_depth == 0)
13193 				sdinfo->satadrv_max_queue_depth = 1;
13194 		} else
13195 			sdinfo->satadrv_max_queue_depth = 1;
13196 
13197 		rval = SATA_SUCCESS;
13198 	} else {
13199 		/*
13200 		 * Woops, no Identify Data.
13201 		 */
13202 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
13203 			rval = SATA_RETRY; /* may retry later */
13204 		} else if (rval == SATA_TRAN_ACCEPTED) {
13205 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
13206 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
13207 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13208 			    spkt->satapkt_reason == SATA_PKT_RESET)
13209 				rval = SATA_RETRY; /* may retry later */
13210 			else
13211 				rval = SATA_FAILURE;
13212 		} else {
13213 			rval = SATA_FAILURE;
13214 		}
13215 	}
13216 fail:
13217 	/* Free allocated resources */
13218 	sata_free_local_buffer(spx);
13219 	sata_pkt_free(spx);
13220 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13221 
13222 	return (rval);
13223 }
13224 
13225 
13226 /*
13227  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13228  * UDMA mode is checked first, followed by MWDMA mode.
13229  * set correctly, so this function is setting it to the highest supported level.
13230  * Older SATA spec required that the device supports at least DMA 4 mode and
13231  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13232  * restriction has been removed.
13233  *
13234  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13235  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13236  *
13237  * NOTE: This function should be called only if DMA mode is supported.
13238  */
13239 static int
13240 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13241 {
13242 	sata_pkt_t *spkt;
13243 	sata_cmd_t *scmd;
13244 	sata_pkt_txlate_t *spx;
13245 	int i, mode;
13246 	uint8_t subcmd;
13247 	int rval = SATA_SUCCESS;
13248 
13249 	ASSERT(sdinfo != NULL);
13250 	ASSERT(sata_hba_inst != NULL);
13251 
13252 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13253 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13254 		/* Find highest Ultra DMA mode supported */
13255 		for (mode = 6; mode >= 0; --mode) {
13256 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13257 				break;
13258 		}
13259 #if 0
13260 		/* Left for historical reasons */
13261 		/*
13262 		 * Some initial version of SATA spec indicated that at least
13263 		 * UDMA mode 4 has to be supported. It is not mentioned in
13264 		 * SerialATA 2.6, so this restriction is removed.
13265 		 */
13266 		if (mode < 4)
13267 			return (SATA_FAILURE);
13268 #endif
13269 
13270 		/*
13271 		 * For disk, we're still going to set DMA mode whatever is
13272 		 * selected by default
13273 		 *
13274 		 * We saw an old maxtor sata drive will select Ultra DMA and
13275 		 * Multi-Word DMA simultaneouly by default, which is going
13276 		 * to cause DMA command timed out, so we need to select DMA
13277 		 * mode even when it's already done by default
13278 		 */
13279 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13280 
13281 			/* Find UDMA mode currently selected */
13282 			for (i = 6; i >= 0; --i) {
13283 				if (sdinfo->satadrv_id.ai_ultradma &
13284 				    (1 << (i + 8)))
13285 					break;
13286 			}
13287 			if (i >= mode)
13288 				/* Nothing to do */
13289 				return (SATA_SUCCESS);
13290 		}
13291 
13292 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13293 
13294 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13295 		/* Find highest MultiWord DMA mode supported */
13296 		for (mode = 2; mode >= 0; --mode) {
13297 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13298 				break;
13299 		}
13300 
13301 		/*
13302 		 * For disk, We're still going to set DMA mode whatever is
13303 		 * selected by default
13304 		 *
13305 		 * We saw an old maxtor sata drive will select Ultra DMA and
13306 		 * Multi-Word DMA simultaneouly by default, which is going
13307 		 * to cause DMA command timed out, so we need to select DMA
13308 		 * mode even when it's already done by default
13309 		 */
13310 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13311 
13312 			/* Find highest MultiWord DMA mode selected */
13313 			for (i = 2; i >= 0; --i) {
13314 				if (sdinfo->satadrv_id.ai_dworddma &
13315 				    (1 << (i + 8)))
13316 					break;
13317 			}
13318 			if (i >= mode)
13319 				/* Nothing to do */
13320 				return (SATA_SUCCESS);
13321 		}
13322 
13323 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
13324 	} else
13325 		return (SATA_SUCCESS);
13326 
13327 	/*
13328 	 * Set DMA mode via SET FEATURES COMMAND.
13329 	 * Prepare packet for SET FEATURES COMMAND.
13330 	 */
13331 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13332 	spx->txlt_sata_hba_inst = sata_hba_inst;
13333 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13334 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13335 	if (spkt == NULL) {
13336 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13337 		    "sata_set_dma_mode: could not set DMA mode %d", mode));
13338 		rval = SATA_FAILURE;
13339 		goto done;
13340 	}
13341 	/* Fill sata_pkt */
13342 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13343 	/* Timeout 30s */
13344 	spkt->satapkt_time = sata_default_pkt_time;
13345 	/* Synchronous mode, no callback, interrupts */
13346 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13347 	spkt->satapkt_comp = NULL;
13348 	scmd = &spkt->satapkt_cmd;
13349 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13350 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13351 	scmd->satacmd_addr_type = 0;
13352 	scmd->satacmd_device_reg = 0;
13353 	scmd->satacmd_status_reg = 0;
13354 	scmd->satacmd_error_reg = 0;
13355 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13356 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
13357 	scmd->satacmd_sec_count_lsb = subcmd | mode;
13358 
13359 	/* Transfer command to HBA */
13360 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
13361 	    spkt) != SATA_TRAN_ACCEPTED ||
13362 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13363 		/* Pkt execution failed */
13364 		rval = SATA_FAILURE;
13365 	}
13366 done:
13367 
13368 	/* Free allocated resources */
13369 	if (spkt != NULL)
13370 		sata_pkt_free(spx);
13371 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13372 
13373 	return (rval);
13374 }
13375 
13376 
13377 /*
13378  * Set device caching mode.
13379  * One of the following operations should be specified:
13380  * SATAC_SF_ENABLE_READ_AHEAD
13381  * SATAC_SF_DISABLE_READ_AHEAD
13382  * SATAC_SF_ENABLE_WRITE_CACHE
13383  * SATAC_SF_DISABLE_WRITE_CACHE
13384  *
13385  * If operation fails, system log messgage is emitted.
13386  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
13387  * command was sent but did not succeed, and SATA_FAILURE otherwise.
13388  */
13389 
13390 static int
13391 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13392     int cache_op)
13393 {
13394 	sata_pkt_t *spkt;
13395 	sata_cmd_t *scmd;
13396 	sata_pkt_txlate_t *spx;
13397 	int rval = SATA_SUCCESS;
13398 	int hba_rval;
13399 	char *infop;
13400 
13401 	ASSERT(sdinfo != NULL);
13402 	ASSERT(sata_hba_inst != NULL);
13403 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
13404 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
13405 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
13406 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
13407 
13408 
13409 	/* Prepare packet for SET FEATURES COMMAND */
13410 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13411 	spx->txlt_sata_hba_inst = sata_hba_inst;
13412 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13413 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13414 	if (spkt == NULL) {
13415 		rval = SATA_FAILURE;
13416 		goto failure;
13417 	}
13418 	/* Fill sata_pkt */
13419 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13420 	/* Timeout 30s */
13421 	spkt->satapkt_time = sata_default_pkt_time;
13422 	/* Synchronous mode, no callback, interrupts */
13423 	spkt->satapkt_op_mode =
13424 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13425 	spkt->satapkt_comp = NULL;
13426 	scmd = &spkt->satapkt_cmd;
13427 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13428 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13429 	scmd->satacmd_addr_type = 0;
13430 	scmd->satacmd_device_reg = 0;
13431 	scmd->satacmd_status_reg = 0;
13432 	scmd->satacmd_error_reg = 0;
13433 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13434 	scmd->satacmd_features_reg = cache_op;
13435 
13436 	/* Transfer command to HBA */
13437 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
13438 	    SATA_DIP(sata_hba_inst), spkt);
13439 
13440 #ifdef SATA_INJECT_FAULTS
13441 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13442 #endif
13443 
13444 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
13445 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13446 		/* Pkt execution failed */
13447 		switch (cache_op) {
13448 		case SATAC_SF_ENABLE_READ_AHEAD:
13449 			infop = "enabling read ahead failed";
13450 			break;
13451 		case SATAC_SF_DISABLE_READ_AHEAD:
13452 			infop = "disabling read ahead failed";
13453 			break;
13454 		case SATAC_SF_ENABLE_WRITE_CACHE:
13455 			infop = "enabling write cache failed";
13456 			break;
13457 		case SATAC_SF_DISABLE_WRITE_CACHE:
13458 			infop = "disabling write cache failed";
13459 			break;
13460 		}
13461 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13462 		rval = SATA_RETRY;
13463 	}
13464 failure:
13465 	/* Free allocated resources */
13466 	if (spkt != NULL)
13467 		sata_pkt_free(spx);
13468 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13469 	return (rval);
13470 }
13471 
13472 /*
13473  * Set Removable Media Status Notification (enable/disable)
13474  * state == 0 , disable
13475  * state != 0 , enable
13476  *
13477  * If operation fails, system log messgage is emitted.
13478  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
13479  */
13480 
13481 static int
13482 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13483     int state)
13484 {
13485 	sata_pkt_t *spkt;
13486 	sata_cmd_t *scmd;
13487 	sata_pkt_txlate_t *spx;
13488 	int rval = SATA_SUCCESS;
13489 	char *infop;
13490 
13491 	ASSERT(sdinfo != NULL);
13492 	ASSERT(sata_hba_inst != NULL);
13493 
13494 	/* Prepare packet for SET FEATURES COMMAND */
13495 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13496 	spx->txlt_sata_hba_inst = sata_hba_inst;
13497 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13498 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13499 	if (spkt == NULL) {
13500 		rval = SATA_FAILURE;
13501 		goto failure;
13502 	}
13503 	/* Fill sata_pkt */
13504 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13505 	/* Timeout 30s */
13506 	spkt->satapkt_time = sata_default_pkt_time;
13507 	/* Synchronous mode, no callback, interrupts */
13508 	spkt->satapkt_op_mode =
13509 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13510 	spkt->satapkt_comp = NULL;
13511 	scmd = &spkt->satapkt_cmd;
13512 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13513 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13514 	scmd->satacmd_addr_type = 0;
13515 	scmd->satacmd_device_reg = 0;
13516 	scmd->satacmd_status_reg = 0;
13517 	scmd->satacmd_error_reg = 0;
13518 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13519 	if (state == 0)
13520 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
13521 	else
13522 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
13523 
13524 	/* Transfer command to HBA */
13525 	if (((*SATA_START_FUNC(sata_hba_inst))(
13526 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
13527 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13528 		/* Pkt execution failed */
13529 		if (state == 0)
13530 			infop = "disabling Removable Media Status "
13531 			    "Notification failed";
13532 		else
13533 			infop = "enabling Removable Media Status "
13534 			    "Notification failed";
13535 
13536 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13537 		rval = SATA_FAILURE;
13538 	}
13539 failure:
13540 	/* Free allocated resources */
13541 	if (spkt != NULL)
13542 		sata_pkt_free(spx);
13543 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13544 	return (rval);
13545 }
13546 
13547 
13548 /*
13549  * Update state and copy port ss* values from passed sata_device structure.
13550  * sata_address is validated - if not valid, nothing is changed in sata_scsi
13551  * configuration struct.
13552  *
13553  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
13554  * regardless of the state in device argument.
13555  *
13556  * Port mutex should be held while calling this function.
13557  */
13558 static void
13559 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
13560     sata_device_t *sata_device)
13561 {
13562 	sata_cport_info_t *cportinfo;
13563 
13564 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
13565 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
13566 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
13567 		    sata_device->satadev_addr.cport)
13568 			return;
13569 
13570 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
13571 		    sata_device->satadev_addr.cport);
13572 
13573 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
13574 		cportinfo->cport_scr = sata_device->satadev_scr;
13575 
13576 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
13577 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
13578 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13579 		cportinfo->cport_state |=
13580 		    sata_device->satadev_state & SATA_PSTATE_VALID;
13581 	}
13582 }
13583 
13584 void
13585 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
13586     sata_device_t *sata_device)
13587 {
13588 	sata_pmport_info_t *pmportinfo;
13589 
13590 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
13591 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
13592 	    SATA_NUM_PMPORTS(sata_hba_inst,
13593 	    sata_device->satadev_addr.cport) <
13594 	    sata_device->satadev_addr.pmport) {
13595 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
13596 		    "sata_update_port_info: error address %p.",
13597 		    &sata_device->satadev_addr);
13598 		return;
13599 	}
13600 
13601 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
13602 	    sata_device->satadev_addr.cport,
13603 	    sata_device->satadev_addr.pmport);
13604 
13605 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
13606 	pmportinfo->pmport_scr = sata_device->satadev_scr;
13607 
13608 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
13609 	pmportinfo->pmport_state &=
13610 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13611 	pmportinfo->pmport_state |=
13612 	    sata_device->satadev_state & SATA_PSTATE_VALID;
13613 }
13614 
13615 /*
13616  * Extract SATA port specification from an IOCTL argument.
13617  *
13618  * This function return the port the user land send us as is, unless it
13619  * cannot retrieve port spec, then -1 is returned.
13620  *
13621  * Support port multiplier.
13622  */
13623 static int32_t
13624 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
13625 {
13626 	int32_t port;
13627 
13628 	/* Extract port number from nvpair in dca structure  */
13629 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
13630 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
13631 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
13632 		    port));
13633 		port = -1;
13634 	}
13635 
13636 	return (port);
13637 }
13638 
13639 /*
13640  * Get dev_info_t pointer to the device node pointed to by port argument.
13641  * NOTE: target argument is a value used in ioctls to identify
13642  * the AP - it is not a sata_address.
13643  * It is a combination of cport, pmport and address qualifier, encodded same
13644  * way as a scsi target number.
13645  * At this moment it carries only cport number.
13646  *
13647  * PMult hotplug is supported now.
13648  *
13649  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13650  */
13651 
13652 static dev_info_t *
13653 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
13654 {
13655 	dev_info_t	*cdip = NULL;
13656 	int		target, tgt;
13657 	int 		circ;
13658 	uint8_t		qual;
13659 
13660 	sata_hba_inst_t	*sata_hba_inst;
13661 	scsi_hba_tran_t *scsi_hba_tran;
13662 
13663 	/* Get target id */
13664 	scsi_hba_tran = ddi_get_driver_private(dip);
13665 	if (scsi_hba_tran == NULL)
13666 		return (NULL);
13667 
13668 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
13669 
13670 	if (sata_hba_inst == NULL)
13671 		return (NULL);
13672 
13673 	/* Identify a port-mult by cport_info.cport_dev_type */
13674 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
13675 		qual = SATA_ADDR_DPMPORT;
13676 	else
13677 		qual = SATA_ADDR_DCPORT;
13678 
13679 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
13680 
13681 	/* Retrieve target dip */
13682 	ndi_devi_enter(dip, &circ);
13683 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13684 		dev_info_t *next = ddi_get_next_sibling(cdip);
13685 
13686 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13687 		    DDI_PROP_DONTPASS, "target", -1);
13688 		if (tgt == -1) {
13689 			/*
13690 			 * This is actually an error condition, but not
13691 			 * a fatal one. Just continue the search.
13692 			 */
13693 			cdip = next;
13694 			continue;
13695 		}
13696 
13697 		if (tgt == target)
13698 			break;
13699 
13700 		cdip = next;
13701 	}
13702 	ndi_devi_exit(dip, circ);
13703 
13704 	return (cdip);
13705 }
13706 
13707 /*
13708  * Get dev_info_t pointer to the device node pointed to by port argument.
13709  * NOTE: target argument is a value used in ioctls to identify
13710  * the AP - it is not a sata_address.
13711  * It is a combination of cport, pmport and address qualifier, encoded same
13712  * way as a scsi target number.
13713  *
13714  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13715  */
13716 
13717 static dev_info_t *
13718 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
13719 {
13720 	dev_info_t	*cdip = NULL;
13721 	int		target, tgt;
13722 	int 		circ;
13723 
13724 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
13725 
13726 	ndi_devi_enter(dip, &circ);
13727 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13728 		dev_info_t *next = ddi_get_next_sibling(cdip);
13729 
13730 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13731 		    DDI_PROP_DONTPASS, "target", -1);
13732 		if (tgt == -1) {
13733 			/*
13734 			 * This is actually an error condition, but not
13735 			 * a fatal one. Just continue the search.
13736 			 */
13737 			cdip = next;
13738 			continue;
13739 		}
13740 
13741 		if (tgt == target)
13742 			break;
13743 
13744 		cdip = next;
13745 	}
13746 	ndi_devi_exit(dip, circ);
13747 
13748 	return (cdip);
13749 }
13750 
13751 /*
13752  * Process sata port disconnect request.
13753  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
13754  * before this request. Nevertheless, if a device is still configured,
13755  * we need to attempt to offline and unconfigure device.
13756  * Regardless of the unconfigure operation results the port is marked as
13757  * deactivated and no access to the attached device is possible.
13758  * If the target node remains because unconfigure operation failed, its state
13759  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
13760  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
13761  * the device and remove old target node.
13762  *
13763  * This function invokes sata_hba_inst->satahba_tran->
13764  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13765  * If successful, the device structure (if any) attached to the specified port
13766  * is removed and state of the port marked appropriately.
13767  * Failure of the port_deactivate may keep port in the physically active state,
13768  * or may fail the port.
13769  *
13770  * NOTE: Port multiplier is supported.
13771  */
13772 
13773 static int
13774 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
13775     sata_device_t *sata_device)
13776 {
13777 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
13778 	sata_cport_info_t *cportinfo = NULL;
13779 	sata_pmport_info_t *pmportinfo = NULL;
13780 	sata_pmult_info_t *pmultinfo = NULL;
13781 	sata_device_t subsdevice;
13782 	int cport, pmport, qual;
13783 	int rval = SATA_SUCCESS;
13784 	int npmport = 0;
13785 	int rv = 0;
13786 
13787 	cport = sata_device->satadev_addr.cport;
13788 	pmport = sata_device->satadev_addr.pmport;
13789 	qual = sata_device->satadev_addr.qual;
13790 
13791 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13792 	if (qual == SATA_ADDR_DCPORT)
13793 		qual = SATA_ADDR_CPORT;
13794 	else
13795 		qual = SATA_ADDR_PMPORT;
13796 
13797 	/*
13798 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
13799 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13800 	 * Do the sanity check.
13801 	 */
13802 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
13803 		/* No physical port deactivation supported. */
13804 		return (EINVAL);
13805 	}
13806 
13807 	/* Check the current state of the port */
13808 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
13809 	    (SATA_DIP(sata_hba_inst), sata_device);
13810 
13811 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13812 
13813 	/*
13814 	 * Processing port mulitiplier
13815 	 */
13816 	if (qual == SATA_ADDR_CPORT &&
13817 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
13818 		mutex_enter(&cportinfo->cport_mutex);
13819 
13820 		/* Check controller port status */
13821 		sata_update_port_info(sata_hba_inst, sata_device);
13822 		if (rval != SATA_SUCCESS ||
13823 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13824 			/*
13825 			 * Device port status is unknown or it is in failed
13826 			 * state
13827 			 */
13828 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13829 			    SATA_PSTATE_FAILED;
13830 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13831 			    "sata_hba_ioctl: connect: failed to deactivate "
13832 			    "SATA port %d", cport);
13833 			mutex_exit(&cportinfo->cport_mutex);
13834 			return (EIO);
13835 		}
13836 
13837 		/* Disconnect all sub-devices. */
13838 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13839 		if (pmultinfo != NULL) {
13840 
13841 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
13842 			    sata_hba_inst, cport); npmport ++) {
13843 				subsdinfo = SATA_PMPORT_DRV_INFO(
13844 				    sata_hba_inst, cport, npmport);
13845 				if (subsdinfo == NULL)
13846 					continue;
13847 
13848 				subsdevice.satadev_addr = subsdinfo->
13849 				    satadrv_addr;
13850 
13851 				mutex_exit(&cportinfo->cport_mutex);
13852 				if (sata_ioctl_disconnect(sata_hba_inst,
13853 				    &subsdevice) == SATA_SUCCESS) {
13854 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
13855 					"[Remove] device at port %d:%d "
13856 					"successfully.", cport, npmport);
13857 				}
13858 				mutex_enter(&cportinfo->cport_mutex);
13859 			}
13860 		}
13861 
13862 		/* Disconnect the port multiplier */
13863 		cportinfo->cport_state &= ~SATA_STATE_READY;
13864 		mutex_exit(&cportinfo->cport_mutex);
13865 
13866 		sata_device->satadev_addr.qual = qual;
13867 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13868 		    (SATA_DIP(sata_hba_inst), sata_device);
13869 
13870 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13871 		    SE_NO_HINT);
13872 
13873 		mutex_enter(&cportinfo->cport_mutex);
13874 		sata_update_port_info(sata_hba_inst, sata_device);
13875 		if (rval != SATA_SUCCESS &&
13876 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13877 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13878 			rv = EIO;
13879 		} else {
13880 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13881 		}
13882 		mutex_exit(&cportinfo->cport_mutex);
13883 
13884 		return (rv);
13885 	}
13886 
13887 	/*
13888 	 * Process non-port-multiplier device - it could be a drive connected
13889 	 * to a port multiplier port or a controller port.
13890 	 */
13891 	if (qual == SATA_ADDR_PMPORT) {
13892 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13893 		mutex_enter(&pmportinfo->pmport_mutex);
13894 		sata_update_pmport_info(sata_hba_inst, sata_device);
13895 		if (rval != SATA_SUCCESS ||
13896 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13897 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
13898 			    SATA_PSTATE_FAILED;
13899 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13900 			    "sata_hba_ioctl: connect: failed to deactivate "
13901 			    "SATA port %d:%d", cport, pmport);
13902 			mutex_exit(&pmportinfo->pmport_mutex);
13903 			return (EIO);
13904 		}
13905 
13906 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
13907 			sdinfo = pmportinfo->pmport_sata_drive;
13908 			ASSERT(sdinfo != NULL);
13909 		}
13910 
13911 		/*
13912 		 * Set port's dev_state to not ready - this will disable
13913 		 * an access to a potentially attached device.
13914 		 */
13915 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
13916 
13917 		/* Remove and release sata_drive info structure. */
13918 		if (sdinfo != NULL) {
13919 			if ((sdinfo->satadrv_type &
13920 			    SATA_VALID_DEV_TYPE) != 0) {
13921 				/*
13922 				 * If a target node exists, try to offline
13923 				 * a device and remove target node.
13924 				 */
13925 				mutex_exit(&pmportinfo->pmport_mutex);
13926 				(void) sata_offline_device(sata_hba_inst,
13927 				    sata_device, sdinfo);
13928 				mutex_enter(&pmportinfo->pmport_mutex);
13929 			}
13930 
13931 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
13932 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
13933 			(void) kmem_free((void *)sdinfo,
13934 			    sizeof (sata_drive_info_t));
13935 		}
13936 		mutex_exit(&pmportinfo->pmport_mutex);
13937 
13938 	} else if (qual == SATA_ADDR_CPORT) {
13939 		mutex_enter(&cportinfo->cport_mutex);
13940 		sata_update_port_info(sata_hba_inst, sata_device);
13941 		if (rval != SATA_SUCCESS ||
13942 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13943 			/*
13944 			 * Device port status is unknown or it is in failed
13945 			 * state
13946 			 */
13947 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13948 			    SATA_PSTATE_FAILED;
13949 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13950 			    "sata_hba_ioctl: connect: failed to deactivate "
13951 			    "SATA port %d", cport);
13952 			mutex_exit(&cportinfo->cport_mutex);
13953 			return (EIO);
13954 		}
13955 
13956 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
13957 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13958 			ASSERT(pmultinfo != NULL);
13959 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
13960 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
13961 			ASSERT(sdinfo != NULL);
13962 		}
13963 		cportinfo->cport_state &= ~SATA_STATE_READY;
13964 
13965 		if (sdinfo != NULL) {
13966 			if ((sdinfo->satadrv_type &
13967 			    SATA_VALID_DEV_TYPE) != 0) {
13968 				/*
13969 				 * If a target node exists, try to offline
13970 				 * a device and remove target node.
13971 				 */
13972 				mutex_exit(&cportinfo->cport_mutex);
13973 				(void) sata_offline_device(sata_hba_inst,
13974 				    sata_device, sdinfo);
13975 				mutex_enter(&cportinfo->cport_mutex);
13976 			}
13977 
13978 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
13979 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
13980 			(void) kmem_free((void *)sdinfo,
13981 			    sizeof (sata_drive_info_t));
13982 		}
13983 		mutex_exit(&cportinfo->cport_mutex);
13984 	}
13985 
13986 	/* Just ask HBA driver to deactivate port */
13987 	sata_device->satadev_addr.qual = qual;
13988 
13989 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13990 	    (SATA_DIP(sata_hba_inst), sata_device);
13991 
13992 	/*
13993 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13994 	 * without the hint (to force listener to investivate the state).
13995 	 */
13996 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13997 	    SE_NO_HINT);
13998 
13999 	if (qual == SATA_ADDR_PMPORT) {
14000 		mutex_enter(&pmportinfo->pmport_mutex);
14001 		sata_update_pmport_info(sata_hba_inst, sata_device);
14002 
14003 		if (rval != SATA_SUCCESS &&
14004 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14005 			/*
14006 			 * Port deactivation failure - do not change port
14007 			 * state unless the state returned by HBA indicates a
14008 			 * port failure.
14009 			 *
14010 			 * NOTE: device structures were released, so devices
14011 			 * now are invisible! Port reset is needed to
14012 			 * re-enumerate devices.
14013 			 */
14014 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14015 			rv = EIO;
14016 		} else {
14017 			/*
14018 			 * Deactivation succeded. From now on the sata framework
14019 			 * will not care what is happening to the device, until
14020 			 * the port is activated again.
14021 			 */
14022 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14023 		}
14024 		mutex_exit(&pmportinfo->pmport_mutex);
14025 	} else if (qual == SATA_ADDR_CPORT) {
14026 		mutex_enter(&cportinfo->cport_mutex);
14027 		sata_update_port_info(sata_hba_inst, sata_device);
14028 
14029 		if (rval != SATA_SUCCESS &&
14030 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14031 			cportinfo->cport_state = SATA_PSTATE_FAILED;
14032 			rv = EIO;
14033 		} else {
14034 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14035 		}
14036 		mutex_exit(&cportinfo->cport_mutex);
14037 	}
14038 
14039 	return (rv);
14040 }
14041 
14042 
14043 
14044 /*
14045  * Process sata port connect request
14046  * The sata cfgadm pluging will invoke this operation only if port was found
14047  * in the disconnect state (failed state is also treated as the disconnected
14048  * state).
14049  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
14050  * sata_tran_hotplug_ops->sata_tran_port_activate().
14051  * If successful and a device is found attached to the port,
14052  * the initialization sequence is executed to attach a device structure to
14053  * a port structure. The state of the port and a device would be set
14054  * appropriately.
14055  * The device is not set in configured state (system-wise) by this operation.
14056  *
14057  * Note, that activating the port may generate link events,
14058  * so it is important that following processing and the
14059  * event processing does not interfere with each other!
14060  *
14061  * This operation may remove port failed state and will
14062  * try to make port active and in good standing.
14063  *
14064  * NOTE: Port multiplier is supported.
14065  */
14066 
14067 static int
14068 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
14069     sata_device_t *sata_device)
14070 {
14071 	sata_pmport_info_t	*pmportinfo = NULL;
14072 	uint8_t cport, pmport, qual;
14073 	int rv = 0;
14074 
14075 	cport = sata_device->satadev_addr.cport;
14076 	pmport = sata_device->satadev_addr.pmport;
14077 	qual = sata_device->satadev_addr.qual;
14078 
14079 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14080 	if (qual == SATA_ADDR_DCPORT)
14081 		qual = SATA_ADDR_CPORT;
14082 	else
14083 		qual = SATA_ADDR_PMPORT;
14084 
14085 	if (qual == SATA_ADDR_PMPORT)
14086 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14087 
14088 	/*
14089 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
14090 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
14091 	 * Perform sanity check now.
14092 	 */
14093 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
14094 		/* No physical port activation supported. */
14095 		return (EINVAL);
14096 	}
14097 
14098 	/* Just ask HBA driver to activate port */
14099 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14100 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14101 		/*
14102 		 * Port activation failure.
14103 		 */
14104 		if (qual == SATA_ADDR_CPORT) {
14105 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14106 			    cport)->cport_mutex);
14107 			sata_update_port_info(sata_hba_inst, sata_device);
14108 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14109 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14110 				    SATA_PSTATE_FAILED;
14111 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14112 				    "sata_hba_ioctl: connect: failed to "
14113 				    "activate SATA port %d", cport);
14114 			}
14115 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14116 			    cport)->cport_mutex);
14117 		} else { /* port multiplier device port */
14118 			mutex_enter(&pmportinfo->pmport_mutex);
14119 			sata_update_pmport_info(sata_hba_inst, sata_device);
14120 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14121 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14122 				    pmport) = SATA_PSTATE_FAILED;
14123 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14124 				    "sata_hba_ioctl: connect: failed to "
14125 				    "activate SATA port %d:%d", cport, pmport);
14126 			}
14127 			mutex_exit(&pmportinfo->pmport_mutex);
14128 		}
14129 		return (EIO);
14130 	}
14131 
14132 	/* Virgin port state - will be updated by the port re-probe. */
14133 	if (qual == SATA_ADDR_CPORT) {
14134 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14135 		    cport)->cport_mutex);
14136 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
14137 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14138 		    cport)->cport_mutex);
14139 	} else { /* port multiplier device port */
14140 		mutex_enter(&pmportinfo->pmport_mutex);
14141 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
14142 		mutex_exit(&pmportinfo->pmport_mutex);
14143 	}
14144 
14145 	/*
14146 	 * Probe the port to find its state and attached device.
14147 	 */
14148 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14149 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
14150 		rv = EIO;
14151 
14152 	/*
14153 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14154 	 * without the hint
14155 	 */
14156 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14157 	    SE_NO_HINT);
14158 
14159 	/*
14160 	 * If there is a device attached to the port, emit
14161 	 * a message.
14162 	 */
14163 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
14164 
14165 		if (qual == SATA_ADDR_CPORT) {
14166 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
14167 				sata_log(sata_hba_inst, CE_WARN,
14168 				    "SATA port multiplier detected "
14169 				    "at port %d", cport);
14170 			} else {
14171 				sata_log(sata_hba_inst, CE_WARN,
14172 				    "SATA device detected at port %d", cport);
14173 				if (sata_device->satadev_type ==
14174 				    SATA_DTYPE_UNKNOWN) {
14175 				/*
14176 				 * A device was not successfully identified
14177 				 */
14178 				sata_log(sata_hba_inst, CE_WARN,
14179 				    "Could not identify SATA "
14180 				    "device at port %d", cport);
14181 				}
14182 			}
14183 		} else { /* port multiplier device port */
14184 			sata_log(sata_hba_inst, CE_WARN,
14185 			    "SATA device detected at port %d:%d",
14186 			    cport, pmport);
14187 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14188 				/*
14189 				 * A device was not successfully identified
14190 				 */
14191 				sata_log(sata_hba_inst, CE_WARN,
14192 				    "Could not identify SATA "
14193 				    "device at port %d:%d", cport, pmport);
14194 			}
14195 		}
14196 	}
14197 
14198 	return (rv);
14199 }
14200 
14201 
14202 /*
14203  * Process sata device unconfigure request.
14204  * The unconfigure operation uses generic nexus operation to
14205  * offline a device. It leaves a target device node attached.
14206  * and obviously sata_drive_info attached as well, because
14207  * from the hardware point of view nothing has changed.
14208  */
14209 static int
14210 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14211     sata_device_t *sata_device)
14212 {
14213 	int rv = 0;
14214 	dev_info_t *tdip;
14215 
14216 	/* We are addressing attached device, not a port */
14217 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14218 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14219 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14220 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14221 
14222 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14223 	    &sata_device->satadev_addr)) != NULL) {
14224 
14225 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14226 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14227 			    "sata_hba_ioctl: unconfigure: "
14228 			    "failed to unconfigure device at SATA port %d:%d",
14229 			    sata_device->satadev_addr.cport,
14230 			    sata_device->satadev_addr.pmport));
14231 			rv = EIO;
14232 		}
14233 		/*
14234 		 * The target node devi_state should be marked with
14235 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14236 		 * This would be the indication for cfgadm that
14237 		 * the AP node occupant state is 'unconfigured'.
14238 		 */
14239 
14240 	} else {
14241 		/*
14242 		 * This would indicate a failure on the part of cfgadm
14243 		 * to detect correct state of the node prior to this
14244 		 * call - one cannot unconfigure non-existing device.
14245 		 */
14246 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14247 		    "sata_hba_ioctl: unconfigure: "
14248 		    "attempt to unconfigure non-existing device "
14249 		    "at SATA port %d:%d",
14250 		    sata_device->satadev_addr.cport,
14251 		    sata_device->satadev_addr.pmport));
14252 		rv = ENXIO;
14253 	}
14254 	return (rv);
14255 }
14256 
14257 /*
14258  * Process sata device configure request
14259  * If port is in a failed state, operation is aborted - one has to use
14260  * an explicit connect or port activate request to try to get a port into
14261  * non-failed mode. Port reset wil also work in such situation.
14262  * If the port is in disconnected (shutdown) state, the connect operation is
14263  * attempted prior to any other action.
14264  * When port is in the active state, there is a device attached and the target
14265  * node exists, a device was most likely offlined.
14266  * If target node does not exist, a new target node is created. In both cases
14267  * an attempt is made to online (configure) the device.
14268  *
14269  * NOTE: Port multiplier is supported.
14270  */
14271 static int
14272 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14273     sata_device_t *sata_device)
14274 {
14275 	int cport, pmport, qual;
14276 	int rval;
14277 	boolean_t target = TRUE;
14278 	sata_cport_info_t *cportinfo;
14279 	sata_pmport_info_t *pmportinfo = NULL;
14280 	dev_info_t *tdip;
14281 	sata_drive_info_t *sdinfo;
14282 
14283 	cport = sata_device->satadev_addr.cport;
14284 	pmport = sata_device->satadev_addr.pmport;
14285 	qual = sata_device->satadev_addr.qual;
14286 
14287 	/* Get current port state */
14288 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14289 	    (SATA_DIP(sata_hba_inst), sata_device);
14290 
14291 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14292 	if (qual == SATA_ADDR_DPMPORT) {
14293 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14294 		mutex_enter(&pmportinfo->pmport_mutex);
14295 		sata_update_pmport_info(sata_hba_inst, sata_device);
14296 		if (rval != SATA_SUCCESS ||
14297 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14298 			/*
14299 			 * Obviously, device on a failed port is not visible
14300 			 */
14301 			mutex_exit(&pmportinfo->pmport_mutex);
14302 			return (ENXIO);
14303 		}
14304 		mutex_exit(&pmportinfo->pmport_mutex);
14305 	} else {
14306 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14307 		    cport)->cport_mutex);
14308 		sata_update_port_info(sata_hba_inst, sata_device);
14309 		if (rval != SATA_SUCCESS ||
14310 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14311 			/*
14312 			 * Obviously, device on a failed port is not visible
14313 			 */
14314 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14315 			    cport)->cport_mutex);
14316 			return (ENXIO);
14317 		}
14318 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14319 		    cport)->cport_mutex);
14320 	}
14321 
14322 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
14323 		/* need to activate port */
14324 		target = FALSE;
14325 
14326 		/* Sanity check */
14327 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14328 			return (ENXIO);
14329 
14330 		/* Just let HBA driver to activate port */
14331 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14332 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14333 			/*
14334 			 * Port activation failure - do not change port state
14335 			 * unless the state returned by HBA indicates a port
14336 			 * failure.
14337 			 */
14338 			if (qual == SATA_ADDR_DPMPORT) {
14339 				mutex_enter(&pmportinfo->pmport_mutex);
14340 				sata_update_pmport_info(sata_hba_inst,
14341 				    sata_device);
14342 				if (sata_device->satadev_state &
14343 				    SATA_PSTATE_FAILED)
14344 					pmportinfo->pmport_state =
14345 					    SATA_PSTATE_FAILED;
14346 				mutex_exit(&pmportinfo->pmport_mutex);
14347 			} else {
14348 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14349 				    cport)->cport_mutex);
14350 				sata_update_port_info(sata_hba_inst,
14351 				    sata_device);
14352 				if (sata_device->satadev_state &
14353 				    SATA_PSTATE_FAILED)
14354 					cportinfo->cport_state =
14355 					    SATA_PSTATE_FAILED;
14356 				mutex_exit(&SATA_CPORT_INFO(
14357 				    sata_hba_inst, cport)->cport_mutex);
14358 			}
14359 		}
14360 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14361 		    "sata_hba_ioctl: configure: "
14362 		    "failed to activate SATA port %d:%d",
14363 		    cport, pmport));
14364 		return (EIO);
14365 	}
14366 	/*
14367 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14368 	 * without the hint.
14369 	 */
14370 	sata_gen_sysevent(sata_hba_inst,
14371 	    &sata_device->satadev_addr, SE_NO_HINT);
14372 
14373 	/* Virgin port state */
14374 	if (qual == SATA_ADDR_DPMPORT) {
14375 		mutex_enter(&pmportinfo->pmport_mutex);
14376 		pmportinfo->pmport_state = 0;
14377 		mutex_exit(&pmportinfo->pmport_mutex);
14378 	} else {
14379 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14380 		    cport)-> cport_mutex);
14381 		cportinfo->cport_state = 0;
14382 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14383 		    cport)->cport_mutex);
14384 	}
14385 	/*
14386 	 * Always reprobe port, to get current device info.
14387 	 */
14388 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14389 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14390 		return (EIO);
14391 
14392 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
14393 		if (qual == SATA_ADDR_DPMPORT) {
14394 			/*
14395 			 * That's the transition from "inactive" port
14396 			 * to active one with device attached.
14397 			 */
14398 			sata_log(sata_hba_inst, CE_WARN,
14399 			    "SATA device detected at port %d:%d",
14400 			    cport, pmport);
14401 		} else {
14402 			/*
14403 			 * When PM is attached to the cport and cport is
14404 			 * activated, every PM device port needs to be reprobed.
14405 			 * We need to emit message for all devices detected
14406 			 * at port multiplier's device ports.
14407 			 * Add such code here.
14408 			 * For now, just inform about device attached to
14409 			 * cport.
14410 			 */
14411 			sata_log(sata_hba_inst, CE_WARN,
14412 			    "SATA device detected at port %d", cport);
14413 		}
14414 	}
14415 
14416 	/*
14417 	 * This is where real configuration operation starts.
14418 	 *
14419 	 * When PM is attached to the cport and cport is activated,
14420 	 * devices attached PM device ports may have to be configured
14421 	 * explicitly. This may change when port multiplier is supported.
14422 	 * For now, configure only disks and other valid target devices.
14423 	 */
14424 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
14425 		if (qual == SATA_ADDR_DCPORT) {
14426 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14427 				/*
14428 				 * A device was not successfully identified
14429 				 */
14430 				sata_log(sata_hba_inst, CE_WARN,
14431 				    "Could not identify SATA "
14432 				    "device at port %d", cport);
14433 			}
14434 		} else { /* port multiplier device port */
14435 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14436 				/*
14437 				 * A device was not successfully identified
14438 				 */
14439 				sata_log(sata_hba_inst, CE_WARN,
14440 				    "Could not identify SATA "
14441 				    "device at port %d:%d", cport, pmport);
14442 			}
14443 		}
14444 		return (ENXIO);		/* No device to configure */
14445 	}
14446 
14447 	/*
14448 	 * Here we may have a device in reset condition,
14449 	 * but because we are just configuring it, there is
14450 	 * no need to process the reset other than just
14451 	 * to clear device reset condition in the HBA driver.
14452 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
14453 	 * cause a first command sent the HBA driver with the request
14454 	 * to clear device reset condition.
14455 	 */
14456 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14457 	if (qual == SATA_ADDR_DPMPORT)
14458 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14459 	else
14460 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14461 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14462 	if (sdinfo == NULL) {
14463 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14464 		return (ENXIO);
14465 	}
14466 	if (sdinfo->satadrv_event_flags &
14467 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14468 		sdinfo->satadrv_event_flags = 0;
14469 	}
14470 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14471 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14472 
14473 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14474 	    &sata_device->satadev_addr)) != NULL) {
14475 		/*
14476 		 * Target node exists. Verify, that it belongs
14477 		 * to existing, attached device and not to
14478 		 * a removed device.
14479 		 */
14480 		if (sata_check_device_removed(tdip) == B_TRUE) {
14481 			if (qual == SATA_ADDR_DPMPORT)
14482 				sata_log(sata_hba_inst, CE_WARN,
14483 				    "SATA device at port %d cannot be "
14484 				    "configured. "
14485 				    "Application(s) accessing "
14486 				    "previously attached device "
14487 				    "have to release it before newly "
14488 				    "inserted device can be made accessible.",
14489 				    cport);
14490 			else
14491 				sata_log(sata_hba_inst, CE_WARN,
14492 				    "SATA device at port %d:%d cannot be"
14493 				    "configured. "
14494 				    "Application(s) accessing "
14495 				    "previously attached device "
14496 				    "have to release it before newly "
14497 				    "inserted device can be made accessible.",
14498 				    cport, pmport);
14499 			return (EIO);
14500 		}
14501 		/*
14502 		 * Device was not removed and re-inserted.
14503 		 * Try to online it.
14504 		 */
14505 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
14506 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14507 			    "sata_hba_ioctl: configure: "
14508 			    "onlining device at SATA port "
14509 			    "%d:%d failed", cport, pmport));
14510 			return (EIO);
14511 		}
14512 
14513 		if (qual == SATA_ADDR_DPMPORT) {
14514 			mutex_enter(&pmportinfo->pmport_mutex);
14515 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14516 			mutex_exit(&pmportinfo->pmport_mutex);
14517 		} else {
14518 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14519 			    cport)->cport_mutex);
14520 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14521 			mutex_exit(&SATA_CPORT_INFO(
14522 			    sata_hba_inst, cport)->cport_mutex);
14523 		}
14524 	} else {
14525 		/*
14526 		 * No target node - need to create a new target node.
14527 		 */
14528 		if (qual == SATA_ADDR_DPMPORT) {
14529 			mutex_enter(&pmportinfo->pmport_mutex);
14530 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14531 			mutex_exit(&pmportinfo->pmport_mutex);
14532 		} else {
14533 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14534 			    cport_mutex);
14535 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14536 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14537 			    cport_mutex);
14538 		}
14539 
14540 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
14541 		    sata_hba_inst, &sata_device->satadev_addr);
14542 		if (tdip == NULL) {
14543 			/* Configure operation failed */
14544 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14545 			    "sata_hba_ioctl: configure: "
14546 			    "configuring SATA device at port %d:%d "
14547 			    "failed", cport, pmport));
14548 			return (EIO);
14549 		}
14550 	}
14551 	return (0);
14552 }
14553 
14554 
14555 /*
14556  * Process ioctl deactivate port request.
14557  * Arbitrarily unconfigure attached device, if any.
14558  * Even if the unconfigure fails, proceed with the
14559  * port deactivation.
14560  *
14561  * NOTE: Port Multiplier is supported now.
14562  */
14563 
14564 static int
14565 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
14566     sata_device_t *sata_device)
14567 {
14568 	int cport, pmport, qual;
14569 	int rval, rv = 0;
14570 	int npmport;
14571 	sata_cport_info_t *cportinfo;
14572 	sata_pmport_info_t *pmportinfo;
14573 	sata_pmult_info_t *pmultinfo;
14574 	dev_info_t *tdip;
14575 	sata_drive_info_t *sdinfo = NULL;
14576 	sata_device_t subsdevice;
14577 
14578 	/* Sanity check */
14579 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
14580 		return (ENOTSUP);
14581 
14582 	cport = sata_device->satadev_addr.cport;
14583 	pmport = sata_device->satadev_addr.pmport;
14584 	qual = sata_device->satadev_addr.qual;
14585 
14586 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
14587 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14588 	if (qual == SATA_ADDR_DCPORT)
14589 		qual = SATA_ADDR_CPORT;
14590 	else
14591 		qual = SATA_ADDR_PMPORT;
14592 
14593 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14594 	if (qual == SATA_ADDR_PMPORT)
14595 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14596 
14597 	/*
14598 	 * Processing port multiplier
14599 	 */
14600 	if (qual == SATA_ADDR_CPORT &&
14601 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14602 		mutex_enter(&cportinfo->cport_mutex);
14603 
14604 		/* Deactivate all sub-deices */
14605 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14606 		if (pmultinfo != NULL) {
14607 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14608 			    sata_hba_inst, cport); npmport++) {
14609 
14610 				subsdevice.satadev_addr.cport = cport;
14611 				subsdevice.satadev_addr.pmport =
14612 				    (uint8_t)npmport;
14613 				subsdevice.satadev_addr.qual =
14614 				    SATA_ADDR_DPMPORT;
14615 
14616 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14617 				    "sata_hba_ioctl: deactivate: trying to "
14618 				    "deactivate SATA port %d:%d",
14619 				    cport, npmport);
14620 
14621 				mutex_exit(&cportinfo->cport_mutex);
14622 				if (sata_ioctl_deactivate(sata_hba_inst,
14623 				    &subsdevice) == SATA_SUCCESS) {
14624 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14625 					    "[Deactivate] device at port %d:%d "
14626 					    "successfully.", cport, npmport);
14627 				}
14628 				mutex_enter(&cportinfo->cport_mutex);
14629 			}
14630 		}
14631 
14632 		/* Deactivate the port multiplier now. */
14633 		cportinfo->cport_state &= ~SATA_STATE_READY;
14634 		mutex_exit(&cportinfo->cport_mutex);
14635 
14636 		sata_device->satadev_addr.qual = qual;
14637 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14638 		    (SATA_DIP(sata_hba_inst), sata_device);
14639 
14640 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14641 		    SE_NO_HINT);
14642 
14643 		mutex_enter(&cportinfo->cport_mutex);
14644 		sata_update_port_info(sata_hba_inst, sata_device);
14645 		if (rval != SATA_SUCCESS) {
14646 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14647 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14648 			}
14649 			rv = EIO;
14650 		} else {
14651 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14652 		}
14653 		mutex_exit(&cportinfo->cport_mutex);
14654 
14655 		return (rv);
14656 	}
14657 
14658 	/*
14659 	 * Process non-port-multiplier device - it could be a drive connected
14660 	 * to a port multiplier port or a controller port.
14661 	 */
14662 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14663 	if (qual == SATA_ADDR_CPORT) {
14664 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14665 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14666 			/* deal only with valid devices */
14667 			if ((cportinfo->cport_dev_type &
14668 			    SATA_VALID_DEV_TYPE) != 0)
14669 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14670 		}
14671 		cportinfo->cport_state &= ~SATA_STATE_READY;
14672 	} else {
14673 		/* Port multiplier device port */
14674 		mutex_enter(&pmportinfo->pmport_mutex);
14675 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14676 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
14677 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
14678 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
14679 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14680 		mutex_exit(&pmportinfo->pmport_mutex);
14681 	}
14682 
14683 	if (sdinfo != NULL) {
14684 		/*
14685 		 * If a target node exists, try to offline a device and
14686 		 * to remove a target node.
14687 		 */
14688 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14689 		    cport_mutex);
14690 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14691 		    &sata_device->satadev_addr);
14692 		if (tdip != NULL) {
14693 			/* target node exist */
14694 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14695 			    "sata_hba_ioctl: port deactivate: "
14696 			    "target node exists.", NULL);
14697 
14698 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
14699 			    NDI_SUCCESS) {
14700 				SATA_LOG_D((sata_hba_inst, CE_WARN,
14701 				    "sata_hba_ioctl: port deactivate: "
14702 				    "failed to unconfigure device at port "
14703 				    "%d:%d before deactivating the port",
14704 				    cport, pmport));
14705 				/*
14706 				 * Set DEVICE REMOVED state in the target
14707 				 * node. It will prevent an access to
14708 				 * the device even when a new device is
14709 				 * attached, until the old target node is
14710 				 * released, removed and recreated for a new
14711 				 * device.
14712 				 */
14713 				sata_set_device_removed(tdip);
14714 
14715 				/*
14716 				 * Instruct the event daemon to try the
14717 				 * target node cleanup later.
14718 				 */
14719 				sata_set_target_node_cleanup(sata_hba_inst,
14720 				    &sata_device->satadev_addr);
14721 			}
14722 		}
14723 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14724 		    cport_mutex);
14725 		/*
14726 		 * In any case, remove and release sata_drive_info
14727 		 * structure.
14728 		 */
14729 		if (qual == SATA_ADDR_CPORT) {
14730 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14731 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14732 		} else { /* port multiplier device port */
14733 			mutex_enter(&pmportinfo->pmport_mutex);
14734 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14735 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14736 			mutex_exit(&pmportinfo->pmport_mutex);
14737 		}
14738 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
14739 	}
14740 
14741 	if (qual == SATA_ADDR_CPORT) {
14742 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
14743 		    SATA_STATE_PROBING);
14744 	} else if (qual == SATA_ADDR_PMPORT) {
14745 		mutex_enter(&pmportinfo->pmport_mutex);
14746 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
14747 		    SATA_STATE_PROBING);
14748 		mutex_exit(&pmportinfo->pmport_mutex);
14749 	}
14750 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14751 
14752 	/* Just let HBA driver to deactivate port */
14753 	sata_device->satadev_addr.qual = qual;
14754 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14755 	    (SATA_DIP(sata_hba_inst), sata_device);
14756 
14757 	/*
14758 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14759 	 * without the hint
14760 	 */
14761 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14762 	    SE_NO_HINT);
14763 
14764 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14765 	sata_update_port_info(sata_hba_inst, sata_device);
14766 	if (qual == SATA_ADDR_CPORT) {
14767 		if (rval != SATA_SUCCESS) {
14768 			/*
14769 			 * Port deactivation failure - do not change port state
14770 			 * unless the state returned by HBA indicates a port
14771 			 * failure.
14772 			 */
14773 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14774 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14775 				    SATA_PSTATE_FAILED;
14776 			}
14777 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14778 			    "sata_hba_ioctl: port deactivate: "
14779 			    "cannot deactivate SATA port %d", cport));
14780 			rv = EIO;
14781 		} else {
14782 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14783 		}
14784 	} else {
14785 		mutex_enter(&pmportinfo->pmport_mutex);
14786 		if (rval != SATA_SUCCESS) {
14787 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14788 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14789 				    pmport) = SATA_PSTATE_FAILED;
14790 			}
14791 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14792 			    "sata_hba_ioctl: port deactivate: "
14793 			    "cannot deactivate SATA port %d:%d",
14794 			    cport, pmport));
14795 			rv = EIO;
14796 		} else {
14797 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14798 		}
14799 		mutex_exit(&pmportinfo->pmport_mutex);
14800 	}
14801 
14802 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14803 
14804 	return (rv);
14805 }
14806 
14807 /*
14808  * Process ioctl port activate request.
14809  *
14810  * NOTE: Port multiplier is supported now.
14811  */
14812 static int
14813 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
14814     sata_device_t *sata_device)
14815 {
14816 	int cport, pmport, qual;
14817 	sata_cport_info_t *cportinfo;
14818 	sata_pmport_info_t *pmportinfo = NULL;
14819 	boolean_t dev_existed = TRUE;
14820 
14821 	/* Sanity check */
14822 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14823 		return (ENOTSUP);
14824 
14825 	cport = sata_device->satadev_addr.cport;
14826 	pmport = sata_device->satadev_addr.pmport;
14827 	qual = sata_device->satadev_addr.qual;
14828 
14829 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14830 
14831 	/*
14832 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14833 	 * is a device. But what we are dealing with is port/pmport.
14834 	 */
14835 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14836 	if (qual == SATA_ADDR_DCPORT)
14837 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14838 	else
14839 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14840 
14841 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14842 	if (qual == SATA_ADDR_PMPORT) {
14843 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14844 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
14845 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
14846 			dev_existed = FALSE;
14847 	} else { /* cport */
14848 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
14849 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
14850 			dev_existed = FALSE;
14851 	}
14852 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14853 
14854 	/* Just let HBA driver to activate port, if necessary */
14855 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14856 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14857 		/*
14858 		 * Port activation failure - do not change port state unless
14859 		 * the state returned by HBA indicates a port failure.
14860 		 */
14861 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14862 		    cport)->cport_mutex);
14863 		sata_update_port_info(sata_hba_inst, sata_device);
14864 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14865 			if (qual == SATA_ADDR_PMPORT) {
14866 				mutex_enter(&pmportinfo->pmport_mutex);
14867 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14868 				mutex_exit(&pmportinfo->pmport_mutex);
14869 			} else
14870 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14871 
14872 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14873 			    cport)->cport_mutex);
14874 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14875 			    "sata_hba_ioctl: port activate: cannot activate "
14876 			    "SATA port %d:%d", cport, pmport));
14877 			return (EIO);
14878 		}
14879 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14880 	}
14881 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14882 	if (qual == SATA_ADDR_PMPORT) {
14883 		mutex_enter(&pmportinfo->pmport_mutex);
14884 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
14885 		mutex_exit(&pmportinfo->pmport_mutex);
14886 	} else
14887 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
14888 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14889 
14890 	/*
14891 	 * Re-probe port to find its current state and possibly attached device.
14892 	 * Port re-probing may change the cportinfo device type if device is
14893 	 * found attached.
14894 	 * If port probing failed, the device type would be set to
14895 	 * SATA_DTYPE_NONE.
14896 	 */
14897 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
14898 	    SATA_DEV_IDENTIFY_RETRY);
14899 
14900 	/*
14901 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14902 	 * without the hint.
14903 	 */
14904 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14905 	    SE_NO_HINT);
14906 
14907 	if (dev_existed == FALSE) {
14908 		if (qual == SATA_ADDR_PMPORT &&
14909 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14910 			/*
14911 			 * That's the transition from the "inactive" port state
14912 			 * or the active port without a device attached to the
14913 			 * active port state with a device attached.
14914 			 */
14915 			sata_log(sata_hba_inst, CE_WARN,
14916 			    "SATA device detected at port %d:%d",
14917 			    cport, pmport);
14918 		} else if (qual == SATA_ADDR_CPORT &&
14919 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14920 			/*
14921 			 * That's the transition from the "inactive" port state
14922 			 * or the active port without a device attached to the
14923 			 * active port state with a device attached.
14924 			 */
14925 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
14926 				sata_log(sata_hba_inst, CE_WARN,
14927 				    "SATA device detected at port %d", cport);
14928 			} else {
14929 				sata_log(sata_hba_inst, CE_WARN,
14930 				    "SATA port multiplier detected at port %d",
14931 				    cport);
14932 			}
14933 		}
14934 	}
14935 	return (0);
14936 }
14937 
14938 
14939 
14940 /*
14941  * Process ioctl reset port request.
14942  *
14943  * NOTE: Port-Multiplier is supported.
14944  */
14945 static int
14946 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
14947     sata_device_t *sata_device)
14948 {
14949 	int cport, pmport, qual;
14950 	int rv = 0;
14951 
14952 	cport = sata_device->satadev_addr.cport;
14953 	pmport = sata_device->satadev_addr.pmport;
14954 	qual = sata_device->satadev_addr.qual;
14955 
14956 	/*
14957 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14958 	 * is a device. But what we are dealing with is port/pmport.
14959 	 */
14960 	if (qual == SATA_ADDR_DCPORT)
14961 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14962 	else
14963 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14964 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
14965 
14966 	/* Sanity check */
14967 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14968 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14969 		    "sata_hba_ioctl: sata_hba_tran missing required "
14970 		    "function sata_tran_reset_dport"));
14971 		return (ENOTSUP);
14972 	}
14973 
14974 	/* Ask HBA to reset port */
14975 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
14976 	    sata_device) != SATA_SUCCESS) {
14977 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14978 		    "sata_hba_ioctl: reset port: failed %d:%d",
14979 		    cport, pmport));
14980 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14981 		    cport_mutex);
14982 		sata_update_port_info(sata_hba_inst, sata_device);
14983 		if (qual == SATA_ADDR_CPORT)
14984 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14985 			    SATA_PSTATE_FAILED;
14986 		else {
14987 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14988 			    pmport));
14989 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14990 			    SATA_PSTATE_FAILED;
14991 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14992 			    pmport));
14993 		}
14994 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14995 		    cport_mutex);
14996 		rv = EIO;
14997 	}
14998 	/*
14999 	 * Beacuse the port was reset, it should be probed and
15000 	 * attached device reinitialized. At this point the
15001 	 * port state is unknown - it's state is HBA-specific.
15002 	 * Re-probe port to get its state.
15003 	 */
15004 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15005 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
15006 		rv = EIO;
15007 	}
15008 	return (rv);
15009 }
15010 
15011 /*
15012  * Process ioctl reset device request.
15013  *
15014  * NOTE: Port multiplier is supported.
15015  */
15016 static int
15017 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
15018     sata_device_t *sata_device)
15019 {
15020 	sata_drive_info_t *sdinfo = NULL;
15021 	sata_pmult_info_t *pmultinfo = NULL;
15022 	int cport, pmport;
15023 	int rv = 0;
15024 
15025 	/* Sanity check */
15026 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15027 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15028 		    "sata_hba_ioctl: sata_hba_tran missing required "
15029 		    "function sata_tran_reset_dport"));
15030 		return (ENOTSUP);
15031 	}
15032 
15033 	cport = sata_device->satadev_addr.cport;
15034 	pmport = sata_device->satadev_addr.pmport;
15035 
15036 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15037 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
15038 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
15039 		    SATA_DTYPE_PMULT)
15040 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
15041 			    cport_devp.cport_sata_pmult;
15042 		else
15043 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15044 			    sata_device->satadev_addr.cport);
15045 	} else { /* port multiplier */
15046 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15047 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15048 		    sata_device->satadev_addr.cport,
15049 		    sata_device->satadev_addr.pmport);
15050 	}
15051 	if (sdinfo == NULL && pmultinfo == NULL) {
15052 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15053 		return (EINVAL);
15054 	}
15055 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15056 
15057 	/* Ask HBA to reset device */
15058 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15059 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15060 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15061 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
15062 		    cport, pmport));
15063 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15064 		    cport_mutex);
15065 		sata_update_port_info(sata_hba_inst, sata_device);
15066 		/*
15067 		 * Device info structure remains attached. Another device reset
15068 		 * or port disconnect/connect and re-probing is
15069 		 * needed to change it's state
15070 		 */
15071 		if (sdinfo != NULL) {
15072 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
15073 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
15074 		} else if (pmultinfo != NULL) {
15075 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
15076 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
15077 		}
15078 
15079 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15080 		rv = EIO;
15081 	}
15082 	/*
15083 	 * If attached device was a port multiplier, some extra processing
15084 	 * may be needed to bring it back. SATA specification requies a
15085 	 * mandatory software reset on host port to reliably enumerate a port
15086 	 * multiplier, the HBA driver should handle that after reset
15087 	 * operation.
15088 	 */
15089 	return (rv);
15090 }
15091 
15092 
15093 /*
15094  * Process ioctl reset all request.
15095  */
15096 static int
15097 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
15098 {
15099 	sata_device_t sata_device;
15100 	int rv = 0;
15101 	int tcport;
15102 	int tpmport = 0;
15103 
15104 	sata_device.satadev_rev = SATA_DEVICE_REV;
15105 
15106 	/*
15107 	 * There is no protection here for configured devices.
15108 	 */
15109 	/* Sanity check */
15110 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15111 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15112 		    "sata_hba_ioctl: sata_hba_tran missing required "
15113 		    "function sata_tran_reset_dport"));
15114 		return (ENOTSUP);
15115 	}
15116 
15117 	/*
15118 	 * Need to lock all ports, not just one.
15119 	 * If any port is locked by event processing, fail the whole operation.
15120 	 * One port is already locked, but for simplicity lock it again.
15121 	 */
15122 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15123 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15124 		    cport_mutex);
15125 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
15126 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
15127 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15128 			    cport_mutex);
15129 			rv = EBUSY;
15130 			break;
15131 		} else {
15132 			/*
15133 			 * It is enough to lock cport in command-based
15134 			 * switching mode.
15135 			 */
15136 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
15137 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
15138 		}
15139 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15140 		    cport_mutex);
15141 	}
15142 
15143 	if (rv == 0) {
15144 		/*
15145 		 * All cports were successfully locked.
15146 		 * Reset main SATA controller.
15147 		 * Set the device address to port 0, to have a valid device
15148 		 * address.
15149 		 */
15150 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
15151 		sata_device.satadev_addr.cport = 0;
15152 		sata_device.satadev_addr.pmport = 0;
15153 
15154 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15155 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
15156 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15157 			    "sata_hba_ioctl: reset controller failed"));
15158 			return (EIO);
15159 		}
15160 		/*
15161 		 * Because ports were reset, port states are unknown.
15162 		 * They should be re-probed to get their state and
15163 		 * attached devices should be reinitialized.
15164 		 */
15165 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
15166 		    tcport++) {
15167 			sata_device.satadev_addr.cport = tcport;
15168 			sata_device.satadev_addr.pmport = tpmport;
15169 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
15170 
15171 			/*
15172 			 * The sata_reprobe_port() will mark a
15173 			 * SATA_EVNT_DEVICE_RESET event on the port
15174 			 * multiplier, all its sub-ports will be probed by
15175 			 * sata daemon afterwards.
15176 			 */
15177 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
15178 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15179 				rv = EIO;
15180 		}
15181 	}
15182 	/*
15183 	 * Unlock all ports
15184 	 */
15185 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15186 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15187 		    cport_mutex);
15188 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
15189 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
15190 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15191 		    cport_mutex);
15192 	}
15193 
15194 	/*
15195 	 * This operation returns EFAULT if either reset
15196 	 * controller failed or a re-probing of any port failed.
15197 	 */
15198 	return (rv);
15199 }
15200 
15201 
15202 /*
15203  * Process ioctl port self test request.
15204  *
15205  * NOTE: Port multiplier code is not completed nor tested.
15206  */
15207 static int
15208 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15209     sata_device_t *sata_device)
15210 {
15211 	int cport, pmport, qual;
15212 	int rv = 0;
15213 
15214 	/* Sanity check */
15215 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15216 		return (ENOTSUP);
15217 
15218 	cport = sata_device->satadev_addr.cport;
15219 	pmport = sata_device->satadev_addr.pmport;
15220 	qual = sata_device->satadev_addr.qual;
15221 
15222 	/*
15223 	 * There is no protection here for a configured
15224 	 * device attached to this port.
15225 	 */
15226 
15227 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15228 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15229 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15230 		    "sata_hba_ioctl: port selftest: "
15231 		    "failed port %d:%d", cport, pmport));
15232 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15233 		    cport_mutex);
15234 		sata_update_port_info(sata_hba_inst, sata_device);
15235 		if (qual == SATA_ADDR_CPORT)
15236 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15237 			    SATA_PSTATE_FAILED;
15238 		else { /* port multiplier device port */
15239 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15240 			    cport, pmport));
15241 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15242 			    SATA_PSTATE_FAILED;
15243 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15244 			    cport, pmport));
15245 		}
15246 
15247 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15248 		    cport_mutex);
15249 		return (EIO);
15250 	}
15251 	/*
15252 	 * Beacuse the port was reset in the course of testing, it should be
15253 	 * re-probed and attached device state should be restored. At this
15254 	 * point the port state is unknown - it's state is HBA-specific.
15255 	 * Force port re-probing to get it into a known state.
15256 	 */
15257 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15258 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15259 		rv = EIO;
15260 	return (rv);
15261 }
15262 
15263 
15264 /*
15265  * sata_cfgadm_state:
15266  * Use the sata port state and state of the target node to figure out
15267  * the cfgadm_state.
15268  *
15269  * The port argument is a value with encoded cport,
15270  * pmport and address qualifier, in the same manner as a scsi target number.
15271  * SCSI_TO_SATA_CPORT macro extracts cport number,
15272  * SCSI_TO_SATA_PMPORT extracts pmport number and
15273  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15274  *
15275  * Port multiplier is supported.
15276  */
15277 
15278 static void
15279 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15280     devctl_ap_state_t *ap_state)
15281 {
15282 	uint8_t		cport, pmport, qual;
15283 	uint32_t	port_state, pmult_state;
15284 	uint32_t	dev_type;
15285 	sata_drive_info_t *sdinfo;
15286 
15287 	cport = SCSI_TO_SATA_CPORT(port);
15288 	pmport = SCSI_TO_SATA_PMPORT(port);
15289 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15290 
15291 	/* Check cport state */
15292 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15293 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15294 	    port_state & SATA_PSTATE_FAILED) {
15295 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15296 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15297 		if (port_state & SATA_PSTATE_FAILED)
15298 			ap_state->ap_condition = AP_COND_FAILED;
15299 		else
15300 			ap_state->ap_condition = AP_COND_UNKNOWN;
15301 
15302 		return;
15303 	}
15304 
15305 	/* cport state is okay. Now check pmport state */
15306 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15307 		/* Sanity check */
15308 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15309 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15310 		    cport, pmport) == NULL)
15311 			return;
15312 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15313 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15314 		    port_state & SATA_PSTATE_FAILED) {
15315 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15316 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15317 			if (port_state & SATA_PSTATE_FAILED)
15318 				ap_state->ap_condition = AP_COND_FAILED;
15319 			else
15320 				ap_state->ap_condition = AP_COND_UNKNOWN;
15321 
15322 			return;
15323 		}
15324 	}
15325 
15326 	/* Port is enabled and ready */
15327 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15328 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15329 	else
15330 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15331 
15332 	switch (dev_type) {
15333 	case SATA_DTYPE_NONE:
15334 	{
15335 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15336 		ap_state->ap_condition = AP_COND_OK;
15337 		/* No device attached */
15338 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
15339 		break;
15340 	}
15341 	case SATA_DTYPE_PMULT:
15342 	{
15343 		/* Need to check port multiplier state */
15344 		ASSERT(qual == SATA_ADDR_DCPORT);
15345 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
15346 		    pmult_state;
15347 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
15348 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15349 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15350 			if (pmult_state & SATA_PSTATE_FAILED)
15351 				ap_state->ap_condition = AP_COND_FAILED;
15352 			else
15353 				ap_state->ap_condition = AP_COND_UNKNOWN;
15354 
15355 			return;
15356 		}
15357 
15358 		/* Port multiplier is not configurable */
15359 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
15360 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15361 		ap_state->ap_condition = AP_COND_OK;
15362 		break;
15363 	}
15364 
15365 	case SATA_DTYPE_ATADISK:
15366 	case SATA_DTYPE_ATAPICD:
15367 	case SATA_DTYPE_ATAPITAPE:
15368 	case SATA_DTYPE_ATAPIDISK:
15369 	{
15370 		dev_info_t *tdip = NULL;
15371 		dev_info_t *dip = NULL;
15372 		int circ;
15373 
15374 		dip = SATA_DIP(sata_hba_inst);
15375 		tdip = sata_get_target_dip(dip, cport, pmport);
15376 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15377 		if (tdip != NULL) {
15378 			ndi_devi_enter(dip, &circ);
15379 			mutex_enter(&(DEVI(tdip)->devi_lock));
15380 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
15381 				/*
15382 				 * There could be the case where previously
15383 				 * configured and opened device was removed
15384 				 * and unknown device was plugged.
15385 				 * In such case we want to show a device, and
15386 				 * its configured or unconfigured state but
15387 				 * indicate unusable condition untill the
15388 				 * old target node is released and removed.
15389 				 */
15390 				ap_state->ap_condition = AP_COND_UNUSABLE;
15391 			} else {
15392 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
15393 				    cport));
15394 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15395 				    cport);
15396 				if (sdinfo != NULL) {
15397 					if ((sdinfo->satadrv_state &
15398 					    SATA_DSTATE_FAILED) != 0)
15399 						ap_state->ap_condition =
15400 						    AP_COND_FAILED;
15401 					else
15402 						ap_state->ap_condition =
15403 						    AP_COND_OK;
15404 				} else {
15405 					ap_state->ap_condition =
15406 					    AP_COND_UNKNOWN;
15407 				}
15408 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
15409 				    cport));
15410 			}
15411 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
15412 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
15413 				ap_state->ap_ostate =
15414 				    AP_OSTATE_UNCONFIGURED;
15415 			} else {
15416 				ap_state->ap_ostate =
15417 				    AP_OSTATE_CONFIGURED;
15418 			}
15419 			mutex_exit(&(DEVI(tdip)->devi_lock));
15420 			ndi_devi_exit(dip, circ);
15421 		} else {
15422 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15423 			ap_state->ap_condition = AP_COND_UNKNOWN;
15424 		}
15425 		break;
15426 	}
15427 	default:
15428 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15429 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15430 		ap_state->ap_condition = AP_COND_UNKNOWN;
15431 		/*
15432 		 * This is actually internal error condition (non fatal),
15433 		 * because we have already checked all defined device types.
15434 		 */
15435 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15436 		    "sata_cfgadm_state: Internal error: "
15437 		    "unknown device type"));
15438 		break;
15439 	}
15440 }
15441 
15442 
15443 /*
15444  * Process ioctl get device path request.
15445  *
15446  * NOTE: Port multiplier has no target dip. Devices connected to port
15447  * multiplier have target node attached to the HBA node. The only difference
15448  * between them and the directly-attached device node is a target address.
15449  */
15450 static int
15451 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
15452     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15453 {
15454 	char path[MAXPATHLEN];
15455 	uint32_t size;
15456 	dev_info_t *tdip;
15457 
15458 	(void) strcpy(path, "/devices");
15459 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15460 	    &sata_device->satadev_addr)) == NULL) {
15461 		/*
15462 		 * No such device. If this is a request for a size, do not
15463 		 * return EINVAL for non-existing target, because cfgadm
15464 		 * will then indicate a meaningless ioctl failure.
15465 		 * If this is a request for a path, indicate invalid
15466 		 * argument.
15467 		 */
15468 		if (ioc->get_size == 0)
15469 			return (EINVAL);
15470 	} else {
15471 		(void) ddi_pathname(tdip, path + strlen(path));
15472 	}
15473 	size = strlen(path) + 1;
15474 
15475 	if (ioc->get_size != 0) {
15476 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
15477 		    mode) != 0)
15478 			return (EFAULT);
15479 	} else {
15480 		if (ioc->bufsiz != size)
15481 			return (EINVAL);
15482 
15483 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
15484 		    mode) != 0)
15485 			return (EFAULT);
15486 	}
15487 	return (0);
15488 }
15489 
15490 /*
15491  * Process ioctl get attachment point type request.
15492  *
15493  * NOTE: Port multiplier is supported.
15494  */
15495 static	int
15496 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
15497     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15498 {
15499 	uint32_t	type_len;
15500 	const char	*ap_type;
15501 	int		dev_type;
15502 
15503 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15504 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
15505 		    sata_device->satadev_addr.cport);
15506 	else /* pmport */
15507 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
15508 		    sata_device->satadev_addr.cport,
15509 		    sata_device->satadev_addr.pmport);
15510 
15511 	switch (dev_type) {
15512 	case SATA_DTYPE_NONE:
15513 		ap_type = "port";
15514 		break;
15515 
15516 	case SATA_DTYPE_ATADISK:
15517 	case SATA_DTYPE_ATAPIDISK:
15518 		ap_type = "disk";
15519 		break;
15520 
15521 	case SATA_DTYPE_ATAPICD:
15522 		ap_type = "cd/dvd";
15523 		break;
15524 
15525 	case SATA_DTYPE_ATAPITAPE:
15526 		ap_type = "tape";
15527 		break;
15528 
15529 	case SATA_DTYPE_PMULT:
15530 		ap_type = "sata-pmult";
15531 		break;
15532 
15533 	case SATA_DTYPE_UNKNOWN:
15534 		ap_type = "unknown";
15535 		break;
15536 
15537 	default:
15538 		ap_type = "unsupported";
15539 		break;
15540 
15541 	} /* end of dev_type switch */
15542 
15543 	type_len = strlen(ap_type) + 1;
15544 
15545 	if (ioc->get_size) {
15546 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
15547 		    mode) != 0)
15548 			return (EFAULT);
15549 	} else {
15550 		if (ioc->bufsiz != type_len)
15551 			return (EINVAL);
15552 
15553 		if (ddi_copyout((void *)ap_type, ioc->buf,
15554 		    ioc->bufsiz, mode) != 0)
15555 			return (EFAULT);
15556 	}
15557 	return (0);
15558 
15559 }
15560 
15561 /*
15562  * Process ioctl get device model info request.
15563  * This operation should return to cfgadm the device model
15564  * information string
15565  *
15566  * NOTE: Port multiplier is supported.
15567  */
15568 static	int
15569 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
15570     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15571 {
15572 	sata_drive_info_t *sdinfo;
15573 	uint32_t info_len;
15574 	char ap_info[SATA_ID_MODEL_LEN + 1];
15575 
15576 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15577 	    sata_device->satadev_addr.cport)->cport_mutex);
15578 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15579 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15580 		    sata_device->satadev_addr.cport);
15581 	else /* port multiplier */
15582 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15583 		    sata_device->satadev_addr.cport,
15584 		    sata_device->satadev_addr.pmport);
15585 	if (sdinfo == NULL) {
15586 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15587 		    sata_device->satadev_addr.cport)->cport_mutex);
15588 		return (EINVAL);
15589 	}
15590 
15591 #ifdef	_LITTLE_ENDIAN
15592 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15593 #else	/* _LITTLE_ENDIAN */
15594 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15595 #endif	/* _LITTLE_ENDIAN */
15596 
15597 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15598 	    sata_device->satadev_addr.cport)->cport_mutex);
15599 
15600 	ap_info[SATA_ID_MODEL_LEN] = '\0';
15601 
15602 	info_len = strlen(ap_info) + 1;
15603 
15604 	if (ioc->get_size) {
15605 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15606 		    mode) != 0)
15607 			return (EFAULT);
15608 	} else {
15609 		if (ioc->bufsiz < info_len)
15610 			return (EINVAL);
15611 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15612 		    mode) != 0)
15613 			return (EFAULT);
15614 	}
15615 	return (0);
15616 }
15617 
15618 
15619 /*
15620  * Process ioctl get device firmware revision info request.
15621  * This operation should return to cfgadm the device firmware revision
15622  * information string
15623  *
15624  * Port multiplier is supported.
15625  */
15626 static	int
15627 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
15628     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15629 {
15630 	sata_drive_info_t *sdinfo;
15631 	uint32_t info_len;
15632 	char ap_info[SATA_ID_FW_LEN + 1];
15633 
15634 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15635 	    sata_device->satadev_addr.cport)->cport_mutex);
15636 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15637 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15638 		    sata_device->satadev_addr.cport);
15639 	else /* port multiplier */
15640 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15641 		    sata_device->satadev_addr.cport,
15642 		    sata_device->satadev_addr.pmport);
15643 	if (sdinfo == NULL) {
15644 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15645 		    sata_device->satadev_addr.cport)->cport_mutex);
15646 		return (EINVAL);
15647 	}
15648 
15649 #ifdef	_LITTLE_ENDIAN
15650 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15651 #else	/* _LITTLE_ENDIAN */
15652 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15653 #endif	/* _LITTLE_ENDIAN */
15654 
15655 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15656 	    sata_device->satadev_addr.cport)->cport_mutex);
15657 
15658 	ap_info[SATA_ID_FW_LEN] = '\0';
15659 
15660 	info_len = strlen(ap_info) + 1;
15661 
15662 	if (ioc->get_size) {
15663 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15664 		    mode) != 0)
15665 			return (EFAULT);
15666 	} else {
15667 		if (ioc->bufsiz < info_len)
15668 			return (EINVAL);
15669 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15670 		    mode) != 0)
15671 			return (EFAULT);
15672 	}
15673 	return (0);
15674 }
15675 
15676 
15677 /*
15678  * Process ioctl get device serial number info request.
15679  * This operation should return to cfgadm the device serial number string.
15680  *
15681  * NOTE: Port multiplier is supported.
15682  */
15683 static	int
15684 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
15685     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15686 {
15687 	sata_drive_info_t *sdinfo;
15688 	uint32_t info_len;
15689 	char ap_info[SATA_ID_SERIAL_LEN + 1];
15690 
15691 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15692 	    sata_device->satadev_addr.cport)->cport_mutex);
15693 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15694 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15695 		    sata_device->satadev_addr.cport);
15696 	else /* port multiplier */
15697 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15698 		    sata_device->satadev_addr.cport,
15699 		    sata_device->satadev_addr.pmport);
15700 	if (sdinfo == NULL) {
15701 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15702 		    sata_device->satadev_addr.cport)->cport_mutex);
15703 		return (EINVAL);
15704 	}
15705 
15706 #ifdef	_LITTLE_ENDIAN
15707 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15708 #else	/* _LITTLE_ENDIAN */
15709 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15710 #endif	/* _LITTLE_ENDIAN */
15711 
15712 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15713 	    sata_device->satadev_addr.cport)->cport_mutex);
15714 
15715 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
15716 
15717 	info_len = strlen(ap_info) + 1;
15718 
15719 	if (ioc->get_size) {
15720 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15721 		    mode) != 0)
15722 			return (EFAULT);
15723 	} else {
15724 		if (ioc->bufsiz < info_len)
15725 			return (EINVAL);
15726 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15727 		    mode) != 0)
15728 			return (EFAULT);
15729 	}
15730 	return (0);
15731 }
15732 
15733 
15734 /*
15735  * Preset scsi extended sense data (to NO SENSE)
15736  * First 18 bytes of the sense data are preset to current valid sense
15737  * with a key NO SENSE data.
15738  *
15739  * Returns void
15740  */
15741 static void
15742 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
15743 {
15744 	sense->es_valid = 1;		/* Valid sense */
15745 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
15746 	sense->es_key = KEY_NO_SENSE;
15747 	sense->es_info_1 = 0;
15748 	sense->es_info_2 = 0;
15749 	sense->es_info_3 = 0;
15750 	sense->es_info_4 = 0;
15751 	sense->es_add_len = 10;	/* Additional length - replace with a def */
15752 	sense->es_cmd_info[0] = 0;
15753 	sense->es_cmd_info[1] = 0;
15754 	sense->es_cmd_info[2] = 0;
15755 	sense->es_cmd_info[3] = 0;
15756 	sense->es_add_code = 0;
15757 	sense->es_qual_code = 0;
15758 }
15759 
15760 /*
15761  * Register a legacy cmdk-style devid for the target (disk) device.
15762  *
15763  * Note: This function is called only when the HBA devinfo node has the
15764  * property "use-cmdk-devid-format" set. This property indicates that
15765  * devid compatible with old cmdk (target) driver is to be generated
15766  * for any target device attached to this controller. This will take
15767  * precedence over the devid generated by sd (target) driver.
15768  * This function is derived from cmdk_devid_setup() function in cmdk.c.
15769  */
15770 static void
15771 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
15772 {
15773 	char	*hwid;
15774 	int	modlen;
15775 	int	serlen;
15776 	int	rval;
15777 	ddi_devid_t	devid;
15778 
15779 	/*
15780 	 * device ID is a concatanation of model number, "=", serial number.
15781 	 */
15782 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
15783 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
15784 	    sizeof (sdinfo->satadrv_id.ai_model));
15785 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
15786 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
15787 	if (modlen == 0)
15788 		goto err;
15789 	hwid[modlen++] = '=';
15790 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
15791 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15792 	swab(&hwid[modlen], &hwid[modlen],
15793 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15794 	serlen = sata_check_modser(&hwid[modlen],
15795 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15796 	if (serlen == 0)
15797 		goto err;
15798 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
15799 
15800 	/* initialize/register devid */
15801 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
15802 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
15803 		rval = ddi_devid_register(dip, devid);
15804 		/*
15805 		 * Free up the allocated devid buffer.
15806 		 * NOTE: This doesn't mean unregistering devid.
15807 		 */
15808 		ddi_devid_free(devid);
15809 	}
15810 
15811 	if (rval != DDI_SUCCESS)
15812 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
15813 		    " on port %d", sdinfo->satadrv_addr.cport);
15814 err:
15815 	kmem_free(hwid, LEGACY_HWID_LEN);
15816 }
15817 
15818 /*
15819  * valid model/serial string must contain a non-zero non-space characters.
15820  * trim trailing spaces/NULLs.
15821  */
15822 static int
15823 sata_check_modser(char *buf, int buf_len)
15824 {
15825 	boolean_t ret;
15826 	char *s;
15827 	int i;
15828 	int tb;
15829 	char ch;
15830 
15831 	ret = B_FALSE;
15832 	s = buf;
15833 	for (i = 0; i < buf_len; i++) {
15834 		ch = *s++;
15835 		if (ch != ' ' && ch != '\0')
15836 			tb = i + 1;
15837 		if (ch != ' ' && ch != '\0' && ch != '0')
15838 			ret = B_TRUE;
15839 	}
15840 
15841 	if (ret == B_FALSE)
15842 		return (0); /* invalid string */
15843 
15844 	return (tb); /* return length */
15845 }
15846 
15847 /*
15848  * sata_set_drive_features function compares current device features setting
15849  * with the saved device features settings and, if there is a difference,
15850  * it restores device features setting to the previously saved state.
15851  * It also arbitrarily tries to select the highest supported DMA mode.
15852  * Device Identify or Identify Packet Device data has to be current.
15853  * At the moment read ahead and write cache are considered for all devices.
15854  * For atapi devices, Removable Media Status Notification is set in addition
15855  * to common features.
15856  *
15857  * This function cannot be called in the interrupt context (it may sleep).
15858  *
15859  * The input argument sdinfo should point to the drive info structure
15860  * to be updated after features are set. Note, that only
15861  * device (packet) identify data is updated, not the flags indicating the
15862  * supported features.
15863  *
15864  * Returns SATA_SUCCESS if successful or there was nothing to do.
15865  * Device Identify data in the drive info structure pointed to by the sdinfo
15866  * arguments is updated even when no features were set or changed.
15867  *
15868  * Returns SATA_FAILURE if device features could not be set or DMA mode
15869  * for a disk cannot be set and device identify data cannot be fetched.
15870  *
15871  * Returns SATA_RETRY if device features could not be set (other than disk
15872  * DMA mode) but the device identify data was fetched successfully.
15873  *
15874  * Note: This function may fail the port, making it inaccessible.
15875  * In such case the explicit port disconnect/connect or physical device
15876  * detach/attach is required to re-evaluate port state again.
15877  */
15878 
15879 static int
15880 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
15881     sata_drive_info_t *sdinfo, int restore)
15882 {
15883 	int rval = SATA_SUCCESS;
15884 	int rval_set;
15885 	sata_drive_info_t new_sdinfo;
15886 	char *finfo = "sata_set_drive_features: cannot";
15887 	char *finfox;
15888 	int cache_op;
15889 
15890 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
15891 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
15892 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
15893 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15894 		/*
15895 		 * Cannot get device identification - caller may retry later
15896 		 */
15897 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15898 		    "%s fetch device identify data\n", finfo);
15899 		return (SATA_FAILURE);
15900 	}
15901 	finfox = (restore != 0) ? " restore device features" :
15902 	    " initialize device features\n";
15903 
15904 	switch (sdinfo->satadrv_type) {
15905 	case SATA_DTYPE_ATADISK:
15906 		/* Arbitrarily set UDMA mode */
15907 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15908 		    SATA_SUCCESS) {
15909 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15910 			    "%s set UDMA mode\n", finfo));
15911 			return (SATA_FAILURE);
15912 		}
15913 		break;
15914 	case SATA_DTYPE_ATAPICD:
15915 	case SATA_DTYPE_ATAPITAPE:
15916 	case SATA_DTYPE_ATAPIDISK:
15917 		/*  Set Removable Media Status Notification, if necessary */
15918 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
15919 		    restore != 0) {
15920 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
15921 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
15922 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
15923 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
15924 				/* Current setting does not match saved one */
15925 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
15926 				    sdinfo->satadrv_settings &
15927 				    SATA_DEV_RMSN) != SATA_SUCCESS)
15928 					rval = SATA_FAILURE;
15929 			}
15930 		}
15931 		/*
15932 		 * We have to set Multiword DMA or UDMA, if it is supported, as
15933 		 * we want to use DMA transfer mode whenever possible.
15934 		 * Some devices require explicit setting of the DMA mode.
15935 		 */
15936 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
15937 			/* Set highest supported DMA mode */
15938 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15939 			    SATA_SUCCESS) {
15940 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15941 				    "%s set UDMA mode\n", finfo));
15942 				rval = SATA_FAILURE;
15943 			}
15944 		}
15945 		break;
15946 	}
15947 
15948 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
15949 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15950 		/*
15951 		 * neither READ AHEAD nor WRITE CACHE is supported
15952 		 * - do nothing
15953 		 */
15954 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15955 		    "settable features not supported\n", NULL);
15956 		goto update_sdinfo;
15957 	}
15958 
15959 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
15960 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
15961 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
15962 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
15963 		/*
15964 		 * both READ AHEAD and WRITE CACHE are enabled
15965 		 * - Nothing to do
15966 		 */
15967 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15968 		    "no device features to set\n", NULL);
15969 		goto update_sdinfo;
15970 	}
15971 
15972 	cache_op = 0;
15973 
15974 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
15975 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15976 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15977 			/* Enable read ahead / read cache */
15978 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
15979 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15980 			    "enabling read cache\n", NULL);
15981 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15982 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15983 			/* Disable read ahead  / read cache */
15984 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
15985 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15986 			    "disabling read cache\n", NULL);
15987 		}
15988 
15989 		if (cache_op != 0) {
15990 			/* Try to set read cache mode */
15991 			rval_set = sata_set_cache_mode(sata_hba_inst,
15992 			    &new_sdinfo, cache_op);
15993 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15994 				rval = rval_set;
15995 		}
15996 	}
15997 
15998 	cache_op = 0;
15999 
16000 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
16001 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
16002 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
16003 			/* Enable write cache */
16004 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
16005 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16006 			    "enabling write cache\n", NULL);
16007 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
16008 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
16009 			/* Disable write cache */
16010 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
16011 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16012 			    "disabling write cache\n", NULL);
16013 		}
16014 
16015 		if (cache_op != 0) {
16016 			/* Try to set write cache mode */
16017 			rval_set = sata_set_cache_mode(sata_hba_inst,
16018 			    &new_sdinfo, cache_op);
16019 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
16020 				rval = rval_set;
16021 		}
16022 	}
16023 	if (rval != SATA_SUCCESS)
16024 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16025 		    "%s %s", finfo, finfox));
16026 
16027 update_sdinfo:
16028 	/*
16029 	 * We need to fetch Device Identify data again
16030 	 */
16031 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
16032 		/*
16033 		 * Cannot get device identification - retry later
16034 		 */
16035 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16036 		    "%s re-fetch device identify data\n", finfo));
16037 		rval = SATA_FAILURE;
16038 	}
16039 	/* Copy device sata info. */
16040 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
16041 
16042 	return (rval);
16043 }
16044 
16045 
16046 /*
16047  *
16048  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
16049  * unable to determine.
16050  *
16051  * Cannot be called in an interrupt context.
16052  *
16053  * Called by sata_build_lsense_page_2f()
16054  */
16055 
16056 static int
16057 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
16058     sata_drive_info_t *sdinfo)
16059 {
16060 	sata_pkt_t *spkt;
16061 	sata_cmd_t *scmd;
16062 	sata_pkt_txlate_t *spx;
16063 	int rval;
16064 
16065 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16066 	spx->txlt_sata_hba_inst = sata_hba_inst;
16067 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16068 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16069 	if (spkt == NULL) {
16070 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16071 		return (-1);
16072 	}
16073 	/* address is needed now */
16074 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16075 
16076 
16077 	/* Fill sata_pkt */
16078 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16079 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16080 	/* Synchronous mode, no callback */
16081 	spkt->satapkt_comp = NULL;
16082 	/* Timeout 30s */
16083 	spkt->satapkt_time = sata_default_pkt_time;
16084 
16085 	scmd = &spkt->satapkt_cmd;
16086 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
16087 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
16088 
16089 	/* Set up which registers need to be returned */
16090 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
16091 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
16092 
16093 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
16094 	scmd->satacmd_addr_type = 0;		/* N/A */
16095 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16096 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16097 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16098 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16099 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
16100 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16101 	scmd->satacmd_cmd_reg = SATAC_SMART;
16102 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16103 	    sdinfo->satadrv_addr.cport)));
16104 
16105 
16106 	/* Send pkt to SATA HBA driver */
16107 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16108 	    SATA_TRAN_ACCEPTED ||
16109 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16110 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16111 		    sdinfo->satadrv_addr.cport)));
16112 		/*
16113 		 * Whoops, no SMART RETURN STATUS
16114 		 */
16115 		rval = -1;
16116 	} else {
16117 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16118 		    sdinfo->satadrv_addr.cport)));
16119 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
16120 			rval = -1;
16121 			goto fail;
16122 		}
16123 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
16124 			rval = -1;
16125 			goto fail;
16126 		}
16127 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
16128 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
16129 			rval = 0;
16130 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
16131 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
16132 			rval = 1;
16133 		else {
16134 			rval = -1;
16135 			goto fail;
16136 		}
16137 	}
16138 fail:
16139 	/* Free allocated resources */
16140 	sata_pkt_free(spx);
16141 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16142 
16143 	return (rval);
16144 }
16145 
16146 /*
16147  *
16148  * Returns 0 if succeeded, -1 otherwise
16149  *
16150  * Cannot be called in an interrupt context.
16151  *
16152  */
16153 static int
16154 sata_fetch_smart_data(
16155 	sata_hba_inst_t *sata_hba_inst,
16156 	sata_drive_info_t *sdinfo,
16157 	struct smart_data *smart_data)
16158 {
16159 	sata_pkt_t *spkt;
16160 	sata_cmd_t *scmd;
16161 	sata_pkt_txlate_t *spx;
16162 	int rval;
16163 
16164 #if ! defined(lint)
16165 	ASSERT(sizeof (struct smart_data) == 512);
16166 #endif
16167 
16168 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16169 	spx->txlt_sata_hba_inst = sata_hba_inst;
16170 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16171 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16172 	if (spkt == NULL) {
16173 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16174 		return (-1);
16175 	}
16176 	/* address is needed now */
16177 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16178 
16179 
16180 	/* Fill sata_pkt */
16181 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16182 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16183 	/* Synchronous mode, no callback */
16184 	spkt->satapkt_comp = NULL;
16185 	/* Timeout 30s */
16186 	spkt->satapkt_time = sata_default_pkt_time;
16187 
16188 	scmd = &spkt->satapkt_cmd;
16189 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16190 
16191 	/*
16192 	 * Allocate buffer for SMART data
16193 	 */
16194 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16195 	    sizeof (struct smart_data));
16196 	if (scmd->satacmd_bp == NULL) {
16197 		sata_pkt_free(spx);
16198 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16199 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16200 		    "sata_fetch_smart_data: "
16201 		    "cannot allocate buffer"));
16202 		return (-1);
16203 	}
16204 
16205 
16206 	/* Build SMART_READ_DATA cmd in the sata_pkt */
16207 	scmd->satacmd_addr_type = 0;		/* N/A */
16208 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16209 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16210 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16211 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16212 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16213 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16214 	scmd->satacmd_cmd_reg = SATAC_SMART;
16215 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16216 	    sdinfo->satadrv_addr.cport)));
16217 
16218 	/* Send pkt to SATA HBA driver */
16219 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16220 	    SATA_TRAN_ACCEPTED ||
16221 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16222 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16223 		    sdinfo->satadrv_addr.cport)));
16224 		/*
16225 		 * Whoops, no SMART DATA available
16226 		 */
16227 		rval = -1;
16228 		goto fail;
16229 	} else {
16230 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16231 		    sdinfo->satadrv_addr.cport)));
16232 		if (spx->txlt_buf_dma_handle != NULL) {
16233 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16234 			    DDI_DMA_SYNC_FORKERNEL);
16235 			ASSERT(rval == DDI_SUCCESS);
16236 		}
16237 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16238 		    sizeof (struct smart_data));
16239 	}
16240 
16241 fail:
16242 	/* Free allocated resources */
16243 	sata_free_local_buffer(spx);
16244 	sata_pkt_free(spx);
16245 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16246 
16247 	return (rval);
16248 }
16249 
16250 /*
16251  * Used by LOG SENSE page 0x10
16252  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16253  * Note: cannot be called in the interrupt context.
16254  *
16255  * return 0 for success, -1 otherwise
16256  *
16257  */
16258 static int
16259 sata_ext_smart_selftest_read_log(
16260 	sata_hba_inst_t *sata_hba_inst,
16261 	sata_drive_info_t *sdinfo,
16262 	struct smart_ext_selftest_log *ext_selftest_log,
16263 	uint16_t block_num)
16264 {
16265 	sata_pkt_txlate_t *spx;
16266 	sata_pkt_t *spkt;
16267 	sata_cmd_t *scmd;
16268 	int rval;
16269 
16270 #if ! defined(lint)
16271 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16272 #endif
16273 
16274 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16275 	spx->txlt_sata_hba_inst = sata_hba_inst;
16276 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16277 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16278 	if (spkt == NULL) {
16279 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16280 		return (-1);
16281 	}
16282 	/* address is needed now */
16283 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16284 
16285 
16286 	/* Fill sata_pkt */
16287 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16288 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16289 	/* Synchronous mode, no callback */
16290 	spkt->satapkt_comp = NULL;
16291 	/* Timeout 30s */
16292 	spkt->satapkt_time = sata_default_pkt_time;
16293 
16294 	scmd = &spkt->satapkt_cmd;
16295 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16296 
16297 	/*
16298 	 * Allocate buffer for SMART extended self-test log
16299 	 */
16300 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16301 	    sizeof (struct smart_ext_selftest_log));
16302 	if (scmd->satacmd_bp == NULL) {
16303 		sata_pkt_free(spx);
16304 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16305 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16306 		    "sata_ext_smart_selftest_log: "
16307 		    "cannot allocate buffer"));
16308 		return (-1);
16309 	}
16310 
16311 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16312 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16313 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16314 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16315 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16316 	scmd->satacmd_lba_low_msb = 0;
16317 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16318 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16319 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16320 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16321 
16322 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16323 	    sdinfo->satadrv_addr.cport)));
16324 
16325 	/* Send pkt to SATA HBA driver */
16326 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16327 	    SATA_TRAN_ACCEPTED ||
16328 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16329 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16330 		    sdinfo->satadrv_addr.cport)));
16331 
16332 		/*
16333 		 * Whoops, no SMART selftest log info available
16334 		 */
16335 		rval = -1;
16336 		goto fail;
16337 	} else {
16338 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16339 		    sdinfo->satadrv_addr.cport)));
16340 
16341 		if (spx->txlt_buf_dma_handle != NULL) {
16342 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16343 			    DDI_DMA_SYNC_FORKERNEL);
16344 			ASSERT(rval == DDI_SUCCESS);
16345 		}
16346 		bcopy(scmd->satacmd_bp->b_un.b_addr,
16347 		    (uint8_t *)ext_selftest_log,
16348 		    sizeof (struct smart_ext_selftest_log));
16349 		rval = 0;
16350 	}
16351 
16352 fail:
16353 	/* Free allocated resources */
16354 	sata_free_local_buffer(spx);
16355 	sata_pkt_free(spx);
16356 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16357 
16358 	return (rval);
16359 }
16360 
16361 /*
16362  * Returns 0 for success, -1 otherwise
16363  *
16364  * SMART self-test log data is returned in buffer pointed to by selftest_log
16365  */
16366 static int
16367 sata_smart_selftest_log(
16368 	sata_hba_inst_t *sata_hba_inst,
16369 	sata_drive_info_t *sdinfo,
16370 	struct smart_selftest_log *selftest_log)
16371 {
16372 	sata_pkt_t *spkt;
16373 	sata_cmd_t *scmd;
16374 	sata_pkt_txlate_t *spx;
16375 	int rval;
16376 
16377 #if ! defined(lint)
16378 	ASSERT(sizeof (struct smart_selftest_log) == 512);
16379 #endif
16380 
16381 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16382 	spx->txlt_sata_hba_inst = sata_hba_inst;
16383 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16384 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16385 	if (spkt == NULL) {
16386 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16387 		return (-1);
16388 	}
16389 	/* address is needed now */
16390 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16391 
16392 
16393 	/* Fill sata_pkt */
16394 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16395 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16396 	/* Synchronous mode, no callback */
16397 	spkt->satapkt_comp = NULL;
16398 	/* Timeout 30s */
16399 	spkt->satapkt_time = sata_default_pkt_time;
16400 
16401 	scmd = &spkt->satapkt_cmd;
16402 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16403 
16404 	/*
16405 	 * Allocate buffer for SMART SELFTEST LOG
16406 	 */
16407 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16408 	    sizeof (struct smart_selftest_log));
16409 	if (scmd->satacmd_bp == NULL) {
16410 		sata_pkt_free(spx);
16411 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16412 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16413 		    "sata_smart_selftest_log: "
16414 		    "cannot allocate buffer"));
16415 		return (-1);
16416 	}
16417 
16418 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16419 	scmd->satacmd_addr_type = 0;		/* N/A */
16420 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
16421 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
16422 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16423 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16424 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16425 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16426 	scmd->satacmd_cmd_reg = SATAC_SMART;
16427 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16428 	    sdinfo->satadrv_addr.cport)));
16429 
16430 	/* Send pkt to SATA HBA driver */
16431 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16432 	    SATA_TRAN_ACCEPTED ||
16433 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16434 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16435 		    sdinfo->satadrv_addr.cport)));
16436 		/*
16437 		 * Whoops, no SMART DATA available
16438 		 */
16439 		rval = -1;
16440 		goto fail;
16441 	} else {
16442 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16443 		    sdinfo->satadrv_addr.cport)));
16444 		if (spx->txlt_buf_dma_handle != NULL) {
16445 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16446 			    DDI_DMA_SYNC_FORKERNEL);
16447 			ASSERT(rval == DDI_SUCCESS);
16448 		}
16449 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
16450 		    sizeof (struct smart_selftest_log));
16451 		rval = 0;
16452 	}
16453 
16454 fail:
16455 	/* Free allocated resources */
16456 	sata_free_local_buffer(spx);
16457 	sata_pkt_free(spx);
16458 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16459 
16460 	return (rval);
16461 }
16462 
16463 
16464 /*
16465  * Returns 0 for success, -1 otherwise
16466  *
16467  * SMART READ LOG data is returned in buffer pointed to by smart_log
16468  */
16469 static int
16470 sata_smart_read_log(
16471 	sata_hba_inst_t *sata_hba_inst,
16472 	sata_drive_info_t *sdinfo,
16473 	uint8_t *smart_log,		/* where the data should be returned */
16474 	uint8_t which_log,		/* which log should be returned */
16475 	uint8_t log_size)		/* # of 512 bytes in log */
16476 {
16477 	sata_pkt_t *spkt;
16478 	sata_cmd_t *scmd;
16479 	sata_pkt_txlate_t *spx;
16480 	int rval;
16481 
16482 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16483 	spx->txlt_sata_hba_inst = sata_hba_inst;
16484 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16485 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16486 	if (spkt == NULL) {
16487 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16488 		return (-1);
16489 	}
16490 	/* address is needed now */
16491 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16492 
16493 
16494 	/* Fill sata_pkt */
16495 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16496 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16497 	/* Synchronous mode, no callback */
16498 	spkt->satapkt_comp = NULL;
16499 	/* Timeout 30s */
16500 	spkt->satapkt_time = sata_default_pkt_time;
16501 
16502 	scmd = &spkt->satapkt_cmd;
16503 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16504 
16505 	/*
16506 	 * Allocate buffer for SMART READ LOG
16507 	 */
16508 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
16509 	if (scmd->satacmd_bp == NULL) {
16510 		sata_pkt_free(spx);
16511 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16512 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16513 		    "sata_smart_read_log: " "cannot allocate buffer"));
16514 		return (-1);
16515 	}
16516 
16517 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16518 	scmd->satacmd_addr_type = 0;		/* N/A */
16519 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
16520 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
16521 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16522 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16523 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16524 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16525 	scmd->satacmd_cmd_reg = SATAC_SMART;
16526 
16527 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16528 	    sdinfo->satadrv_addr.cport)));
16529 
16530 	/* Send pkt to SATA HBA driver */
16531 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16532 	    SATA_TRAN_ACCEPTED ||
16533 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16534 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16535 		    sdinfo->satadrv_addr.cport)));
16536 
16537 		/*
16538 		 * Whoops, no SMART DATA available
16539 		 */
16540 		rval = -1;
16541 		goto fail;
16542 	} else {
16543 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16544 		    sdinfo->satadrv_addr.cport)));
16545 
16546 		if (spx->txlt_buf_dma_handle != NULL) {
16547 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16548 			    DDI_DMA_SYNC_FORKERNEL);
16549 			ASSERT(rval == DDI_SUCCESS);
16550 		}
16551 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
16552 		rval = 0;
16553 	}
16554 
16555 fail:
16556 	/* Free allocated resources */
16557 	sata_free_local_buffer(spx);
16558 	sata_pkt_free(spx);
16559 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16560 
16561 	return (rval);
16562 }
16563 
16564 /*
16565  * Used by LOG SENSE page 0x10
16566  *
16567  * return 0 for success, -1 otherwise
16568  *
16569  */
16570 static int
16571 sata_read_log_ext_directory(
16572 	sata_hba_inst_t *sata_hba_inst,
16573 	sata_drive_info_t *sdinfo,
16574 	struct read_log_ext_directory *logdir)
16575 {
16576 	sata_pkt_txlate_t *spx;
16577 	sata_pkt_t *spkt;
16578 	sata_cmd_t *scmd;
16579 	int rval;
16580 
16581 #if ! defined(lint)
16582 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
16583 #endif
16584 
16585 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16586 	spx->txlt_sata_hba_inst = sata_hba_inst;
16587 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16588 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16589 	if (spkt == NULL) {
16590 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16591 		return (-1);
16592 	}
16593 
16594 	/* Fill sata_pkt */
16595 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16596 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16597 	/* Synchronous mode, no callback */
16598 	spkt->satapkt_comp = NULL;
16599 	/* Timeout 30s */
16600 	spkt->satapkt_time = sata_default_pkt_time;
16601 
16602 	scmd = &spkt->satapkt_cmd;
16603 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16604 
16605 	/*
16606 	 * Allocate buffer for SMART READ LOG EXTENDED command
16607 	 */
16608 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16609 	    sizeof (struct read_log_ext_directory));
16610 	if (scmd->satacmd_bp == NULL) {
16611 		sata_pkt_free(spx);
16612 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16613 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16614 		    "sata_read_log_ext_directory: "
16615 		    "cannot allocate buffer"));
16616 		return (-1);
16617 	}
16618 
16619 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
16620 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16621 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
16622 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
16623 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
16624 	scmd->satacmd_lba_low_msb = 0;
16625 	scmd->satacmd_lba_mid_lsb = 0;
16626 	scmd->satacmd_lba_mid_msb = 0;
16627 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16628 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16629 
16630 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16631 	    sdinfo->satadrv_addr.cport)));
16632 
16633 	/* Send pkt to SATA HBA driver */
16634 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16635 	    SATA_TRAN_ACCEPTED ||
16636 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16637 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16638 		    sdinfo->satadrv_addr.cport)));
16639 		/*
16640 		 * Whoops, no SMART selftest log info available
16641 		 */
16642 		rval = -1;
16643 		goto fail;
16644 	} else {
16645 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16646 		    sdinfo->satadrv_addr.cport)));
16647 		if (spx->txlt_buf_dma_handle != NULL) {
16648 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16649 			    DDI_DMA_SYNC_FORKERNEL);
16650 			ASSERT(rval == DDI_SUCCESS);
16651 		}
16652 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
16653 		    sizeof (struct read_log_ext_directory));
16654 		rval = 0;
16655 	}
16656 
16657 fail:
16658 	/* Free allocated resources */
16659 	sata_free_local_buffer(spx);
16660 	sata_pkt_free(spx);
16661 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16662 
16663 	return (rval);
16664 }
16665 
16666 /*
16667  * Set up error retrieval sata command for NCQ command error data
16668  * recovery.
16669  *
16670  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
16671  * returns SATA_FAILURE otherwise.
16672  */
16673 static int
16674 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
16675 {
16676 #ifndef __lock_lint
16677 	_NOTE(ARGUNUSED(sdinfo))
16678 #endif
16679 
16680 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
16681 	sata_cmd_t *scmd;
16682 	struct buf *bp;
16683 
16684 	/* Operation modes are up to the caller */
16685 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16686 
16687 	/* Synchronous mode, no callback - may be changed by the caller */
16688 	spkt->satapkt_comp = NULL;
16689 	spkt->satapkt_time = sata_default_pkt_time;
16690 
16691 	scmd = &spkt->satapkt_cmd;
16692 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
16693 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
16694 
16695 	/*
16696 	 * Allocate dma_able buffer error data.
16697 	 * Buffer allocation will take care of buffer alignment and other DMA
16698 	 * attributes.
16699 	 */
16700 	bp = sata_alloc_local_buffer(spx,
16701 	    sizeof (struct sata_ncq_error_recovery_page));
16702 	if (bp == NULL)
16703 		return (SATA_FAILURE);
16704 
16705 	bp_mapin(bp); /* make data buffer accessible */
16706 	scmd->satacmd_bp = bp;
16707 
16708 	/*
16709 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
16710 	 * before accessing it. Handle is in usual place in translate struct.
16711 	 */
16712 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
16713 
16714 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
16715 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
16716 
16717 	return (SATA_SUCCESS);
16718 }
16719 
16720 /*
16721  * sata_xlate_errors() is used to translate (S)ATA error
16722  * information to SCSI information returned in the SCSI
16723  * packet.
16724  */
16725 static void
16726 sata_xlate_errors(sata_pkt_txlate_t *spx)
16727 {
16728 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
16729 	struct scsi_extended_sense *sense;
16730 
16731 	scsipkt->pkt_reason = CMD_INCOMPLETE;
16732 	*scsipkt->pkt_scbp = STATUS_CHECK;
16733 	sense = sata_arq_sense(spx);
16734 
16735 	switch (spx->txlt_sata_pkt->satapkt_reason) {
16736 	case SATA_PKT_PORT_ERROR:
16737 		/*
16738 		 * We have no device data. Assume no data transfered.
16739 		 */
16740 		sense->es_key = KEY_HARDWARE_ERROR;
16741 		break;
16742 
16743 	case SATA_PKT_DEV_ERROR:
16744 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
16745 		    SATA_STATUS_ERR) {
16746 			/*
16747 			 * determine dev error reason from error
16748 			 * reg content
16749 			 */
16750 			sata_decode_device_error(spx, sense);
16751 			break;
16752 		}
16753 		/* No extended sense key - no info available */
16754 		break;
16755 
16756 	case SATA_PKT_TIMEOUT:
16757 		scsipkt->pkt_reason = CMD_TIMEOUT;
16758 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
16759 		/* No extended sense key */
16760 		break;
16761 
16762 	case SATA_PKT_ABORTED:
16763 		scsipkt->pkt_reason = CMD_ABORTED;
16764 		scsipkt->pkt_statistics |= STAT_ABORTED;
16765 		/* No extended sense key */
16766 		break;
16767 
16768 	case SATA_PKT_RESET:
16769 		/*
16770 		 * pkt aborted either by an explicit reset request from
16771 		 * a host, or due to error recovery
16772 		 */
16773 		scsipkt->pkt_reason = CMD_RESET;
16774 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
16775 		break;
16776 
16777 	default:
16778 		scsipkt->pkt_reason = CMD_TRAN_ERR;
16779 		break;
16780 	}
16781 }
16782 
16783 
16784 
16785 
16786 /*
16787  * Log sata message
16788  * dev pathname msg line preceeds the logged message.
16789  */
16790 
16791 static	void
16792 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
16793 {
16794 	char pathname[128];
16795 	dev_info_t *dip = NULL;
16796 	va_list ap;
16797 
16798 	mutex_enter(&sata_log_mutex);
16799 
16800 	va_start(ap, fmt);
16801 	(void) vsprintf(sata_log_buf, fmt, ap);
16802 	va_end(ap);
16803 
16804 	if (sata_hba_inst != NULL) {
16805 		dip = SATA_DIP(sata_hba_inst);
16806 		(void) ddi_pathname(dip, pathname);
16807 	} else {
16808 		pathname[0] = 0;
16809 	}
16810 	if (level == CE_CONT) {
16811 		if (sata_debug_flags == 0)
16812 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
16813 		else
16814 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
16815 	} else {
16816 		if (level != CE_NOTE) {
16817 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
16818 		} else if (sata_msg) {
16819 			cmn_err(level, "%s:\n %s", pathname,
16820 			    sata_log_buf);
16821 		}
16822 	}
16823 
16824 	/* sata trace debug */
16825 	sata_trace_debug(dip, sata_log_buf);
16826 
16827 	mutex_exit(&sata_log_mutex);
16828 }
16829 
16830 
16831 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
16832 
16833 /*
16834  * Start or terminate the thread, depending on flag arg and current state
16835  */
16836 static void
16837 sata_event_thread_control(int startstop)
16838 {
16839 	static 	int sata_event_thread_terminating = 0;
16840 	static 	int sata_event_thread_starting = 0;
16841 	int i;
16842 
16843 	mutex_enter(&sata_event_mutex);
16844 
16845 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
16846 	    sata_event_thread_terminating == 1)) {
16847 		mutex_exit(&sata_event_mutex);
16848 		return;
16849 	}
16850 	if (startstop == 1 && sata_event_thread_starting == 1) {
16851 		mutex_exit(&sata_event_mutex);
16852 		return;
16853 	}
16854 	if (startstop == 1 && sata_event_thread_terminating == 1) {
16855 		sata_event_thread_starting = 1;
16856 		/* wait til terminate operation completes */
16857 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16858 		while (sata_event_thread_terminating == 1) {
16859 			if (i-- <= 0) {
16860 				sata_event_thread_starting = 0;
16861 				mutex_exit(&sata_event_mutex);
16862 #ifdef SATA_DEBUG
16863 				cmn_err(CE_WARN, "sata_event_thread_control: "
16864 				    "timeout waiting for thread to terminate");
16865 #endif
16866 				return;
16867 			}
16868 			mutex_exit(&sata_event_mutex);
16869 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16870 			mutex_enter(&sata_event_mutex);
16871 		}
16872 	}
16873 	if (startstop == 1) {
16874 		if (sata_event_thread == NULL) {
16875 			sata_event_thread = thread_create(NULL, 0,
16876 			    (void (*)())sata_event_daemon,
16877 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
16878 		}
16879 		sata_event_thread_starting = 0;
16880 		mutex_exit(&sata_event_mutex);
16881 		return;
16882 	}
16883 
16884 	/*
16885 	 * If we got here, thread may need to be terminated
16886 	 */
16887 	if (sata_event_thread != NULL) {
16888 		int i;
16889 		/* Signal event thread to go away */
16890 		sata_event_thread_terminating = 1;
16891 		sata_event_thread_terminate = 1;
16892 		cv_signal(&sata_event_cv);
16893 		/*
16894 		 * Wait til daemon terminates.
16895 		 */
16896 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16897 		while (sata_event_thread_terminate == 1) {
16898 			mutex_exit(&sata_event_mutex);
16899 			if (i-- <= 0) {
16900 				/* Daemon did not go away !!! */
16901 #ifdef SATA_DEBUG
16902 				cmn_err(CE_WARN, "sata_event_thread_control: "
16903 				    "cannot terminate event daemon thread");
16904 #endif
16905 				mutex_enter(&sata_event_mutex);
16906 				break;
16907 			}
16908 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16909 			mutex_enter(&sata_event_mutex);
16910 		}
16911 		sata_event_thread_terminating = 0;
16912 	}
16913 	ASSERT(sata_event_thread_terminating == 0);
16914 	ASSERT(sata_event_thread_starting == 0);
16915 	mutex_exit(&sata_event_mutex);
16916 }
16917 
16918 
16919 /*
16920  * SATA HBA event notification function.
16921  * Events reported by SATA HBA drivers per HBA instance relate to a change in
16922  * a port and/or device state or a controller itself.
16923  * Events for different addresses/addr types cannot be combined.
16924  * A warning message is generated for each event type.
16925  * Events are not processed by this function, so only the
16926  * event flag(s)is set for an affected entity and the event thread is
16927  * waken up. Event daemon thread processes all events.
16928  *
16929  * NOTE: Since more than one event may be reported at the same time, one
16930  * cannot determine a sequence of events when opposite event are reported, eg.
16931  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
16932  * is taking precedence over reported events, i.e. may cause ignoring some
16933  * events.
16934  */
16935 #define	SATA_EVENT_MAX_MSG_LENGTH	79
16936 
16937 void
16938 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
16939 {
16940 	sata_hba_inst_t *sata_hba_inst = NULL;
16941 	sata_address_t *saddr;
16942 	sata_pmult_info_t *pmultinfo;
16943 	sata_drive_info_t *sdinfo;
16944 	sata_port_stats_t *pstats;
16945 	sata_cport_info_t *cportinfo;
16946 	sata_pmport_info_t *pmportinfo;
16947 	int cport, pmport;
16948 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
16949 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
16950 	char *lcp;
16951 	static char *err_msg_evnt_1 =
16952 	    "sata_hba_event_notify: invalid port event 0x%x ";
16953 	static char *err_msg_evnt_2 =
16954 	    "sata_hba_event_notify: invalid device event 0x%x ";
16955 	int linkevent;
16956 
16957 	/*
16958 	 * There is a possibility that an event will be generated on HBA
16959 	 * that has not completed attachment or is detaching. We still want
16960 	 * to process events until HBA is detached.
16961 	 */
16962 	mutex_enter(&sata_mutex);
16963 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
16964 	    sata_hba_inst = sata_hba_inst->satahba_next) {
16965 		if (SATA_DIP(sata_hba_inst) == dip)
16966 			if (sata_hba_inst->satahba_attached == 1)
16967 				break;
16968 	}
16969 	mutex_exit(&sata_mutex);
16970 	if (sata_hba_inst == NULL)
16971 		/* HBA not attached */
16972 		return;
16973 
16974 	ASSERT(sata_device != NULL);
16975 
16976 	/*
16977 	 * Validate address before - do not proceed with invalid address.
16978 	 */
16979 	saddr = &sata_device->satadev_addr;
16980 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
16981 		return;
16982 
16983 	cport = saddr->cport;
16984 	pmport = saddr->pmport;
16985 
16986 	buf1[0] = buf2[0] = '\0';
16987 
16988 	/*
16989 	 * If event relates to port or device, check port state.
16990 	 * Port has to be initialized, or we cannot accept an event.
16991 	 */
16992 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
16993 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
16994 		mutex_enter(&sata_hba_inst->satahba_mutex);
16995 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
16996 		mutex_exit(&sata_hba_inst->satahba_mutex);
16997 		if (cportinfo == NULL || cportinfo->cport_state == 0)
16998 			return;
16999 	}
17000 
17001 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
17002 	    SATA_ADDR_DPMPORT)) != 0) {
17003 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
17004 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17005 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
17006 			    "is attached to port %d, ignore pmult/pmport "
17007 			    "event 0x%x", cportinfo->cport_dev_type,
17008 			    cport, event));
17009 			return;
17010 		}
17011 
17012 		mutex_enter(&cportinfo->cport_mutex);
17013 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17014 		mutex_exit(&cportinfo->cport_mutex);
17015 
17016 		/*
17017 		 * The daemon might be processing attachment of port
17018 		 * multiplier, in that case we should ignore events on its
17019 		 * sub-devices.
17020 		 *
17021 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
17022 		 * The pmport_state is checked by sata daemon.
17023 		 */
17024 		if (pmultinfo == NULL ||
17025 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
17026 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17027 			    "sata_hba_event_notify: pmult is not"
17028 			    "available at port %d:%d, ignore event 0x%x",
17029 			    cport, pmport, event));
17030 			return;
17031 		}
17032 	}
17033 
17034 	if ((saddr->qual &
17035 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
17036 
17037 		mutex_enter(&cportinfo->cport_mutex);
17038 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
17039 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17040 			    "sata_hba_event_notify: invalid/"
17041 			    "un-implemented port %d:%d (%d ports), "
17042 			    "ignore event 0x%x", cport, pmport,
17043 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
17044 			mutex_exit(&cportinfo->cport_mutex);
17045 			return;
17046 		}
17047 		mutex_exit(&cportinfo->cport_mutex);
17048 
17049 		mutex_enter(&sata_hba_inst->satahba_mutex);
17050 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17051 		    cport, pmport);
17052 		mutex_exit(&sata_hba_inst->satahba_mutex);
17053 
17054 		/* pmport is implemented/valid? */
17055 		if (pmportinfo == NULL) {
17056 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17057 			    "sata_hba_event_notify: invalid/"
17058 			    "un-implemented port %d:%d, ignore "
17059 			    "event 0x%x", cport, pmport, event));
17060 			return;
17061 		}
17062 	}
17063 
17064 	/*
17065 	 * Events refer to devices, ports and controllers - each has
17066 	 * unique address. Events for different addresses cannot be combined.
17067 	 */
17068 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
17069 
17070 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17071 
17072 		/* qualify this event(s) */
17073 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
17074 			/* Invalid event for the device port */
17075 			(void) sprintf(buf2, err_msg_evnt_1,
17076 			    event & SATA_EVNT_PORT_EVENTS);
17077 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17078 			goto event_info;
17079 		}
17080 		if (saddr->qual == SATA_ADDR_CPORT) {
17081 			/* Controller's device port event */
17082 
17083 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
17084 			    cport_event_flags |=
17085 			    event & SATA_EVNT_PORT_EVENTS;
17086 			pstats =
17087 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
17088 			    cport_stats;
17089 		} else {
17090 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17091 			mutex_enter(&pmportinfo->pmport_mutex);
17092 			/* Port multiplier's device port event */
17093 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17094 			    pmport_event_flags |=
17095 			    event & SATA_EVNT_PORT_EVENTS;
17096 			pstats =
17097 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17098 			    pmport_stats;
17099 			mutex_exit(&pmportinfo->pmport_mutex);
17100 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17101 		}
17102 
17103 		/*
17104 		 * Add to statistics and log the message. We have to do it
17105 		 * here rather than in the event daemon, because there may be
17106 		 * multiple events occuring before they are processed.
17107 		 */
17108 		linkevent = event &
17109 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
17110 		if (linkevent) {
17111 			if (linkevent == (SATA_EVNT_LINK_LOST |
17112 			    SATA_EVNT_LINK_ESTABLISHED)) {
17113 				/* This is likely event combination */
17114 				(void) strlcat(buf1, "link lost/established, ",
17115 				    SATA_EVENT_MAX_MSG_LENGTH);
17116 
17117 				if (pstats->link_lost < 0xffffffffffffffffULL)
17118 					pstats->link_lost++;
17119 				if (pstats->link_established <
17120 				    0xffffffffffffffffULL)
17121 					pstats->link_established++;
17122 				linkevent = 0;
17123 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
17124 				(void) strlcat(buf1, "link lost, ",
17125 				    SATA_EVENT_MAX_MSG_LENGTH);
17126 
17127 				if (pstats->link_lost < 0xffffffffffffffffULL)
17128 					pstats->link_lost++;
17129 			} else {
17130 				(void) strlcat(buf1, "link established, ",
17131 				    SATA_EVENT_MAX_MSG_LENGTH);
17132 				if (pstats->link_established <
17133 				    0xffffffffffffffffULL)
17134 					pstats->link_established++;
17135 			}
17136 		}
17137 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
17138 			(void) strlcat(buf1, "device attached, ",
17139 			    SATA_EVENT_MAX_MSG_LENGTH);
17140 			if (pstats->device_attached < 0xffffffffffffffffULL)
17141 				pstats->device_attached++;
17142 		}
17143 		if (event & SATA_EVNT_DEVICE_DETACHED) {
17144 			(void) strlcat(buf1, "device detached, ",
17145 			    SATA_EVENT_MAX_MSG_LENGTH);
17146 			if (pstats->device_detached < 0xffffffffffffffffULL)
17147 				pstats->device_detached++;
17148 		}
17149 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
17150 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17151 			    "port %d power level changed", cport);
17152 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
17153 				pstats->port_pwr_changed++;
17154 		}
17155 
17156 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
17157 			/* There should be no other events for this address */
17158 			(void) sprintf(buf2, err_msg_evnt_1,
17159 			    event & ~SATA_EVNT_PORT_EVENTS);
17160 		}
17161 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17162 
17163 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
17164 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17165 
17166 		/* qualify this event */
17167 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
17168 			/* Invalid event for a device */
17169 			(void) sprintf(buf2, err_msg_evnt_2,
17170 			    event & SATA_EVNT_DEVICE_RESET);
17171 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17172 			goto event_info;
17173 		}
17174 		/* drive event */
17175 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
17176 		if (sdinfo != NULL) {
17177 			if (event & SATA_EVNT_DEVICE_RESET) {
17178 				(void) strlcat(buf1, "device reset, ",
17179 				    SATA_EVENT_MAX_MSG_LENGTH);
17180 				if (sdinfo->satadrv_stats.drive_reset <
17181 				    0xffffffffffffffffULL)
17182 					sdinfo->satadrv_stats.drive_reset++;
17183 				sdinfo->satadrv_event_flags |=
17184 				    SATA_EVNT_DEVICE_RESET;
17185 			}
17186 		}
17187 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
17188 			/* Invalid event for a device */
17189 			(void) sprintf(buf2, err_msg_evnt_2,
17190 			    event & ~SATA_EVNT_DRIVE_EVENTS);
17191 		}
17192 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17193 	} else if (saddr->qual == SATA_ADDR_PMULT) {
17194 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17195 
17196 		/* qualify this event */
17197 		if ((event & (SATA_EVNT_DEVICE_RESET |
17198 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
17199 			/* Invalid event for a port multiplier */
17200 			(void) sprintf(buf2, err_msg_evnt_2,
17201 			    event & SATA_EVNT_DEVICE_RESET);
17202 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17203 			goto event_info;
17204 		}
17205 
17206 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17207 
17208 		if (event & SATA_EVNT_DEVICE_RESET) {
17209 
17210 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17211 			    "[Reset] port-mult on cport %d", cport);
17212 			pmultinfo->pmult_event_flags |=
17213 			    SATA_EVNT_DEVICE_RESET;
17214 			(void) strlcat(buf1, "pmult reset, ",
17215 			    SATA_EVENT_MAX_MSG_LENGTH);
17216 		}
17217 
17218 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17219 
17220 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17221 			    "pmult link changed on cport %d", cport);
17222 			pmultinfo->pmult_event_flags |=
17223 			    SATA_EVNT_PMULT_LINK_CHANGED;
17224 			(void) strlcat(buf1, "pmult link changed, ",
17225 			    SATA_EVENT_MAX_MSG_LENGTH);
17226 		}
17227 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17228 
17229 	} else {
17230 		if (saddr->qual != SATA_ADDR_NULL) {
17231 			/* Wrong address qualifier */
17232 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17233 			    "sata_hba_event_notify: invalid address 0x%x",
17234 			    *(uint32_t *)saddr));
17235 			return;
17236 		}
17237 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17238 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17239 			/* Invalid event for the controller */
17240 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17241 			    "sata_hba_event_notify: invalid event 0x%x for "
17242 			    "controller",
17243 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17244 			return;
17245 		}
17246 		buf1[0] = '\0';
17247 		/* This may be a frequent and not interesting event */
17248 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17249 		    "controller power level changed\n", NULL);
17250 
17251 		mutex_enter(&sata_hba_inst->satahba_mutex);
17252 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17253 		    0xffffffffffffffffULL)
17254 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17255 
17256 		sata_hba_inst->satahba_event_flags |=
17257 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17258 		mutex_exit(&sata_hba_inst->satahba_mutex);
17259 	}
17260 	/*
17261 	 * If we got here, there is something to do with this HBA
17262 	 * instance.
17263 	 */
17264 	mutex_enter(&sata_hba_inst->satahba_mutex);
17265 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17266 	mutex_exit(&sata_hba_inst->satahba_mutex);
17267 	mutex_enter(&sata_mutex);
17268 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17269 	mutex_exit(&sata_mutex);
17270 
17271 	/* Tickle event thread */
17272 	mutex_enter(&sata_event_mutex);
17273 	if (sata_event_thread_active == 0)
17274 		cv_signal(&sata_event_cv);
17275 	mutex_exit(&sata_event_mutex);
17276 
17277 event_info:
17278 	if (buf1[0] != '\0') {
17279 		lcp = strrchr(buf1, ',');
17280 		if (lcp != NULL)
17281 			*lcp = '\0';
17282 	}
17283 	if (saddr->qual == SATA_ADDR_CPORT ||
17284 	    saddr->qual == SATA_ADDR_DCPORT) {
17285 		if (buf1[0] != '\0') {
17286 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17287 			    cport, buf1);
17288 		}
17289 		if (buf2[0] != '\0') {
17290 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17291 			    cport, buf2);
17292 		}
17293 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
17294 	    saddr->qual == SATA_ADDR_DPMPORT) {
17295 		if (buf1[0] != '\0') {
17296 			sata_log(sata_hba_inst, CE_NOTE,
17297 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
17298 		}
17299 		if (buf2[0] != '\0') {
17300 			sata_log(sata_hba_inst, CE_NOTE,
17301 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
17302 		}
17303 	}
17304 }
17305 
17306 
17307 /*
17308  * Event processing thread.
17309  * Arg is a pointer to the sata_hba_list pointer.
17310  * It is not really needed, because sata_hba_list is global and static
17311  */
17312 static void
17313 sata_event_daemon(void *arg)
17314 {
17315 #ifndef __lock_lint
17316 	_NOTE(ARGUNUSED(arg))
17317 #endif
17318 	sata_hba_inst_t *sata_hba_inst;
17319 	clock_t delta;
17320 
17321 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17322 	    "SATA event daemon started\n", NULL);
17323 loop:
17324 	/*
17325 	 * Process events here. Walk through all registered HBAs
17326 	 */
17327 	mutex_enter(&sata_mutex);
17328 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17329 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17330 		ASSERT(sata_hba_inst != NULL);
17331 		mutex_enter(&sata_hba_inst->satahba_mutex);
17332 		if (sata_hba_inst->satahba_attached == 0 ||
17333 		    (sata_hba_inst->satahba_event_flags &
17334 		    SATA_EVNT_SKIP) != 0) {
17335 			mutex_exit(&sata_hba_inst->satahba_mutex);
17336 			continue;
17337 		}
17338 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
17339 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
17340 			mutex_exit(&sata_hba_inst->satahba_mutex);
17341 			mutex_exit(&sata_mutex);
17342 			/* Got the controller with pending event */
17343 			sata_process_controller_events(sata_hba_inst);
17344 			/*
17345 			 * Since global mutex was released, there is a
17346 			 * possibility that HBA list has changed, so start
17347 			 * over from the top. Just processed controller
17348 			 * will be passed-over because of the SKIP flag.
17349 			 */
17350 			goto loop;
17351 		}
17352 		mutex_exit(&sata_hba_inst->satahba_mutex);
17353 	}
17354 	/* Clear SKIP flag in all controllers */
17355 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17356 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17357 		mutex_enter(&sata_hba_inst->satahba_mutex);
17358 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
17359 		mutex_exit(&sata_hba_inst->satahba_mutex);
17360 	}
17361 	mutex_exit(&sata_mutex);
17362 
17363 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17364 	    "SATA EVENT DAEMON suspending itself", NULL);
17365 
17366 #ifdef SATA_DEBUG
17367 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
17368 		sata_log(sata_hba_inst, CE_WARN,
17369 		    "SATA EVENTS PROCESSING DISABLED\n");
17370 		thread_exit(); /* Daemon will not run again */
17371 	}
17372 #endif
17373 	mutex_enter(&sata_event_mutex);
17374 	sata_event_thread_active = 0;
17375 	mutex_exit(&sata_event_mutex);
17376 	/*
17377 	 * Go to sleep/suspend itself and wake up either because new event or
17378 	 * wait timeout. Exit if there is a termination request (driver
17379 	 * unload).
17380 	 */
17381 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
17382 	do {
17383 		mutex_enter(&sata_event_mutex);
17384 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
17385 		    delta, TR_CLOCK_TICK);
17386 
17387 		if (sata_event_thread_active != 0) {
17388 			mutex_exit(&sata_event_mutex);
17389 			continue;
17390 		}
17391 
17392 		/* Check if it is time to go away */
17393 		if (sata_event_thread_terminate == 1) {
17394 			/*
17395 			 * It is up to the thread setting above flag to make
17396 			 * sure that this thread is not killed prematurely.
17397 			 */
17398 			sata_event_thread_terminate = 0;
17399 			sata_event_thread = NULL;
17400 			mutex_exit(&sata_event_mutex);
17401 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17402 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
17403 			thread_exit();  { _NOTE(NOT_REACHED) }
17404 		}
17405 		mutex_exit(&sata_event_mutex);
17406 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
17407 
17408 	mutex_enter(&sata_event_mutex);
17409 	sata_event_thread_active = 1;
17410 	mutex_exit(&sata_event_mutex);
17411 
17412 	mutex_enter(&sata_mutex);
17413 	sata_event_pending &= ~SATA_EVNT_MAIN;
17414 	mutex_exit(&sata_mutex);
17415 
17416 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17417 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
17418 
17419 	goto loop;
17420 }
17421 
17422 /*
17423  * Specific HBA instance event processing.
17424  *
17425  * NOTE: At the moment, device event processing is limited to hard disks
17426  * only.
17427  * Port multiplier is supported now.
17428  */
17429 static void
17430 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
17431 {
17432 	int ncport;
17433 	uint32_t event_flags;
17434 	sata_address_t *saddr;
17435 	sata_cport_info_t *cportinfo;
17436 	sata_pmult_info_t *pmultinfo;
17437 
17438 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
17439 	    "Processing controller %d event(s)",
17440 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
17441 
17442 	mutex_enter(&sata_hba_inst->satahba_mutex);
17443 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
17444 	event_flags = sata_hba_inst->satahba_event_flags;
17445 	mutex_exit(&sata_hba_inst->satahba_mutex);
17446 	/*
17447 	 * Process controller power change first
17448 	 * HERE
17449 	 */
17450 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
17451 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
17452 
17453 	/*
17454 	 * Search through ports/devices to identify affected port/device.
17455 	 * We may have to process events for more than one port/device.
17456 	 */
17457 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
17458 		/*
17459 		 * Not all ports may be processed in attach by the time we
17460 		 * get an event. Check if port info is initialized.
17461 		 */
17462 		mutex_enter(&sata_hba_inst->satahba_mutex);
17463 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
17464 		mutex_exit(&sata_hba_inst->satahba_mutex);
17465 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
17466 			continue;
17467 
17468 		/* We have initialized controller port info */
17469 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17470 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
17471 		    cport_event_flags;
17472 		/* Check if port was locked by IOCTL processing */
17473 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
17474 			/*
17475 			 * We ignore port events because port is busy
17476 			 * with AP control processing. Set again
17477 			 * controller and main event flag, so that
17478 			 * events may be processed by the next daemon
17479 			 * run.
17480 			 */
17481 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17482 			mutex_enter(&sata_hba_inst->satahba_mutex);
17483 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17484 			mutex_exit(&sata_hba_inst->satahba_mutex);
17485 			mutex_enter(&sata_mutex);
17486 			sata_event_pending |= SATA_EVNT_MAIN;
17487 			mutex_exit(&sata_mutex);
17488 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
17489 			    "Event processing postponed until "
17490 			    "AP control processing completes",
17491 			    NULL);
17492 			/* Check other ports */
17493 			continue;
17494 		} else {
17495 			/*
17496 			 * Set BSY flag so that AP control would not
17497 			 * interfere with events processing for
17498 			 * this port.
17499 			 */
17500 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17501 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
17502 		}
17503 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17504 
17505 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
17506 
17507 		if ((event_flags &
17508 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17509 			/*
17510 			 * Got port event.
17511 			 * We need some hierarchy of event processing as they
17512 			 * are affecting each other:
17513 			 * 1. port failed
17514 			 * 2. device detached/attached
17515 			 * 3. link events - link events may trigger device
17516 			 *    detached or device attached events in some
17517 			 *    circumstances.
17518 			 * 4. port power level changed
17519 			 */
17520 			if (event_flags & SATA_EVNT_PORT_FAILED) {
17521 				sata_process_port_failed_event(sata_hba_inst,
17522 				    saddr);
17523 			}
17524 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17525 				sata_process_device_detached(sata_hba_inst,
17526 				    saddr);
17527 			}
17528 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17529 				sata_process_device_attached(sata_hba_inst,
17530 				    saddr);
17531 			}
17532 			if (event_flags &
17533 			    (SATA_EVNT_LINK_ESTABLISHED |
17534 			    SATA_EVNT_LINK_LOST)) {
17535 				sata_process_port_link_events(sata_hba_inst,
17536 				    saddr);
17537 			}
17538 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
17539 				sata_process_port_pwr_change(sata_hba_inst,
17540 				    saddr);
17541 			}
17542 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17543 				sata_process_target_node_cleanup(
17544 				    sata_hba_inst, saddr);
17545 			}
17546 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
17547 				sata_process_device_autoonline(
17548 				    sata_hba_inst, saddr);
17549 			}
17550 		}
17551 
17552 
17553 		/*
17554 		 * Scan port multiplier and all its sub-ports event flags.
17555 		 * The events are marked by
17556 		 * (1) sata_pmult_info.pmult_event_flags
17557 		 * (2) sata_pmport_info.pmport_event_flags
17558 		 */
17559 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17560 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
17561 			/*
17562 			 * There should be another extra check: this
17563 			 * port multiplier still exists?
17564 			 */
17565 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
17566 			    ncport);
17567 
17568 			if (pmultinfo != NULL) {
17569 				mutex_exit(&(SATA_CPORT_MUTEX(
17570 				    sata_hba_inst, ncport)));
17571 				sata_process_pmult_events(
17572 				    sata_hba_inst, ncport);
17573 				mutex_enter(&(SATA_CPORT_MUTEX(
17574 				    sata_hba_inst, ncport)));
17575 			} else {
17576 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17577 				    "Port-multiplier is gone. "
17578 				    "Ignore all sub-device events "
17579 				    "at port %d.", ncport);
17580 			}
17581 		}
17582 
17583 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
17584 		    SATA_DTYPE_NONE) &&
17585 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
17586 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
17587 			    satadrv_event_flags &
17588 			    (SATA_EVNT_DEVICE_RESET |
17589 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17590 				/* Have device event */
17591 				sata_process_device_reset(sata_hba_inst,
17592 				    saddr);
17593 			}
17594 		}
17595 		/* Release PORT_BUSY flag */
17596 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17597 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17598 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17599 
17600 	} /* End of loop through the controller SATA ports */
17601 }
17602 
17603 /*
17604  * Specific port multiplier instance event processing. At the moment, device
17605  * event processing is limited to link/attach event only.
17606  *
17607  * NOTE: power management event is not supported yet.
17608  */
17609 static void
17610 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
17611 {
17612 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17613 	sata_pmult_info_t *pmultinfo;
17614 	sata_pmport_info_t *pmportinfo;
17615 	sata_address_t *saddr;
17616 	sata_device_t sata_device;
17617 	uint32_t event_flags;
17618 	int npmport;
17619 	int rval;
17620 
17621 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17622 	    "Processing pmult event(s) on cport %d of controller %d",
17623 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17624 
17625 	/* First process events on port multiplier */
17626 	mutex_enter(&cportinfo->cport_mutex);
17627 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17628 	event_flags = pmultinfo->pmult_event_flags;
17629 
17630 	/*
17631 	 * Reset event (of port multiplier) has higher priority because the
17632 	 * port multiplier itself might be failed or removed after reset.
17633 	 */
17634 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
17635 		/*
17636 		 * The status of the sub-links are uncertain,
17637 		 * so mark all sub-ports as RESET
17638 		 */
17639 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
17640 		    sata_hba_inst, cport); npmport ++) {
17641 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17642 			    cport, npmport);
17643 			if (pmportinfo == NULL) {
17644 				/* That's weird. */
17645 				SATA_LOG_D((sata_hba_inst, CE_WARN,
17646 				    "sata_hba_event_notify: "
17647 				    "invalid/un-implemented "
17648 				    "port %d:%d (%d ports), ",
17649 				    cport, npmport, SATA_NUM_PMPORTS(
17650 				    sata_hba_inst, cport)));
17651 				continue;
17652 			}
17653 
17654 			mutex_enter(&pmportinfo->pmport_mutex);
17655 
17656 			/* Mark all pmport to unknow state. */
17657 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
17658 			/* Mark all pmports with link events. */
17659 			pmportinfo->pmport_event_flags =
17660 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
17661 			mutex_exit(&pmportinfo->pmport_mutex);
17662 		}
17663 
17664 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
17665 		/*
17666 		 * We need probe the port multiplier to know what has
17667 		 * happened.
17668 		 */
17669 		bzero(&sata_device, sizeof (sata_device_t));
17670 		sata_device.satadev_rev = SATA_DEVICE_REV;
17671 		sata_device.satadev_addr.cport = cport;
17672 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
17673 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
17674 
17675 		mutex_exit(&cportinfo->cport_mutex);
17676 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17677 		    (SATA_DIP(sata_hba_inst), &sata_device);
17678 		mutex_enter(&cportinfo->cport_mutex);
17679 		if (rval != SATA_SUCCESS) {
17680 			/* Something went wrong? Fail the port */
17681 			cportinfo->cport_state = SATA_PSTATE_FAILED;
17682 			mutex_exit(&cportinfo->cport_mutex);
17683 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17684 			    "SATA port %d probing failed", cport));
17685 
17686 			/* PMult structure must be released.  */
17687 			sata_free_pmult(sata_hba_inst, &sata_device);
17688 			return;
17689 		}
17690 
17691 		sata_update_port_info(sata_hba_inst, &sata_device);
17692 
17693 		/*
17694 		 * Sanity check - Port is active? Is the link active?
17695 		 * The device is still a port multiplier?
17696 		 */
17697 		if ((cportinfo->cport_state &
17698 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
17699 		    ((cportinfo->cport_scr.sstatus &
17700 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
17701 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
17702 			mutex_exit(&cportinfo->cport_mutex);
17703 
17704 			/* PMult structure must be released.  */
17705 			sata_free_pmult(sata_hba_inst, &sata_device);
17706 			return;
17707 		}
17708 
17709 		/* Probed succeed, set port ready. */
17710 		cportinfo->cport_state |=
17711 		    SATA_STATE_PROBED | SATA_STATE_READY;
17712 	}
17713 
17714 	/* Release port multiplier event flags. */
17715 	pmultinfo->pmult_event_flags &=
17716 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
17717 	mutex_exit(&cportinfo->cport_mutex);
17718 
17719 	/*
17720 	 * Check all sub-links.
17721 	 */
17722 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
17723 	    npmport ++) {
17724 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
17725 		mutex_enter(&pmportinfo->pmport_mutex);
17726 		event_flags = pmportinfo->pmport_event_flags;
17727 		mutex_exit(&pmportinfo->pmport_mutex);
17728 		saddr = &pmportinfo->pmport_addr;
17729 
17730 		if ((event_flags &
17731 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17732 			/*
17733 			 * Got port multiplier port event.
17734 			 * We need some hierarchy of event processing as they
17735 			 * are affecting each other:
17736 			 * 1. device detached/attached
17737 			 * 2. link events - link events may trigger device
17738 			 *    detached or device attached events in some
17739 			 *    circumstances.
17740 			 */
17741 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17742 				sata_process_pmdevice_detached(sata_hba_inst,
17743 				    saddr);
17744 			}
17745 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17746 				sata_process_pmdevice_attached(sata_hba_inst,
17747 				    saddr);
17748 			}
17749 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
17750 			    event_flags & SATA_EVNT_LINK_LOST) {
17751 				sata_process_pmport_link_events(sata_hba_inst,
17752 				    saddr);
17753 			}
17754 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17755 				sata_process_target_node_cleanup(
17756 				    sata_hba_inst, saddr);
17757 			}
17758 		}
17759 
17760 		/* Checking drive event(s). */
17761 		mutex_enter(&pmportinfo->pmport_mutex);
17762 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
17763 		    pmportinfo->pmport_sata_drive != NULL) {
17764 			event_flags = pmportinfo->pmport_sata_drive->
17765 			    satadrv_event_flags;
17766 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
17767 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17768 
17769 				/* Have device event */
17770 				sata_process_pmdevice_reset(sata_hba_inst,
17771 				    saddr);
17772 			}
17773 		}
17774 		mutex_exit(&pmportinfo->pmport_mutex);
17775 
17776 		/* Release PORT_BUSY flag */
17777 		mutex_enter(&cportinfo->cport_mutex);
17778 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17779 		mutex_exit(&cportinfo->cport_mutex);
17780 	}
17781 
17782 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17783 	    "[DONE] pmult event(s) on cport %d of controller %d",
17784 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17785 }
17786 
17787 /*
17788  * Process HBA power level change reported by HBA driver.
17789  * Not implemented at this time - event is ignored.
17790  */
17791 static void
17792 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
17793 {
17794 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17795 	    "Processing controller power level change", NULL);
17796 
17797 	/* Ignoring it for now */
17798 	mutex_enter(&sata_hba_inst->satahba_mutex);
17799 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17800 	mutex_exit(&sata_hba_inst->satahba_mutex);
17801 }
17802 
17803 /*
17804  * Process port power level change reported by HBA driver.
17805  * Not implemented at this time - event is ignored.
17806  */
17807 static void
17808 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
17809     sata_address_t *saddr)
17810 {
17811 	sata_cport_info_t *cportinfo;
17812 
17813 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17814 	    "Processing port power level change", NULL);
17815 
17816 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17817 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17818 	/* Reset event flag */
17819 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17820 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17821 }
17822 
17823 /*
17824  * Process port failure reported by HBA driver.
17825  * cports support only - no pmports.
17826  */
17827 static void
17828 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
17829     sata_address_t *saddr)
17830 {
17831 	sata_cport_info_t *cportinfo;
17832 
17833 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17834 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17835 	/* Reset event flag first */
17836 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
17837 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
17838 	if ((cportinfo->cport_state &
17839 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
17840 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17841 		    cport_mutex);
17842 		return;
17843 	}
17844 	/* Fail the port */
17845 	cportinfo->cport_state = SATA_PSTATE_FAILED;
17846 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17847 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
17848 }
17849 
17850 /*
17851  * Device Reset Event processing.
17852  * The seqeunce is managed by 3 stage flags:
17853  * - reset event reported,
17854  * - reset event being processed,
17855  * - request to clear device reset state.
17856  *
17857  * NOTE: This function has to be entered with cport mutex held. It exits with
17858  * mutex held as well, but can release mutex during the processing.
17859  */
17860 static void
17861 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
17862     sata_address_t *saddr)
17863 {
17864 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17865 	sata_drive_info_t *sdinfo;
17866 	sata_cport_info_t *cportinfo;
17867 	sata_device_t sata_device;
17868 	int rval_probe, rval_set;
17869 
17870 	/* We only care about host sata cport for now */
17871 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17872 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17873 	/*
17874 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17875 	 * state, ignore reset event.
17876 	 */
17877 	if (((cportinfo->cport_state &
17878 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17879 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17880 		sdinfo->satadrv_event_flags &=
17881 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17882 		return;
17883 	}
17884 
17885 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
17886 	    SATA_DTYPE_PMULT)) {
17887 		/*
17888 		 * Should not happened: this is already handled in
17889 		 * sata_hba_event_notify()
17890 		 */
17891 		mutex_exit(&cportinfo->cport_mutex);
17892 		goto done;
17893 	}
17894 
17895 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
17896 	    SATA_VALID_DEV_TYPE) == 0) {
17897 		/*
17898 		 * This should not happen - coding error.
17899 		 * But we can recover, so do not panic, just clean up
17900 		 * and if in debug mode, log the message.
17901 		 */
17902 #ifdef SATA_DEBUG
17903 		sata_log(sata_hba_inst, CE_WARN,
17904 		    "sata_process_device_reset: "
17905 		    "Invalid device type with sdinfo!", NULL);
17906 #endif
17907 		sdinfo->satadrv_event_flags = 0;
17908 		return;
17909 	}
17910 
17911 #ifdef SATA_DEBUG
17912 	if ((sdinfo->satadrv_event_flags &
17913 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17914 		/* Nothing to do */
17915 		/* Something is weird - why we are processing dev reset? */
17916 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17917 		    "No device reset event!!!!", NULL);
17918 
17919 		return;
17920 	}
17921 	if ((sdinfo->satadrv_event_flags &
17922 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17923 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17924 		/* Something is weird - new device reset event */
17925 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17926 		    "Overlapping device reset events!", NULL);
17927 	}
17928 #endif
17929 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17930 	    "Processing port %d device reset", saddr->cport);
17931 
17932 	/* Clear event flag */
17933 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17934 
17935 	/* It seems that we always need to check the port state first */
17936 	sata_device.satadev_rev = SATA_DEVICE_REV;
17937 	sata_device.satadev_addr = *saddr;
17938 	/*
17939 	 * We have to exit mutex, because the HBA probe port function may
17940 	 * block on its own mutex.
17941 	 */
17942 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17943 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17944 	    (SATA_DIP(sata_hba_inst), &sata_device);
17945 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17946 	sata_update_port_info(sata_hba_inst, &sata_device);
17947 	if (rval_probe != SATA_SUCCESS) {
17948 		/* Something went wrong? Fail the port */
17949 		cportinfo->cport_state = SATA_PSTATE_FAILED;
17950 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17951 		if (sdinfo != NULL)
17952 			sdinfo->satadrv_event_flags = 0;
17953 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17954 		    cport_mutex);
17955 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17956 		    "SATA port %d probing failed",
17957 		    saddr->cport));
17958 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
17959 		    saddr->cport)->cport_mutex);
17960 		return;
17961 	}
17962 	if ((sata_device.satadev_scr.sstatus  &
17963 	    SATA_PORT_DEVLINK_UP_MASK) !=
17964 	    SATA_PORT_DEVLINK_UP ||
17965 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
17966 		/*
17967 		 * No device to process, anymore. Some other event processing
17968 		 * would or have already performed port info cleanup.
17969 		 * To be safe (HBA may need it), request clearing device
17970 		 * reset condition.
17971 		 */
17972 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17973 		if (sdinfo != NULL) {
17974 			sdinfo->satadrv_event_flags &=
17975 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17976 			sdinfo->satadrv_event_flags |=
17977 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17978 		}
17979 		return;
17980 	}
17981 
17982 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17983 	if (sdinfo == NULL) {
17984 		return;
17985 	}
17986 	if ((sdinfo->satadrv_event_flags &
17987 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
17988 		/*
17989 		 * Start tracking time for device feature restoration and
17990 		 * identification. Save current time (lbolt value).
17991 		 */
17992 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
17993 	}
17994 	/* Mark device reset processing as active */
17995 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
17996 
17997 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
17998 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17999 
18000 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
18001 
18002 	if (rval_set  != SATA_SUCCESS) {
18003 		/*
18004 		 * Restoring drive setting failed.
18005 		 * Probe the port first, to check if the port state has changed
18006 		 */
18007 		sata_device.satadev_rev = SATA_DEVICE_REV;
18008 		sata_device.satadev_addr = *saddr;
18009 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
18010 		/* probe port */
18011 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18012 		    (SATA_DIP(sata_hba_inst), &sata_device);
18013 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18014 		    cport_mutex);
18015 		if (rval_probe == SATA_SUCCESS &&
18016 		    (sata_device.satadev_state &
18017 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18018 		    (sata_device.satadev_scr.sstatus  &
18019 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18020 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18021 			/*
18022 			 * We may retry this a bit later - in-process reset
18023 			 * condition should be already set.
18024 			 * Track retry time for device identification.
18025 			 */
18026 			if ((cportinfo->cport_dev_type &
18027 			    SATA_VALID_DEV_TYPE) != 0 &&
18028 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
18029 			    sdinfo->satadrv_reset_time != 0) {
18030 				clock_t cur_time = ddi_get_lbolt();
18031 				/*
18032 				 * If the retry time limit was not
18033 				 * exceeded, retry.
18034 				 */
18035 				if ((cur_time - sdinfo->satadrv_reset_time) <
18036 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18037 					mutex_enter(
18038 					    &sata_hba_inst->satahba_mutex);
18039 					sata_hba_inst->satahba_event_flags |=
18040 					    SATA_EVNT_MAIN;
18041 					mutex_exit(
18042 					    &sata_hba_inst->satahba_mutex);
18043 					mutex_enter(&sata_mutex);
18044 					sata_event_pending |= SATA_EVNT_MAIN;
18045 					mutex_exit(&sata_mutex);
18046 					return;
18047 				}
18048 				if (rval_set == SATA_RETRY) {
18049 					/*
18050 					 * Setting drive features failed, but
18051 					 * the drive is still accessible,
18052 					 * so emit a warning message before
18053 					 * return.
18054 					 */
18055 					mutex_exit(&SATA_CPORT_INFO(
18056 					    sata_hba_inst,
18057 					    saddr->cport)->cport_mutex);
18058 					goto done;
18059 				}
18060 			}
18061 			/* Fail the drive */
18062 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18063 
18064 			sata_log(sata_hba_inst, CE_WARN,
18065 			    "SATA device at port %d - device failed",
18066 			    saddr->cport);
18067 		}
18068 		/*
18069 		 * No point of retrying - device failed or some other event
18070 		 * processing or already did or will do port info cleanup.
18071 		 * To be safe (HBA may need it),
18072 		 * request clearing device reset condition.
18073 		 */
18074 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
18075 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18076 		sdinfo->satadrv_reset_time = 0;
18077 		return;
18078 	}
18079 done:
18080 	/*
18081 	 * If setting of drive features failed, but the drive is still
18082 	 * accessible, emit a warning message.
18083 	 */
18084 	if (rval_set == SATA_RETRY) {
18085 		sata_log(sata_hba_inst, CE_WARN,
18086 		    "SATA device at port %d - desired setting could not be "
18087 		    "restored after reset. Device may not operate as expected.",
18088 		    saddr->cport);
18089 	}
18090 	/*
18091 	 * Raise the flag indicating that the next sata command could
18092 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18093 	 * reset is reported.
18094 	 */
18095 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18096 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18097 		sdinfo->satadrv_reset_time = 0;
18098 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
18099 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18100 			sdinfo->satadrv_event_flags &=
18101 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18102 			sdinfo->satadrv_event_flags |=
18103 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18104 		}
18105 	}
18106 }
18107 
18108 
18109 /*
18110  * Port Multiplier Port Device Reset Event processing.
18111  *
18112  * NOTE: This function has to be entered with pmport mutex held. It exits with
18113  * mutex held as well, but can release mutex during the processing.
18114  */
18115 static void
18116 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
18117     sata_address_t *saddr)
18118 {
18119 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18120 	sata_drive_info_t *sdinfo = NULL;
18121 	sata_cport_info_t *cportinfo = NULL;
18122 	sata_pmport_info_t *pmportinfo = NULL;
18123 	sata_pmult_info_t *pminfo = NULL;
18124 	sata_device_t sata_device;
18125 	uint8_t cport = saddr->cport;
18126 	uint8_t pmport = saddr->pmport;
18127 	int rval;
18128 
18129 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18130 	    "Processing drive reset at port %d:%d", cport, pmport);
18131 
18132 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
18133 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18134 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
18135 
18136 	/*
18137 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18138 	 * state, ignore reset event.
18139 	 */
18140 	if (((cportinfo->cport_state &
18141 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18142 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18143 		sdinfo->satadrv_event_flags &=
18144 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18145 		return;
18146 	}
18147 
18148 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
18149 		/*
18150 		 * This should not happen - coding error.
18151 		 * But we can recover, so do not panic, just clean up
18152 		 * and if in debug mode, log the message.
18153 		 */
18154 #ifdef SATA_DEBUG
18155 		sata_log(sata_hba_inst, CE_WARN,
18156 		    "sata_process_pmdevice_reset: "
18157 		    "Invalid device type with sdinfo!", NULL);
18158 #endif
18159 		sdinfo->satadrv_event_flags = 0;
18160 		return;
18161 	}
18162 
18163 #ifdef SATA_DEBUG
18164 	if ((sdinfo->satadrv_event_flags &
18165 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18166 		/* Nothing to do */
18167 		/* Something is weird - why we are processing dev reset? */
18168 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18169 		    "No device reset event!!!!", NULL);
18170 
18171 		return;
18172 	}
18173 	if ((sdinfo->satadrv_event_flags &
18174 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18175 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18176 		/* Something is weird - new device reset event */
18177 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18178 		    "Overlapping device reset events!", NULL);
18179 	}
18180 #endif
18181 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18182 	    "Processing port %d:%d device reset", cport, pmport);
18183 
18184 	/* Clear event flag */
18185 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18186 
18187 	/* It seems that we always need to check the port state first */
18188 	sata_device.satadev_rev = SATA_DEVICE_REV;
18189 	sata_device.satadev_addr = *saddr;
18190 	/*
18191 	 * We have to exit mutex, because the HBA probe port function may
18192 	 * block on its own mutex.
18193 	 */
18194 	mutex_exit(&pmportinfo->pmport_mutex);
18195 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18196 	    (SATA_DIP(sata_hba_inst), &sata_device);
18197 	mutex_enter(&pmportinfo->pmport_mutex);
18198 
18199 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18200 	if (rval != SATA_SUCCESS) {
18201 		/* Something went wrong? Fail the port */
18202 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18203 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18204 		    saddr->pmport);
18205 		if (sdinfo != NULL)
18206 			sdinfo->satadrv_event_flags = 0;
18207 		mutex_exit(&pmportinfo->pmport_mutex);
18208 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18209 		    "SATA port %d:%d probing failed",
18210 		    saddr->cport, saddr->pmport));
18211 		mutex_enter(&pmportinfo->pmport_mutex);
18212 		return;
18213 	}
18214 	if ((sata_device.satadev_scr.sstatus  &
18215 	    SATA_PORT_DEVLINK_UP_MASK) !=
18216 	    SATA_PORT_DEVLINK_UP ||
18217 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18218 		/*
18219 		 * No device to process, anymore. Some other event processing
18220 		 * would or have already performed port info cleanup.
18221 		 * To be safe (HBA may need it), request clearing device
18222 		 * reset condition.
18223 		 */
18224 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18225 		    saddr->pmport);
18226 		if (sdinfo != NULL) {
18227 			sdinfo->satadrv_event_flags &=
18228 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18229 			/* must clear flags on cport */
18230 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18231 			    saddr->cport);
18232 			pminfo->pmult_event_flags |=
18233 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18234 		}
18235 		return;
18236 	}
18237 
18238 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18239 	    saddr->pmport);
18240 	if (sdinfo == NULL) {
18241 		return;
18242 	}
18243 	if ((sdinfo->satadrv_event_flags &
18244 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18245 		/*
18246 		 * Start tracking time for device feature restoration and
18247 		 * identification. Save current time (lbolt value).
18248 		 */
18249 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18250 	}
18251 	/* Mark device reset processing as active */
18252 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18253 
18254 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18255 	mutex_exit(&pmportinfo->pmport_mutex);
18256 
18257 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18258 	    SATA_FAILURE) {
18259 		/*
18260 		 * Restoring drive setting failed.
18261 		 * Probe the port first, to check if the port state has changed
18262 		 */
18263 		sata_device.satadev_rev = SATA_DEVICE_REV;
18264 		sata_device.satadev_addr = *saddr;
18265 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18266 
18267 		/* probe port */
18268 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18269 		    (SATA_DIP(sata_hba_inst), &sata_device);
18270 		mutex_enter(&pmportinfo->pmport_mutex);
18271 		if (rval == SATA_SUCCESS &&
18272 		    (sata_device.satadev_state &
18273 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18274 		    (sata_device.satadev_scr.sstatus  &
18275 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18276 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18277 			/*
18278 			 * We may retry this a bit later - in-process reset
18279 			 * condition should be already set.
18280 			 * Track retry time for device identification.
18281 			 */
18282 			if ((pmportinfo->pmport_dev_type &
18283 			    SATA_VALID_DEV_TYPE) != 0 &&
18284 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18285 			    sdinfo->satadrv_reset_time != 0) {
18286 				clock_t cur_time = ddi_get_lbolt();
18287 				/*
18288 				 * If the retry time limit was not
18289 				 * exceeded, retry.
18290 				 */
18291 				if ((cur_time - sdinfo->satadrv_reset_time) <
18292 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18293 					mutex_enter(
18294 					    &sata_hba_inst->satahba_mutex);
18295 					sata_hba_inst->satahba_event_flags |=
18296 					    SATA_EVNT_MAIN;
18297 					mutex_exit(
18298 					    &sata_hba_inst->satahba_mutex);
18299 					mutex_enter(&sata_mutex);
18300 					sata_event_pending |= SATA_EVNT_MAIN;
18301 					mutex_exit(&sata_mutex);
18302 					return;
18303 				}
18304 			}
18305 			/* Fail the drive */
18306 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18307 
18308 			sata_log(sata_hba_inst, CE_WARN,
18309 			    "SATA device at port %d:%d - device failed",
18310 			    saddr->cport, saddr->pmport);
18311 		} else {
18312 			/*
18313 			 * No point of retrying - some other event processing
18314 			 * would or already did port info cleanup.
18315 			 * To be safe (HBA may need it),
18316 			 * request clearing device reset condition.
18317 			 */
18318 			sdinfo->satadrv_event_flags |=
18319 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18320 		}
18321 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18322 		sdinfo->satadrv_reset_time = 0;
18323 		return;
18324 	}
18325 	/*
18326 	 * Raise the flag indicating that the next sata command could
18327 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18328 	 * reset is reported.
18329 	 */
18330 	mutex_enter(&pmportinfo->pmport_mutex);
18331 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18332 		sdinfo->satadrv_reset_time = 0;
18333 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
18334 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18335 			sdinfo->satadrv_event_flags &=
18336 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18337 			/* must clear flags on cport */
18338 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18339 			    saddr->cport);
18340 			pminfo->pmult_event_flags |=
18341 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18342 		}
18343 	}
18344 }
18345 
18346 /*
18347  * Port Link Events processing.
18348  * Every link established event may involve device reset (due to
18349  * COMRESET signal, equivalent of the hard reset) so arbitrarily
18350  * set device reset event for an attached device (if any).
18351  * If the port is in SHUTDOWN or FAILED state, ignore link events.
18352  *
18353  * The link established event processing varies, depending on the state
18354  * of the target node, HBA hotplugging capabilities, state of the port.
18355  * If the link is not active, the link established event is ignored.
18356  * If HBA cannot detect device attachment and there is no target node,
18357  * the link established event triggers device attach event processing.
18358  * Else, link established event triggers device reset event processing.
18359  *
18360  * The link lost event processing varies, depending on a HBA hotplugging
18361  * capability and the state of the port (link active or not active).
18362  * If the link is active, the lost link event is ignored.
18363  * If HBA cannot detect device removal, the lost link event triggers
18364  * device detached event processing after link lost timeout.
18365  * Else, the event is ignored.
18366  *
18367  * NOTE: Port multiplier ports events are handled by
18368  * sata_process_pmport_link_events();
18369  */
18370 static void
18371 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
18372     sata_address_t *saddr)
18373 {
18374 	sata_device_t sata_device;
18375 	sata_cport_info_t *cportinfo;
18376 	sata_drive_info_t *sdinfo;
18377 	uint32_t event_flags;
18378 	int rval;
18379 
18380 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18381 	    "Processing port %d link event(s)", saddr->cport);
18382 
18383 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18384 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18385 	event_flags = cportinfo->cport_event_flags;
18386 
18387 	/* Reset event flags first */
18388 	cportinfo->cport_event_flags &=
18389 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18390 
18391 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18392 	if ((cportinfo->cport_state &
18393 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18394 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18395 		    cport_mutex);
18396 		return;
18397 	}
18398 
18399 	/*
18400 	 * For the sanity sake get current port state.
18401 	 * Set device address only. Other sata_device fields should be
18402 	 * set by HBA driver.
18403 	 */
18404 	sata_device.satadev_rev = SATA_DEVICE_REV;
18405 	sata_device.satadev_addr = *saddr;
18406 	/*
18407 	 * We have to exit mutex, because the HBA probe port function may
18408 	 * block on its own mutex.
18409 	 */
18410 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18411 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18412 	    (SATA_DIP(sata_hba_inst), &sata_device);
18413 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18414 	sata_update_port_info(sata_hba_inst, &sata_device);
18415 	if (rval != SATA_SUCCESS) {
18416 		/* Something went wrong? Fail the port */
18417 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18418 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18419 		    cport_mutex);
18420 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18421 		    "SATA port %d probing failed",
18422 		    saddr->cport));
18423 		/*
18424 		 * We may want to release device info structure, but
18425 		 * it is not necessary.
18426 		 */
18427 		return;
18428 	} else {
18429 		/* port probed successfully */
18430 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18431 	}
18432 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18433 
18434 		if ((sata_device.satadev_scr.sstatus &
18435 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18436 			/* Ignore event */
18437 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18438 			    "Ignoring port %d link established event - "
18439 			    "link down",
18440 			    saddr->cport);
18441 			goto linklost;
18442 		}
18443 
18444 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18445 		    "Processing port %d link established event",
18446 		    saddr->cport);
18447 
18448 		/*
18449 		 * For the sanity sake check if a device is attached - check
18450 		 * return state of a port probing.
18451 		 */
18452 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
18453 			/*
18454 			 * HBA port probe indicated that there is a device
18455 			 * attached. Check if the framework had device info
18456 			 * structure attached for this device.
18457 			 */
18458 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
18459 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
18460 				    NULL);
18461 
18462 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18463 				if ((sdinfo->satadrv_type &
18464 				    SATA_VALID_DEV_TYPE) != 0) {
18465 					/*
18466 					 * Dev info structure is present.
18467 					 * If dev_type is set to known type in
18468 					 * the framework's drive info struct
18469 					 * then the device existed before and
18470 					 * the link was probably lost
18471 					 * momentarily - in such case
18472 					 * we may want to check device
18473 					 * identity.
18474 					 * Identity check is not supported now.
18475 					 *
18476 					 * Link established event
18477 					 * triggers device reset event.
18478 					 */
18479 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
18480 					    satadrv_event_flags |=
18481 					    SATA_EVNT_DEVICE_RESET;
18482 				}
18483 			} else if (cportinfo->cport_dev_type ==
18484 			    SATA_DTYPE_NONE) {
18485 				/*
18486 				 * We got new device attached! If HBA does not
18487 				 * generate device attached events, trigger it
18488 				 * here.
18489 				 */
18490 				if (!(SATA_FEATURES(sata_hba_inst) &
18491 				    SATA_CTLF_HOTPLUG)) {
18492 					cportinfo->cport_event_flags |=
18493 					    SATA_EVNT_DEVICE_ATTACHED;
18494 				}
18495 			}
18496 			/* Reset link lost timeout */
18497 			cportinfo->cport_link_lost_time = 0;
18498 		}
18499 	}
18500 linklost:
18501 	if (event_flags & SATA_EVNT_LINK_LOST) {
18502 		if ((sata_device.satadev_scr.sstatus &
18503 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18504 			/* Ignore event */
18505 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18506 			    "Ignoring port %d link lost event - link is up",
18507 			    saddr->cport);
18508 			goto done;
18509 		}
18510 #ifdef SATA_DEBUG
18511 		if (cportinfo->cport_link_lost_time == 0) {
18512 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18513 			    "Processing port %d link lost event",
18514 			    saddr->cport);
18515 		}
18516 #endif
18517 		/*
18518 		 * When HBA cannot generate device attached/detached events,
18519 		 * we need to track link lost time and eventually generate
18520 		 * device detach event.
18521 		 */
18522 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18523 			/* We are tracking link lost time */
18524 			if (cportinfo->cport_link_lost_time == 0) {
18525 				/* save current time (lbolt value) */
18526 				cportinfo->cport_link_lost_time =
18527 				    ddi_get_lbolt();
18528 				/* just keep link lost event */
18529 				cportinfo->cport_event_flags |=
18530 				    SATA_EVNT_LINK_LOST;
18531 			} else {
18532 				clock_t cur_time = ddi_get_lbolt();
18533 				if ((cur_time -
18534 				    cportinfo->cport_link_lost_time) >=
18535 				    drv_usectohz(
18536 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18537 					/* trigger device detach event */
18538 					cportinfo->cport_event_flags |=
18539 					    SATA_EVNT_DEVICE_DETACHED;
18540 					cportinfo->cport_link_lost_time = 0;
18541 					SATADBG1(SATA_DBG_EVENTS,
18542 					    sata_hba_inst,
18543 					    "Triggering port %d "
18544 					    "device detached event",
18545 					    saddr->cport);
18546 				} else {
18547 					/* keep link lost event */
18548 					cportinfo->cport_event_flags |=
18549 					    SATA_EVNT_LINK_LOST;
18550 				}
18551 			}
18552 		}
18553 		/*
18554 		 * We could change port state to disable/delay access to
18555 		 * the attached device until the link is recovered.
18556 		 */
18557 	}
18558 done:
18559 	event_flags = cportinfo->cport_event_flags;
18560 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18561 	if (event_flags != 0) {
18562 		mutex_enter(&sata_hba_inst->satahba_mutex);
18563 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18564 		mutex_exit(&sata_hba_inst->satahba_mutex);
18565 		mutex_enter(&sata_mutex);
18566 		sata_event_pending |= SATA_EVNT_MAIN;
18567 		mutex_exit(&sata_mutex);
18568 	}
18569 }
18570 
18571 /*
18572  * Port Multiplier Port Link Events processing.
18573  */
18574 static void
18575 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
18576     sata_address_t *saddr)
18577 {
18578 	sata_device_t sata_device;
18579 	sata_pmport_info_t *pmportinfo = NULL;
18580 	sata_drive_info_t *sdinfo = NULL;
18581 	uint32_t event_flags;
18582 	uint8_t cport = saddr->cport;
18583 	uint8_t pmport = saddr->pmport;
18584 	int rval;
18585 
18586 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18587 	    "Processing port %d:%d link event(s)",
18588 	    cport, pmport);
18589 
18590 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18591 	mutex_enter(&pmportinfo->pmport_mutex);
18592 	event_flags = pmportinfo->pmport_event_flags;
18593 
18594 	/* Reset event flags first */
18595 	pmportinfo->pmport_event_flags &=
18596 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18597 
18598 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18599 	if ((pmportinfo->pmport_state &
18600 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18601 		mutex_exit(&pmportinfo->pmport_mutex);
18602 		return;
18603 	}
18604 
18605 	/*
18606 	 * For the sanity sake get current port state.
18607 	 * Set device address only. Other sata_device fields should be
18608 	 * set by HBA driver.
18609 	 */
18610 	sata_device.satadev_rev = SATA_DEVICE_REV;
18611 	sata_device.satadev_addr = *saddr;
18612 	/*
18613 	 * We have to exit mutex, because the HBA probe port function may
18614 	 * block on its own mutex.
18615 	 */
18616 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18617 	    saddr->pmport));
18618 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18619 	    (SATA_DIP(sata_hba_inst), &sata_device);
18620 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18621 	    saddr->pmport));
18622 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18623 	if (rval != SATA_SUCCESS) {
18624 		/* Something went wrong? Fail the port */
18625 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18626 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18627 		    saddr->pmport));
18628 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18629 		    "SATA port %d:%d probing failed",
18630 		    saddr->cport, saddr->pmport));
18631 		/*
18632 		 * We may want to release device info structure, but
18633 		 * it is not necessary.
18634 		 */
18635 		return;
18636 	} else {
18637 		/* port probed successfully */
18638 		pmportinfo->pmport_state |=
18639 		    SATA_STATE_PROBED | SATA_STATE_READY;
18640 	}
18641 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
18642 	    saddr->cport, saddr->pmport));
18643 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
18644 	    saddr->cport, saddr->pmport));
18645 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18646 
18647 		if ((sata_device.satadev_scr.sstatus &
18648 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18649 			/* Ignore event */
18650 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18651 			    "Ignoring port %d:%d link established event - "
18652 			    "link down",
18653 			    saddr->cport, saddr->pmport);
18654 			goto linklost;
18655 		}
18656 
18657 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18658 		    "Processing port %d:%d link established event",
18659 		    cport, pmport);
18660 
18661 		/*
18662 		 * For the sanity sake check if a device is attached - check
18663 		 * return state of a port probing.
18664 		 */
18665 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
18666 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
18667 			/*
18668 			 * HBA port probe indicated that there is a device
18669 			 * attached. Check if the framework had device info
18670 			 * structure attached for this device.
18671 			 */
18672 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
18673 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
18674 				    NULL);
18675 
18676 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18677 				if ((sdinfo->satadrv_type &
18678 				    SATA_VALID_DEV_TYPE) != 0) {
18679 					/*
18680 					 * Dev info structure is present.
18681 					 * If dev_type is set to known type in
18682 					 * the framework's drive info struct
18683 					 * then the device existed before and
18684 					 * the link was probably lost
18685 					 * momentarily - in such case
18686 					 * we may want to check device
18687 					 * identity.
18688 					 * Identity check is not supported now.
18689 					 *
18690 					 * Link established event
18691 					 * triggers device reset event.
18692 					 */
18693 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
18694 					    satadrv_event_flags |=
18695 					    SATA_EVNT_DEVICE_RESET;
18696 				}
18697 			} else if (pmportinfo->pmport_dev_type ==
18698 			    SATA_DTYPE_NONE) {
18699 				/*
18700 				 * We got new device attached! If HBA does not
18701 				 * generate device attached events, trigger it
18702 				 * here.
18703 				 */
18704 				if (!(SATA_FEATURES(sata_hba_inst) &
18705 				    SATA_CTLF_HOTPLUG)) {
18706 					pmportinfo->pmport_event_flags |=
18707 					    SATA_EVNT_DEVICE_ATTACHED;
18708 				}
18709 			}
18710 			/* Reset link lost timeout */
18711 			pmportinfo->pmport_link_lost_time = 0;
18712 		}
18713 	}
18714 linklost:
18715 	if (event_flags & SATA_EVNT_LINK_LOST) {
18716 #ifdef SATA_DEBUG
18717 		if (pmportinfo->pmport_link_lost_time == 0) {
18718 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18719 			    "Processing port %d:%d link lost event",
18720 			    saddr->cport, saddr->pmport);
18721 		}
18722 #endif
18723 		if ((sata_device.satadev_scr.sstatus &
18724 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18725 			/* Ignore event */
18726 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18727 			    "Ignoring port %d:%d link lost event - link is up",
18728 			    saddr->cport, saddr->pmport);
18729 			goto done;
18730 		}
18731 		/*
18732 		 * When HBA cannot generate device attached/detached events,
18733 		 * we need to track link lost time and eventually generate
18734 		 * device detach event.
18735 		 */
18736 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18737 			/* We are tracking link lost time */
18738 			if (pmportinfo->pmport_link_lost_time == 0) {
18739 				/* save current time (lbolt value) */
18740 				pmportinfo->pmport_link_lost_time =
18741 				    ddi_get_lbolt();
18742 				/* just keep link lost event */
18743 				pmportinfo->pmport_event_flags |=
18744 				    SATA_EVNT_LINK_LOST;
18745 			} else {
18746 				clock_t cur_time = ddi_get_lbolt();
18747 				if ((cur_time -
18748 				    pmportinfo->pmport_link_lost_time) >=
18749 				    drv_usectohz(
18750 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18751 					/* trigger device detach event */
18752 					pmportinfo->pmport_event_flags |=
18753 					    SATA_EVNT_DEVICE_DETACHED;
18754 					pmportinfo->pmport_link_lost_time = 0;
18755 					SATADBG2(SATA_DBG_EVENTS,
18756 					    sata_hba_inst,
18757 					    "Triggering port %d:%d "
18758 					    "device detached event",
18759 					    saddr->cport, saddr->pmport);
18760 				} else {
18761 					/* keep link lost event */
18762 					pmportinfo->pmport_event_flags |=
18763 					    SATA_EVNT_LINK_LOST;
18764 				}
18765 			}
18766 		}
18767 		/*
18768 		 * We could change port state to disable/delay access to
18769 		 * the attached device until the link is recovered.
18770 		 */
18771 	}
18772 done:
18773 	event_flags = pmportinfo->pmport_event_flags;
18774 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18775 	    saddr->pmport));
18776 	if (event_flags != 0) {
18777 		mutex_enter(&sata_hba_inst->satahba_mutex);
18778 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18779 		mutex_exit(&sata_hba_inst->satahba_mutex);
18780 		mutex_enter(&sata_mutex);
18781 		sata_event_pending |= SATA_EVNT_MAIN;
18782 		mutex_exit(&sata_mutex);
18783 	}
18784 }
18785 
18786 /*
18787  * Device Detached Event processing.
18788  * Port is probed to find if a device is really gone. If so,
18789  * the device info structure is detached from the SATA port info structure
18790  * and released.
18791  * Port status is updated.
18792  *
18793  * NOTE: Port multiplier ports events are handled by
18794  * sata_process_pmdevice_detached()
18795  */
18796 static void
18797 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
18798     sata_address_t *saddr)
18799 {
18800 	sata_cport_info_t *cportinfo;
18801 	sata_pmport_info_t *pmportinfo;
18802 	sata_drive_info_t *sdevinfo;
18803 	sata_device_t sata_device;
18804 	sata_address_t pmport_addr;
18805 	char name[16];
18806 	uint8_t cport = saddr->cport;
18807 	int npmport;
18808 	int rval;
18809 
18810 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18811 	    "Processing port %d device detached", saddr->cport);
18812 
18813 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18814 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18815 	/* Clear event flag */
18816 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18817 
18818 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18819 	if ((cportinfo->cport_state &
18820 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18821 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18822 		    cport_mutex);
18823 		return;
18824 	}
18825 	/* For sanity, re-probe the port */
18826 	sata_device.satadev_rev = SATA_DEVICE_REV;
18827 	sata_device.satadev_addr = *saddr;
18828 
18829 	/*
18830 	 * We have to exit mutex, because the HBA probe port function may
18831 	 * block on its own mutex.
18832 	 */
18833 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18834 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18835 	    (SATA_DIP(sata_hba_inst), &sata_device);
18836 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18837 	sata_update_port_info(sata_hba_inst, &sata_device);
18838 	if (rval != SATA_SUCCESS) {
18839 		/* Something went wrong? Fail the port */
18840 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18841 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18842 		    cport_mutex);
18843 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18844 		    "SATA port %d probing failed",
18845 		    saddr->cport));
18846 		/*
18847 		 * We may want to release device info structure, but
18848 		 * it is not necessary.
18849 		 */
18850 		return;
18851 	} else {
18852 		/* port probed successfully */
18853 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18854 	}
18855 	/*
18856 	 * Check if a device is still attached. For sanity, check also
18857 	 * link status - if no link, there is no device.
18858 	 */
18859 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18860 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18861 	    SATA_DTYPE_NONE) {
18862 		/*
18863 		 * Device is still attached - ignore detach event.
18864 		 */
18865 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18866 		    cport_mutex);
18867 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18868 		    "Ignoring detach - device still attached to port %d",
18869 		    sata_device.satadev_addr.cport);
18870 		return;
18871 	}
18872 	/*
18873 	 * We need to detach and release device info structure here
18874 	 */
18875 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18876 		/*
18877 		 * A port-multiplier is removed.
18878 		 *
18879 		 * Calling sata_process_pmdevice_detached() does not work
18880 		 * here. The port multiplier is gone, so we cannot probe
18881 		 * sub-port any more and all pmult-related data structure must
18882 		 * be de-allocated immediately. Following structure of every
18883 		 * implemented sub-port behind the pmult are required to
18884 		 * released.
18885 		 *
18886 		 *   - attachment point
18887 		 *   - target node
18888 		 *   - sata_drive_info
18889 		 *   - sata_pmport_info
18890 		 */
18891 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
18892 		    cport); npmport ++) {
18893 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
18894 			    sata_hba_inst,
18895 			    "Detaching target node at port %d:%d",
18896 			    cport, npmport);
18897 
18898 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18899 
18900 			/* Remove attachment point. */
18901 			name[0] = '\0';
18902 			(void) sprintf(name, "%d.%d", cport, npmport);
18903 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
18904 			sata_log(sata_hba_inst, CE_NOTE,
18905 			    "Remove attachment point of port %d:%d",
18906 			    cport, npmport);
18907 
18908 			/* Remove target node */
18909 			pmport_addr.cport = cport;
18910 			pmport_addr.pmport = (uint8_t)npmport;
18911 			pmport_addr.qual = SATA_ADDR_PMPORT;
18912 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
18913 
18914 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18915 
18916 			/* Release sata_pmport_info & sata_drive_info. */
18917 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18918 			    cport, npmport);
18919 			ASSERT(pmportinfo != NULL);
18920 
18921 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18922 			if (sdevinfo != NULL) {
18923 				(void) kmem_free((void *) sdevinfo,
18924 				    sizeof (sata_drive_info_t));
18925 			}
18926 
18927 			/* Release sata_pmport_info at last */
18928 			(void) kmem_free((void *) pmportinfo,
18929 			    sizeof (sata_pmport_info_t));
18930 		}
18931 
18932 		/* Finally, release sata_pmult_info */
18933 		(void) kmem_free((void *)
18934 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
18935 		    sizeof (sata_pmult_info_t));
18936 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
18937 
18938 		sata_log(sata_hba_inst, CE_WARN,
18939 		    "SATA port-multiplier detached at port %d", cport);
18940 
18941 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18942 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18943 		    saddr->cport)->cport_mutex);
18944 	} else {
18945 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18946 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18947 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18948 			(void) kmem_free((void *)sdevinfo,
18949 			    sizeof (sata_drive_info_t));
18950 		}
18951 		sata_log(sata_hba_inst, CE_WARN,
18952 		    "SATA device detached at port %d", cport);
18953 
18954 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18955 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18956 		    saddr->cport)->cport_mutex);
18957 
18958 		/*
18959 		 * Try to offline a device and remove target node
18960 		 * if it still exists
18961 		 */
18962 		sata_remove_target_node(sata_hba_inst, saddr);
18963 	}
18964 
18965 
18966 	/*
18967 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18968 	 * with the hint: SE_HINT_REMOVE
18969 	 */
18970 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18971 }
18972 
18973 /*
18974  * Port Multiplier Port Device Deattached Event processing.
18975  *
18976  * NOTE: No Mutex should be hold.
18977  */
18978 static void
18979 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
18980     sata_address_t *saddr)
18981 {
18982 	sata_pmport_info_t *pmportinfo;
18983 	sata_drive_info_t *sdevinfo;
18984 	sata_device_t sata_device;
18985 	int rval;
18986 	uint8_t cport, pmport;
18987 
18988 	cport = saddr->cport;
18989 	pmport = saddr->pmport;
18990 
18991 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18992 	    "Processing port %d:%d device detached",
18993 	    cport, pmport);
18994 
18995 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18996 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18997 
18998 	/* Clear event flag */
18999 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
19000 
19001 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
19002 	if ((pmportinfo->pmport_state &
19003 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19004 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19005 		return;
19006 	}
19007 	/* For sanity, re-probe the port */
19008 	sata_device.satadev_rev = SATA_DEVICE_REV;
19009 	sata_device.satadev_addr = *saddr;
19010 
19011 	/*
19012 	 * We have to exit mutex, because the HBA probe port function may
19013 	 * block on its own mutex.
19014 	 */
19015 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19016 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19017 	    (SATA_DIP(sata_hba_inst), &sata_device);
19018 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19019 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19020 	if (rval != SATA_SUCCESS) {
19021 		/* Something went wrong? Fail the port */
19022 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19023 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19024 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19025 		    "SATA port %d:%d probing failed",
19026 		    saddr->pmport));
19027 		/*
19028 		 * We may want to release device info structure, but
19029 		 * it is not necessary.
19030 		 */
19031 		return;
19032 	} else {
19033 		/* port probed successfully */
19034 		pmportinfo->pmport_state |=
19035 		    SATA_STATE_PROBED | SATA_STATE_READY;
19036 	}
19037 	/*
19038 	 * Check if a device is still attached. For sanity, check also
19039 	 * link status - if no link, there is no device.
19040 	 */
19041 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19042 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19043 	    SATA_DTYPE_NONE) {
19044 		/*
19045 		 * Device is still attached - ignore detach event.
19046 		 */
19047 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19048 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19049 		    "Ignoring detach - device still attached to port %d",
19050 		    sata_device.satadev_addr.pmport);
19051 		return;
19052 	}
19053 	/*
19054 	 * We need to detach and release device info structure here
19055 	 */
19056 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19057 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19058 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19059 		(void) kmem_free((void *)sdevinfo,
19060 		    sizeof (sata_drive_info_t));
19061 	}
19062 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19063 	/*
19064 	 * Device cannot be reached anymore, even if the target node may be
19065 	 * still present.
19066 	 */
19067 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19068 
19069 	/*
19070 	 * Try to offline a device and remove target node if it still exists
19071 	 */
19072 	sata_remove_target_node(sata_hba_inst, saddr);
19073 
19074 	/*
19075 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19076 	 * with the hint: SE_HINT_REMOVE
19077 	 */
19078 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19079 }
19080 
19081 
19082 /*
19083  * Device Attached Event processing.
19084  * Port state is checked to verify that a device is really attached. If so,
19085  * the device info structure is created and attached to the SATA port info
19086  * structure.
19087  *
19088  * If attached device cannot be identified or set-up, the retry for the
19089  * attach processing is set-up. Subsequent daemon run would try again to
19090  * identify the device, until the time limit is reached
19091  * (SATA_DEV_IDENTIFY_TIMEOUT).
19092  *
19093  * This function cannot be called in interrupt context (it may sleep).
19094  *
19095  * NOTE: Port multiplier ports events are handled by
19096  * sata_process_pmdevice_attached()
19097  */
19098 static void
19099 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
19100     sata_address_t *saddr)
19101 {
19102 	sata_cport_info_t *cportinfo = NULL;
19103 	sata_drive_info_t *sdevinfo = NULL;
19104 	sata_pmult_info_t *pmultinfo = NULL;
19105 	sata_pmport_info_t *pmportinfo = NULL;
19106 	sata_device_t sata_device;
19107 	dev_info_t *tdip;
19108 	uint32_t event_flags = 0, pmult_event_flags = 0;
19109 	int rval;
19110 	int npmport;
19111 
19112 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19113 	    "Processing port %d device attached", saddr->cport);
19114 
19115 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19116 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19117 
19118 	/* Clear attach event flag first */
19119 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19120 
19121 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19122 	if ((cportinfo->cport_state &
19123 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19124 		cportinfo->cport_dev_attach_time = 0;
19125 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19126 		    cport_mutex);
19127 		return;
19128 	}
19129 
19130 	/*
19131 	 * If the sata_drive_info structure is found attached to the port info,
19132 	 * despite the fact the device was removed and now it is re-attached,
19133 	 * the old drive info structure was not removed.
19134 	 * Arbitrarily release device info structure.
19135 	 */
19136 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19137 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19138 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19139 		(void) kmem_free((void *)sdevinfo,
19140 		    sizeof (sata_drive_info_t));
19141 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19142 		    "Arbitrarily detaching old device info.", NULL);
19143 	}
19144 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19145 
19146 	/* For sanity, re-probe the port */
19147 	sata_device.satadev_rev = SATA_DEVICE_REV;
19148 	sata_device.satadev_addr = *saddr;
19149 
19150 	/*
19151 	 * We have to exit mutex, because the HBA probe port function may
19152 	 * block on its own mutex.
19153 	 */
19154 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19155 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19156 	    (SATA_DIP(sata_hba_inst), &sata_device);
19157 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19158 	sata_update_port_info(sata_hba_inst, &sata_device);
19159 	if (rval != SATA_SUCCESS) {
19160 		/* Something went wrong? Fail the port */
19161 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19162 		cportinfo->cport_dev_attach_time = 0;
19163 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19164 		    cport_mutex);
19165 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19166 		    "SATA port %d probing failed",
19167 		    saddr->cport));
19168 		return;
19169 	} else {
19170 		/* port probed successfully */
19171 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19172 	}
19173 	/*
19174 	 * Check if a device is still attached. For sanity, check also
19175 	 * link status - if no link, there is no device.
19176 	 */
19177 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19178 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19179 	    SATA_DTYPE_NONE) {
19180 		/*
19181 		 * No device - ignore attach event.
19182 		 */
19183 		cportinfo->cport_dev_attach_time = 0;
19184 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19185 		    cport_mutex);
19186 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19187 		    "Ignoring attach - no device connected to port %d",
19188 		    sata_device.satadev_addr.cport);
19189 		return;
19190 	}
19191 
19192 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19193 	/*
19194 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19195 	 * with the hint: SE_HINT_INSERT
19196 	 */
19197 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19198 
19199 	/*
19200 	 * Port reprobing will take care of the creation of the device
19201 	 * info structure and determination of the device type.
19202 	 */
19203 	sata_device.satadev_addr = *saddr;
19204 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19205 	    SATA_DEV_IDENTIFY_NORETRY);
19206 
19207 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19208 	    cport_mutex);
19209 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19210 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19211 		/* Some device is attached to the port */
19212 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19213 			/*
19214 			 * A device was not successfully attached.
19215 			 * Track retry time for device identification.
19216 			 */
19217 			if (cportinfo->cport_dev_attach_time != 0) {
19218 				clock_t cur_time = ddi_get_lbolt();
19219 				/*
19220 				 * If the retry time limit was not exceeded,
19221 				 * reinstate attach event.
19222 				 */
19223 				if ((cur_time -
19224 				    cportinfo->cport_dev_attach_time) <
19225 				    drv_usectohz(
19226 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19227 					/* OK, restore attach event */
19228 					cportinfo->cport_event_flags |=
19229 					    SATA_EVNT_DEVICE_ATTACHED;
19230 				} else {
19231 					/* Timeout - cannot identify device */
19232 					cportinfo->cport_dev_attach_time = 0;
19233 					sata_log(sata_hba_inst,
19234 					    CE_WARN,
19235 					    "Could not identify SATA device "
19236 					    "at port %d",
19237 					    saddr->cport);
19238 				}
19239 			} else {
19240 				/*
19241 				 * Start tracking time for device
19242 				 * identification.
19243 				 * Save current time (lbolt value).
19244 				 */
19245 				cportinfo->cport_dev_attach_time =
19246 				    ddi_get_lbolt();
19247 				/* Restore attach event */
19248 				cportinfo->cport_event_flags |=
19249 				    SATA_EVNT_DEVICE_ATTACHED;
19250 			}
19251 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19252 			cportinfo->cport_dev_attach_time = 0;
19253 			sata_log(sata_hba_inst, CE_NOTE,
19254 			    "SATA port-multiplier detected at port %d",
19255 			    saddr->cport);
19256 
19257 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19258 				/* Log the info of new port multiplier */
19259 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19260 				    saddr->cport)->cport_mutex);
19261 				sata_show_pmult_info(sata_hba_inst,
19262 				    &sata_device);
19263 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19264 				    saddr->cport)->cport_mutex);
19265 			}
19266 
19267 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19268 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19269 			for (npmport = 0; npmport <
19270 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19271 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19272 				    saddr->cport, npmport);
19273 				ASSERT(pmportinfo != NULL);
19274 
19275 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19276 				    saddr->cport)->cport_mutex);
19277 				mutex_enter(&pmportinfo->pmport_mutex);
19278 				/* Marked all pmports with link events. */
19279 				pmportinfo->pmport_event_flags =
19280 				    SATA_EVNT_LINK_ESTABLISHED;
19281 				pmult_event_flags |=
19282 				    pmportinfo->pmport_event_flags;
19283 				mutex_exit(&pmportinfo->pmport_mutex);
19284 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19285 				    saddr->cport)->cport_mutex);
19286 			}
19287 			/* Auto-online is not available for PMult now. */
19288 
19289 		} else {
19290 			/*
19291 			 * If device was successfully attached, the subsequent
19292 			 * action depends on a state of the
19293 			 * sata_auto_online variable. If it is set to zero.
19294 			 * an explicit 'configure' command will be needed to
19295 			 * configure it. If its value is non-zero, we will
19296 			 * attempt to online (configure) the device.
19297 			 * First, log the message indicating that a device
19298 			 * was attached.
19299 			 */
19300 			cportinfo->cport_dev_attach_time = 0;
19301 			sata_log(sata_hba_inst, CE_WARN,
19302 			    "SATA device detected at port %d", saddr->cport);
19303 
19304 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19305 				sata_drive_info_t new_sdinfo;
19306 
19307 				/* Log device info data */
19308 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
19309 				    cportinfo));
19310 				sata_show_drive_info(sata_hba_inst,
19311 				    &new_sdinfo);
19312 			}
19313 
19314 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19315 			    saddr->cport)->cport_mutex);
19316 
19317 			/*
19318 			 * Make sure that there is no target node for that
19319 			 * device. If so, release it. It should not happen,
19320 			 * unless we had problem removing the node when
19321 			 * device was detached.
19322 			 */
19323 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19324 			    saddr->cport, saddr->pmport);
19325 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19326 			    saddr->cport)->cport_mutex);
19327 			if (tdip != NULL) {
19328 
19329 #ifdef SATA_DEBUG
19330 				if ((cportinfo->cport_event_flags &
19331 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19332 					sata_log(sata_hba_inst, CE_WARN,
19333 					    "sata_process_device_attached: "
19334 					    "old device target node exists!");
19335 #endif
19336 				/*
19337 				 * target node exists - try to unconfigure
19338 				 * device and remove the node.
19339 				 */
19340 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19341 				    saddr->cport)->cport_mutex);
19342 				rval = ndi_devi_offline(tdip,
19343 				    NDI_DEVI_REMOVE);
19344 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19345 				    saddr->cport)->cport_mutex);
19346 
19347 				if (rval == NDI_SUCCESS) {
19348 					cportinfo->cport_event_flags &=
19349 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19350 					cportinfo->cport_tgtnode_clean = B_TRUE;
19351 				} else {
19352 					/*
19353 					 * PROBLEM - the target node remained
19354 					 * and it belongs to a previously
19355 					 * attached device.
19356 					 * This happens when the file was open
19357 					 * or the node was waiting for
19358 					 * resources at the time the
19359 					 * associated device was removed.
19360 					 * Instruct event daemon to retry the
19361 					 * cleanup later.
19362 					 */
19363 					sata_log(sata_hba_inst,
19364 					    CE_WARN,
19365 					    "Application(s) accessing "
19366 					    "previously attached SATA "
19367 					    "device have to release "
19368 					    "it before newly inserted "
19369 					    "device can be made accessible.",
19370 					    saddr->cport);
19371 					cportinfo->cport_event_flags |=
19372 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19373 					cportinfo->cport_tgtnode_clean =
19374 					    B_FALSE;
19375 				}
19376 			}
19377 			if (sata_auto_online != 0) {
19378 				cportinfo->cport_event_flags |=
19379 				    SATA_EVNT_AUTOONLINE_DEVICE;
19380 			}
19381 
19382 		}
19383 	} else {
19384 		cportinfo->cport_dev_attach_time = 0;
19385 	}
19386 
19387 	event_flags = cportinfo->cport_event_flags;
19388 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19389 	if (event_flags != 0 || pmult_event_flags != 0) {
19390 		mutex_enter(&sata_hba_inst->satahba_mutex);
19391 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19392 		mutex_exit(&sata_hba_inst->satahba_mutex);
19393 		mutex_enter(&sata_mutex);
19394 		sata_event_pending |= SATA_EVNT_MAIN;
19395 		mutex_exit(&sata_mutex);
19396 	}
19397 }
19398 
19399 /*
19400  * Port Multiplier Port Device Attached Event processing.
19401  *
19402  * NOTE: No Mutex should be hold.
19403  */
19404 static void
19405 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
19406     sata_address_t *saddr)
19407 {
19408 	sata_pmport_info_t *pmportinfo;
19409 	sata_drive_info_t *sdinfo;
19410 	sata_device_t sata_device;
19411 	dev_info_t *tdip;
19412 	uint32_t event_flags;
19413 	uint8_t cport = saddr->cport;
19414 	uint8_t pmport = saddr->pmport;
19415 	int rval;
19416 
19417 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19418 	    "Processing port %d:%d device attached", cport, pmport);
19419 
19420 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19421 
19422 	mutex_enter(&pmportinfo->pmport_mutex);
19423 
19424 	/* Clear attach event flag first */
19425 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19426 
19427 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19428 	if ((pmportinfo->pmport_state &
19429 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19430 		pmportinfo->pmport_dev_attach_time = 0;
19431 		mutex_exit(&pmportinfo->pmport_mutex);
19432 		return;
19433 	}
19434 
19435 	/*
19436 	 * If the sata_drive_info structure is found attached to the port info,
19437 	 * despite the fact the device was removed and now it is re-attached,
19438 	 * the old drive info structure was not removed.
19439 	 * Arbitrarily release device info structure.
19440 	 */
19441 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19442 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19443 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19444 		(void) kmem_free((void *)sdinfo,
19445 		    sizeof (sata_drive_info_t));
19446 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19447 		    "Arbitrarily detaching old device info.", NULL);
19448 	}
19449 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19450 
19451 	/* For sanity, re-probe the port */
19452 	sata_device.satadev_rev = SATA_DEVICE_REV;
19453 	sata_device.satadev_addr = *saddr;
19454 
19455 	/*
19456 	 * We have to exit mutex, because the HBA probe port function may
19457 	 * block on its own mutex.
19458 	 */
19459 	mutex_exit(&pmportinfo->pmport_mutex);
19460 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19461 	    (SATA_DIP(sata_hba_inst), &sata_device);
19462 	mutex_enter(&pmportinfo->pmport_mutex);
19463 
19464 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19465 	if (rval != SATA_SUCCESS) {
19466 		/* Something went wrong? Fail the port */
19467 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19468 		pmportinfo->pmport_dev_attach_time = 0;
19469 		mutex_exit(&pmportinfo->pmport_mutex);
19470 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19471 		    "SATA port %d:%d probing failed", cport, pmport));
19472 		return;
19473 	} else {
19474 		/* pmport probed successfully */
19475 		pmportinfo->pmport_state |=
19476 		    SATA_STATE_PROBED | SATA_STATE_READY;
19477 	}
19478 	/*
19479 	 * Check if a device is still attached. For sanity, check also
19480 	 * link status - if no link, there is no device.
19481 	 */
19482 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19483 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19484 	    SATA_DTYPE_NONE) {
19485 		/*
19486 		 * No device - ignore attach event.
19487 		 */
19488 		pmportinfo->pmport_dev_attach_time = 0;
19489 		mutex_exit(&pmportinfo->pmport_mutex);
19490 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19491 		    "Ignoring attach - no device connected to port %d:%d",
19492 		    cport, pmport);
19493 		return;
19494 	}
19495 
19496 	mutex_exit(&pmportinfo->pmport_mutex);
19497 	/*
19498 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19499 	 * with the hint: SE_HINT_INSERT
19500 	 */
19501 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19502 
19503 	/*
19504 	 * Port reprobing will take care of the creation of the device
19505 	 * info structure and determination of the device type.
19506 	 */
19507 	sata_device.satadev_addr = *saddr;
19508 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19509 	    SATA_DEV_IDENTIFY_NORETRY);
19510 
19511 	mutex_enter(&pmportinfo->pmport_mutex);
19512 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
19513 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
19514 		/* Some device is attached to the port */
19515 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
19516 			/*
19517 			 * A device was not successfully attached.
19518 			 * Track retry time for device identification.
19519 			 */
19520 			if (pmportinfo->pmport_dev_attach_time != 0) {
19521 				clock_t cur_time = ddi_get_lbolt();
19522 				/*
19523 				 * If the retry time limit was not exceeded,
19524 				 * reinstate attach event.
19525 				 */
19526 				if ((cur_time -
19527 				    pmportinfo->pmport_dev_attach_time) <
19528 				    drv_usectohz(
19529 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19530 					/* OK, restore attach event */
19531 					pmportinfo->pmport_event_flags |=
19532 					    SATA_EVNT_DEVICE_ATTACHED;
19533 				} else {
19534 					/* Timeout - cannot identify device */
19535 					pmportinfo->pmport_dev_attach_time = 0;
19536 					sata_log(sata_hba_inst, CE_WARN,
19537 					    "Could not identify SATA device "
19538 					    "at port %d:%d",
19539 					    cport, pmport);
19540 				}
19541 			} else {
19542 				/*
19543 				 * Start tracking time for device
19544 				 * identification.
19545 				 * Save current time (lbolt value).
19546 				 */
19547 				pmportinfo->pmport_dev_attach_time =
19548 				    ddi_get_lbolt();
19549 				/* Restore attach event */
19550 				pmportinfo->pmport_event_flags |=
19551 				    SATA_EVNT_DEVICE_ATTACHED;
19552 			}
19553 		} else {
19554 			/*
19555 			 * If device was successfully attached, the subsequent
19556 			 * action depends on a state of the
19557 			 * sata_auto_online variable. If it is set to zero.
19558 			 * an explicit 'configure' command will be needed to
19559 			 * configure it. If its value is non-zero, we will
19560 			 * attempt to online (configure) the device.
19561 			 * First, log the message indicating that a device
19562 			 * was attached.
19563 			 */
19564 			pmportinfo->pmport_dev_attach_time = 0;
19565 			sata_log(sata_hba_inst, CE_WARN,
19566 			    "SATA device detected at port %d:%d",
19567 			    cport, pmport);
19568 
19569 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19570 				sata_drive_info_t new_sdinfo;
19571 
19572 				/* Log device info data */
19573 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
19574 				    pmportinfo));
19575 				sata_show_drive_info(sata_hba_inst,
19576 				    &new_sdinfo);
19577 			}
19578 
19579 			mutex_exit(&pmportinfo->pmport_mutex);
19580 
19581 			/*
19582 			 * Make sure that there is no target node for that
19583 			 * device. If so, release it. It should not happen,
19584 			 * unless we had problem removing the node when
19585 			 * device was detached.
19586 			 */
19587 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19588 			    saddr->cport, saddr->pmport);
19589 			mutex_enter(&pmportinfo->pmport_mutex);
19590 			if (tdip != NULL) {
19591 
19592 #ifdef SATA_DEBUG
19593 				if ((pmportinfo->pmport_event_flags &
19594 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19595 					sata_log(sata_hba_inst, CE_WARN,
19596 					    "sata_process_device_attached: "
19597 					    "old device target node exists!");
19598 #endif
19599 				/*
19600 				 * target node exists - try to unconfigure
19601 				 * device and remove the node.
19602 				 */
19603 				mutex_exit(&pmportinfo->pmport_mutex);
19604 				rval = ndi_devi_offline(tdip,
19605 				    NDI_DEVI_REMOVE);
19606 				mutex_enter(&pmportinfo->pmport_mutex);
19607 
19608 				if (rval == NDI_SUCCESS) {
19609 					pmportinfo->pmport_event_flags &=
19610 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19611 					pmportinfo->pmport_tgtnode_clean =
19612 					    B_TRUE;
19613 				} else {
19614 					/*
19615 					 * PROBLEM - the target node remained
19616 					 * and it belongs to a previously
19617 					 * attached device.
19618 					 * This happens when the file was open
19619 					 * or the node was waiting for
19620 					 * resources at the time the
19621 					 * associated device was removed.
19622 					 * Instruct event daemon to retry the
19623 					 * cleanup later.
19624 					 */
19625 					sata_log(sata_hba_inst,
19626 					    CE_WARN,
19627 					    "Application(s) accessing "
19628 					    "previously attached SATA "
19629 					    "device have to release "
19630 					    "it before newly inserted "
19631 					    "device can be made accessible."
19632 					    "at port %d:%d",
19633 					    cport, pmport);
19634 					pmportinfo->pmport_event_flags |=
19635 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19636 					pmportinfo->pmport_tgtnode_clean =
19637 					    B_FALSE;
19638 				}
19639 			}
19640 			if (sata_auto_online != 0) {
19641 				pmportinfo->pmport_event_flags |=
19642 				    SATA_EVNT_AUTOONLINE_DEVICE;
19643 			}
19644 
19645 		}
19646 	} else {
19647 		pmportinfo->pmport_dev_attach_time = 0;
19648 	}
19649 
19650 	event_flags = pmportinfo->pmport_event_flags;
19651 	mutex_exit(&pmportinfo->pmport_mutex);
19652 	if (event_flags != 0) {
19653 		mutex_enter(&sata_hba_inst->satahba_mutex);
19654 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19655 		mutex_exit(&sata_hba_inst->satahba_mutex);
19656 		mutex_enter(&sata_mutex);
19657 		sata_event_pending |= SATA_EVNT_MAIN;
19658 		mutex_exit(&sata_mutex);
19659 	}
19660 
19661 	/* clear the reset_in_progress events */
19662 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19663 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19664 			/* must clear flags on cport */
19665 			sata_pmult_info_t *pminfo =
19666 			    SATA_PMULT_INFO(sata_hba_inst,
19667 			    saddr->cport);
19668 			pminfo->pmult_event_flags |=
19669 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19670 		}
19671 	}
19672 }
19673 
19674 /*
19675  * Device Target Node Cleanup Event processing.
19676  * If the target node associated with a sata port device is in
19677  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
19678  * If the target node cannot be removed, the event flag is left intact,
19679  * so that event daemon may re-run this function later.
19680  *
19681  * This function cannot be called in interrupt context (it may sleep).
19682  *
19683  * NOTE: Processes cport events only, not port multiplier ports.
19684  */
19685 static void
19686 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19687     sata_address_t *saddr)
19688 {
19689 	sata_cport_info_t *cportinfo;
19690 	dev_info_t *tdip;
19691 
19692 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19693 	    "Processing port %d device target node cleanup", saddr->cport);
19694 
19695 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19696 
19697 	/*
19698 	 * Check if there is target node for that device and it is in the
19699 	 * DEVI_DEVICE_REMOVED state. If so, release it.
19700 	 */
19701 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19702 	    saddr->pmport);
19703 	if (tdip != NULL) {
19704 		/*
19705 		 * target node exists - check if it is target node of
19706 		 * a removed device.
19707 		 */
19708 		if (sata_check_device_removed(tdip) == B_TRUE) {
19709 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19710 			    "sata_process_target_node_cleanup: "
19711 			    "old device target node exists!", NULL);
19712 			/*
19713 			 * Unconfigure and remove the target node
19714 			 */
19715 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
19716 			    NDI_SUCCESS) {
19717 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19718 				    saddr->cport)->cport_mutex);
19719 				cportinfo->cport_event_flags &=
19720 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19721 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19722 				    saddr->cport)->cport_mutex);
19723 				return;
19724 			}
19725 			/*
19726 			 * Event daemon will retry the cleanup later.
19727 			 */
19728 			mutex_enter(&sata_hba_inst->satahba_mutex);
19729 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19730 			mutex_exit(&sata_hba_inst->satahba_mutex);
19731 			mutex_enter(&sata_mutex);
19732 			sata_event_pending |= SATA_EVNT_MAIN;
19733 			mutex_exit(&sata_mutex);
19734 		}
19735 	} else {
19736 		if (saddr->qual == SATA_ADDR_CPORT ||
19737 		    saddr->qual == SATA_ADDR_DCPORT) {
19738 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19739 			    saddr->cport)->cport_mutex);
19740 			cportinfo->cport_event_flags &=
19741 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19742 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19743 			    saddr->cport)->cport_mutex);
19744 		} else {
19745 			/* sanity check */
19746 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
19747 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
19748 			    saddr->cport) == NULL)
19749 				return;
19750 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19751 			    saddr->pmport) == NULL)
19752 				return;
19753 
19754 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19755 			    saddr->cport, saddr->pmport)->pmport_mutex);
19756 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19757 			    saddr->pmport)->pmport_event_flags &=
19758 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19759 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19760 			    saddr->cport, saddr->pmport)->pmport_mutex);
19761 		}
19762 	}
19763 }
19764 
19765 /*
19766  * Device AutoOnline Event processing.
19767  * If attached device is to be onlined, an attempt is made to online this
19768  * device, but only if there is no lingering (old) target node present.
19769  * If the device cannot be onlined, the event flag is left intact,
19770  * so that event daemon may re-run this function later.
19771  *
19772  * This function cannot be called in interrupt context (it may sleep).
19773  *
19774  * NOTE: Processes cport events only, not port multiplier ports.
19775  */
19776 static void
19777 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
19778     sata_address_t *saddr)
19779 {
19780 	sata_cport_info_t *cportinfo;
19781 	sata_drive_info_t *sdinfo;
19782 	sata_device_t sata_device;
19783 	dev_info_t *tdip;
19784 
19785 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19786 	    "Processing port %d attached device auto-onlining", saddr->cport);
19787 
19788 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19789 
19790 	/*
19791 	 * Check if device is present and recognized. If not, reset event.
19792 	 */
19793 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19794 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
19795 		/* Nothing to online */
19796 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19797 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19798 		    saddr->cport)->cport_mutex);
19799 		return;
19800 	}
19801 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19802 
19803 	/*
19804 	 * Check if there is target node for this device and if it is in the
19805 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
19806 	 * the event for later processing.
19807 	 */
19808 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19809 	    saddr->pmport);
19810 	if (tdip != NULL) {
19811 		/*
19812 		 * target node exists - check if it is target node of
19813 		 * a removed device.
19814 		 */
19815 		if (sata_check_device_removed(tdip) == B_TRUE) {
19816 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19817 			    "sata_process_device_autoonline: "
19818 			    "old device target node exists!", NULL);
19819 			/*
19820 			 * Event daemon will retry device onlining later.
19821 			 */
19822 			mutex_enter(&sata_hba_inst->satahba_mutex);
19823 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19824 			mutex_exit(&sata_hba_inst->satahba_mutex);
19825 			mutex_enter(&sata_mutex);
19826 			sata_event_pending |= SATA_EVNT_MAIN;
19827 			mutex_exit(&sata_mutex);
19828 			return;
19829 		}
19830 		/*
19831 		 * If the target node is not in the 'removed" state, assume
19832 		 * that it belongs to this device. There is nothing more to do,
19833 		 * but reset the event.
19834 		 */
19835 	} else {
19836 
19837 		/*
19838 		 * Try to online the device
19839 		 * If there is any reset-related event, remove it. We are
19840 		 * configuring the device and no state restoring is needed.
19841 		 */
19842 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19843 		    saddr->cport)->cport_mutex);
19844 		sata_device.satadev_addr = *saddr;
19845 		if (saddr->qual == SATA_ADDR_CPORT)
19846 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
19847 		else
19848 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
19849 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
19850 		if (sdinfo != NULL) {
19851 			if (sdinfo->satadrv_event_flags &
19852 			    (SATA_EVNT_DEVICE_RESET |
19853 			    SATA_EVNT_INPROC_DEVICE_RESET))
19854 				sdinfo->satadrv_event_flags = 0;
19855 			sdinfo->satadrv_event_flags |=
19856 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19857 
19858 			/* Need to create a new target node. */
19859 			cportinfo->cport_tgtnode_clean = B_TRUE;
19860 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19861 			    saddr->cport)->cport_mutex);
19862 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
19863 			    sata_hba_inst, &sata_device.satadev_addr);
19864 			if (tdip == NULL) {
19865 				/*
19866 				 * Configure (onlining) failed.
19867 				 * We will NOT retry
19868 				 */
19869 				SATA_LOG_D((sata_hba_inst, CE_WARN,
19870 				    "sata_process_device_autoonline: "
19871 				    "configuring SATA device at port %d failed",
19872 				    saddr->cport));
19873 			}
19874 		} else {
19875 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19876 			    saddr->cport)->cport_mutex);
19877 		}
19878 
19879 	}
19880 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19881 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19882 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19883 	    saddr->cport)->cport_mutex);
19884 }
19885 
19886 
19887 static void
19888 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
19889     int hint)
19890 {
19891 	char ap[MAXPATHLEN];
19892 	nvlist_t *ev_attr_list = NULL;
19893 	int err;
19894 
19895 	/* Allocate and build sysevent attribute list */
19896 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
19897 	if (err != 0) {
19898 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19899 		    "sata_gen_sysevent: "
19900 		    "cannot allocate memory for sysevent attributes\n"));
19901 		return;
19902 	}
19903 	/* Add hint attribute */
19904 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
19905 	if (err != 0) {
19906 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19907 		    "sata_gen_sysevent: "
19908 		    "failed to add DR_HINT attr for sysevent"));
19909 		nvlist_free(ev_attr_list);
19910 		return;
19911 	}
19912 	/*
19913 	 * Add AP attribute.
19914 	 * Get controller pathname and convert it into AP pathname by adding
19915 	 * a target number.
19916 	 */
19917 	(void) snprintf(ap, MAXPATHLEN, "/devices");
19918 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
19919 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
19920 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
19921 
19922 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
19923 	if (err != 0) {
19924 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19925 		    "sata_gen_sysevent: "
19926 		    "failed to add DR_AP_ID attr for sysevent"));
19927 		nvlist_free(ev_attr_list);
19928 		return;
19929 	}
19930 
19931 	/* Generate/log sysevent */
19932 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
19933 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
19934 	if (err != DDI_SUCCESS) {
19935 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19936 		    "sata_gen_sysevent: "
19937 		    "cannot log sysevent, err code %x\n", err));
19938 	}
19939 
19940 	nvlist_free(ev_attr_list);
19941 }
19942 
19943 
19944 
19945 
19946 /*
19947  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
19948  */
19949 static void
19950 sata_set_device_removed(dev_info_t *tdip)
19951 {
19952 	int circ;
19953 
19954 	ASSERT(tdip != NULL);
19955 
19956 	ndi_devi_enter(tdip, &circ);
19957 	mutex_enter(&DEVI(tdip)->devi_lock);
19958 	DEVI_SET_DEVICE_REMOVED(tdip);
19959 	mutex_exit(&DEVI(tdip)->devi_lock);
19960 	ndi_devi_exit(tdip, circ);
19961 }
19962 
19963 
19964 /*
19965  * Set internal event instructing event daemon to try
19966  * to perform the target node cleanup.
19967  */
19968 static void
19969 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19970     sata_address_t *saddr)
19971 {
19972 	if (saddr->qual == SATA_ADDR_CPORT ||
19973 	    saddr->qual == SATA_ADDR_DCPORT) {
19974 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19975 		    saddr->cport)->cport_mutex);
19976 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
19977 		    SATA_EVNT_TARGET_NODE_CLEANUP;
19978 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19979 		    cport_tgtnode_clean = B_FALSE;
19980 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19981 		    saddr->cport)->cport_mutex);
19982 	} else {
19983 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19984 		    saddr->cport, saddr->pmport)->pmport_mutex);
19985 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
19986 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
19987 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
19988 		    pmport_tgtnode_clean = B_FALSE;
19989 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19990 		    saddr->cport, saddr->pmport)->pmport_mutex);
19991 	}
19992 	mutex_enter(&sata_hba_inst->satahba_mutex);
19993 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19994 	mutex_exit(&sata_hba_inst->satahba_mutex);
19995 	mutex_enter(&sata_mutex);
19996 	sata_event_pending |= SATA_EVNT_MAIN;
19997 	mutex_exit(&sata_mutex);
19998 }
19999 
20000 
20001 /*
20002  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
20003  * i.e. check if the target node state indicates that it belongs to a removed
20004  * device.
20005  *
20006  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
20007  * B_FALSE otherwise.
20008  */
20009 static boolean_t
20010 sata_check_device_removed(dev_info_t *tdip)
20011 {
20012 	ASSERT(tdip != NULL);
20013 
20014 	if (DEVI_IS_DEVICE_REMOVED(tdip))
20015 		return (B_TRUE);
20016 	else
20017 		return (B_FALSE);
20018 }
20019 
20020 /* ************************ FAULT INJECTTION **************************** */
20021 
20022 #ifdef SATA_INJECT_FAULTS
20023 
20024 static	uint32_t sata_fault_count = 0;
20025 static	uint32_t sata_fault_suspend_count = 0;
20026 
20027 /*
20028  * Inject sata pkt fault
20029  * It modifies returned values of the sata packet.
20030  * It returns immediately if:
20031  * pkt fault injection is not enabled (via sata_inject_fault,
20032  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
20033  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
20034  * pkt is not directed to specified fault controller/device
20035  * (sata_fault_ctrl_dev and sata_fault_device).
20036  * If fault controller is not specified, fault injection applies to all
20037  * controllers and devices.
20038  *
20039  * First argument is the pointer to the executed sata packet.
20040  * Second argument is a pointer to a value returned by the HBA tran_start
20041  * function.
20042  * Third argument specifies injected error. Injected sata packet faults
20043  * are the satapkt_reason values.
20044  * SATA_PKT_BUSY		-1	Not completed, busy
20045  * SATA_PKT_DEV_ERROR		1	Device reported error
20046  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
20047  * SATA_PKT_PORT_ERROR		3	Not completed, port error
20048  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
20049  * SATA_PKT_ABORTED		5	Aborted by request
20050  * SATA_PKT_TIMEOUT		6	Operation timeut
20051  * SATA_PKT_RESET		7	Aborted by reset request
20052  *
20053  * Additional global variables affecting the execution:
20054  *
20055  * sata_inject_fault_count variable specifies number of times in row the
20056  * error is injected. Value of -1 specifies permanent fault, ie. every time
20057  * the fault injection point is reached, the fault is injected and a pause
20058  * between fault injection specified by sata_inject_fault_pause_count is
20059  * ignored). Fault injection routine decrements sata_inject_fault_count
20060  * (if greater than zero) until it reaches 0. No fault is injected when
20061  * sata_inject_fault_count is 0 (zero).
20062  *
20063  * sata_inject_fault_pause_count variable specifies number of times a fault
20064  * injection is bypassed (pause between fault injections).
20065  * If set to 0, a fault is injected only a number of times specified by
20066  * sata_inject_fault_count.
20067  *
20068  * The fault counts are static, so for periodic errors they have to be manually
20069  * reset to start repetition sequence from scratch.
20070  * If the original value returned by the HBA tran_start function is not
20071  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
20072  * is injected (to avoid masking real problems);
20073  *
20074  * NOTE: In its current incarnation, this function should be invoked only for
20075  * commands executed in SYNCHRONOUS mode.
20076  */
20077 
20078 
20079 static void
20080 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
20081 {
20082 
20083 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
20084 		return;
20085 
20086 	if (sata_inject_fault_count == 0)
20087 		return;
20088 
20089 	if (fault == 0)
20090 		return;
20091 
20092 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
20093 		return;
20094 
20095 	if (sata_fault_ctrl != NULL) {
20096 		sata_pkt_txlate_t *spx =
20097 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
20098 
20099 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
20100 		    spx->txlt_sata_hba_inst->satahba_dip)
20101 			return;
20102 
20103 		if (sata_fault_device.satadev_addr.cport !=
20104 		    spkt->satapkt_device.satadev_addr.cport ||
20105 		    sata_fault_device.satadev_addr.pmport !=
20106 		    spkt->satapkt_device.satadev_addr.pmport ||
20107 		    sata_fault_device.satadev_addr.qual !=
20108 		    spkt->satapkt_device.satadev_addr.qual)
20109 			return;
20110 	}
20111 
20112 	/* Modify pkt return parameters */
20113 	if (*rval != SATA_TRAN_ACCEPTED ||
20114 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
20115 		sata_fault_count = 0;
20116 		sata_fault_suspend_count = 0;
20117 		return;
20118 	}
20119 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
20120 		/* Pause in the injection */
20121 		sata_fault_suspend_count -= 1;
20122 		return;
20123 	}
20124 
20125 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
20126 		/*
20127 		 * Init inject fault cycle. If fault count is set to -1,
20128 		 * it is a permanent fault.
20129 		 */
20130 		if (sata_inject_fault_count != -1) {
20131 			sata_fault_count = sata_inject_fault_count;
20132 			sata_fault_suspend_count =
20133 			    sata_inject_fault_pause_count;
20134 			if (sata_fault_suspend_count == 0)
20135 				sata_inject_fault_count = 0;
20136 		}
20137 	}
20138 
20139 	if (sata_fault_count != 0)
20140 		sata_fault_count -= 1;
20141 
20142 	switch (fault) {
20143 	case SATA_PKT_BUSY:
20144 		*rval = SATA_TRAN_BUSY;
20145 		spkt->satapkt_reason = SATA_PKT_BUSY;
20146 		break;
20147 
20148 	case SATA_PKT_QUEUE_FULL:
20149 		*rval = SATA_TRAN_QUEUE_FULL;
20150 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
20151 		break;
20152 
20153 	case SATA_PKT_CMD_UNSUPPORTED:
20154 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
20155 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
20156 		break;
20157 
20158 	case SATA_PKT_PORT_ERROR:
20159 		/* This is "rejected" command */
20160 		*rval = SATA_TRAN_PORT_ERROR;
20161 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
20162 		/* Additional error setup could be done here - port state */
20163 		break;
20164 
20165 	case SATA_PKT_DEV_ERROR:
20166 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
20167 		/*
20168 		 * Additional error setup could be done here
20169 		 */
20170 		break;
20171 
20172 	case SATA_PKT_ABORTED:
20173 		spkt->satapkt_reason = SATA_PKT_ABORTED;
20174 		break;
20175 
20176 	case SATA_PKT_TIMEOUT:
20177 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
20178 		/* Additional error setup could be done here */
20179 		break;
20180 
20181 	case SATA_PKT_RESET:
20182 		spkt->satapkt_reason = SATA_PKT_RESET;
20183 		/*
20184 		 * Additional error setup could be done here - device reset
20185 		 */
20186 		break;
20187 
20188 	default:
20189 		break;
20190 	}
20191 }
20192 
20193 #endif
20194 
20195 /*
20196  * SATA Trace Ring Buffer
20197  * ----------------------
20198  *
20199  * Overview
20200  *
20201  * The SATA trace ring buffer is a ring buffer created and managed by
20202  * the SATA framework module that can be used by any module or driver
20203  * within the SATA framework to store debug messages.
20204  *
20205  * Ring Buffer Interfaces:
20206  *
20207  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20208  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20209  *
20210  *	Note that the sata_trace_debug() interface was created to give
20211  *	consumers the flexibilty of sending debug messages to ring buffer
20212  *	as variable arguments.  Consumers can send type va_list debug
20213  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20214  *	and sata_vtrace_debug() relationship is similar to that of
20215  *	cmn_err(9F) and vcmn_err(9F).
20216  *
20217  * Below is a diagram of the SATA trace ring buffer interfaces and
20218  * sample consumers:
20219  *
20220  * +---------------------------------+
20221  * |    o  o  SATA Framework Module  |
20222  * | o  SATA  o     +------------------+      +------------------+
20223  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20224  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20225  * | o        o     +------------------+   |  +------------------+
20226  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20227  * |                        |        |        +------------------+
20228  * |           +------------------+  |
20229  * |           |SATA Debug Message|  |
20230  * |           +------------------+  |
20231  * +---------------------------------+
20232  *
20233  * Supporting Routines:
20234  *
20235  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20236  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20237  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20238  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20239  *
20240  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20241  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20242  * /etc/system to desired size in unit of bytes.
20243  *
20244  * The individual debug message size in the ring buffer is restricted
20245  * to DMSG_BUF_SIZE.
20246  */
20247 void
20248 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20249 {
20250 	sata_trace_dmsg_t *dmsg;
20251 
20252 	if (sata_debug_rbuf == NULL) {
20253 		return;
20254 	}
20255 
20256 	/*
20257 	 * If max size of ring buffer is smaller than size
20258 	 * required for one debug message then just return
20259 	 * since we have no room for the debug message.
20260 	 */
20261 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20262 		return;
20263 	}
20264 
20265 	mutex_enter(&sata_debug_rbuf->lock);
20266 
20267 	/* alloc or reuse on ring buffer */
20268 	dmsg = sata_trace_dmsg_alloc();
20269 
20270 	if (dmsg == NULL) {
20271 		/* resource allocation failed */
20272 		mutex_exit(&sata_debug_rbuf->lock);
20273 		return;
20274 	}
20275 
20276 	dmsg->dip = dip;
20277 	gethrestime(&dmsg->timestamp);
20278 
20279 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
20280 
20281 	mutex_exit(&sata_debug_rbuf->lock);
20282 }
20283 
20284 void
20285 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
20286 {
20287 	va_list ap;
20288 
20289 	va_start(ap, fmt);
20290 	sata_vtrace_debug(dip, fmt, ap);
20291 	va_end(ap);
20292 }
20293 
20294 /*
20295  * This routine is used to manage debug messages
20296  * on ring buffer.
20297  */
20298 static sata_trace_dmsg_t *
20299 sata_trace_dmsg_alloc(void)
20300 {
20301 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
20302 
20303 	if (sata_debug_rbuf->looped == TRUE) {
20304 		sata_debug_rbuf->dmsgp = dmsg->next;
20305 		return (sata_debug_rbuf->dmsgp);
20306 	}
20307 
20308 	/*
20309 	 * If we're looping for the first time,
20310 	 * connect the ring.
20311 	 */
20312 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
20313 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
20314 		dmsg->next = sata_debug_rbuf->dmsgh;
20315 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
20316 		sata_debug_rbuf->looped = TRUE;
20317 		return (sata_debug_rbuf->dmsgp);
20318 	}
20319 
20320 	/* If we've gotten this far then memory allocation is needed */
20321 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
20322 	if (dmsg_alloc == NULL) {
20323 		sata_debug_rbuf->allocfailed++;
20324 		return (dmsg_alloc);
20325 	} else {
20326 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
20327 	}
20328 
20329 	if (sata_debug_rbuf->dmsgp != NULL) {
20330 		dmsg->next = dmsg_alloc;
20331 		sata_debug_rbuf->dmsgp = dmsg->next;
20332 		return (sata_debug_rbuf->dmsgp);
20333 	} else {
20334 		/*
20335 		 * We should only be here if we're initializing
20336 		 * the ring buffer.
20337 		 */
20338 		if (sata_debug_rbuf->dmsgh == NULL) {
20339 			sata_debug_rbuf->dmsgh = dmsg_alloc;
20340 		} else {
20341 			/* Something is wrong */
20342 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
20343 			return (NULL);
20344 		}
20345 
20346 		sata_debug_rbuf->dmsgp = dmsg_alloc;
20347 		return (sata_debug_rbuf->dmsgp);
20348 	}
20349 }
20350 
20351 
20352 /*
20353  * Free all messages on debug ring buffer.
20354  */
20355 static void
20356 sata_trace_dmsg_free(void)
20357 {
20358 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
20359 
20360 	while (dmsg != NULL) {
20361 		dmsg_next = dmsg->next;
20362 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
20363 
20364 		/*
20365 		 * If we've looped around the ring than we're done.
20366 		 */
20367 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
20368 			break;
20369 		} else {
20370 			dmsg = dmsg_next;
20371 		}
20372 	}
20373 }
20374 
20375 
20376 /*
20377  * This function can block
20378  */
20379 static void
20380 sata_trace_rbuf_alloc(void)
20381 {
20382 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
20383 
20384 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
20385 
20386 	if (dmsg_ring_size > 0) {
20387 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
20388 	}
20389 }
20390 
20391 
20392 static void
20393 sata_trace_rbuf_free(void)
20394 {
20395 	sata_trace_dmsg_free();
20396 	mutex_destroy(&sata_debug_rbuf->lock);
20397 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
20398 }
20399 
20400 /*
20401  * If SATA_DEBUG is not defined then this routine is called instead
20402  * of sata_log() via the SATA_LOG_D macro.
20403  */
20404 static void
20405 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
20406     const char *fmt, ...)
20407 {
20408 #ifndef __lock_lint
20409 	_NOTE(ARGUNUSED(level))
20410 #endif
20411 
20412 	dev_info_t *dip = NULL;
20413 	va_list ap;
20414 
20415 	if (sata_hba_inst != NULL) {
20416 		dip = SATA_DIP(sata_hba_inst);
20417 	}
20418 
20419 	va_start(ap, fmt);
20420 	sata_vtrace_debug(dip, fmt, ap);
20421 	va_end(ap);
20422 }
20423