xref: /titanic_51/usr/src/uts/common/io/sata/impl/sata.c (revision e4f45209f4f7f1c995b641816839749f6129d135)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 
28 /*
29  * SATA Framework
30  * Generic SATA Host Adapter Implementation
31  */
32 
33 #include <sys/conf.h>
34 #include <sys/file.h>
35 #include <sys/ddi.h>
36 #include <sys/sunddi.h>
37 #include <sys/modctl.h>
38 #include <sys/cmn_err.h>
39 #include <sys/errno.h>
40 #include <sys/thread.h>
41 #include <sys/kstat.h>
42 #include <sys/note.h>
43 #include <sys/sysevent.h>
44 #include <sys/sysevent/eventdefs.h>
45 #include <sys/sysevent/dr.h>
46 #include <sys/taskq.h>
47 #include <sys/disp.h>
48 
49 #include <sys/sata/impl/sata.h>
50 #include <sys/sata/sata_hba.h>
51 #include <sys/sata/sata_defs.h>
52 #include <sys/sata/sata_cfgadm.h>
53 #include <sys/sata/sata_blacklist.h>
54 #include <sys/sata/sata_satl.h>
55 
56 #include <sys/scsi/impl/spc3_types.h>
57 
58 /* Debug flags - defined in sata.h */
59 int	sata_debug_flags = 0;
60 int	sata_msg = 0;
61 
62 /*
63  * Flags enabling selected SATA HBA framework functionality
64  */
65 #define	SATA_ENABLE_QUEUING		1
66 #define	SATA_ENABLE_NCQ			2
67 #define	SATA_ENABLE_PROCESS_EVENTS	4
68 #define	SATA_ENABLE_PMULT_FBS		8 /* FIS-Based Switching */
69 int sata_func_enable =
70 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
71 
72 /*
73  * Global variable setting default maximum queue depth (NCQ or TCQ)
74  * Note:minimum queue depth is 1
75  */
76 int sata_max_queue_depth = SATA_MAX_QUEUE_DEPTH; /* max NCQ/TCQ queue depth */
77 
78 /*
79  * Currently used default NCQ/TCQ queue depth. It is set-up during the driver
80  * initialization, using value from sata_max_queue_depth
81  * It is adjusted to minimum supported by the controller and by the device,
82  * if queueing is enabled.
83  */
84 static	int sata_current_max_qdepth;
85 
86 /*
87  * Global variable determining the default behavior after device hotpluggin.
88  * If non-zero, the hotplugged device is onlined (if possible) without explicit
89  * IOCTL request (AP_CONFIGURE).
90  * If zero, hotplugged device is identified, but not onlined.
91  * Enabling (AP_CONNECT) device port with an attached device does not result
92  * in device onlining regardless of the flag setting
93  */
94 int sata_auto_online = 0;
95 
96 #ifdef SATA_DEBUG
97 
98 #define	SATA_LOG_D(args)	sata_log args
99 uint64_t mbuf_count = 0;
100 uint64_t mbuffail_count = 0;
101 
102 sata_atapi_cmd_t sata_atapi_trace[64];
103 uint32_t sata_atapi_trace_index = 0;
104 int sata_atapi_trace_save = 1;
105 static	void sata_save_atapi_trace(sata_pkt_txlate_t *, int);
106 #define	SATAATAPITRACE(spx, count)	if (sata_atapi_trace_save) \
107     sata_save_atapi_trace(spx, count);
108 
109 #else
110 #define	SATA_LOG_D(args)	sata_trace_log args
111 #define	SATAATAPITRACE(spx, count)
112 #endif
113 
114 #if 0
115 static void
116 sata_test_atapi_packet_command(sata_hba_inst_t *, int);
117 #endif
118 
119 #ifdef SATA_INJECT_FAULTS
120 
121 #define		SATA_INJECT_PKT_FAULT	1
122 uint32_t	sata_inject_fault = 0;
123 
124 uint32_t	sata_inject_fault_count = 0;
125 uint32_t	sata_inject_fault_pause_count = 0;
126 uint32_t	sata_fault_type = 0;
127 uint32_t	sata_fault_cmd = 0;
128 dev_info_t	*sata_fault_ctrl = NULL;
129 sata_device_t	sata_fault_device;
130 
131 static	void sata_inject_pkt_fault(sata_pkt_t *, int *, int);
132 
133 #endif
134 
135 #define	LEGACY_HWID_LEN	64	/* Model (40) + Serial (20) + pad */
136 
137 static char sata_rev_tag[] = {"1.46"};
138 
139 /*
140  * SATA cb_ops functions
141  */
142 static 	int sata_hba_open(dev_t *, int, int, cred_t *);
143 static 	int sata_hba_close(dev_t, int, int, cred_t *);
144 static 	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
145 
146 /*
147  * SCSA required entry points
148  */
149 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
150     scsi_hba_tran_t *, struct scsi_device *);
151 static	int sata_scsi_tgt_probe(struct scsi_device *,
152     int (*callback)(void));
153 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
154     scsi_hba_tran_t *, struct scsi_device *);
155 static 	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
156 static 	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
157 static 	int sata_scsi_reset(struct scsi_address *, int);
158 static 	int sata_scsi_getcap(struct scsi_address *, char *, int);
159 static 	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
160 static 	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
161     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
162     caddr_t);
163 static 	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
164 static 	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
165 static 	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
166 
167 /*
168  * SATA HBA interface functions are defined in sata_hba.h header file
169  */
170 
171 /* Event processing functions */
172 static	void sata_event_daemon(void *);
173 static	void sata_event_thread_control(int);
174 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
175 static	void sata_process_pmult_events(sata_hba_inst_t *, uint8_t);
176 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
177 static	void sata_process_pmdevice_reset(sata_hba_inst_t *, sata_address_t *);
178 static	void sata_process_port_failed_event(sata_hba_inst_t *,
179     sata_address_t *);
180 static	void sata_process_port_link_events(sata_hba_inst_t *,
181     sata_address_t *);
182 static	void sata_process_pmport_link_events(sata_hba_inst_t *,
183     sata_address_t *);
184 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
185 static	void sata_process_pmdevice_detached(sata_hba_inst_t *,
186     sata_address_t *);
187 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
188 static	void sata_process_pmdevice_attached(sata_hba_inst_t *,
189     sata_address_t *);
190 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
191 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
192 static	void sata_process_target_node_cleanup(sata_hba_inst_t *,
193     sata_address_t *);
194 static	void sata_process_device_autoonline(sata_hba_inst_t *,
195     sata_address_t *saddr);
196 
197 /*
198  * Local translation functions
199  */
200 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
201 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
202 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
203 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
204 static	int sata_txlt_request_sense(sata_pkt_txlate_t *);
205 static	int sata_txlt_read(sata_pkt_txlate_t *);
206 static	int sata_txlt_write(sata_pkt_txlate_t *);
207 static	int sata_txlt_log_sense(sata_pkt_txlate_t *);
208 static	int sata_txlt_log_select(sata_pkt_txlate_t *);
209 static	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
210 static	int sata_txlt_mode_select(sata_pkt_txlate_t *);
211 static	int sata_txlt_ata_pass_thru(sata_pkt_txlate_t *);
212 static	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
213 static	int sata_txlt_write_buffer(sata_pkt_txlate_t *);
214 static	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
215 
216 static	int sata_hba_start(sata_pkt_txlate_t *, int *);
217 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
218 static	int sata_txlt_check_condition(sata_pkt_txlate_t *, uchar_t, uchar_t);
219 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
220 static	int sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *);
221 static	void sata_txlt_rw_completion(sata_pkt_t *);
222 static	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
223 static	void sata_txlt_apt_completion(sata_pkt_t *sata_pkt);
224 static	void sata_txlt_download_mcode_cmd_completion(sata_pkt_t *);
225 static	int sata_emul_rw_completion(sata_pkt_txlate_t *);
226 static	void sata_fill_ata_return_desc(sata_pkt_t *, uint8_t, uint8_t,
227     uint8_t);
228 static	struct scsi_extended_sense *sata_immediate_error_response(
229     sata_pkt_txlate_t *, int);
230 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
231 
232 static	int sata_txlt_atapi(sata_pkt_txlate_t *);
233 static	void sata_txlt_atapi_completion(sata_pkt_t *);
234 
235 /*
236  * Local functions for ioctl
237  */
238 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
239 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
240     devctl_ap_state_t *);
241 static	dev_info_t *sata_get_target_dip(dev_info_t *, uint8_t, uint8_t);
242 static	dev_info_t *sata_get_scsi_target_dip(dev_info_t *, sata_address_t *);
243 static	dev_info_t *sata_devt_to_devinfo(dev_t);
244 static	int sata_ioctl_connect(sata_hba_inst_t *, sata_device_t *);
245 static	int sata_ioctl_disconnect(sata_hba_inst_t *, sata_device_t *);
246 static	int sata_ioctl_configure(sata_hba_inst_t *, sata_device_t *);
247 static	int sata_ioctl_unconfigure(sata_hba_inst_t *, sata_device_t *);
248 static	int sata_ioctl_activate(sata_hba_inst_t *, sata_device_t *);
249 static	int sata_ioctl_deactivate(sata_hba_inst_t *, sata_device_t *);
250 static	int sata_ioctl_reset_port(sata_hba_inst_t *, sata_device_t *);
251 static	int sata_ioctl_reset_device(sata_hba_inst_t *, sata_device_t *);
252 static	int sata_ioctl_reset_all(sata_hba_inst_t *);
253 static	int sata_ioctl_port_self_test(sata_hba_inst_t *, sata_device_t *);
254 static	int sata_ioctl_get_device_path(sata_hba_inst_t *, sata_device_t *,
255     sata_ioctl_data_t *, int mode);
256 static	int sata_ioctl_get_ap_type(sata_hba_inst_t *, sata_device_t *,
257     sata_ioctl_data_t *, int mode);
258 static	int sata_ioctl_get_model_info(sata_hba_inst_t *, sata_device_t *,
259     sata_ioctl_data_t *, int mode);
260 static	int sata_ioctl_get_revfirmware_info(sata_hba_inst_t *, sata_device_t *,
261     sata_ioctl_data_t *, int mode);
262 static	int sata_ioctl_get_serialnumber_info(sata_hba_inst_t *,
263     sata_device_t *, sata_ioctl_data_t *, int mode);
264 
265 /*
266  * Local functions
267  */
268 static 	void sata_remove_hba_instance(dev_info_t *);
269 static 	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
270 static 	void sata_probe_ports(sata_hba_inst_t *);
271 static	void sata_probe_pmports(sata_hba_inst_t *, uint8_t);
272 static 	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
273 static 	int sata_reprobe_pmult(sata_hba_inst_t *, sata_device_t *, int);
274 static 	int sata_reprobe_pmport(sata_hba_inst_t *, sata_device_t *, int);
275 static	int sata_alloc_pmult(sata_hba_inst_t *, sata_device_t *);
276 static	void sata_free_pmult(sata_hba_inst_t *, sata_device_t *);
277 static 	int sata_add_device(dev_info_t *, sata_hba_inst_t *, sata_device_t *);
278 static	int sata_offline_device(sata_hba_inst_t *, sata_device_t *,
279     sata_drive_info_t *);
280 static 	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
281     sata_address_t *);
282 static 	void sata_remove_target_node(sata_hba_inst_t *,
283     sata_address_t *);
284 static 	int sata_validate_scsi_address(sata_hba_inst_t *,
285     struct scsi_address *, sata_device_t *);
286 static 	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
287 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
288 static	void sata_pkt_free(sata_pkt_txlate_t *);
289 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
290     caddr_t, ddi_dma_attr_t *);
291 static	void sata_common_free_dma_rsrcs(sata_pkt_txlate_t *);
292 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
293 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
294     sata_device_t *);
295 static 	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
296 static	void sata_reidentify_device(sata_pkt_txlate_t *);
297 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
298 static 	void sata_free_local_buffer(sata_pkt_txlate_t *);
299 static 	uint64_t sata_check_capacity(sata_drive_info_t *);
300 void 	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
301     ddi_dma_attr_t *);
302 static 	int sata_fetch_device_identify_data(sata_hba_inst_t *,
303     sata_drive_info_t *);
304 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
305 static	void sata_update_pmport_info(sata_hba_inst_t *, sata_device_t *);
306 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
307 static	int sata_set_dma_mode(sata_hba_inst_t *, sata_drive_info_t *);
308 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
309 static	int sata_set_rmsn(sata_hba_inst_t *, sata_drive_info_t *, int);
310 static	int sata_set_drive_features(sata_hba_inst_t *,
311     sata_drive_info_t *, int flag);
312 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
313 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
314 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
315     uint8_t *);
316 static	int sata_get_atapi_inquiry_data(sata_hba_inst_t *, sata_address_t *,
317     struct scsi_inquiry *);
318 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
319 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
320 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
321 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
322 static	int sata_build_msense_page_30(sata_drive_info_t *, int, uint8_t *);
323 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
324     struct mode_cache_scsi3 *, int, int *, int *, int *);
325 static	int sata_mode_select_page_1a(sata_pkt_txlate_t *,
326     struct mode_info_power_cond *, int, int *, int *, int *);
327 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
328     struct mode_info_excpt_page *, int, int *, int *, int *);
329 static	int sata_mode_select_page_30(sata_pkt_txlate_t *,
330     struct mode_acoustic_management *, int, int *, int *, int *);
331 
332 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
333 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
334     sata_hba_inst_t *);
335 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
336     sata_hba_inst_t *);
337 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
338     sata_hba_inst_t *);
339 static	int sata_build_lsense_page_0e(sata_drive_info_t *, uint8_t *,
340     sata_pkt_txlate_t *);
341 
342 static	void sata_set_arq_data(sata_pkt_t *);
343 static	void sata_build_read_verify_cmd(sata_cmd_t *, uint16_t, uint64_t);
344 static	void sata_build_generic_cmd(sata_cmd_t *, uint8_t);
345 static	uint8_t sata_get_standby_timer(uint8_t *timer);
346 
347 static	void sata_save_drive_settings(sata_drive_info_t *);
348 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
349 static	void sata_show_pmult_info(sata_hba_inst_t *, sata_device_t *);
350 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
351 static	void sata_trace_log(sata_hba_inst_t *, uint_t, const char *fmt, ...);
352 static	int sata_fetch_smart_return_status(sata_hba_inst_t *,
353     sata_drive_info_t *);
354 static	int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
355     struct smart_data *);
356 static	int sata_smart_selftest_log(sata_hba_inst_t *,
357     sata_drive_info_t *,
358     struct smart_selftest_log *);
359 static	int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
360     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
361 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
362     uint8_t *, uint8_t, uint8_t);
363 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
364     struct read_log_ext_directory *);
365 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
366 static	void sata_xlate_errors(sata_pkt_txlate_t *);
367 static	void sata_decode_device_error(sata_pkt_txlate_t *,
368     struct scsi_extended_sense *);
369 static	void sata_set_device_removed(dev_info_t *);
370 static	boolean_t sata_check_device_removed(dev_info_t *);
371 static	void sata_set_target_node_cleanup(sata_hba_inst_t *, sata_address_t *);
372 static	int sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *,
373     sata_drive_info_t *);
374 static	int sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *,
375     sata_drive_info_t *);
376 static	void sata_atapi_packet_cmd_setup(sata_cmd_t *, sata_drive_info_t *);
377 static	void sata_fixed_sense_data_preset(struct scsi_extended_sense *);
378 static  void sata_target_devid_register(dev_info_t *, sata_drive_info_t *);
379 static  int sata_check_modser(char *, int);
380 
381 
382 
383 /*
384  * SATA Framework will ignore SATA HBA driver cb_ops structure and
385  * register following one with SCSA framework.
386  * Open & close are provided, so scsi framework will not use its own
387  */
388 static struct cb_ops sata_cb_ops = {
389 	sata_hba_open,			/* open */
390 	sata_hba_close,			/* close */
391 	nodev,				/* strategy */
392 	nodev,				/* print */
393 	nodev,				/* dump */
394 	nodev,				/* read */
395 	nodev,				/* write */
396 	sata_hba_ioctl,			/* ioctl */
397 	nodev,				/* devmap */
398 	nodev,				/* mmap */
399 	nodev,				/* segmap */
400 	nochpoll,			/* chpoll */
401 	ddi_prop_op,			/* cb_prop_op */
402 	0,				/* streamtab */
403 	D_NEW | D_MP,			/* cb_flag */
404 	CB_REV,				/* rev */
405 	nodev,				/* aread */
406 	nodev				/* awrite */
407 };
408 
409 
410 extern struct mod_ops mod_miscops;
411 extern uchar_t	scsi_cdb_size[];
412 
413 static struct modlmisc modlmisc = {
414 	&mod_miscops,			/* Type of module */
415 	"SATA Module"			/* module name */
416 };
417 
418 
419 static struct modlinkage modlinkage = {
420 	MODREV_1,
421 	(void *)&modlmisc,
422 	NULL
423 };
424 
425 /*
426  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
427  * i.e. when scsi_pkt has not timeout specified.
428  */
429 static int sata_default_pkt_time = 60;	/* 60 seconds */
430 
431 /*
432  * Intermediate buffer device access attributes - they are required,
433  * but not necessarily used.
434  */
435 static ddi_device_acc_attr_t sata_acc_attr = {
436 	DDI_DEVICE_ATTR_V0,
437 	DDI_STRUCTURE_LE_ACC,
438 	DDI_STRICTORDER_ACC
439 };
440 
441 
442 /*
443  * Mutexes protecting structures in multithreaded operations.
444  * Because events are relatively rare, a single global mutex protecting
445  * data structures should be sufficient. To increase performance, add
446  * separate mutex per each sata port and use global mutex only to protect
447  * common data structures.
448  */
449 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
450 static	kmutex_t sata_log_mutex;	/* protects log */
451 
452 static 	char sata_log_buf[256];
453 
454 /*
455  * sata trace debug
456  */
457 static	sata_trace_rbuf_t *sata_debug_rbuf;
458 static	sata_trace_dmsg_t *sata_trace_dmsg_alloc(void);
459 static	void sata_trace_dmsg_free(void);
460 static	void sata_trace_rbuf_alloc(void);
461 static	void sata_trace_rbuf_free(void);
462 
463 int	dmsg_ring_size = DMSG_RING_SIZE;
464 
465 /* Default write cache setting for SATA hard disks */
466 int	sata_write_cache = 1;		/* enabled */
467 
468 /* Default write cache setting for SATA ATAPI CD/DVD */
469 int	sata_atapicdvd_write_cache = 1; /* enabled */
470 
471 /* Default write cache setting for SATA ATAPI tape */
472 int	sata_atapitape_write_cache = 1; /* enabled */
473 
474 /* Default write cache setting for SATA ATAPI disk */
475 int	sata_atapidisk_write_cache = 1;	/* enabled */
476 
477 /*
478  * Linked list of HBA instances
479  */
480 static 	sata_hba_inst_t *sata_hba_list = NULL;
481 static 	sata_hba_inst_t *sata_hba_list_tail = NULL;
482 /*
483  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
484  * structure and in sata soft state.
485  */
486 
487 /*
488  * Event daemon related variables
489  */
490 static 	kmutex_t sata_event_mutex;
491 static 	kcondvar_t sata_event_cv;
492 static 	kthread_t *sata_event_thread = NULL;
493 static 	int sata_event_thread_terminate = 0;
494 static 	int sata_event_pending = 0;
495 static 	int sata_event_thread_active = 0;
496 extern 	pri_t minclsyspri;
497 
498 /*
499  * NCQ error recovery command
500  */
501 static const sata_cmd_t sata_rle_cmd = {
502 	SATA_CMD_REV,
503 	NULL,
504 	{
505 		SATA_DIR_READ
506 	},
507 	ATA_ADDR_LBA48,
508 	0,
509 	0,
510 	0,
511 	0,
512 	0,
513 	1,
514 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
515 	0,
516 	0,
517 	0,
518 	SATAC_READ_LOG_EXT,
519 	0,
520 	0,
521 	0,
522 };
523 
524 /*
525  * ATAPI error recovery CDB
526  */
527 static const uint8_t sata_rqsense_cdb[SATA_ATAPI_RQSENSE_CDB_LEN] = {
528 	SCMD_REQUEST_SENSE,
529 	0,			/* Only fixed RQ format is supported */
530 	0,
531 	0,
532 	SATA_ATAPI_MIN_RQSENSE_LEN, /* Less data may be returned */
533 	0
534 };
535 
536 
537 /* Warlock directives */
538 
539 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
540 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
541 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
542 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
543 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
544 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
545 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
546 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
547 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_info::devi_state))
548 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
549 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
550 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
551 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
552 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
553     sata_hba_inst::satahba_scsi_tran))
554 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
555 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
556 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
557 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
558 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
559     sata_hba_inst::satahba_event_flags))
560 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
561     sata_cport_info::cport_devp))
562 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
563 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
564 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
565     sata_cport_info::cport_dev_type))
566 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
567 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
568     sata_cport_info::cport_state))
569 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
570 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
571     sata_pmport_info::pmport_state))
572 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_state))
573 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
574     sata_pmport_info::pmport_dev_type))
575 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
576 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
577     sata_pmport_info::pmport_sata_drive))
578 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
579     sata_pmport_info::pmport_tgtnode_clean))
580 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
581     sata_pmport_info::pmport_event_flags))
582 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
583 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
584 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
585 #ifdef SATA_DEBUG
586 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
587 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
588 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace))
589 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace_index))
590 #endif
591 
592 /* End of warlock directives */
593 
594 /* ************** loadable module configuration functions ************** */
595 
596 int
597 _init()
598 {
599 	int rval;
600 
601 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
602 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
603 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
604 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
605 	sata_trace_rbuf_alloc();
606 	if ((rval = mod_install(&modlinkage)) != 0) {
607 #ifdef SATA_DEBUG
608 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
609 #endif
610 		sata_trace_rbuf_free();
611 		mutex_destroy(&sata_log_mutex);
612 		cv_destroy(&sata_event_cv);
613 		mutex_destroy(&sata_event_mutex);
614 		mutex_destroy(&sata_mutex);
615 	}
616 	return (rval);
617 }
618 
619 int
620 _fini()
621 {
622 	int rval;
623 
624 	if ((rval = mod_remove(&modlinkage)) != 0)
625 		return (rval);
626 
627 	sata_trace_rbuf_free();
628 	mutex_destroy(&sata_log_mutex);
629 	cv_destroy(&sata_event_cv);
630 	mutex_destroy(&sata_event_mutex);
631 	mutex_destroy(&sata_mutex);
632 	return (rval);
633 }
634 
635 int
636 _info(struct modinfo *modinfop)
637 {
638 	return (mod_info(&modlinkage, modinfop));
639 }
640 
641 
642 
643 /* ********************* SATA HBA entry points ********************* */
644 
645 
646 /*
647  * Called by SATA HBA from _init().
648  * Registers HBA driver instance/sata framework pair with scsi framework, by
649  * calling scsi_hba_init().
650  *
651  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
652  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
653  * cb_ops pointer in SATA HBA driver dev_ops structure.
654  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
655  *
656  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
657  * driver.
658  */
659 int
660 sata_hba_init(struct modlinkage *modlp)
661 {
662 	int rval;
663 	struct dev_ops *hba_ops;
664 
665 	SATADBG1(SATA_DBG_HBA_IF, NULL,
666 	    "sata_hba_init: name %s \n",
667 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
668 	/*
669 	 * Fill-up cb_ops and dev_ops when necessary
670 	 */
671 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
672 	/*
673 	 * Provide pointer to SATA dev_ops
674 	 */
675 	hba_ops->devo_cb_ops = &sata_cb_ops;
676 
677 	/*
678 	 * Register SATA HBA with SCSI framework
679 	 */
680 	if ((rval = scsi_hba_init(modlp)) != 0) {
681 		SATADBG1(SATA_DBG_HBA_IF, NULL,
682 		    "sata_hba_init: scsi hba init failed\n", NULL);
683 		return (rval);
684 	}
685 
686 	return (0);
687 }
688 
689 
690 /* HBA attach stages */
691 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
692 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
693 #define	HBA_ATTACH_STAGE_SETUP		4
694 #define	HBA_ATTACH_STAGE_LINKED		8
695 
696 
697 /*
698  *
699  * Called from SATA HBA driver's attach routine to attach an instance of
700  * the HBA.
701  *
702  * For DDI_ATTACH command:
703  * sata_hba_inst structure is allocated here and initialized with pointers to
704  * SATA framework implementation of required scsi tran functions.
705  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
706  * to the soft structure (sata_hba_inst) allocated by SATA framework for
707  * SATA HBA instance related data.
708  * The scsi_tran's tran_hba_private field is used by SATA framework to
709  * store a pointer to per-HBA-instance of sata_hba_inst structure.
710  * The sata_hba_inst structure is cross-linked to scsi tran structure.
711  * Among other info, a pointer to sata_hba_tran structure is stored in
712  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
713  * linked together into the list, pointed to by sata_hba_list.
714  * On the first HBA instance attach the sata event thread is initialized.
715  * Attachment points are created for all SATA ports of the HBA being attached.
716  * All HBA instance's SATA ports are probed and type of plugged devices is
717  * determined. For each device of a supported type, a target node is created.
718  *
719  * DDI_SUCCESS is returned when attachment process is successful,
720  * DDI_FAILURE is returned otherwise.
721  *
722  * For DDI_RESUME command:
723  * Not implemented at this time (postponed until phase 2 of the development).
724  */
725 int
726 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
727     ddi_attach_cmd_t cmd)
728 {
729 	sata_hba_inst_t	*sata_hba_inst;
730 	scsi_hba_tran_t *scsi_tran = NULL;
731 	int hba_attach_state = 0;
732 	char taskq_name[MAXPATHLEN];
733 
734 	SATADBG3(SATA_DBG_HBA_IF, NULL,
735 	    "sata_hba_attach: node %s (%s%d)\n",
736 	    ddi_node_name(dip), ddi_driver_name(dip),
737 	    ddi_get_instance(dip));
738 
739 	if (cmd == DDI_RESUME) {
740 		/*
741 		 * Postponed until phase 2 of the development
742 		 */
743 		return (DDI_FAILURE);
744 	}
745 
746 	if (cmd != DDI_ATTACH) {
747 		return (DDI_FAILURE);
748 	}
749 
750 	/* cmd == DDI_ATTACH */
751 
752 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
753 		SATA_LOG_D((NULL, CE_WARN,
754 		    "sata_hba_attach: invalid sata_hba_tran"));
755 		return (DDI_FAILURE);
756 	}
757 	/*
758 	 * Allocate and initialize SCSI tran structure.
759 	 * SATA copy of tran_bus_config is provided to create port nodes.
760 	 */
761 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
762 	if (scsi_tran == NULL)
763 		return (DDI_FAILURE);
764 	/*
765 	 * Allocate soft structure for SATA HBA instance.
766 	 * There is a separate softstate for each HBA instance.
767 	 */
768 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
769 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
770 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
771 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
772 
773 	/*
774 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
775 	 * soft structure allocated by SATA framework for
776 	 * SATA HBA instance related data.
777 	 */
778 	scsi_tran->tran_hba_private	= sata_hba_inst;
779 	scsi_tran->tran_tgt_private	= NULL;
780 
781 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
782 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
783 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
784 
785 	scsi_tran->tran_start		= sata_scsi_start;
786 	scsi_tran->tran_reset		= sata_scsi_reset;
787 	scsi_tran->tran_abort		= sata_scsi_abort;
788 	scsi_tran->tran_getcap		= sata_scsi_getcap;
789 	scsi_tran->tran_setcap		= sata_scsi_setcap;
790 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
791 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
792 
793 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
794 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
795 
796 	scsi_tran->tran_reset_notify	= NULL;
797 	scsi_tran->tran_get_bus_addr	= NULL;
798 	scsi_tran->tran_quiesce		= NULL;
799 	scsi_tran->tran_unquiesce	= NULL;
800 	scsi_tran->tran_bus_reset	= NULL;
801 
802 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
803 	    scsi_tran, 0) != DDI_SUCCESS) {
804 #ifdef SATA_DEBUG
805 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
806 		    ddi_driver_name(dip), ddi_get_instance(dip));
807 #endif
808 		goto fail;
809 	}
810 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
811 
812 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
813 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
814 		    "sata", 1) != DDI_PROP_SUCCESS) {
815 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
816 			    "failed to create hba sata prop"));
817 			goto fail;
818 		}
819 	}
820 
821 	/*
822 	 * Save pointers in hba instance soft state.
823 	 */
824 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
825 	sata_hba_inst->satahba_tran = sata_tran;
826 	sata_hba_inst->satahba_dip = dip;
827 
828 	/*
829 	 * Create a task queue to handle emulated commands completion
830 	 * Use node name, dash, instance number as the queue name.
831 	 */
832 	taskq_name[0] = '\0';
833 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
834 	    sizeof (taskq_name));
835 	(void) snprintf(taskq_name + strlen(taskq_name),
836 	    sizeof (taskq_name) - strlen(taskq_name),
837 	    "-%d", DEVI(dip)->devi_instance);
838 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
839 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports * 4,
840 	    TASKQ_DYNAMIC);
841 
842 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
843 
844 	/*
845 	 * Create events thread if not created yet.
846 	 */
847 	sata_event_thread_control(1);
848 
849 	/*
850 	 * Link this hba instance into the list.
851 	 */
852 	mutex_enter(&sata_mutex);
853 
854 	if (sata_hba_list == NULL) {
855 		/*
856 		 * The first instance of HBA is attached.
857 		 * Set current/active default maximum NCQ/TCQ queue depth for
858 		 * all SATA devices. It is done here and now, to eliminate the
859 		 * possibility of the dynamic, programatic modification of the
860 		 * queue depth via global (and public) sata_max_queue_depth
861 		 * variable (this would require special handling in HBA drivers)
862 		 */
863 		sata_current_max_qdepth = sata_max_queue_depth;
864 		if (sata_current_max_qdepth > 32)
865 			sata_current_max_qdepth = 32;
866 		else if (sata_current_max_qdepth < 1)
867 			sata_current_max_qdepth = 1;
868 	}
869 
870 	sata_hba_inst->satahba_next = NULL;
871 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
872 	if (sata_hba_list == NULL) {
873 		sata_hba_list = sata_hba_inst;
874 	}
875 	if (sata_hba_list_tail != NULL) {
876 		sata_hba_list_tail->satahba_next = sata_hba_inst;
877 	}
878 	sata_hba_list_tail = sata_hba_inst;
879 	mutex_exit(&sata_mutex);
880 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
881 
882 	/*
883 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
884 	 * SATA HBA driver should not use its own open/close entry points.
885 	 *
886 	 * Make sure that instance number doesn't overflow
887 	 * when forming minor numbers.
888 	 */
889 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
890 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
891 	    INST2DEVCTL(ddi_get_instance(dip)),
892 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
893 #ifdef SATA_DEBUG
894 		cmn_err(CE_WARN, "sata_hba_attach: "
895 		    "cannot create devctl minor node");
896 #endif
897 		goto fail;
898 	}
899 
900 
901 	/*
902 	 * Set-up kstats here, if necessary.
903 	 * (postponed until future phase of the development).
904 	 */
905 
906 	/*
907 	 * Indicate that HBA is attached. This will enable events processing
908 	 * for this HBA.
909 	 */
910 	sata_hba_inst->satahba_attached = 1;
911 	/*
912 	 * Probe controller ports. This operation will describe a current
913 	 * controller/port/multipliers/device configuration and will create
914 	 * attachment points.
915 	 * We may end-up with just a controller with no devices attached.
916 	 * For the ports with a supported device attached, device target nodes
917 	 * are created and devices are initialized.
918 	 */
919 	sata_probe_ports(sata_hba_inst);
920 
921 	return (DDI_SUCCESS);
922 
923 fail:
924 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
925 		(void) sata_remove_hba_instance(dip);
926 		if (sata_hba_list == NULL)
927 			sata_event_thread_control(0);
928 	}
929 
930 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
931 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
932 		taskq_destroy(sata_hba_inst->satahba_taskq);
933 	}
934 
935 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
936 		(void) scsi_hba_detach(dip);
937 
938 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
939 		mutex_destroy(&sata_hba_inst->satahba_mutex);
940 		kmem_free((void *)sata_hba_inst,
941 		    sizeof (struct sata_hba_inst));
942 		scsi_hba_tran_free(scsi_tran);
943 	}
944 
945 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
946 	    ddi_driver_name(dip), ddi_get_instance(dip));
947 
948 	return (DDI_FAILURE);
949 }
950 
951 
952 /*
953  * Called by SATA HBA from to detach an instance of the driver.
954  *
955  * For DDI_DETACH command:
956  * Free local structures allocated for SATA HBA instance during
957  * sata_hba_attach processing.
958  *
959  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
960  *
961  * For DDI_SUSPEND command:
962  * Not implemented at this time (postponed until phase 2 of the development)
963  * Returnd DDI_SUCCESS.
964  *
965  * When the last HBA instance is detached, the event daemon is terminated.
966  *
967  * NOTE: Port multiplier is supported.
968  */
969 int
970 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
971 {
972 	dev_info_t	*tdip;
973 	sata_hba_inst_t	*sata_hba_inst;
974 	scsi_hba_tran_t *scsi_hba_tran;
975 	sata_cport_info_t *cportinfo;
976 	sata_pmult_info_t *pminfo;
977 	sata_drive_info_t *sdinfo;
978 	sata_device_t	sdevice;
979 	int ncport, npmport;
980 
981 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
982 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
983 
984 	switch (cmd) {
985 	case DDI_DETACH:
986 
987 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
988 			return (DDI_FAILURE);
989 
990 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
991 		if (sata_hba_inst == NULL)
992 			return (DDI_FAILURE);
993 
994 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
995 			sata_hba_inst->satahba_attached = 1;
996 			return (DDI_FAILURE);
997 		}
998 
999 		/*
1000 		 * Free all target nodes - at this point
1001 		 * devices should be at least offlined
1002 		 * otherwise scsi_hba_detach() should not be called.
1003 		 */
1004 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1005 		    ncport++) {
1006 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1007 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1008 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
1009 				if (sdinfo != NULL) {
1010 					tdip = sata_get_target_dip(dip,
1011 					    ncport, 0);
1012 					if (tdip != NULL) {
1013 						if (ndi_devi_offline(tdip,
1014 						    NDI_DEVI_REMOVE) !=
1015 						    NDI_SUCCESS) {
1016 							SATA_LOG_D((
1017 							    sata_hba_inst,
1018 							    CE_WARN,
1019 							    "sata_hba_detach: "
1020 							    "Target node not "
1021 							    "removed !"));
1022 							return (DDI_FAILURE);
1023 						}
1024 					}
1025 				}
1026 			} else { /* SATA_DTYPE_PMULT */
1027 				mutex_enter(&cportinfo->cport_mutex);
1028 				pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
1029 
1030 				if (pminfo == NULL) {
1031 					SATA_LOG_D((sata_hba_inst, CE_WARN,
1032 					    "sata_hba_detach: Port multiplier "
1033 					    "not ready yet!"));
1034 					mutex_exit(&cportinfo->cport_mutex);
1035 					return (DDI_FAILURE);
1036 				}
1037 
1038 				/*
1039 				 * Detach would fail if removal of any of the
1040 				 * target nodes is failed - albeit in that
1041 				 * case some of them may have been removed.
1042 				 */
1043 				for (npmport = 0; npmport < SATA_NUM_PMPORTS(
1044 				    sata_hba_inst, ncport); npmport++) {
1045 					tdip = sata_get_target_dip(dip, ncport,
1046 					    npmport);
1047 					if (tdip != NULL) {
1048 						if (ndi_devi_offline(tdip,
1049 						    NDI_DEVI_REMOVE) !=
1050 						    NDI_SUCCESS) {
1051 							SATA_LOG_D((
1052 							    sata_hba_inst,
1053 							    CE_WARN,
1054 							    "sata_hba_detach: "
1055 							    "Target node not "
1056 							    "removed !"));
1057 							mutex_exit(&cportinfo->
1058 							    cport_mutex);
1059 							return (DDI_FAILURE);
1060 						}
1061 					}
1062 				}
1063 				mutex_exit(&cportinfo->cport_mutex);
1064 			}
1065 		}
1066 		/*
1067 		 * Disable sata event daemon processing for this HBA
1068 		 */
1069 		sata_hba_inst->satahba_attached = 0;
1070 
1071 		/*
1072 		 * Remove event daemon thread, if it is last HBA instance.
1073 		 */
1074 
1075 		mutex_enter(&sata_mutex);
1076 		if (sata_hba_list->satahba_next == NULL) {
1077 			mutex_exit(&sata_mutex);
1078 			sata_event_thread_control(0);
1079 			mutex_enter(&sata_mutex);
1080 		}
1081 		mutex_exit(&sata_mutex);
1082 
1083 		/* Remove this HBA instance from the HBA list */
1084 		sata_remove_hba_instance(dip);
1085 
1086 		/*
1087 		 * At this point there should be no target nodes attached.
1088 		 * Detach and destroy device and port info structures.
1089 		 */
1090 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1091 		    ncport++) {
1092 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1093 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1094 				sdinfo =
1095 				    cportinfo->cport_devp.cport_sata_drive;
1096 				if (sdinfo != NULL) {
1097 					/* Release device structure */
1098 					kmem_free(sdinfo,
1099 					    sizeof (sata_drive_info_t));
1100 				}
1101 				/* Release cport info */
1102 				mutex_destroy(&cportinfo->cport_mutex);
1103 				kmem_free(cportinfo,
1104 				    sizeof (sata_cport_info_t));
1105 			} else { /* SATA_DTYPE_PMULT */
1106 				sdevice.satadev_addr.cport = (uint8_t)ncport;
1107 				sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
1108 				sata_free_pmult(sata_hba_inst, &sdevice);
1109 			}
1110 		}
1111 
1112 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
1113 
1114 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
1115 
1116 		taskq_destroy(sata_hba_inst->satahba_taskq);
1117 
1118 		mutex_destroy(&sata_hba_inst->satahba_mutex);
1119 		kmem_free((void *)sata_hba_inst,
1120 		    sizeof (struct sata_hba_inst));
1121 
1122 		return (DDI_SUCCESS);
1123 
1124 	case DDI_SUSPEND:
1125 		/*
1126 		 * Postponed until phase 2
1127 		 */
1128 		return (DDI_FAILURE);
1129 
1130 	default:
1131 		return (DDI_FAILURE);
1132 	}
1133 }
1134 
1135 
1136 /*
1137  * Called by an HBA drive from _fini() routine.
1138  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
1139  */
1140 void
1141 sata_hba_fini(struct modlinkage *modlp)
1142 {
1143 	SATADBG1(SATA_DBG_HBA_IF, NULL,
1144 	    "sata_hba_fini: name %s\n",
1145 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
1146 
1147 	scsi_hba_fini(modlp);
1148 }
1149 
1150 
1151 /*
1152  * Default open and close routine for sata_hba framework.
1153  *
1154  */
1155 /*
1156  * Open devctl node.
1157  *
1158  * Returns:
1159  * 0 if node was open successfully, error code otherwise.
1160  *
1161  *
1162  */
1163 
1164 static int
1165 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
1166 {
1167 #ifndef __lock_lint
1168 	_NOTE(ARGUNUSED(credp))
1169 #endif
1170 	int rv = 0;
1171 	dev_info_t *dip;
1172 	scsi_hba_tran_t *scsi_hba_tran;
1173 	sata_hba_inst_t	*sata_hba_inst;
1174 
1175 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
1176 
1177 	if (otyp != OTYP_CHR)
1178 		return (EINVAL);
1179 
1180 	dip = sata_devt_to_devinfo(*devp);
1181 	if (dip == NULL)
1182 		return (ENXIO);
1183 
1184 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1185 		return (ENXIO);
1186 
1187 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1188 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1189 		return (ENXIO);
1190 
1191 	mutex_enter(&sata_mutex);
1192 	if (flags & FEXCL) {
1193 		if (sata_hba_inst->satahba_open_flag != 0) {
1194 			rv = EBUSY;
1195 		} else {
1196 			sata_hba_inst->satahba_open_flag =
1197 			    SATA_DEVCTL_EXOPENED;
1198 		}
1199 	} else {
1200 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
1201 			rv = EBUSY;
1202 		} else {
1203 			sata_hba_inst->satahba_open_flag =
1204 			    SATA_DEVCTL_SOPENED;
1205 		}
1206 	}
1207 	mutex_exit(&sata_mutex);
1208 
1209 	return (rv);
1210 }
1211 
1212 
1213 /*
1214  * Close devctl node.
1215  * Returns:
1216  * 0 if node was closed successfully, error code otherwise.
1217  *
1218  */
1219 
1220 static int
1221 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
1222 {
1223 #ifndef __lock_lint
1224 	_NOTE(ARGUNUSED(credp))
1225 	_NOTE(ARGUNUSED(flag))
1226 #endif
1227 	dev_info_t *dip;
1228 	scsi_hba_tran_t *scsi_hba_tran;
1229 	sata_hba_inst_t	*sata_hba_inst;
1230 
1231 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
1232 
1233 	if (otyp != OTYP_CHR)
1234 		return (EINVAL);
1235 
1236 	dip = sata_devt_to_devinfo(dev);
1237 	if (dip == NULL)
1238 		return (ENXIO);
1239 
1240 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1241 		return (ENXIO);
1242 
1243 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1244 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1245 		return (ENXIO);
1246 
1247 	mutex_enter(&sata_mutex);
1248 	sata_hba_inst->satahba_open_flag = 0;
1249 	mutex_exit(&sata_mutex);
1250 	return (0);
1251 }
1252 
1253 
1254 
1255 /*
1256  * Standard IOCTL commands for SATA hotplugging.
1257  * Implemented DEVCTL_AP commands:
1258  * DEVCTL_AP_CONNECT
1259  * DEVCTL_AP_DISCONNECT
1260  * DEVCTL_AP_CONFIGURE
1261  * DEVCTL_UNCONFIGURE
1262  * DEVCTL_AP_CONTROL
1263  *
1264  * Commands passed to default ndi ioctl handler:
1265  * DEVCTL_DEVICE_GETSTATE
1266  * DEVCTL_DEVICE_ONLINE
1267  * DEVCTL_DEVICE_OFFLINE
1268  * DEVCTL_DEVICE_REMOVE
1269  * DEVCTL_DEVICE_INSERT
1270  * DEVCTL_BUS_GETSTATE
1271  *
1272  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1273  * if not.
1274  *
1275  * Returns:
1276  * 0 if successful,
1277  * error code if operation failed.
1278  *
1279  * Port Multiplier support is supported now.
1280  *
1281  * NOTE: qual should be SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT
1282  */
1283 
1284 static int
1285 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1286     int *rvalp)
1287 {
1288 #ifndef __lock_lint
1289 	_NOTE(ARGUNUSED(credp))
1290 	_NOTE(ARGUNUSED(rvalp))
1291 #endif
1292 	int rv = 0;
1293 	int32_t	comp_port = -1;
1294 	dev_info_t *dip;
1295 	devctl_ap_state_t ap_state;
1296 	struct devctl_iocdata *dcp = NULL;
1297 	scsi_hba_tran_t *scsi_hba_tran;
1298 	sata_hba_inst_t *sata_hba_inst;
1299 	sata_device_t sata_device;
1300 	sata_cport_info_t *cportinfo;
1301 	int cport, pmport, qual;
1302 	int rval = SATA_SUCCESS;
1303 
1304 	dip = sata_devt_to_devinfo(dev);
1305 	if (dip == NULL)
1306 		return (ENXIO);
1307 
1308 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1309 		return (ENXIO);
1310 
1311 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1312 	if (sata_hba_inst == NULL)
1313 		return (ENXIO);
1314 
1315 	if (sata_hba_inst->satahba_tran == NULL)
1316 		return (ENXIO);
1317 
1318 	switch (cmd) {
1319 
1320 	case DEVCTL_DEVICE_GETSTATE:
1321 	case DEVCTL_DEVICE_ONLINE:
1322 	case DEVCTL_DEVICE_OFFLINE:
1323 	case DEVCTL_DEVICE_REMOVE:
1324 	case DEVCTL_BUS_GETSTATE:
1325 		/*
1326 		 * There may be more cases that we want to pass to default
1327 		 * handler rather than fail them.
1328 		 */
1329 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1330 	}
1331 
1332 	/* read devctl ioctl data */
1333 	if (cmd != DEVCTL_AP_CONTROL) {
1334 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1335 			return (EFAULT);
1336 
1337 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1338 		    -1) {
1339 			if (dcp)
1340 				ndi_dc_freehdl(dcp);
1341 			return (EINVAL);
1342 		}
1343 
1344 		/*
1345 		 * According to SCSI_TO_SATA_ADDR_QUAL, qual should be either
1346 		 * SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT.
1347 		 */
1348 		cport = SCSI_TO_SATA_CPORT(comp_port);
1349 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1350 		qual = SCSI_TO_SATA_ADDR_QUAL(comp_port);
1351 
1352 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1353 		    qual) != 0) {
1354 			ndi_dc_freehdl(dcp);
1355 			return (EINVAL);
1356 		}
1357 
1358 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1359 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1360 		    cport_mutex);
1361 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1362 			/*
1363 			 * Cannot process ioctl request now. Come back later.
1364 			 */
1365 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1366 			    cport_mutex);
1367 			ndi_dc_freehdl(dcp);
1368 			return (EBUSY);
1369 		}
1370 		/* Block event processing for this port */
1371 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1372 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1373 
1374 		sata_device.satadev_addr.cport = cport;
1375 		sata_device.satadev_addr.pmport = pmport;
1376 		sata_device.satadev_addr.qual = qual;
1377 		sata_device.satadev_rev = SATA_DEVICE_REV;
1378 	}
1379 
1380 	switch (cmd) {
1381 
1382 	case DEVCTL_AP_DISCONNECT:
1383 
1384 		/*
1385 		 * Normally, cfgadm sata plugin will try to offline
1386 		 * (unconfigure) device before this request. Nevertheless,
1387 		 * if a device is still configured, we need to
1388 		 * attempt to offline and unconfigure device first, and we will
1389 		 * deactivate the port regardless of the unconfigure
1390 		 * operation results.
1391 		 *
1392 		 */
1393 		rv = sata_ioctl_disconnect(sata_hba_inst, &sata_device);
1394 
1395 		break;
1396 
1397 	case DEVCTL_AP_UNCONFIGURE:
1398 
1399 		/*
1400 		 * The unconfigure operation uses generic nexus operation to
1401 		 * offline a device. It leaves a target device node attached.
1402 		 * and obviously sata_drive_info attached as well, because
1403 		 * from the hardware point of view nothing has changed.
1404 		 */
1405 		rv = sata_ioctl_unconfigure(sata_hba_inst, &sata_device);
1406 		break;
1407 
1408 	case DEVCTL_AP_CONNECT:
1409 	{
1410 		/*
1411 		 * The sata cfgadm pluging will invoke this operation only if
1412 		 * port was found in the disconnect state (failed state
1413 		 * is also treated as the disconnected state).
1414 		 * If port activation is successful and a device is found
1415 		 * attached to the port, the initialization sequence is
1416 		 * executed to probe the port and attach
1417 		 * a device structure to a port structure. The device is not
1418 		 * set in configured state (system-wise) by this operation.
1419 		 */
1420 
1421 		rv = sata_ioctl_connect(sata_hba_inst, &sata_device);
1422 
1423 		break;
1424 	}
1425 
1426 	case DEVCTL_AP_CONFIGURE:
1427 	{
1428 		/*
1429 		 * A port may be in an active or shutdown state.
1430 		 * If port is in a failed state, operation is aborted.
1431 		 * If a port is in a shutdown state, sata_tran_port_activate()
1432 		 * is invoked prior to any other operation.
1433 		 *
1434 		 * Onlining the device involves creating a new target node.
1435 		 * If there is an old target node present (belonging to
1436 		 * previously removed device), the operation is aborted - the
1437 		 * old node has to be released and removed before configure
1438 		 * operation is attempted.
1439 		 */
1440 
1441 		rv = sata_ioctl_configure(sata_hba_inst, &sata_device);
1442 
1443 		break;
1444 	}
1445 
1446 	case DEVCTL_AP_GETSTATE:
1447 
1448 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1449 
1450 		ap_state.ap_last_change = (time_t)-1;
1451 		ap_state.ap_error_code = 0;
1452 		ap_state.ap_in_transition = 0;
1453 
1454 		/* Copy the return AP-state information to the user space */
1455 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1456 			rv = EFAULT;
1457 		}
1458 		break;
1459 
1460 	case DEVCTL_AP_CONTROL:
1461 	{
1462 		/*
1463 		 * Generic devctl for hardware specific functionality
1464 		 */
1465 		sata_ioctl_data_t	ioc;
1466 
1467 		ASSERT(dcp == NULL);
1468 
1469 		/* Copy in user ioctl data first */
1470 #ifdef _MULTI_DATAMODEL
1471 		if (ddi_model_convert_from(mode & FMODELS) ==
1472 		    DDI_MODEL_ILP32) {
1473 
1474 			sata_ioctl_data_32_t	ioc32;
1475 
1476 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1477 			    sizeof (ioc32), mode) != 0) {
1478 				rv = EFAULT;
1479 				break;
1480 			}
1481 			ioc.cmd 	= (uint_t)ioc32.cmd;
1482 			ioc.port	= (uint_t)ioc32.port;
1483 			ioc.get_size	= (uint_t)ioc32.get_size;
1484 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1485 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1486 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1487 		} else
1488 #endif /* _MULTI_DATAMODEL */
1489 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1490 		    mode) != 0) {
1491 			return (EFAULT);
1492 		}
1493 
1494 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1495 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1496 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1497 
1498 		/*
1499 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1500 		 * a 32-bit number.
1501 		 */
1502 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1503 			return (EINVAL);
1504 		}
1505 		/* validate address */
1506 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1507 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1508 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1509 
1510 		SATADBG3(SATA_DBG_IOCTL_IF, sata_hba_inst,
1511 		    "sata_hba_ioctl: target port is %d:%d (%d)",
1512 		    cport, pmport, qual);
1513 
1514 		if (sata_validate_sata_address(sata_hba_inst, cport,
1515 		    pmport, qual) != 0)
1516 			return (EINVAL);
1517 
1518 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1519 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1520 		    cport_mutex);
1521 		/* Is the port locked by event processing daemon ? */
1522 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1523 			/*
1524 			 * Cannot process ioctl request now. Come back later
1525 			 */
1526 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1527 			    cport_mutex);
1528 			return (EBUSY);
1529 		}
1530 		/* Block event processing for this port */
1531 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1532 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1533 
1534 
1535 		sata_device.satadev_addr.cport = cport;
1536 		sata_device.satadev_addr.pmport = pmport;
1537 		sata_device.satadev_addr.qual = qual;
1538 		sata_device.satadev_rev = SATA_DEVICE_REV;
1539 
1540 		switch (ioc.cmd) {
1541 
1542 		case SATA_CFGA_RESET_PORT:
1543 			/*
1544 			 * There is no protection for configured device.
1545 			 */
1546 			rv = sata_ioctl_reset_port(sata_hba_inst, &sata_device);
1547 			break;
1548 
1549 		case SATA_CFGA_RESET_DEVICE:
1550 			/*
1551 			 * There is no protection for configured device.
1552 			 */
1553 			rv = sata_ioctl_reset_device(sata_hba_inst,
1554 			    &sata_device);
1555 			break;
1556 
1557 		case SATA_CFGA_RESET_ALL:
1558 			/*
1559 			 * There is no protection for configured devices.
1560 			 */
1561 			rv = sata_ioctl_reset_all(sata_hba_inst);
1562 			/*
1563 			 * We return here, because common return is for
1564 			 * a single port operation - we have already unlocked
1565 			 * all ports and no dc handle was allocated.
1566 			 */
1567 			return (rv);
1568 
1569 		case SATA_CFGA_PORT_DEACTIVATE:
1570 			/*
1571 			 * Arbitrarily unconfigure attached device, if any.
1572 			 * Even if the unconfigure fails, proceed with the
1573 			 * port deactivation.
1574 			 */
1575 			rv = sata_ioctl_deactivate(sata_hba_inst, &sata_device);
1576 
1577 			break;
1578 
1579 		case SATA_CFGA_PORT_ACTIVATE:
1580 
1581 			rv = sata_ioctl_activate(sata_hba_inst, &sata_device);
1582 			break;
1583 
1584 		case SATA_CFGA_PORT_SELF_TEST:
1585 
1586 			rv = sata_ioctl_port_self_test(sata_hba_inst,
1587 			    &sata_device);
1588 			break;
1589 
1590 		case SATA_CFGA_GET_DEVICE_PATH:
1591 
1592 			rv = sata_ioctl_get_device_path(sata_hba_inst,
1593 			    &sata_device, &ioc, mode);
1594 			break;
1595 
1596 		case SATA_CFGA_GET_AP_TYPE:
1597 
1598 			rv = sata_ioctl_get_ap_type(sata_hba_inst,
1599 			    &sata_device, &ioc, mode);
1600 			break;
1601 
1602 		case SATA_CFGA_GET_MODEL_INFO:
1603 
1604 			rv = sata_ioctl_get_model_info(sata_hba_inst,
1605 			    &sata_device, &ioc, mode);
1606 			break;
1607 
1608 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
1609 
1610 			rv = sata_ioctl_get_revfirmware_info(sata_hba_inst,
1611 			    &sata_device, &ioc, mode);
1612 			break;
1613 
1614 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
1615 
1616 			rv = sata_ioctl_get_serialnumber_info(sata_hba_inst,
1617 			    &sata_device, &ioc, mode);
1618 			break;
1619 
1620 		default:
1621 			rv = EINVAL;
1622 			break;
1623 
1624 		} /* End of DEVCTL_AP_CONTROL cmd switch */
1625 
1626 		break;
1627 	}
1628 
1629 	default:
1630 	{
1631 		/*
1632 		 * If we got here, we got an IOCTL that SATA HBA Framework
1633 		 * does not recognize. Pass ioctl to HBA driver, in case
1634 		 * it could process it.
1635 		 */
1636 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
1637 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
1638 
1639 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1640 		    "IOCTL 0x%2x not supported in SATA framework, "
1641 		    "passthrough to HBA", cmd);
1642 
1643 		if (sata_tran->sata_tran_ioctl == NULL) {
1644 			rv = EINVAL;
1645 			break;
1646 		}
1647 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
1648 		if (rval != 0) {
1649 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1650 			    "IOCTL 0x%2x failed in HBA", cmd);
1651 			rv = rval;
1652 		}
1653 		break;
1654 	}
1655 
1656 	} /* End of main IOCTL switch */
1657 
1658 	if (dcp) {
1659 		ndi_dc_freehdl(dcp);
1660 	}
1661 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1662 	cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
1663 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1664 
1665 	return (rv);
1666 }
1667 
1668 
1669 /*
1670  * Create error retrieval sata packet
1671  *
1672  * A sata packet is allocated and set-up to contain specified error retrieval
1673  * command and appropriate dma-able data buffer.
1674  * No association with any scsi packet is made and no callback routine is
1675  * specified.
1676  *
1677  * Returns a pointer to sata packet upon successfull packet creation.
1678  * Returns NULL, if packet cannot be created.
1679  */
1680 sata_pkt_t *
1681 sata_get_error_retrieval_pkt(dev_info_t *dip, sata_device_t *sata_device,
1682     int pkt_type)
1683 {
1684 	sata_hba_inst_t	*sata_hba_inst;
1685 	sata_pkt_txlate_t *spx;
1686 	sata_pkt_t *spkt;
1687 	sata_drive_info_t *sdinfo;
1688 
1689 	mutex_enter(&sata_mutex);
1690 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1691 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1692 		if (SATA_DIP(sata_hba_inst) == dip)
1693 			break;
1694 	}
1695 	mutex_exit(&sata_mutex);
1696 	ASSERT(sata_hba_inst != NULL);
1697 
1698 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
1699 	if (sdinfo == NULL) {
1700 		sata_log(sata_hba_inst, CE_WARN,
1701 		    "sata: error recovery request for non-attached device at "
1702 		    "cport %d", sata_device->satadev_addr.cport);
1703 		return (NULL);
1704 	}
1705 
1706 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1707 	spx->txlt_sata_hba_inst = sata_hba_inst;
1708 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
1709 	spkt = sata_pkt_alloc(spx, NULL);
1710 	if (spkt == NULL) {
1711 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1712 		return (NULL);
1713 	}
1714 	/* address is needed now */
1715 	spkt->satapkt_device.satadev_addr = sata_device->satadev_addr;
1716 
1717 	switch (pkt_type) {
1718 	case SATA_ERR_RETR_PKT_TYPE_NCQ:
1719 		if (sata_ncq_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1720 			return (spkt);
1721 		break;
1722 
1723 	case SATA_ERR_RETR_PKT_TYPE_ATAPI:
1724 		if (sata_atapi_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1725 			return (spkt);
1726 		break;
1727 
1728 	default:
1729 		break;
1730 	}
1731 
1732 	sata_pkt_free(spx);
1733 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1734 	return (NULL);
1735 
1736 }
1737 
1738 
1739 /*
1740  * Free error retrieval sata packet
1741  *
1742  * Free sata packet and any associated resources allocated previously by
1743  * sata_get_error_retrieval_pkt().
1744  *
1745  * Void return.
1746  */
1747 void
1748 sata_free_error_retrieval_pkt(sata_pkt_t *sata_pkt)
1749 {
1750 	sata_pkt_txlate_t *spx =
1751 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1752 
1753 	ASSERT(sata_pkt != NULL);
1754 
1755 	sata_free_local_buffer(spx);
1756 	sata_pkt_free(spx);
1757 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1758 
1759 }
1760 
1761 /*
1762  * Create READ PORT MULTIPLIER and WRITE PORT MULTIPLIER sata packet
1763  *
1764  * No association with any scsi packet is made and no callback routine is
1765  * specified.
1766  *
1767  * Returns a pointer to sata packet upon successfull packet creation.
1768  * Returns NULL, if packet cannot be created.
1769  *
1770  * NOTE: Input/Output value includes 64 bits accoring to SATA Spec 2.6,
1771  * only lower 32 bits are available currently.
1772  */
1773 sata_pkt_t *
1774 sata_get_rdwr_pmult_pkt(dev_info_t *dip, sata_device_t *sd,
1775     uint8_t regn, uint32_t regv, uint32_t type)
1776 {
1777 	sata_hba_inst_t	*sata_hba_inst;
1778 	sata_pkt_txlate_t *spx;
1779 	sata_pkt_t *spkt;
1780 	sata_cmd_t *scmd;
1781 
1782 	/* Only READ/WRITE commands are accepted. */
1783 	ASSERT(type == SATA_RDWR_PMULT_PKT_TYPE_READ ||
1784 	    type == SATA_RDWR_PMULT_PKT_TYPE_WRITE);
1785 
1786 	mutex_enter(&sata_mutex);
1787 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1788 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1789 		if (SATA_DIP(sata_hba_inst) == dip)
1790 			break;
1791 	}
1792 	mutex_exit(&sata_mutex);
1793 	ASSERT(sata_hba_inst != NULL);
1794 
1795 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1796 	spx->txlt_sata_hba_inst = sata_hba_inst;
1797 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
1798 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
1799 	if (spkt == NULL) {
1800 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1801 		return (NULL);
1802 	}
1803 
1804 	/*
1805 	 * NOTE: We need to send this command to the port multiplier,
1806 	 * that means send to SATA_PMULT_HOSTPORT(0xf) pmport
1807 	 *
1808 	 * sata_device contains the address of actual target device, and the
1809 	 * pmport number in the command comes from the sata_device structure.
1810 	 */
1811 	spkt->satapkt_device.satadev_addr = sd->satadev_addr;
1812 	spkt->satapkt_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
1813 	spkt->satapkt_device.satadev_addr.qual = SATA_ADDR_PMULT;
1814 
1815 	/* Fill sata_pkt */
1816 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING;
1817 	spkt->satapkt_comp = NULL; /* Synchronous mode, no callback */
1818 	spkt->satapkt_time = 10; /* Timeout 10s */
1819 
1820 	/* Build READ PORT MULTIPLIER cmd in the sata_pkt */
1821 	scmd = &spkt->satapkt_cmd;
1822 	scmd->satacmd_features_reg = regn & 0xff;
1823 	scmd->satacmd_features_reg_ext = (regn >> 8) & 0xff;
1824 	scmd->satacmd_device_reg = sd->satadev_addr.pmport;
1825 	scmd->satacmd_addr_type = 0;		/* N/A */
1826 
1827 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
1828 
1829 	if (type == SATA_RDWR_PMULT_PKT_TYPE_READ) {
1830 		scmd->satacmd_cmd_reg = SATAC_READ_PORTMULT;
1831 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
1832 		scmd->satacmd_flags.sata_special_regs = 1;
1833 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
1834 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
1835 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
1836 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
1837 	} else if (type == SATA_RDWR_PMULT_PKT_TYPE_WRITE) {
1838 		scmd->satacmd_cmd_reg = SATAC_WRITE_PORTMULT;
1839 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
1840 		scmd->satacmd_sec_count_lsb = regv & 0xff;
1841 		scmd->satacmd_lba_low_lsb = regv >> 8 & 0xff;
1842 		scmd->satacmd_lba_mid_lsb = regv >> 16 & 0xff;
1843 		scmd->satacmd_lba_high_lsb = regv >> 24 & 0xff;
1844 	}
1845 
1846 	return (spkt);
1847 }
1848 
1849 /*
1850  * Free sata packet and any associated resources allocated previously by
1851  * sata_get_rdwr_pmult_pkt().
1852  *
1853  * Void return.
1854  */
1855 void
1856 sata_free_rdwr_pmult_pkt(sata_pkt_t *sata_pkt)
1857 {
1858 	sata_pkt_txlate_t *spx =
1859 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1860 
1861 	/* Free allocated resources */
1862 	sata_pkt_free(spx);
1863 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1864 }
1865 
1866 /*
1867  * Register a port multiplier to framework.
1868  * 1) Store the GSCR values in the previous allocated pmult_info strctures.
1869  * 2) Search in the blacklist and update the number of the device ports of the
1870  * port multiplier.
1871  *
1872  * Void return.
1873  */
1874 void
1875 sata_register_pmult(dev_info_t *dip, sata_device_t *sd, sata_pmult_gscr_t *sg)
1876 {
1877 	sata_hba_inst_t *sata_hba_inst = NULL;
1878 	sata_pmult_info_t *pmultinfo;
1879 	sata_pmult_bl_t *blp;
1880 	int cport = sd->satadev_addr.cport;
1881 
1882 	mutex_enter(&sata_mutex);
1883 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1884 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1885 		if (SATA_DIP(sata_hba_inst) == dip)
1886 			if (sata_hba_inst->satahba_attached == 1)
1887 				break;
1888 	}
1889 	mutex_exit(&sata_mutex);
1890 	/* HBA not attached? */
1891 	if (sata_hba_inst == NULL)
1892 		return;
1893 
1894 	/* Number of pmports */
1895 	sd->satadev_add_info = sg->gscr2 & SATA_PMULT_PORTNUM_MASK;
1896 
1897 	/* Check the blacklist */
1898 	for (blp = sata_pmult_blacklist; blp->bl_gscr0; blp++) {
1899 		if (sg->gscr0 != blp->bl_gscr0 && blp->bl_gscr0)
1900 			continue;
1901 		if (sg->gscr1 != blp->bl_gscr1 && blp->bl_gscr1)
1902 			continue;
1903 		if (sg->gscr2 != blp->bl_gscr2 && blp->bl_gscr2)
1904 			continue;
1905 
1906 		cmn_err(CE_WARN, "!Port multiplier is on the blacklist.");
1907 		sd->satadev_add_info = blp->bl_flags;
1908 		break;
1909 	}
1910 
1911 	/* Register the port multiplier GSCR */
1912 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1913 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
1914 	if (pmultinfo != NULL) {
1915 		pmultinfo->pmult_gscr = *sg;
1916 		pmultinfo->pmult_num_dev_ports =
1917 		    sd->satadev_add_info & SATA_PMULT_PORTNUM_MASK;
1918 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
1919 		    "Port multiplier registered at port %d", cport);
1920 	}
1921 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1922 }
1923 
1924 /*
1925  * sata_name_child is for composing the name of the node
1926  * the format of the name is "target,0".
1927  */
1928 static int
1929 sata_name_child(dev_info_t *dip, char *name, int namelen)
1930 {
1931 	int target;
1932 
1933 	target = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1934 	    DDI_PROP_DONTPASS, "target", -1);
1935 	if (target == -1)
1936 		return (DDI_FAILURE);
1937 	(void) snprintf(name, namelen, "%x,0", target);
1938 	return (DDI_SUCCESS);
1939 }
1940 
1941 
1942 
1943 /* ****************** SCSA required entry points *********************** */
1944 
1945 /*
1946  * Implementation of scsi tran_tgt_init.
1947  * sata_scsi_tgt_init() initializes scsi_device structure
1948  *
1949  * If successful, DDI_SUCCESS is returned.
1950  * DDI_FAILURE is returned if addressed device does not exist
1951  */
1952 
1953 static int
1954 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1955     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1956 {
1957 #ifndef __lock_lint
1958 	_NOTE(ARGUNUSED(hba_dip))
1959 	_NOTE(ARGUNUSED(tgt_dip))
1960 #endif
1961 	sata_device_t		sata_device;
1962 	sata_drive_info_t	*sdinfo;
1963 	struct sata_id		*sid;
1964 	sata_hba_inst_t		*sata_hba_inst;
1965 	char			model[SATA_ID_MODEL_LEN + 1];
1966 	char			fw[SATA_ID_FW_LEN + 1];
1967 	char			*vid, *pid;
1968 	int			i;
1969 
1970 	/*
1971 	 * Fail tran_tgt_init for .conf stub node
1972 	 */
1973 	if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
1974 		(void) ndi_merge_node(tgt_dip, sata_name_child);
1975 		ddi_set_name_addr(tgt_dip, NULL);
1976 		return (DDI_FAILURE);
1977 	}
1978 
1979 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1980 
1981 	/* Validate scsi device address */
1982 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1983 	    &sata_device) != 0)
1984 		return (DDI_FAILURE);
1985 
1986 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1987 	    sata_device.satadev_addr.cport)));
1988 
1989 	/* sata_device now contains a valid sata address */
1990 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1991 	if (sdinfo == NULL) {
1992 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1993 		    sata_device.satadev_addr.cport)));
1994 		return (DDI_FAILURE);
1995 	}
1996 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1997 	    sata_device.satadev_addr.cport)));
1998 
1999 	/*
2000 	 * Check if we need to create a legacy devid (i.e cmdk style) for
2001 	 * the target disks.
2002 	 *
2003 	 * HBA devinfo node will have the property "use-cmdk-devid-format"
2004 	 * if we need to create cmdk-style devid for all the disk devices
2005 	 * attached to this controller. This property may have been set
2006 	 * from HBA driver's .conf file or by the HBA driver in its
2007 	 * attach(9F) function.
2008 	 */
2009 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2010 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2011 	    "use-cmdk-devid-format", 0) == 1)) {
2012 		/* register a legacy devid for this target node */
2013 		sata_target_devid_register(tgt_dip, sdinfo);
2014 	}
2015 
2016 
2017 	/*
2018 	 * 'Identify Device Data' does not always fit in standard SCSI
2019 	 * INQUIRY data, so establish INQUIRY_* properties with full-form
2020 	 * of information.
2021 	 */
2022 	sid = &sdinfo->satadrv_id;
2023 #ifdef	_LITTLE_ENDIAN
2024 	swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
2025 	swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
2026 #else	/* _LITTLE_ENDIAN */
2027 	bcopy(sid->ai_model, model, SATA_ID_MODEL_LEN);
2028 	bcopy(sid->ai_fw, fw, SATA_ID_FW_LEN);
2029 #endif	/* _LITTLE_ENDIAN */
2030 	model[SATA_ID_MODEL_LEN] = 0;
2031 	fw[SATA_ID_FW_LEN] = 0;
2032 
2033 	/* split model into into vid/pid */
2034 	for (i = 0, pid = model; i < SATA_ID_MODEL_LEN; i++, pid++)
2035 		if ((*pid == ' ') || (*pid == '\t'))
2036 			break;
2037 	if (i < SATA_ID_MODEL_LEN) {
2038 		vid = model;
2039 		*pid++ = 0;		/* terminate vid, establish pid */
2040 	} else {
2041 		vid = NULL;		/* vid will stay "ATA     " */
2042 		pid = model;		/* model is all pid */
2043 	}
2044 
2045 	if (vid)
2046 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_VENDOR_ID,
2047 		    vid, strlen(vid));
2048 	if (pid)
2049 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_PRODUCT_ID,
2050 		    pid, strlen(pid));
2051 	(void) scsi_device_prop_update_inqstring(sd, INQUIRY_REVISION_ID,
2052 	    fw, strlen(fw));
2053 
2054 	return (DDI_SUCCESS);
2055 }
2056 
2057 /*
2058  * Implementation of scsi tran_tgt_probe.
2059  * Probe target, by calling default scsi routine scsi_hba_probe()
2060  */
2061 static int
2062 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
2063 {
2064 	sata_hba_inst_t *sata_hba_inst =
2065 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
2066 	int rval;
2067 	uint32_t pm_cap;
2068 
2069 	rval = scsi_hba_probe(sd, callback);
2070 	pm_cap = SATA_CAP_POWER_CONDITON | SATA_CAP_SMART_PAGE |
2071 	    SATA_CAP_LOG_SENSE;
2072 
2073 	if (rval == SCSIPROBE_EXISTS) {
2074 		/*
2075 		 * Set property "pm-capable" on the target device node, so that
2076 		 * the target driver will not try to fetch scsi cycle counters
2077 		 * before enabling device power-management.
2078 		 */
2079 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
2080 		    "pm-capable", pm_cap)) != DDI_PROP_SUCCESS) {
2081 			sata_log(sata_hba_inst, CE_WARN,
2082 			    "SATA device at port %d: "
2083 			    "will not be power-managed ",
2084 			    SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
2085 			SATA_LOG_D((sata_hba_inst, CE_WARN,
2086 			    "failure updating pm-capable property"));
2087 		}
2088 	}
2089 	return (rval);
2090 }
2091 
2092 /*
2093  * Implementation of scsi tran_tgt_free.
2094  * Release all resources allocated for scsi_device
2095  */
2096 static void
2097 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2098     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2099 {
2100 #ifndef __lock_lint
2101 	_NOTE(ARGUNUSED(hba_dip))
2102 #endif
2103 	sata_device_t		sata_device;
2104 	sata_drive_info_t	*sdinfo;
2105 	sata_hba_inst_t		*sata_hba_inst;
2106 	ddi_devid_t		devid;
2107 
2108 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2109 
2110 	/* Validate scsi device address */
2111 	/*
2112 	 * Note: tgt_free relates to the SCSA view of a device. If called, there
2113 	 * was a device at this address, so even if the sata framework internal
2114 	 * resources were alredy released because a device was detached,
2115 	 * this function should be executed as long as its actions do
2116 	 * not require the internal sata view of a device and the address
2117 	 * refers to a valid sata address.
2118 	 * Validating the address here means that we do not trust SCSA...
2119 	 */
2120 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2121 	    &sata_device) == -1)
2122 		return;
2123 
2124 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2125 	    sata_device.satadev_addr.cport)));
2126 
2127 	/* sata_device now should contain a valid sata address */
2128 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2129 	if (sdinfo == NULL) {
2130 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2131 		    sata_device.satadev_addr.cport)));
2132 		return;
2133 	}
2134 	/*
2135 	 * We did not allocate any resources in sata_scsi_tgt_init()
2136 	 * other than few properties.
2137 	 * Free them.
2138 	 */
2139 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2140 	    sata_device.satadev_addr.cport)));
2141 	(void) ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "pm-capable");
2142 
2143 	/*
2144 	 * If devid was previously created but not freed up from
2145 	 * sd(7D) driver (i.e during detach(9F)) then do it here.
2146 	 */
2147 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2148 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2149 	    "use-cmdk-devid-format", 0) == 1) &&
2150 	    (ddi_devid_get(tgt_dip, &devid) == DDI_SUCCESS)) {
2151 		ddi_devid_unregister(tgt_dip);
2152 		ddi_devid_free(devid);
2153 	}
2154 }
2155 
2156 /*
2157  * Implementation of scsi tran_init_pkt
2158  * Upon successful return, scsi pkt buffer has DMA resources allocated.
2159  *
2160  * It seems that we should always allocate pkt, even if the address is
2161  * for non-existing device - just use some default for dma_attr.
2162  * The reason is that there is no way to communicate this to a caller here.
2163  * Subsequent call to sata_scsi_start may fail appropriately.
2164  * Simply returning NULL does not seem to discourage a target driver...
2165  *
2166  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
2167  */
2168 static struct scsi_pkt *
2169 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
2170     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
2171     int (*callback)(caddr_t), caddr_t arg)
2172 {
2173 	sata_hba_inst_t *sata_hba_inst =
2174 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2175 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
2176 	sata_device_t sata_device;
2177 	sata_drive_info_t *sdinfo;
2178 	sata_pkt_txlate_t *spx;
2179 	ddi_dma_attr_t cur_dma_attr;
2180 	int rval;
2181 	boolean_t new_pkt = TRUE;
2182 
2183 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
2184 
2185 	/*
2186 	 * We need to translate the address, even if it could be
2187 	 * a bogus one, for a non-existing device
2188 	 */
2189 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
2190 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
2191 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2192 	sata_device.satadev_rev = SATA_DEVICE_REV;
2193 
2194 	if (pkt == NULL) {
2195 		/*
2196 		 * Have to allocate a brand new scsi packet.
2197 		 * We need to operate with auto request sense enabled.
2198 		 */
2199 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
2200 		    MAX(statuslen, SATA_MAX_SENSE_LEN),
2201 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
2202 
2203 		if (pkt == NULL)
2204 			return (NULL);
2205 
2206 		/* Fill scsi packet structure */
2207 		pkt->pkt_comp		= (void (*)())NULL;
2208 		pkt->pkt_time		= 0;
2209 		pkt->pkt_resid		= 0;
2210 		pkt->pkt_statistics	= 0;
2211 		pkt->pkt_reason		= 0;
2212 
2213 		/*
2214 		 * pkt_hba_private will point to sata pkt txlate structure
2215 		 */
2216 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2217 		bzero(spx, sizeof (sata_pkt_txlate_t));
2218 
2219 		spx->txlt_scsi_pkt = pkt;
2220 		spx->txlt_sata_hba_inst = sata_hba_inst;
2221 
2222 		/* Allocate sata_pkt */
2223 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
2224 		if (spx->txlt_sata_pkt == NULL) {
2225 			/* Could not allocate sata pkt */
2226 			scsi_hba_pkt_free(ap, pkt);
2227 			return (NULL);
2228 		}
2229 		/* Set sata address */
2230 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
2231 		    sata_device.satadev_addr;
2232 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
2233 		    sata_device.satadev_rev;
2234 
2235 		if ((bp == NULL) || (bp->b_bcount == 0))
2236 			return (pkt);
2237 
2238 		spx->txlt_total_residue = bp->b_bcount;
2239 	} else {
2240 		new_pkt = FALSE;
2241 		/*
2242 		 * Packet was preallocated/initialized by previous call
2243 		 */
2244 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2245 
2246 		if ((bp == NULL) || (bp->b_bcount == 0)) {
2247 			return (pkt);
2248 		}
2249 
2250 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
2251 	}
2252 
2253 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
2254 
2255 	/*
2256 	 * We use an adjusted version of the dma_attr, to account
2257 	 * for device addressing limitations.
2258 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
2259 	 * happen when a device is not yet configured.
2260 	 */
2261 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2262 	    sata_device.satadev_addr.cport)));
2263 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2264 	    &spx->txlt_sata_pkt->satapkt_device);
2265 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
2266 	sata_adjust_dma_attr(sdinfo,
2267 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
2268 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2269 	    sata_device.satadev_addr.cport)));
2270 	/*
2271 	 * Allocate necessary DMA resources for the packet's data buffer
2272 	 * NOTE:
2273 	 * In case of read/write commands, DMA resource allocation here is
2274 	 * based on the premise that the transfer length specified in
2275 	 * the read/write scsi cdb will match exactly DMA resources -
2276 	 * returning correct packet residue is crucial.
2277 	 */
2278 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
2279 	    &cur_dma_attr)) != DDI_SUCCESS) {
2280 		/*
2281 		 * If a DMA allocation request fails with
2282 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2283 		 * bioerror(9F) with bp and an error code of EFAULT.
2284 		 * If a DMA allocation request fails with
2285 		 * DDI_DMA_TOOBIG, indicate the error by calling
2286 		 * bioerror(9F) with bp and an error code of EINVAL.
2287 		 * For DDI_DMA_NORESOURCES, we may have some of them allocated.
2288 		 * Request may be repeated later - there is no real error.
2289 		 */
2290 		switch (rval) {
2291 		case DDI_DMA_NORESOURCES:
2292 			bioerror(bp, 0);
2293 			break;
2294 		case DDI_DMA_NOMAPPING:
2295 		case DDI_DMA_BADATTR:
2296 			bioerror(bp, EFAULT);
2297 			break;
2298 		case DDI_DMA_TOOBIG:
2299 		default:
2300 			bioerror(bp, EINVAL);
2301 			break;
2302 		}
2303 		if (new_pkt == TRUE) {
2304 			/*
2305 			 * Since this is a new packet, we can clean-up
2306 			 * everything
2307 			 */
2308 			sata_scsi_destroy_pkt(ap, pkt);
2309 		} else {
2310 			/*
2311 			 * This is a re-used packet. It will be target driver's
2312 			 * responsibility to eventually destroy it (which
2313 			 * will free allocated resources).
2314 			 * Here, we just "complete" the request, leaving
2315 			 * allocated resources intact, so the request may
2316 			 * be retried.
2317 			 */
2318 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2319 			sata_pkt_free(spx);
2320 		}
2321 		return (NULL);
2322 	}
2323 	/* Set number of bytes that are not yet accounted for */
2324 	pkt->pkt_resid = spx->txlt_total_residue;
2325 	ASSERT(pkt->pkt_resid >= 0);
2326 
2327 	return (pkt);
2328 }
2329 
2330 /*
2331  * Implementation of scsi tran_start.
2332  * Translate scsi cmd into sata operation and return status.
2333  * ATAPI CDBs are passed to ATAPI devices - the device determines what commands
2334  * are supported.
2335  * For SATA hard disks, supported scsi commands:
2336  * SCMD_INQUIRY
2337  * SCMD_TEST_UNIT_READY
2338  * SCMD_START_STOP
2339  * SCMD_READ_CAPACITY
2340  * SCMD_REQUEST_SENSE
2341  * SCMD_LOG_SENSE_G1
2342  * SCMD_LOG_SELECT_G1
2343  * SCMD_MODE_SENSE	(specific pages)
2344  * SCMD_MODE_SENSE_G1	(specific pages)
2345  * SCMD_MODE_SELECT	(specific pages)
2346  * SCMD_MODE_SELECT_G1	(specific pages)
2347  * SCMD_SYNCHRONIZE_CACHE
2348  * SCMD_SYNCHRONIZE_CACHE_G1
2349  * SCMD_READ
2350  * SCMD_READ_G1
2351  * SCMD_READ_G4
2352  * SCMD_READ_G5
2353  * SCMD_WRITE
2354  * SCMD_WRITE_BUFFER
2355  * SCMD_WRITE_G1
2356  * SCMD_WRITE_G4
2357  * SCMD_WRITE_G5
2358  * SCMD_SEEK		(noop)
2359  * SCMD_SDIAG
2360  *
2361  * All other commands are rejected as unsupported.
2362  *
2363  * Returns:
2364  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2365  * for execution. TRAN_ACCEPT may be returned also if device was removed but
2366  * a callback could be scheduled.
2367  * TRAN_BADPKT if cmd was directed to invalid address.
2368  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2369  * some unspecified error. TRAN_FATAL_ERROR may be also returned if a device
2370  * was removed and there was no callback specified in scsi pkt.
2371  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2372  * framework was busy performing some other operation(s).
2373  *
2374  */
2375 static int
2376 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2377 {
2378 	sata_hba_inst_t *sata_hba_inst =
2379 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2380 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2381 	sata_device_t *sdevice = &spx->txlt_sata_pkt->satapkt_device;
2382 	sata_drive_info_t *sdinfo;
2383 	struct buf *bp;
2384 	uint8_t cport, pmport;
2385 	boolean_t dev_gone = B_FALSE;
2386 	int rval;
2387 
2388 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2389 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2390 
2391 	ASSERT(spx != NULL &&
2392 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2393 
2394 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2395 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2396 
2397 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2398 
2399 	if (sdevice->satadev_addr.qual == SATA_ADDR_DCPORT) {
2400 		sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2401 		if (sdinfo == NULL ||
2402 		    SATA_CPORT_INFO(sata_hba_inst, cport)->
2403 		    cport_tgtnode_clean == B_FALSE ||
2404 		    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2405 			dev_gone = B_TRUE;
2406 		}
2407 	} else if (sdevice->satadev_addr.qual == SATA_ADDR_DPMPORT) {
2408 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
2409 		    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
2410 		    cport) == NULL) {
2411 			dev_gone = B_TRUE;
2412 		} else if (SATA_PMPORT_INFO(sata_hba_inst, cport,
2413 		    pmport) == NULL) {
2414 			dev_gone = B_TRUE;
2415 		} else {
2416 			mutex_enter(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2417 			    cport, pmport)));
2418 			sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2419 			if (sdinfo == NULL ||
2420 			    SATA_PMPORT_INFO(sata_hba_inst, cport, pmport)->
2421 			    pmport_tgtnode_clean == B_FALSE ||
2422 			    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2423 				dev_gone = B_TRUE;
2424 			}
2425 			mutex_exit(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2426 			    cport, pmport)));
2427 		}
2428 	}
2429 
2430 	if (dev_gone == B_TRUE) {
2431 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2432 		pkt->pkt_reason = CMD_DEV_GONE;
2433 		/*
2434 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2435 		 * only in callback function (for normal requests) and
2436 		 * in the dump code path.
2437 		 * So, if the callback is available, we need to do
2438 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2439 		 */
2440 		if (pkt->pkt_comp != NULL) {
2441 			/* scsi callback required */
2442 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2443 			    (task_func_t *)pkt->pkt_comp,
2444 			    (void *)pkt, TQ_NOSLEEP) == NULL)
2445 				/* Scheduling the callback failed */
2446 				return (TRAN_BUSY);
2447 			return (TRAN_ACCEPT);
2448 		}
2449 		/* No callback available */
2450 		return (TRAN_FATAL_ERROR);
2451 	}
2452 
2453 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2454 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2455 		rval = sata_txlt_atapi(spx);
2456 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2457 		    "sata_scsi_start atapi: rval %d\n", rval);
2458 		return (rval);
2459 	}
2460 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2461 
2462 	/*
2463 	 * Checking for power state, if it was on
2464 	 * STOPPED state, then the drive is not capable
2465 	 * of processing media access command.  And
2466 	 * TEST_UNIT_READY, REQUEST_SENSE has special handling
2467 	 * in the function for different power state.
2468 	 */
2469 	if (((sdinfo->satadrv_power_level == SATA_POWER_STANDBY) ||
2470 	    (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)) &&
2471 	    (SATA_IS_MEDIUM_ACCESS_CMD(pkt->pkt_cdbp[0]))) {
2472 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
2473 		    SD_SCSI_ASC_LU_NOT_READY));
2474 	}
2475 
2476 	/* ATA Disk commands processing starts here */
2477 
2478 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2479 
2480 	switch (pkt->pkt_cdbp[0]) {
2481 
2482 	case SCMD_INQUIRY:
2483 		/* Mapped to identify device */
2484 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2485 			bp_mapin(bp);
2486 		rval = sata_txlt_inquiry(spx);
2487 		break;
2488 
2489 	case SCMD_TEST_UNIT_READY:
2490 		/*
2491 		 * SAT "SATA to ATA Translation" doc specifies translation
2492 		 * to ATA CHECK POWER MODE.
2493 		 */
2494 		rval = sata_txlt_test_unit_ready(spx);
2495 		break;
2496 
2497 	case SCMD_START_STOP:
2498 		/* Mapping depends on the command */
2499 		rval = sata_txlt_start_stop_unit(spx);
2500 		break;
2501 
2502 	case SCMD_READ_CAPACITY:
2503 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2504 			bp_mapin(bp);
2505 		rval = sata_txlt_read_capacity(spx);
2506 		break;
2507 
2508 	case SCMD_REQUEST_SENSE:
2509 		/*
2510 		 * Always No Sense, since we force ARQ
2511 		 */
2512 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2513 			bp_mapin(bp);
2514 		rval = sata_txlt_request_sense(spx);
2515 		break;
2516 
2517 	case SCMD_LOG_SENSE_G1:
2518 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2519 			bp_mapin(bp);
2520 		rval = sata_txlt_log_sense(spx);
2521 		break;
2522 
2523 	case SCMD_LOG_SELECT_G1:
2524 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2525 			bp_mapin(bp);
2526 		rval = sata_txlt_log_select(spx);
2527 		break;
2528 
2529 	case SCMD_MODE_SENSE:
2530 	case SCMD_MODE_SENSE_G1:
2531 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2532 			bp_mapin(bp);
2533 		rval = sata_txlt_mode_sense(spx);
2534 		break;
2535 
2536 
2537 	case SCMD_MODE_SELECT:
2538 	case SCMD_MODE_SELECT_G1:
2539 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2540 			bp_mapin(bp);
2541 		rval = sata_txlt_mode_select(spx);
2542 		break;
2543 
2544 	case SCMD_SYNCHRONIZE_CACHE:
2545 	case SCMD_SYNCHRONIZE_CACHE_G1:
2546 		rval = sata_txlt_synchronize_cache(spx);
2547 		break;
2548 
2549 	case SCMD_READ:
2550 	case SCMD_READ_G1:
2551 	case SCMD_READ_G4:
2552 	case SCMD_READ_G5:
2553 		rval = sata_txlt_read(spx);
2554 		break;
2555 	case SCMD_WRITE_BUFFER:
2556 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2557 			bp_mapin(bp);
2558 		rval = sata_txlt_write_buffer(spx);
2559 		break;
2560 
2561 	case SCMD_WRITE:
2562 	case SCMD_WRITE_G1:
2563 	case SCMD_WRITE_G4:
2564 	case SCMD_WRITE_G5:
2565 		rval = sata_txlt_write(spx);
2566 		break;
2567 
2568 	case SCMD_SEEK:
2569 		rval = sata_txlt_nodata_cmd_immediate(spx);
2570 		break;
2571 
2572 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
2573 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
2574 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2575 			bp_mapin(bp);
2576 		rval = sata_txlt_ata_pass_thru(spx);
2577 		break;
2578 
2579 		/* Other cases will be filed later */
2580 		/* postponed until phase 2 of the development */
2581 	default:
2582 		rval = sata_txlt_invalid_command(spx);
2583 		break;
2584 	}
2585 
2586 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2587 	    "sata_scsi_start: rval %d\n", rval);
2588 
2589 	return (rval);
2590 }
2591 
2592 /*
2593  * Implementation of scsi tran_abort.
2594  * Abort specific pkt or all packets.
2595  *
2596  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2597  *
2598  * May be called from an interrupt level.
2599  */
2600 static int
2601 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2602 {
2603 	sata_hba_inst_t *sata_hba_inst =
2604 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2605 	sata_device_t	sata_device;
2606 	sata_pkt_t	*sata_pkt;
2607 
2608 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2609 	    "sata_scsi_abort: %s at target: 0x%x\n",
2610 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2611 
2612 	/* Validate address */
2613 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2614 		/* Invalid address */
2615 		return (0);
2616 
2617 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2618 	    sata_device.satadev_addr.cport)));
2619 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2620 		/* invalid address */
2621 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2622 		    sata_device.satadev_addr.cport)));
2623 		return (0);
2624 	}
2625 	if (scsi_pkt == NULL) {
2626 		/*
2627 		 * Abort all packets.
2628 		 * Although we do not have specific packet, we still need
2629 		 * dummy packet structure to pass device address to HBA.
2630 		 * Allocate one, without sleeping. Fail if pkt cannot be
2631 		 * allocated.
2632 		 */
2633 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2634 		if (sata_pkt == NULL) {
2635 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2636 			    sata_device.satadev_addr.cport)));
2637 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2638 			    "could not allocate sata_pkt"));
2639 			return (0);
2640 		}
2641 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2642 		sata_pkt->satapkt_device = sata_device;
2643 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2644 	} else {
2645 		if (scsi_pkt->pkt_ha_private == NULL) {
2646 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2647 			    sata_device.satadev_addr.cport)));
2648 			return (0); /* Bad scsi pkt */
2649 		}
2650 		/* extract pointer to sata pkt */
2651 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2652 		    txlt_sata_pkt;
2653 	}
2654 
2655 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2656 	    sata_device.satadev_addr.cport)));
2657 	/* Send abort request to HBA */
2658 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2659 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2660 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2661 	    SATA_SUCCESS) {
2662 		if (scsi_pkt == NULL)
2663 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2664 		/* Success */
2665 		return (1);
2666 	}
2667 	/* Else, something did not go right */
2668 	if (scsi_pkt == NULL)
2669 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2670 	/* Failure */
2671 	return (0);
2672 }
2673 
2674 
2675 /*
2676  * Implementation of scsi tran_reset.
2677  * RESET_ALL request is translated into port reset.
2678  * RESET_TARGET requests is translated into a device reset,
2679  * RESET_LUN request is accepted only for LUN 0 and translated into
2680  * device reset.
2681  * The target reset should cause all HBA active and queued packets to
2682  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2683  * the return. HBA should report reset event for the device.
2684  *
2685  * Returns 1 upon success, 0 upon failure.
2686  */
2687 static int
2688 sata_scsi_reset(struct scsi_address *ap, int level)
2689 {
2690 	sata_hba_inst_t	*sata_hba_inst =
2691 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2692 	sata_device_t	sata_device;
2693 	int		val;
2694 
2695 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2696 	    "sata_scsi_reset: level %d target: 0x%x\n",
2697 	    level, ap->a_target);
2698 
2699 	/* Validate address */
2700 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2701 	if (val == -1)
2702 		/* Invalid address */
2703 		return (0);
2704 
2705 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2706 	    sata_device.satadev_addr.cport)));
2707 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2708 		/* invalid address */
2709 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2710 		    sata_device.satadev_addr.cport)));
2711 		return (0);
2712 	}
2713 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2714 	    sata_device.satadev_addr.cport)));
2715 	if (level == RESET_ALL) {
2716 		/* port reset */
2717 		if (sata_device.satadev_addr.qual == SATA_ADDR_DCPORT)
2718 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2719 		else
2720 			sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
2721 
2722 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2723 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2724 			return (1);
2725 		else
2726 			return (0);
2727 
2728 	} else if (val == 0 &&
2729 	    (level == RESET_TARGET || level == RESET_LUN)) {
2730 		/* reset device (device attached) */
2731 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2732 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2733 			return (1);
2734 		else
2735 			return (0);
2736 	}
2737 	return (0);
2738 }
2739 
2740 
2741 /*
2742  * Implementation of scsi tran_getcap (get transport/device capabilities).
2743  * Supported capabilities for SATA hard disks:
2744  * auto-rqsense		(always supported)
2745  * tagged-qing		(supported if HBA supports it)
2746  * untagged-qing	(could be supported if disk supports it, but because
2747  *			 caching behavior allowing untagged queuing actually
2748  *			 results in reduced performance.  sd tries to throttle
2749  *			 back to only 3 outstanding commands, which may
2750  *			 work for real SCSI disks, but with read ahead
2751  *			 caching, having more than 1 outstanding command
2752  *			 results in cache thrashing.)
2753  * sector_size
2754  * dma_max
2755  * interconnect-type	(INTERCONNECT_SATA)
2756  *
2757  * Supported capabilities for ATAPI CD/DVD devices:
2758  * auto-rqsense		(always supported)
2759  * sector_size
2760  * dma_max
2761  * max-cdb-length
2762  * interconnect-type	(INTERCONNECT_SATA)
2763  *
2764  * Supported capabilities for ATAPI TAPE devices:
2765  * auto-rqsense		(always supported)
2766  * dma_max
2767  * max-cdb-length
2768  *
2769  * Supported capabilities for SATA ATAPI hard disks:
2770  * auto-rqsense		(always supported)
2771  * interconnect-type	(INTERCONNECT_SATA)
2772  * max-cdb-length
2773  *
2774  * Request for other capabilities is rejected as unsupported.
2775  *
2776  * Returns supported capability value, or -1 if capability is unsuppported or
2777  * the address is invalid - no device.
2778  */
2779 
2780 static int
2781 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2782 {
2783 
2784 	sata_hba_inst_t 	*sata_hba_inst =
2785 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2786 	sata_device_t		sata_device;
2787 	sata_drive_info_t	*sdinfo;
2788 	ddi_dma_attr_t		adj_dma_attr;
2789 	int 			rval;
2790 
2791 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2792 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2793 	    ap->a_target, cap);
2794 
2795 	/*
2796 	 * We want to process the capabilities on per port granularity.
2797 	 * So, we are specifically restricting ourselves to whom != 0
2798 	 * to exclude the controller wide handling.
2799 	 */
2800 	if (cap == NULL || whom == 0)
2801 		return (-1);
2802 
2803 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2804 		/* Invalid address */
2805 		return (-1);
2806 	}
2807 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2808 	    sata_device.satadev_addr.cport)));
2809 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2810 	    NULL) {
2811 		/* invalid address */
2812 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2813 		    sata_device.satadev_addr.cport)));
2814 		return (-1);
2815 	}
2816 
2817 	switch (scsi_hba_lookup_capstr(cap)) {
2818 	case SCSI_CAP_ARQ:
2819 		rval = 1;		/* ARQ supported, turned on */
2820 		break;
2821 
2822 	case SCSI_CAP_SECTOR_SIZE:
2823 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2824 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2825 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2826 			rval = SATA_ATAPI_SECTOR_SIZE;
2827 		else rval = -1;
2828 		break;
2829 
2830 	/*
2831 	 * untagged queuing cause a performance inversion because of
2832 	 * the way sd operates.  Because of this reason we do not
2833 	 * use it when available.
2834 	 */
2835 	case SCSI_CAP_UNTAGGED_QING:
2836 		if (sdinfo->satadrv_features_enabled &
2837 		    SATA_DEV_F_E_UNTAGGED_QING)
2838 			rval = 1;	/* Untagged queuing available */
2839 		else
2840 			rval = -1;	/* Untagged queuing not available */
2841 		break;
2842 
2843 	case SCSI_CAP_TAGGED_QING:
2844 		if ((sdinfo->satadrv_features_enabled &
2845 		    SATA_DEV_F_E_TAGGED_QING) &&
2846 		    (sdinfo->satadrv_max_queue_depth > 1))
2847 			rval = 1;	/* Tagged queuing available */
2848 		else
2849 			rval = -1;	/* Tagged queuing not available */
2850 		break;
2851 
2852 	case SCSI_CAP_DMA_MAX:
2853 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2854 		    &adj_dma_attr);
2855 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2856 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2857 		break;
2858 
2859 	case SCSI_CAP_INTERCONNECT_TYPE:
2860 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2861 		break;
2862 
2863 	case SCSI_CAP_CDB_LEN:
2864 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2865 			rval = sdinfo->satadrv_atapi_cdb_len;
2866 		else
2867 			rval = -1;
2868 		break;
2869 
2870 	default:
2871 		rval = -1;
2872 		break;
2873 	}
2874 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2875 	    sata_device.satadev_addr.cport)));
2876 	return (rval);
2877 }
2878 
2879 /*
2880  * Implementation of scsi tran_setcap
2881  *
2882  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2883  *
2884  */
2885 static int
2886 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2887 {
2888 	sata_hba_inst_t	*sata_hba_inst =
2889 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2890 	sata_device_t	sata_device;
2891 	sata_drive_info_t	*sdinfo;
2892 	int		rval;
2893 
2894 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2895 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2896 
2897 	/*
2898 	 * We want to process the capabilities on per port granularity.
2899 	 * So, we are specifically restricting ourselves to whom != 0
2900 	 * to exclude the controller wide handling.
2901 	 */
2902 	if (cap == NULL || whom == 0) {
2903 		return (-1);
2904 	}
2905 
2906 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2907 		/* Invalid address */
2908 		return (-1);
2909 	}
2910 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2911 	    sata_device.satadev_addr.cport)));
2912 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2913 	    &sata_device)) == NULL) {
2914 		/* invalid address */
2915 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2916 		    sata_device.satadev_addr.cport)));
2917 		return (-1);
2918 	}
2919 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2920 	    sata_device.satadev_addr.cport)));
2921 
2922 	switch (scsi_hba_lookup_capstr(cap)) {
2923 	case SCSI_CAP_ARQ:
2924 	case SCSI_CAP_SECTOR_SIZE:
2925 	case SCSI_CAP_DMA_MAX:
2926 	case SCSI_CAP_INTERCONNECT_TYPE:
2927 		rval = 0;
2928 		break;
2929 	case SCSI_CAP_UNTAGGED_QING:
2930 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2931 			rval = 1;
2932 			if (value == 1) {
2933 				sdinfo->satadrv_features_enabled |=
2934 				    SATA_DEV_F_E_UNTAGGED_QING;
2935 			} else if (value == 0) {
2936 				sdinfo->satadrv_features_enabled &=
2937 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2938 			} else {
2939 				rval = -1;
2940 			}
2941 		} else {
2942 			rval = 0;
2943 		}
2944 		break;
2945 	case SCSI_CAP_TAGGED_QING:
2946 		/* This can TCQ or NCQ */
2947 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2948 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2949 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
2950 		    (sata_func_enable & SATA_ENABLE_NCQ &&
2951 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
2952 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
2953 		    (sdinfo->satadrv_max_queue_depth > 1)) {
2954 			rval = 1;
2955 			if (value == 1) {
2956 				sdinfo->satadrv_features_enabled |=
2957 				    SATA_DEV_F_E_TAGGED_QING;
2958 			} else if (value == 0) {
2959 				sdinfo->satadrv_features_enabled &=
2960 				    ~SATA_DEV_F_E_TAGGED_QING;
2961 			} else {
2962 				rval = -1;
2963 			}
2964 		} else {
2965 			rval = 0;
2966 		}
2967 		break;
2968 	default:
2969 		rval = -1;
2970 		break;
2971 	}
2972 	return (rval);
2973 }
2974 
2975 /*
2976  * Implementations of scsi tran_destroy_pkt.
2977  * Free resources allocated by sata_scsi_init_pkt()
2978  */
2979 static void
2980 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2981 {
2982 	sata_pkt_txlate_t *spx;
2983 
2984 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2985 
2986 	sata_common_free_dma_rsrcs(spx);
2987 
2988 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2989 	sata_pkt_free(spx);
2990 
2991 	scsi_hba_pkt_free(ap, pkt);
2992 }
2993 
2994 /*
2995  * Implementation of scsi tran_dmafree.
2996  * Free DMA resources allocated by sata_scsi_init_pkt()
2997  */
2998 
2999 static void
3000 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
3001 {
3002 #ifndef __lock_lint
3003 	_NOTE(ARGUNUSED(ap))
3004 #endif
3005 	sata_pkt_txlate_t *spx;
3006 
3007 	ASSERT(pkt != NULL);
3008 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3009 
3010 	sata_common_free_dma_rsrcs(spx);
3011 }
3012 
3013 /*
3014  * Implementation of scsi tran_sync_pkt.
3015  *
3016  * The assumption below is that pkt is unique - there is no need to check ap
3017  *
3018  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
3019  * into/from the real buffer.
3020  */
3021 static void
3022 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3023 {
3024 #ifndef __lock_lint
3025 	_NOTE(ARGUNUSED(ap))
3026 #endif
3027 	int rval;
3028 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3029 	struct buf *bp;
3030 	int direction;
3031 
3032 	ASSERT(spx != NULL);
3033 	if (spx->txlt_buf_dma_handle != NULL) {
3034 		direction = spx->txlt_sata_pkt->
3035 		    satapkt_cmd.satacmd_flags.sata_data_direction;
3036 		if (spx->txlt_sata_pkt != NULL &&
3037 		    direction != SATA_DIR_NODATA_XFER) {
3038 			if (spx->txlt_tmp_buf != NULL) {
3039 				/* Intermediate DMA buffer used */
3040 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3041 
3042 				if (direction & SATA_DIR_WRITE) {
3043 					bcopy(bp->b_un.b_addr,
3044 					    spx->txlt_tmp_buf, bp->b_bcount);
3045 				}
3046 			}
3047 			/* Sync the buffer for device or for CPU */
3048 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
3049 			    (direction & SATA_DIR_WRITE) ?
3050 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
3051 			ASSERT(rval == DDI_SUCCESS);
3052 			if (spx->txlt_tmp_buf != NULL &&
3053 			    !(direction & SATA_DIR_WRITE)) {
3054 				/* Intermediate DMA buffer used for read */
3055 				bcopy(spx->txlt_tmp_buf,
3056 				    bp->b_un.b_addr, bp->b_bcount);
3057 			}
3058 
3059 		}
3060 	}
3061 }
3062 
3063 
3064 
3065 /* *******************  SATA - SCSI Translation functions **************** */
3066 /*
3067  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3068  * translation.
3069  */
3070 
3071 /*
3072  * Checks if a device exists and can be access and translates common
3073  * scsi_pkt data to sata_pkt data.
3074  *
3075  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
3076  * sata_pkt was set-up.
3077  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
3078  * exist and pkt_comp callback was scheduled.
3079  * Returns other TRAN_XXXXX values when error occured and command should be
3080  * rejected with the returned TRAN_XXXXX value.
3081  *
3082  * This function should be called with port mutex held.
3083  */
3084 static int
3085 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason)
3086 {
3087 	sata_drive_info_t *sdinfo;
3088 	sata_device_t sata_device;
3089 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3090 		SATA_DIR_NODATA_XFER,
3091 		/* all other values to 0/FALSE */
3092 	};
3093 	/*
3094 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
3095 	 * and that implies TRAN_ACCEPT return value. Any other returned value
3096 	 * indicates that the scsi packet was not accepted (the reason will not
3097 	 * be checked by the scsi target driver).
3098 	 * To make debugging easier, we set pkt_reason to know value here.
3099 	 * It may be changed later when different completion reason is
3100 	 * determined.
3101 	 */
3102 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
3103 	*reason = CMD_TRAN_ERR;
3104 
3105 	/* Validate address */
3106 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3107 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3108 
3109 	case -1:
3110 		/* Invalid address or invalid device type */
3111 		return (TRAN_BADPKT);
3112 	case 2:
3113 		/*
3114 		 * Valid address but device type is unknown - Chack if it is
3115 		 * in the reset state and therefore in an indeterminate state.
3116 		 */
3117 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3118 		    &spx->txlt_sata_pkt->satapkt_device);
3119 		if (sdinfo != NULL && (sdinfo->satadrv_event_flags &
3120 		    (SATA_EVNT_DEVICE_RESET |
3121 		    SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3122 			if (!ddi_in_panic()) {
3123 				spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3124 				*reason = CMD_INCOMPLETE;
3125 				SATADBG1(SATA_DBG_SCSI_IF,
3126 				    spx->txlt_sata_hba_inst,
3127 				    "sata_scsi_start: rejecting command "
3128 				    "because of device reset state\n", NULL);
3129 				return (TRAN_BUSY);
3130 			}
3131 		}
3132 		/* FALLTHROUGH */
3133 	case 1:
3134 		/* valid address but no valid device - it has disappeared */
3135 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3136 		*reason = CMD_DEV_GONE;
3137 		/*
3138 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
3139 		 * only in callback function (for normal requests) and
3140 		 * in the dump code path.
3141 		 * So, if the callback is available, we need to do
3142 		 * the callback rather than returning TRAN_FATAL_ERROR here.
3143 		 */
3144 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
3145 			/* scsi callback required */
3146 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3147 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3148 			    (void *)spx->txlt_scsi_pkt,
3149 			    TQ_SLEEP) == NULL)
3150 				/* Scheduling the callback failed */
3151 				return (TRAN_BUSY);
3152 
3153 			return (TRAN_ACCEPT);
3154 		}
3155 		return (TRAN_FATAL_ERROR);
3156 	default:
3157 		/* all OK; pkt reason will be overwritten later */
3158 		break;
3159 	}
3160 	/*
3161 	 * If in an interrupt context, reject packet if it is to be
3162 	 * executed in polling mode
3163 	 */
3164 	if (servicing_interrupt() &&
3165 	    (spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3166 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3167 		    "sata_scsi_start: rejecting synchronous command because "
3168 		    "of interrupt context\n", NULL);
3169 		return (TRAN_BUSY);
3170 	}
3171 
3172 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3173 	    &spx->txlt_sata_pkt->satapkt_device);
3174 
3175 	/*
3176 	 * If device is in reset condition, reject the packet with
3177 	 * TRAN_BUSY, unless:
3178 	 * 1. system is panicking (dumping)
3179 	 * In such case only one thread is running and there is no way to
3180 	 * process reset.
3181 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
3182 	 * Some cfgadm operations involve drive commands, so reset condition
3183 	 * needs to be ignored for IOCTL operations.
3184 	 */
3185 	if ((sdinfo->satadrv_event_flags &
3186 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3187 
3188 		if (!ddi_in_panic() &&
3189 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
3190 		    sata_device.satadev_addr.cport) &
3191 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
3192 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3193 			*reason = CMD_INCOMPLETE;
3194 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3195 			    "sata_scsi_start: rejecting command because "
3196 			    "of device reset state\n", NULL);
3197 			return (TRAN_BUSY);
3198 		}
3199 	}
3200 
3201 	/*
3202 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3203 	 * sata_scsi_pkt_init() because pkt init had to work also with
3204 	 * non-existing devices.
3205 	 * Now we know that the packet was set-up for a real device, so its
3206 	 * type is known.
3207 	 */
3208 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3209 
3210 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3211 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
3212 	    sata_device.satadev_addr.cport)->cport_event_flags &
3213 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
3214 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3215 		    sata_ignore_dev_reset = B_TRUE;
3216 	}
3217 	/*
3218 	 * At this point the generic translation routine determined that the
3219 	 * scsi packet should be accepted. Packet completion reason may be
3220 	 * changed later when a different completion reason is determined.
3221 	 */
3222 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3223 	*reason = CMD_CMPLT;
3224 
3225 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3226 		/* Synchronous execution */
3227 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3228 		    SATA_OPMODE_POLLING;
3229 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3230 		    sata_ignore_dev_reset = ddi_in_panic();
3231 	} else {
3232 		/* Asynchronous execution */
3233 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3234 		    SATA_OPMODE_INTERRUPTS;
3235 	}
3236 	/* Convert queuing information */
3237 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3238 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3239 		    B_TRUE;
3240 	else if (spx->txlt_scsi_pkt->pkt_flags &
3241 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3242 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3243 		    B_TRUE;
3244 
3245 	/* Always limit pkt time */
3246 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3247 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3248 	else
3249 		/* Pass on scsi_pkt time */
3250 		spx->txlt_sata_pkt->satapkt_time =
3251 		    spx->txlt_scsi_pkt->pkt_time;
3252 
3253 	return (TRAN_ACCEPT);
3254 }
3255 
3256 
3257 /*
3258  * Translate ATA Identify Device data to SCSI Inquiry data.
3259  * This function may be called only for ATA devices.
3260  * This function should not be called for ATAPI devices - they
3261  * respond directly to SCSI Inquiry command.
3262  *
3263  * SATA Identify Device data has to be valid in sata_drive_info.
3264  * Buffer has to accomodate the inquiry length (36 bytes).
3265  *
3266  * This function should be called with a port mutex held.
3267  */
3268 static	void
3269 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3270     sata_drive_info_t *sdinfo, uint8_t *buf)
3271 {
3272 
3273 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3274 	struct sata_id *sid = &sdinfo->satadrv_id;
3275 
3276 	/* Start with a nice clean slate */
3277 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3278 
3279 	/*
3280 	 * Rely on the dev_type for setting paripheral qualifier.
3281 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
3282 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
3283 	 * ATAPI Inquiry may provide more data to the target driver.
3284 	 */
3285 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3286 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
3287 
3288 	/* CFA type device is not a removable media device */
3289 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
3290 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
3291 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3292 	inq->inq_iso = 0;	/* ISO version */
3293 	inq->inq_ecma = 0;	/* ECMA version */
3294 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3295 	inq->inq_aenc = 0;	/* Async event notification cap. */
3296 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
3297 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3298 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3299 	inq->inq_len = 31;	/* Additional length */
3300 	inq->inq_dualp = 0;	/* dual port device - NO */
3301 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3302 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3303 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3304 				/*
3305 				 * Queuing support - controller has to
3306 				 * support some sort of command queuing.
3307 				 */
3308 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3309 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3310 	else
3311 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3312 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3313 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3314 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3315 
3316 #ifdef	_LITTLE_ENDIAN
3317 	/* Swap text fields to match SCSI format */
3318 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3319 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3320 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3321 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3322 	else
3323 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3324 #else	/* _LITTLE_ENDIAN */
3325 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3326 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3327 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3328 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3329 	else
3330 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3331 #endif	/* _LITTLE_ENDIAN */
3332 }
3333 
3334 
3335 /*
3336  * Scsi response set up for invalid command (command not supported)
3337  *
3338  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3339  */
3340 static int
3341 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3342 {
3343 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3344 	struct scsi_extended_sense *sense;
3345 
3346 	scsipkt->pkt_reason = CMD_CMPLT;
3347 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3348 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3349 
3350 	*scsipkt->pkt_scbp = STATUS_CHECK;
3351 
3352 	sense = sata_arq_sense(spx);
3353 	sense->es_key = KEY_ILLEGAL_REQUEST;
3354 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
3355 
3356 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3357 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3358 
3359 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3360 	    scsipkt->pkt_comp != NULL)
3361 		/* scsi callback required */
3362 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3363 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3364 		    (void *)spx->txlt_scsi_pkt,
3365 		    TQ_SLEEP) == NULL)
3366 			/* Scheduling the callback failed */
3367 			return (TRAN_BUSY);
3368 	return (TRAN_ACCEPT);
3369 }
3370 
3371 /*
3372  * Scsi response set up for check condition with special sense key
3373  * and additional sense code.
3374  *
3375  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3376  */
3377 static int
3378 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3379 {
3380 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3381 	int cport = SATA_TXLT_CPORT(spx);
3382 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3383 	struct scsi_extended_sense *sense;
3384 
3385 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3386 	scsipkt->pkt_reason = CMD_CMPLT;
3387 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3388 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3389 
3390 	*scsipkt->pkt_scbp = STATUS_CHECK;
3391 
3392 	sense = sata_arq_sense(spx);
3393 	sense->es_key = key;
3394 	sense->es_add_code = code;
3395 
3396 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3397 
3398 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3399 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3400 
3401 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3402 		/* scsi callback required */
3403 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3404 		    (task_func_t *)scsi_hba_pkt_comp,
3405 		    (void *)spx->txlt_scsi_pkt,
3406 		    TQ_SLEEP) == NULL)
3407 			/* Scheduling the callback failed */
3408 			return (TRAN_BUSY);
3409 	return (TRAN_ACCEPT);
3410 }
3411 
3412 /*
3413  * Scsi response setup for
3414  * emulated non-data command that requires no action/return data
3415  *
3416  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3417  */
3418 static	int
3419 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3420 {
3421 	int rval;
3422 	int reason;
3423 
3424 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3425 
3426 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3427 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3428 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3429 		return (rval);
3430 	}
3431 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3432 
3433 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3434 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3435 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3436 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3437 
3438 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3439 	    "Scsi_pkt completion reason %x\n",
3440 	    spx->txlt_scsi_pkt->pkt_reason);
3441 
3442 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3443 	    spx->txlt_scsi_pkt->pkt_comp != NULL)
3444 		/* scsi callback required */
3445 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3446 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3447 		    (void *)spx->txlt_scsi_pkt,
3448 		    TQ_SLEEP) == NULL)
3449 			/* Scheduling the callback failed */
3450 			return (TRAN_BUSY);
3451 	return (TRAN_ACCEPT);
3452 }
3453 
3454 
3455 /*
3456  * SATA translate command: Inquiry / Identify Device
3457  * Use cached Identify Device data for now, rather than issuing actual
3458  * Device Identify cmd request. If device is detached and re-attached,
3459  * asynchronous event processing should fetch and refresh Identify Device
3460  * data.
3461  * Two VPD pages are supported now:
3462  * Vital Product Data page
3463  * Unit Serial Number page
3464  *
3465  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3466  */
3467 
3468 #define	EVPD			1	/* Extended Vital Product Data flag */
3469 #define	CMDDT			2	/* Command Support Data - Obsolete */
3470 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3471 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3472 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3473 
3474 static int
3475 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3476 {
3477 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3478 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3479 	sata_drive_info_t *sdinfo;
3480 	struct scsi_extended_sense *sense;
3481 	int count;
3482 	uint8_t *p;
3483 	int i, j;
3484 	uint8_t page_buf[0xff]; /* Max length */
3485 	int rval, reason;
3486 
3487 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3488 
3489 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3490 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3491 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3492 		return (rval);
3493 	}
3494 
3495 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3496 	    &spx->txlt_sata_pkt->satapkt_device);
3497 
3498 	ASSERT(sdinfo != NULL);
3499 
3500 	scsipkt->pkt_reason = CMD_CMPLT;
3501 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3502 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3503 
3504 	/* Reject not supported request */
3505 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3506 		*scsipkt->pkt_scbp = STATUS_CHECK;
3507 		sense = sata_arq_sense(spx);
3508 		sense->es_key = KEY_ILLEGAL_REQUEST;
3509 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3510 		goto done;
3511 	}
3512 
3513 	/* Valid Inquiry request */
3514 	*scsipkt->pkt_scbp = STATUS_GOOD;
3515 
3516 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3517 
3518 		/*
3519 		 * Because it is fully emulated command storing data
3520 		 * programatically in the specified buffer, release
3521 		 * preallocated DMA resources before storing data in the buffer,
3522 		 * so no unwanted DMA sync would take place.
3523 		 */
3524 		sata_scsi_dmafree(NULL, scsipkt);
3525 
3526 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3527 			/* Standard Inquiry Data request */
3528 			struct scsi_inquiry inq;
3529 			unsigned int bufsize;
3530 
3531 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3532 			    sdinfo, (uint8_t *)&inq);
3533 			/* Copy no more than requested */
3534 			count = MIN(bp->b_bcount,
3535 			    sizeof (struct scsi_inquiry));
3536 			bufsize = scsipkt->pkt_cdbp[4];
3537 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3538 			count = MIN(count, bufsize);
3539 			bcopy(&inq, bp->b_un.b_addr, count);
3540 
3541 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3542 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3543 			    bufsize - count : 0;
3544 		} else {
3545 			/*
3546 			 * peripheral_qualifier = 0;
3547 			 *
3548 			 * We are dealing only with HD and will be
3549 			 * dealing with CD/DVD devices soon
3550 			 */
3551 			uint8_t peripheral_device_type =
3552 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3553 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3554 
3555 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3556 			case INQUIRY_SUP_VPD_PAGE:
3557 				/*
3558 				 * Request for suported Vital Product Data
3559 				 * pages - assuming only 2 page codes
3560 				 * supported.
3561 				 */
3562 				page_buf[0] = peripheral_device_type;
3563 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3564 				page_buf[2] = 0;
3565 				page_buf[3] = 2; /* page length */
3566 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3567 				page_buf[5] = INQUIRY_USN_PAGE;
3568 				/* Copy no more than requested */
3569 				count = MIN(bp->b_bcount, 6);
3570 				bcopy(page_buf, bp->b_un.b_addr, count);
3571 				break;
3572 
3573 			case INQUIRY_USN_PAGE:
3574 				/*
3575 				 * Request for Unit Serial Number page.
3576 				 * Set-up the page.
3577 				 */
3578 				page_buf[0] = peripheral_device_type;
3579 				page_buf[1] = INQUIRY_USN_PAGE;
3580 				page_buf[2] = 0;
3581 				/* remaining page length */
3582 				page_buf[3] = SATA_ID_SERIAL_LEN;
3583 
3584 				/*
3585 				 * Copy serial number from Identify Device data
3586 				 * words into the inquiry page and swap bytes
3587 				 * when necessary.
3588 				 */
3589 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3590 #ifdef	_LITTLE_ENDIAN
3591 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3592 #else
3593 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3594 #endif
3595 				/*
3596 				 * Least significant character of the serial
3597 				 * number shall appear as the last byte,
3598 				 * according to SBC-3 spec.
3599 				 * Count trailing spaces to determine the
3600 				 * necessary shift length.
3601 				 */
3602 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3603 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3604 					if (*(p - j) != '\0' &&
3605 					    *(p - j) != '\040')
3606 						break;
3607 				}
3608 
3609 				/*
3610 				 * Shift SN string right, so that the last
3611 				 * non-blank character would appear in last
3612 				 * byte of SN field in the page.
3613 				 * 'j' is the shift length.
3614 				 */
3615 				for (i = 0;
3616 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3617 				    i++, p--)
3618 					*p = *(p - j);
3619 
3620 				/*
3621 				 * Add leading spaces - same number as the
3622 				 * shift size
3623 				 */
3624 				for (; j > 0; j--)
3625 					page_buf[4 + j - 1] = '\040';
3626 
3627 				count = MIN(bp->b_bcount,
3628 				    SATA_ID_SERIAL_LEN + 4);
3629 				bcopy(page_buf, bp->b_un.b_addr, count);
3630 				break;
3631 
3632 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3633 				/*
3634 				 * We may want to implement this page, when
3635 				 * identifiers are common for SATA devices
3636 				 * But not now.
3637 				 */
3638 				/*FALLTHROUGH*/
3639 
3640 			default:
3641 				/* Request for unsupported VPD page */
3642 				*scsipkt->pkt_scbp = STATUS_CHECK;
3643 				sense = sata_arq_sense(spx);
3644 				sense->es_key = KEY_ILLEGAL_REQUEST;
3645 				sense->es_add_code =
3646 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3647 				goto done;
3648 			}
3649 		}
3650 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3651 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3652 		    scsipkt->pkt_cdbp[4] - count : 0;
3653 	}
3654 done:
3655 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3656 
3657 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3658 	    "Scsi_pkt completion reason %x\n",
3659 	    scsipkt->pkt_reason);
3660 
3661 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3662 	    scsipkt->pkt_comp != NULL) {
3663 		/* scsi callback required */
3664 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3665 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3666 		    TQ_SLEEP) == NULL)
3667 			/* Scheduling the callback failed */
3668 			return (TRAN_BUSY);
3669 	}
3670 	return (TRAN_ACCEPT);
3671 }
3672 
3673 /*
3674  * SATA translate command: Request Sense.
3675  *
3676  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3677  * At the moment this is an emulated command (ATA version for SATA hard disks).
3678  * May be translated into Check Power Mode command in the future.
3679  *
3680  * Note: There is a mismatch between already implemented Informational
3681  * Exception Mode Select page 0x1C and this function.
3682  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3683  * NO SENSE and set additional sense code to the exception code - this is not
3684  * implemented here.
3685  */
3686 static int
3687 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3688 {
3689 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3690 	struct scsi_extended_sense sense;
3691 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3692 	sata_drive_info_t *sdinfo;
3693 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3694 	int rval, reason, power_state = 0;
3695 
3696 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3697 
3698 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3699 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3700 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3701 		return (rval);
3702 	}
3703 
3704 	scsipkt->pkt_reason = CMD_CMPLT;
3705 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3706 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3707 	*scsipkt->pkt_scbp = STATUS_GOOD;
3708 
3709 	/*
3710 	 * when CONTROL field's NACA bit == 1
3711 	 * return ILLEGAL_REQUEST
3712 	 */
3713 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3714 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3715 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3716 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3717 	}
3718 
3719 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3720 	    &spx->txlt_sata_pkt->satapkt_device);
3721 	ASSERT(sdinfo != NULL);
3722 
3723 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3724 
3725 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3726 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3727 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3728 	if (sata_hba_start(spx, &rval) != 0) {
3729 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3730 		return (rval);
3731 	} else {
3732 		if (scmd->satacmd_error_reg != 0) {
3733 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3734 			return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3735 			    SD_SCSI_ASC_NO_ADD_SENSE));
3736 		}
3737 	}
3738 
3739 	switch (scmd->satacmd_sec_count_lsb) {
3740 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3741 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3742 			power_state = SATA_POWER_STOPPED;
3743 		else {
3744 			power_state = SATA_POWER_STANDBY;
3745 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
3746 		}
3747 		break;
3748 	case SATA_PWRMODE_IDLE: /* device in idle mode */
3749 		power_state = SATA_POWER_IDLE;
3750 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3751 		break;
3752 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
3753 	default:		  /* 0x40, 0x41 active mode */
3754 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
3755 			power_state = SATA_POWER_IDLE;
3756 		else {
3757 			power_state = SATA_POWER_ACTIVE;
3758 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3759 		}
3760 		break;
3761 	}
3762 
3763 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3764 
3765 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3766 		/*
3767 		 * Because it is fully emulated command storing data
3768 		 * programatically in the specified buffer, release
3769 		 * preallocated DMA resources before storing data in the buffer,
3770 		 * so no unwanted DMA sync would take place.
3771 		 */
3772 		int count = MIN(bp->b_bcount,
3773 		    sizeof (struct scsi_extended_sense));
3774 		sata_scsi_dmafree(NULL, scsipkt);
3775 		bzero(&sense, sizeof (struct scsi_extended_sense));
3776 		sense.es_valid = 0;	/* Valid LBA */
3777 		sense.es_class = 7;	/* Response code 0x70 - current err */
3778 		sense.es_key = KEY_NO_SENSE;
3779 		sense.es_add_len = 6;	/* Additional length */
3780 		/* Copy no more than requested */
3781 		bcopy(&sense, bp->b_un.b_addr, count);
3782 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3783 		scsipkt->pkt_resid = 0;
3784 		switch (power_state) {
3785 		case SATA_POWER_IDLE:
3786 		case SATA_POWER_STANDBY:
3787 			sense.es_add_code =
3788 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
3789 			break;
3790 		case SATA_POWER_STOPPED:
3791 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
3792 			break;
3793 		case SATA_POWER_ACTIVE:
3794 		default:
3795 			break;
3796 		}
3797 	}
3798 
3799 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3800 	    "Scsi_pkt completion reason %x\n",
3801 	    scsipkt->pkt_reason);
3802 
3803 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3804 		/* scsi callback required */
3805 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3806 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
3807 		    TQ_SLEEP) == NULL)
3808 			/* Scheduling the callback failed */
3809 			return (TRAN_BUSY);
3810 	return (TRAN_ACCEPT);
3811 }
3812 
3813 /*
3814  * SATA translate command: Test Unit Ready
3815  * (ATA version for SATA hard disks).
3816  * It is translated into the Check Power Mode command.
3817  *
3818  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3819  */
3820 static int
3821 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3822 {
3823 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3824 	struct scsi_extended_sense *sense;
3825 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3826 	sata_drive_info_t *sdinfo;
3827 	int power_state;
3828 	int rval, reason;
3829 
3830 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3831 
3832 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3833 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3834 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3835 		return (rval);
3836 	}
3837 
3838 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3839 	    &spx->txlt_sata_pkt->satapkt_device);
3840 	ASSERT(sdinfo != NULL);
3841 
3842 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3843 
3844 	/* send CHECK POWER MODE command */
3845 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3846 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3847 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3848 	if (sata_hba_start(spx, &rval) != 0) {
3849 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3850 		return (rval);
3851 	} else {
3852 		if (scmd->satacmd_error_reg != 0) {
3853 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3854 			return (sata_txlt_check_condition(spx, KEY_NOT_READY,
3855 			    SD_SCSI_ASC_LU_NOT_RESPONSE));
3856 		}
3857 	}
3858 
3859 	power_state = scmd->satacmd_sec_count_lsb;
3860 
3861 	/*
3862 	 * return NOT READY when device in STOPPED mode
3863 	 */
3864 	if (power_state == SATA_PWRMODE_STANDBY &&
3865 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
3866 		*scsipkt->pkt_scbp = STATUS_CHECK;
3867 		sense = sata_arq_sense(spx);
3868 		sense->es_key = KEY_NOT_READY;
3869 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3870 	} else {
3871 		/*
3872 		 * For other power mode, return GOOD status
3873 		 */
3874 		*scsipkt->pkt_scbp = STATUS_GOOD;
3875 	}
3876 
3877 	scsipkt->pkt_reason = CMD_CMPLT;
3878 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3879 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3880 
3881 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3882 
3883 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3884 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3885 
3886 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3887 		/* scsi callback required */
3888 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3889 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
3890 		    TQ_SLEEP) == NULL)
3891 			/* Scheduling the callback failed */
3892 			return (TRAN_BUSY);
3893 
3894 	return (TRAN_ACCEPT);
3895 }
3896 
3897 /*
3898  * SATA translate command: Start Stop Unit
3899  * Translation depends on a command:
3900  *
3901  * Power condition bits will be supported
3902  * and the power level should be maintained by SATL,
3903  * When SATL received a command, it will check the
3904  * power level firstly, and return the status according
3905  * to SAT2 v2.6 and SAT-2 Standby Modifications
3906  *
3907  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
3908  * -----------------------------------------------------------------------
3909  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
3910  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
3911  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
3912  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
3913  *
3914  *	Unload Media / NOT SUPPORTED YET
3915  *	Load Media / NOT SUPPROTED YET
3916  *	Immediate bit / NOT SUPPORTED YET (deferred error)
3917  *
3918  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3919  * appropriate values in scsi_pkt fields.
3920  */
3921 static int
3922 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3923 {
3924 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3925 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3926 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3927 	int cport = SATA_TXLT_CPORT(spx);
3928 	int rval, reason;
3929 	sata_drive_info_t *sdinfo;
3930 	sata_id_t *sata_id;
3931 
3932 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3933 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
3934 
3935 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3936 
3937 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3938 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3939 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3940 		return (rval);
3941 	}
3942 
3943 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
3944 		/* IMMED bit - not supported */
3945 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3946 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3947 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
3948 	}
3949 
3950 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3951 	spx->txlt_sata_pkt->satapkt_comp = NULL;
3952 
3953 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3954 	    &spx->txlt_sata_pkt->satapkt_device);
3955 	ASSERT(sdinfo != NULL);
3956 	sata_id = &sdinfo->satadrv_id;
3957 
3958 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
3959 	case 0:
3960 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
3961 			/* Load/Unload Media - invalid request */
3962 			goto err_out;
3963 		}
3964 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
3965 			/* Start Unit */
3966 			sata_build_read_verify_cmd(scmd, 1, 5);
3967 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3968 			/* Transfer command to HBA */
3969 			if (sata_hba_start(spx, &rval) != 0) {
3970 				/* Pkt not accepted for execution */
3971 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3972 				return (rval);
3973 			} else {
3974 				if (scmd->satacmd_error_reg != 0) {
3975 					goto err_out;
3976 				}
3977 			}
3978 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3979 		} else {
3980 			/* Stop Unit */
3981 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
3982 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3983 			if (sata_hba_start(spx, &rval) != 0) {
3984 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3985 				return (rval);
3986 			} else {
3987 				if (scmd->satacmd_error_reg != 0) {
3988 					goto err_out;
3989 				}
3990 			}
3991 			/* ata standby immediate command */
3992 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
3993 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3994 			if (sata_hba_start(spx, &rval) != 0) {
3995 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3996 				return (rval);
3997 			} else {
3998 				if (scmd->satacmd_error_reg != 0) {
3999 					goto err_out;
4000 				}
4001 			}
4002 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4003 		}
4004 		break;
4005 	case 0x1:
4006 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4007 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4008 		if (sata_hba_start(spx, &rval) != 0) {
4009 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4010 			return (rval);
4011 		} else {
4012 			if (scmd->satacmd_error_reg != 0) {
4013 				goto err_out;
4014 			}
4015 		}
4016 		sata_build_read_verify_cmd(scmd, 1, 5);
4017 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4018 		/* Transfer command to HBA */
4019 		if (sata_hba_start(spx, &rval) != 0) {
4020 			/* Pkt not accepted for execution */
4021 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4022 			return (rval);
4023 		} else {
4024 			if (scmd->satacmd_error_reg != 0) {
4025 				goto err_out;
4026 			}
4027 		}
4028 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4029 		break;
4030 	case 0x2:
4031 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4032 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4033 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4034 			if (sata_hba_start(spx, &rval) != 0) {
4035 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4036 				return (rval);
4037 			} else {
4038 				if (scmd->satacmd_error_reg != 0) {
4039 					goto err_out;
4040 				}
4041 			}
4042 		}
4043 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4044 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4045 		if (sata_hba_start(spx, &rval) != 0) {
4046 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4047 			return (rval);
4048 		} else {
4049 			if (scmd->satacmd_error_reg != 0) {
4050 				goto err_out;
4051 			}
4052 		}
4053 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4054 			/*
4055 			 *  POWER CONDITION MODIFIER bit set
4056 			 *  to 0x1 or larger it will be handled
4057 			 *  on the same way as bit = 0x1
4058 			 */
4059 			if (!(sata_id->ai_cmdset84 &
4060 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4061 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4062 				break;
4063 			}
4064 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4065 			scmd->satacmd_features_reg = 0x44;
4066 			scmd->satacmd_lba_low_lsb = 0x4c;
4067 			scmd->satacmd_lba_mid_lsb = 0x4e;
4068 			scmd->satacmd_lba_high_lsb = 0x55;
4069 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4070 			if (sata_hba_start(spx, &rval) != 0) {
4071 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4072 				return (rval);
4073 			} else {
4074 				if (scmd->satacmd_error_reg != 0) {
4075 					goto err_out;
4076 				}
4077 			}
4078 		}
4079 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4080 		break;
4081 	case 0x3:
4082 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4083 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4084 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4085 			if (sata_hba_start(spx, &rval) != 0) {
4086 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4087 				return (rval);
4088 			} else {
4089 				if (scmd->satacmd_error_reg != 0) {
4090 					goto err_out;
4091 				}
4092 			}
4093 		}
4094 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4095 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4096 		if (sata_hba_start(spx, &rval) != 0) {
4097 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4098 			return (rval);
4099 		} else {
4100 			if (scmd->satacmd_error_reg != 0) {
4101 				goto err_out;
4102 			}
4103 		}
4104 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4105 		break;
4106 	case 0x7:
4107 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4108 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4109 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4110 		if (sata_hba_start(spx, &rval) != 0) {
4111 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4112 			return (rval);
4113 		} else {
4114 			if (scmd->satacmd_error_reg != 0) {
4115 				goto err_out;
4116 			}
4117 		}
4118 		switch (scmd->satacmd_sec_count_lsb) {
4119 		case SATA_PWRMODE_STANDBY:
4120 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4121 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4122 			    sdinfo->satadrv_standby_timer);
4123 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4124 			if (sata_hba_start(spx, &rval) != 0) {
4125 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4126 				return (rval);
4127 			} else {
4128 				if (scmd->satacmd_error_reg != 0) {
4129 					goto err_out;
4130 				}
4131 			}
4132 			break;
4133 		case SATA_PWRMODE_IDLE:
4134 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4135 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4136 			    sdinfo->satadrv_standby_timer);
4137 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4138 			if (sata_hba_start(spx, &rval) != 0) {
4139 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4140 				return (rval);
4141 			} else {
4142 				if (scmd->satacmd_error_reg != 0) {
4143 					goto err_out;
4144 				}
4145 			}
4146 			break;
4147 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4148 		case SATA_PWRMODE_ACTIVE_SPINUP:
4149 		case SATA_PWRMODE_ACTIVE:
4150 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4151 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4152 			    sdinfo->satadrv_standby_timer);
4153 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4154 			if (sata_hba_start(spx, &rval) != 0) {
4155 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4156 				return (rval);
4157 			} else {
4158 				if (scmd->satacmd_error_reg != 0) {
4159 					goto err_out;
4160 				}
4161 			}
4162 			sata_build_read_verify_cmd(scmd, 1, 5);
4163 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4164 			if (sata_hba_start(spx, &rval) != 0) {
4165 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4166 				return (rval);
4167 			} else {
4168 				if (scmd->satacmd_error_reg != 0) {
4169 					goto err_out;
4170 				}
4171 			}
4172 			break;
4173 		default:
4174 			goto err_out;
4175 		}
4176 		break;
4177 	case 0xb:
4178 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4179 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4180 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4181 			return (sata_txlt_check_condition(spx,
4182 			    KEY_ILLEGAL_REQUEST,
4183 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4184 		}
4185 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4186 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4187 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4188 			if (sata_hba_start(spx, &rval) != 0) {
4189 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4190 				return (rval);
4191 			} else {
4192 				if (scmd->satacmd_error_reg != 0) {
4193 					goto err_out;
4194 				}
4195 			}
4196 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4197 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4198 			if (sata_hba_start(spx, &rval) != 0) {
4199 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4200 				return (rval);
4201 			} else {
4202 				if (scmd->satacmd_error_reg != 0) {
4203 					goto err_out;
4204 				}
4205 			}
4206 		}
4207 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4208 		break;
4209 	default:
4210 err_out:
4211 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4212 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4213 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4214 	}
4215 
4216 	/*
4217 	 * Since it was a synchronous command,
4218 	 * a callback function will be called directly.
4219 	 */
4220 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4221 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4222 	    "synchronous execution status %x\n",
4223 	    spx->txlt_sata_pkt->satapkt_reason);
4224 
4225 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0) {
4226 		sata_set_arq_data(spx->txlt_sata_pkt);
4227 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4228 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
4229 		    TQ_SLEEP) == 0) {
4230 			return (TRAN_BUSY);
4231 		}
4232 	}
4233 	else
4234 
4235 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4236 
4237 	return (TRAN_ACCEPT);
4238 
4239 }
4240 
4241 /*
4242  * SATA translate command:  Read Capacity.
4243  * Emulated command for SATA disks.
4244  * Capacity is retrieved from cached Idenifty Device data.
4245  * Identify Device data shows effective disk capacity, not the native
4246  * capacity, which may be limitted by Set Max Address command.
4247  * This is ATA version for SATA hard disks.
4248  *
4249  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4250  */
4251 static int
4252 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4253 {
4254 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4255 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4256 	sata_drive_info_t *sdinfo;
4257 	uint64_t val;
4258 	uchar_t *rbuf;
4259 	int rval, reason;
4260 
4261 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4262 	    "sata_txlt_read_capacity: ", NULL);
4263 
4264 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4265 
4266 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4267 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4268 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4269 		return (rval);
4270 	}
4271 
4272 	scsipkt->pkt_reason = CMD_CMPLT;
4273 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4274 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4275 	*scsipkt->pkt_scbp = STATUS_GOOD;
4276 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4277 		/*
4278 		 * Because it is fully emulated command storing data
4279 		 * programatically in the specified buffer, release
4280 		 * preallocated DMA resources before storing data in the buffer,
4281 		 * so no unwanted DMA sync would take place.
4282 		 */
4283 		sata_scsi_dmafree(NULL, scsipkt);
4284 
4285 		sdinfo = sata_get_device_info(
4286 		    spx->txlt_sata_hba_inst,
4287 		    &spx->txlt_sata_pkt->satapkt_device);
4288 		/* Last logical block address */
4289 		val = sdinfo->satadrv_capacity - 1;
4290 		rbuf = (uchar_t *)bp->b_un.b_addr;
4291 		/* Need to swap endians to match scsi format */
4292 		rbuf[0] = (val >> 24) & 0xff;
4293 		rbuf[1] = (val >> 16) & 0xff;
4294 		rbuf[2] = (val >> 8) & 0xff;
4295 		rbuf[3] = val & 0xff;
4296 		/* block size - always 512 bytes, for now */
4297 		rbuf[4] = 0;
4298 		rbuf[5] = 0;
4299 		rbuf[6] = 0x02;
4300 		rbuf[7] = 0;
4301 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4302 		scsipkt->pkt_resid = 0;
4303 
4304 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4305 		    sdinfo->satadrv_capacity -1);
4306 	}
4307 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4308 	/*
4309 	 * If a callback was requested, do it now.
4310 	 */
4311 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4312 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4313 
4314 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4315 	    scsipkt->pkt_comp != NULL)
4316 		/* scsi callback required */
4317 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4318 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4319 		    TQ_SLEEP) == NULL)
4320 			/* Scheduling the callback failed */
4321 			return (TRAN_BUSY);
4322 
4323 	return (TRAN_ACCEPT);
4324 }
4325 
4326 /*
4327  * SATA translate command: Mode Sense.
4328  * Translated into appropriate SATA command or emulated.
4329  * Saved Values Page Control (03) are not supported.
4330  *
4331  * NOTE: only caching mode sense page is currently implemented.
4332  *
4333  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4334  */
4335 
4336 #define	LLBAA	0x10	/* Long LBA Accepted */
4337 
4338 static int
4339 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4340 {
4341 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4342 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4343 	sata_drive_info_t *sdinfo;
4344 	sata_id_t *sata_id;
4345 	struct scsi_extended_sense *sense;
4346 	int 		len, bdlen, count, alc_len;
4347 	int		pc;	/* Page Control code */
4348 	uint8_t		*buf;	/* mode sense buffer */
4349 	int		rval, reason;
4350 
4351 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4352 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4353 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4354 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4355 
4356 	buf = kmem_zalloc(1024, KM_SLEEP);
4357 
4358 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4359 
4360 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4361 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4362 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4363 		kmem_free(buf, 1024);
4364 		return (rval);
4365 	}
4366 
4367 	scsipkt->pkt_reason = CMD_CMPLT;
4368 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4369 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4370 
4371 	pc = scsipkt->pkt_cdbp[2] >> 6;
4372 
4373 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4374 		/*
4375 		 * Because it is fully emulated command storing data
4376 		 * programatically in the specified buffer, release
4377 		 * preallocated DMA resources before storing data in the buffer,
4378 		 * so no unwanted DMA sync would take place.
4379 		 */
4380 		sata_scsi_dmafree(NULL, scsipkt);
4381 
4382 		len = 0;
4383 		bdlen = 0;
4384 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4385 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4386 			    (scsipkt->pkt_cdbp[1] & LLBAA))
4387 				bdlen = 16;
4388 			else
4389 				bdlen = 8;
4390 		}
4391 		/* Build mode parameter header */
4392 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4393 			/* 4-byte mode parameter header */
4394 			buf[len++] = 0;		/* mode data length */
4395 			buf[len++] = 0;		/* medium type */
4396 			buf[len++] = 0;		/* dev-specific param */
4397 			buf[len++] = bdlen;	/* Block Descriptor length */
4398 		} else {
4399 			/* 8-byte mode parameter header */
4400 			buf[len++] = 0;		/* mode data length */
4401 			buf[len++] = 0;
4402 			buf[len++] = 0;		/* medium type */
4403 			buf[len++] = 0;		/* dev-specific param */
4404 			if (bdlen == 16)
4405 				buf[len++] = 1;	/* long lba descriptor */
4406 			else
4407 				buf[len++] = 0;
4408 			buf[len++] = 0;
4409 			buf[len++] = 0;		/* Block Descriptor length */
4410 			buf[len++] = bdlen;
4411 		}
4412 
4413 		sdinfo = sata_get_device_info(
4414 		    spx->txlt_sata_hba_inst,
4415 		    &spx->txlt_sata_pkt->satapkt_device);
4416 
4417 		/* Build block descriptor only if not disabled (DBD) */
4418 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4419 			/* Block descriptor - direct-access device format */
4420 			if (bdlen == 8) {
4421 				/* build regular block descriptor */
4422 				buf[len++] =
4423 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4424 				buf[len++] =
4425 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4426 				buf[len++] =
4427 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4428 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4429 				buf[len++] = 0; /* density code */
4430 				buf[len++] = 0;
4431 				if (sdinfo->satadrv_type ==
4432 				    SATA_DTYPE_ATADISK)
4433 					buf[len++] = 2;
4434 				else
4435 					/* ATAPI */
4436 					buf[len++] = 8;
4437 				buf[len++] = 0;
4438 			} else if (bdlen == 16) {
4439 				/* Long LBA Accepted */
4440 				/* build long lba block descriptor */
4441 #ifndef __lock_lint
4442 				buf[len++] =
4443 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4444 				buf[len++] =
4445 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4446 				buf[len++] =
4447 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4448 				buf[len++] =
4449 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4450 #endif
4451 				buf[len++] =
4452 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4453 				buf[len++] =
4454 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4455 				buf[len++] =
4456 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4457 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4458 				buf[len++] = 0;
4459 				buf[len++] = 0; /* density code */
4460 				buf[len++] = 0;
4461 				buf[len++] = 0;
4462 				if (sdinfo->satadrv_type ==
4463 				    SATA_DTYPE_ATADISK)
4464 					buf[len++] = 2;
4465 				else
4466 					/* ATAPI */
4467 					buf[len++] = 8;
4468 				buf[len++] = 0;
4469 			}
4470 		}
4471 
4472 		sata_id = &sdinfo->satadrv_id;
4473 
4474 		/*
4475 		 * Add requested pages.
4476 		 * Page 3 and 4 are obsolete and we are not supporting them.
4477 		 * We deal now with:
4478 		 * caching (read/write cache control).
4479 		 * We should eventually deal with following mode pages:
4480 		 * error recovery  (0x01),
4481 		 * power condition (0x1a),
4482 		 * exception control page (enables SMART) (0x1c),
4483 		 * enclosure management (ses),
4484 		 * protocol-specific port mode (port control).
4485 		 */
4486 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4487 		case MODEPAGE_RW_ERRRECOV:
4488 			/* DAD_MODE_ERR_RECOV */
4489 			/* R/W recovery */
4490 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4491 			break;
4492 		case MODEPAGE_CACHING:
4493 			/* DAD_MODE_CACHE */
4494 			/* Reject not supported request for saved parameters */
4495 			if (pc == 3) {
4496 				*scsipkt->pkt_scbp = STATUS_CHECK;
4497 				sense = sata_arq_sense(spx);
4498 				sense->es_key = KEY_ILLEGAL_REQUEST;
4499 				sense->es_add_code =
4500 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
4501 				goto done;
4502 			}
4503 
4504 			/* caching */
4505 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4506 			break;
4507 		case MODEPAGE_INFO_EXCPT:
4508 			/* exception cntrl */
4509 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4510 				len += sata_build_msense_page_1c(sdinfo, pc,
4511 				    buf+len);
4512 			}
4513 			else
4514 				goto err;
4515 			break;
4516 		case MODEPAGE_POWER_COND:
4517 			/* DAD_MODE_POWER_COND */
4518 			/* power condition */
4519 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4520 			break;
4521 
4522 		case MODEPAGE_ACOUSTIC_MANAG:
4523 			/* acoustic management */
4524 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4525 			break;
4526 		case MODEPAGE_ALLPAGES:
4527 			/* all pages */
4528 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4529 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4530 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4531 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4532 				len += sata_build_msense_page_1c(sdinfo, pc,
4533 				    buf+len);
4534 			}
4535 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4536 			break;
4537 		default:
4538 		err:
4539 			/* Invalid request */
4540 			*scsipkt->pkt_scbp = STATUS_CHECK;
4541 			sense = sata_arq_sense(spx);
4542 			sense->es_key = KEY_ILLEGAL_REQUEST;
4543 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4544 			goto done;
4545 		}
4546 
4547 		/* fix total mode data length */
4548 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4549 			/* 4-byte mode parameter header */
4550 			buf[0] = len - 1;	/* mode data length */
4551 		} else {
4552 			buf[0] = (len -2) >> 8;
4553 			buf[1] = (len -2) & 0xff;
4554 		}
4555 
4556 
4557 		/* Check allocation length */
4558 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4559 			alc_len = scsipkt->pkt_cdbp[4];
4560 		} else {
4561 			alc_len = scsipkt->pkt_cdbp[7];
4562 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4563 		}
4564 		/*
4565 		 * We do not check for possible parameters truncation
4566 		 * (alc_len < len) assuming that the target driver works
4567 		 * correctly. Just avoiding overrun.
4568 		 * Copy no more than requested and possible, buffer-wise.
4569 		 */
4570 		count = MIN(alc_len, len);
4571 		count = MIN(bp->b_bcount, count);
4572 		bcopy(buf, bp->b_un.b_addr, count);
4573 
4574 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4575 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4576 	}
4577 	*scsipkt->pkt_scbp = STATUS_GOOD;
4578 done:
4579 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4580 	(void) kmem_free(buf, 1024);
4581 
4582 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4583 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4584 
4585 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4586 	    scsipkt->pkt_comp != NULL)
4587 		/* scsi callback required */
4588 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4589 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4590 		    TQ_SLEEP) == NULL)
4591 			/* Scheduling the callback failed */
4592 			return (TRAN_BUSY);
4593 
4594 	return (TRAN_ACCEPT);
4595 }
4596 
4597 
4598 /*
4599  * SATA translate command: Mode Select.
4600  * Translated into appropriate SATA command or emulated.
4601  * Saving parameters is not supported.
4602  * Changing device capacity is not supported (although theoretically
4603  * possible by executing SET FEATURES/SET MAX ADDRESS)
4604  *
4605  * Assumption is that the target driver is working correctly.
4606  *
4607  * More than one SATA command may be executed to perform operations specified
4608  * by mode select pages. The first error terminates further execution.
4609  * Operations performed successully are not backed-up in such case.
4610  *
4611  * NOTE: Implemented pages:
4612  * - caching page
4613  * - informational exception page
4614  * - acoustic management page
4615  * - power condition page
4616  * Caching setup is remembered so it could be re-stored in case of
4617  * an unexpected device reset.
4618  *
4619  * Returns TRAN_XXXX.
4620  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
4621  */
4622 
4623 static int
4624 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4625 {
4626 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4627 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4628 	struct scsi_extended_sense *sense;
4629 	int len, pagelen, count, pllen;
4630 	uint8_t *buf;	/* mode select buffer */
4631 	int rval, stat, reason;
4632 	uint_t nointr_flag;
4633 	int dmod = 0;
4634 
4635 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4636 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4637 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4638 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4639 
4640 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4641 
4642 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4643 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4644 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4645 		return (rval);
4646 	}
4647 	/*
4648 	 * If in interrupt context, reject this packet because it may result
4649 	 * in issuing a synchronous command to HBA.
4650 	 */
4651 	if (servicing_interrupt()) {
4652 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
4653 		    "sata_txlt_mode_select: rejecting command because "
4654 		    "of interrupt context\n", NULL);
4655 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4656 		return (TRAN_BUSY);
4657 	}
4658 
4659 	rval = TRAN_ACCEPT;
4660 
4661 	scsipkt->pkt_reason = CMD_CMPLT;
4662 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4663 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4664 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4665 
4666 	/* Reject not supported request */
4667 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4668 		*scsipkt->pkt_scbp = STATUS_CHECK;
4669 		sense = sata_arq_sense(spx);
4670 		sense->es_key = KEY_ILLEGAL_REQUEST;
4671 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4672 		goto done;
4673 	}
4674 
4675 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4676 		pllen = scsipkt->pkt_cdbp[4];
4677 	} else {
4678 		pllen = scsipkt->pkt_cdbp[7];
4679 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4680 	}
4681 
4682 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4683 
4684 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4685 		buf = (uint8_t *)bp->b_un.b_addr;
4686 		count = MIN(bp->b_bcount, pllen);
4687 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4688 		scsipkt->pkt_resid = 0;
4689 		pllen = count;
4690 
4691 		/*
4692 		 * Check the header to skip the block descriptor(s) - we
4693 		 * do not support setting device capacity.
4694 		 * Existing macros do not recognize long LBA dscriptor,
4695 		 * hence manual calculation.
4696 		 */
4697 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4698 			/* 6-bytes CMD, 4 bytes header */
4699 			if (count <= 4)
4700 				goto done;		/* header only */
4701 			len = buf[3] + 4;
4702 		} else {
4703 			/* 10-bytes CMD, 8 bytes header */
4704 			if (count <= 8)
4705 				goto done;		/* header only */
4706 			len = buf[6];
4707 			len = (len << 8) + buf[7] + 8;
4708 		}
4709 		if (len >= count)
4710 			goto done;	/* header + descriptor(s) only */
4711 
4712 		pllen -= len;		/* remaining data length */
4713 
4714 		/*
4715 		 * We may be executing SATA command and want to execute it
4716 		 * in SYNCH mode, regardless of scsi_pkt setting.
4717 		 * Save scsi_pkt setting and indicate SYNCH mode
4718 		 */
4719 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4720 		    scsipkt->pkt_comp != NULL) {
4721 			scsipkt->pkt_flags |= FLAG_NOINTR;
4722 		}
4723 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
4724 
4725 		/*
4726 		 * len is now the offset to a first mode select page
4727 		 * Process all pages
4728 		 */
4729 		while (pllen > 0) {
4730 			switch ((int)buf[len]) {
4731 			case MODEPAGE_CACHING:
4732 				/* No support for SP (saving) */
4733 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4734 					*scsipkt->pkt_scbp = STATUS_CHECK;
4735 					sense = sata_arq_sense(spx);
4736 					sense->es_key = KEY_ILLEGAL_REQUEST;
4737 					sense->es_add_code =
4738 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4739 					goto done;
4740 				}
4741 				stat = sata_mode_select_page_8(spx,
4742 				    (struct mode_cache_scsi3 *)&buf[len],
4743 				    pllen, &pagelen, &rval, &dmod);
4744 				/*
4745 				 * The pagelen value indicates the number of
4746 				 * parameter bytes already processed.
4747 				 * The rval is the return value from
4748 				 * sata_tran_start().
4749 				 * The stat indicates the overall status of
4750 				 * the operation(s).
4751 				 */
4752 				if (stat != SATA_SUCCESS)
4753 					/*
4754 					 * Page processing did not succeed -
4755 					 * all error info is already set-up,
4756 					 * just return
4757 					 */
4758 					pllen = 0; /* this breaks the loop */
4759 				else {
4760 					len += pagelen;
4761 					pllen -= pagelen;
4762 				}
4763 				break;
4764 
4765 			case MODEPAGE_INFO_EXCPT:
4766 				stat = sata_mode_select_page_1c(spx,
4767 				    (struct mode_info_excpt_page *)&buf[len],
4768 				    pllen, &pagelen, &rval, &dmod);
4769 				/*
4770 				 * The pagelen value indicates the number of
4771 				 * parameter bytes already processed.
4772 				 * The rval is the return value from
4773 				 * sata_tran_start().
4774 				 * The stat indicates the overall status of
4775 				 * the operation(s).
4776 				 */
4777 				if (stat != SATA_SUCCESS)
4778 					/*
4779 					 * Page processing did not succeed -
4780 					 * all error info is already set-up,
4781 					 * just return
4782 					 */
4783 					pllen = 0; /* this breaks the loop */
4784 				else {
4785 					len += pagelen;
4786 					pllen -= pagelen;
4787 				}
4788 				break;
4789 
4790 			case MODEPAGE_ACOUSTIC_MANAG:
4791 				stat = sata_mode_select_page_30(spx,
4792 				    (struct mode_acoustic_management *)
4793 				    &buf[len], pllen, &pagelen, &rval, &dmod);
4794 				/*
4795 				 * The pagelen value indicates the number of
4796 				 * parameter bytes already processed.
4797 				 * The rval is the return value from
4798 				 * sata_tran_start().
4799 				 * The stat indicates the overall status of
4800 				 * the operation(s).
4801 				 */
4802 				if (stat != SATA_SUCCESS)
4803 					/*
4804 					 * Page processing did not succeed -
4805 					 * all error info is already set-up,
4806 					 * just return
4807 					 */
4808 					pllen = 0; /* this breaks the loop */
4809 				else {
4810 					len += pagelen;
4811 					pllen -= pagelen;
4812 				}
4813 
4814 				break;
4815 			case MODEPAGE_POWER_COND:
4816 				stat = sata_mode_select_page_1a(spx,
4817 				    (struct mode_info_power_cond *)&buf[len],
4818 				    pllen, &pagelen, &rval, &dmod);
4819 				/*
4820 				 * The pagelen value indicates the number of
4821 				 * parameter bytes already processed.
4822 				 * The rval is the return value from
4823 				 * sata_tran_start().
4824 				 * The stat indicates the overall status of
4825 				 * the operation(s).
4826 				 */
4827 				if (stat != SATA_SUCCESS)
4828 					/*
4829 					 * Page processing did not succeed -
4830 					 * all error info is already set-up,
4831 					 * just return
4832 					 */
4833 					pllen = 0; /* this breaks the loop */
4834 				else {
4835 					len += pagelen;
4836 					pllen -= pagelen;
4837 				}
4838 				break;
4839 			default:
4840 				*scsipkt->pkt_scbp = STATUS_CHECK;
4841 				sense = sata_arq_sense(spx);
4842 				sense->es_key = KEY_ILLEGAL_REQUEST;
4843 				sense->es_add_code =
4844 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
4845 				goto done;
4846 			}
4847 		}
4848 	}
4849 done:
4850 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4851 	/*
4852 	 * If device parameters were modified, fetch and store the new
4853 	 * Identify Device data. Since port mutex could have been released
4854 	 * for accessing HBA driver, we need to re-check device existence.
4855 	 */
4856 	if (dmod != 0) {
4857 		sata_drive_info_t new_sdinfo, *sdinfo;
4858 		int rv = 0;
4859 
4860 		/*
4861 		 * Following statement has to be changed if this function is
4862 		 * used for devices other than SATA hard disks.
4863 		 */
4864 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4865 
4866 		new_sdinfo.satadrv_addr =
4867 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4868 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4869 		    &new_sdinfo);
4870 
4871 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4872 		/*
4873 		 * Since port mutex could have been released when
4874 		 * accessing HBA driver, we need to re-check that the
4875 		 * framework still holds the device info structure.
4876 		 */
4877 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4878 		    &spx->txlt_sata_pkt->satapkt_device);
4879 		if (sdinfo != NULL) {
4880 			/*
4881 			 * Device still has info structure in the
4882 			 * sata framework. Copy newly fetched info
4883 			 */
4884 			if (rv == 0) {
4885 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4886 				sata_save_drive_settings(sdinfo);
4887 			} else {
4888 				/*
4889 				 * Could not fetch new data - invalidate
4890 				 * sata_drive_info. That makes device
4891 				 * unusable.
4892 				 */
4893 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4894 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4895 			}
4896 		}
4897 		if (rv != 0 || sdinfo == NULL) {
4898 			/*
4899 			 * This changes the overall mode select completion
4900 			 * reason to a failed one !!!!!
4901 			 */
4902 			*scsipkt->pkt_scbp = STATUS_CHECK;
4903 			sense = sata_arq_sense(spx);
4904 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4905 			rval = TRAN_ACCEPT;
4906 		}
4907 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4908 	}
4909 	/* Restore the scsi pkt flags */
4910 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
4911 	scsipkt->pkt_flags |= nointr_flag;
4912 
4913 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4914 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4915 
4916 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4917 	    scsipkt->pkt_comp != NULL)
4918 		/* scsi callback required */
4919 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4920 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4921 		    TQ_SLEEP) == NULL)
4922 			/* Scheduling the callback failed */
4923 			return (TRAN_BUSY);
4924 
4925 	return (rval);
4926 }
4927 
4928 /*
4929  * Translate command: ATA Pass Through
4930  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
4931  * PIO Data-Out protocols.  Also supports CK_COND bit.
4932  *
4933  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
4934  * described in Table 111 of SAT-2 (Draft 9).
4935  */
4936 static  int
4937 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
4938 {
4939 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4940 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4941 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4942 	int extend;
4943 	uint64_t lba;
4944 	uint16_t feature, sec_count;
4945 	int t_len, synch;
4946 	int rval, reason;
4947 
4948 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4949 
4950 	rval = sata_txlt_generic_pkt_info(spx, &reason);
4951 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4952 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4953 		return (rval);
4954 	}
4955 
4956 	/* T_DIR bit */
4957 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
4958 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
4959 	else
4960 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
4961 
4962 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
4963 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
4964 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4965 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4966 	}
4967 
4968 	/* OFFLINE field. If non-zero, invalid command (for now). */
4969 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
4970 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4971 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4972 	}
4973 
4974 	/* PROTOCOL field */
4975 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
4976 	case SATL_APT_P_HW_RESET:
4977 	case SATL_APT_P_SRST:
4978 	case SATL_APT_P_DMA:
4979 	case SATL_APT_P_DMA_QUEUED:
4980 	case SATL_APT_P_DEV_DIAG:
4981 	case SATL_APT_P_DEV_RESET:
4982 	case SATL_APT_P_UDMA_IN:
4983 	case SATL_APT_P_UDMA_OUT:
4984 	case SATL_APT_P_FPDMA:
4985 	case SATL_APT_P_RET_RESP:
4986 		/* Not yet implemented */
4987 	default:
4988 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4989 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4990 
4991 	case SATL_APT_P_NON_DATA:
4992 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
4993 		break;
4994 
4995 	case SATL_APT_P_PIO_DATA_IN:
4996 		/* If PROTOCOL disagrees with T_DIR, invalid command */
4997 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
4998 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4999 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5000 		}
5001 
5002 		/* if there is a buffer, release its DMA resources */
5003 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5004 			sata_scsi_dmafree(NULL, scsipkt);
5005 		} else {
5006 			/* if there is no buffer, how do you PIO in? */
5007 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5008 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5009 		}
5010 
5011 		break;
5012 
5013 	case SATL_APT_P_PIO_DATA_OUT:
5014 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5015 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5016 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5017 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5018 		}
5019 
5020 		/* if there is a buffer, release its DMA resources */
5021 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5022 			sata_scsi_dmafree(NULL, scsipkt);
5023 		} else {
5024 			/* if there is no buffer, how do you PIO out? */
5025 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5026 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5027 		}
5028 
5029 		break;
5030 	}
5031 
5032 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5033 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5034 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5035 		feature = scsipkt->pkt_cdbp[3];
5036 
5037 		sec_count = scsipkt->pkt_cdbp[4];
5038 
5039 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5040 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5041 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5042 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5043 
5044 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5045 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5046 
5047 		break;
5048 
5049 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5050 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5051 			extend = 1;
5052 
5053 			feature = scsipkt->pkt_cdbp[3];
5054 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5055 
5056 			sec_count = scsipkt->pkt_cdbp[5];
5057 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5058 
5059 			lba = scsipkt->pkt_cdbp[11];
5060 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5061 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5062 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5063 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5064 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5065 
5066 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5067 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5068 		} else {
5069 			feature = scsipkt->pkt_cdbp[3];
5070 
5071 			sec_count = scsipkt->pkt_cdbp[5];
5072 
5073 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5074 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5075 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5076 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5077 
5078 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5079 			    0xf0;
5080 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5081 		}
5082 
5083 		break;
5084 	}
5085 
5086 	/* CK_COND bit */
5087 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5088 		if (extend) {
5089 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5090 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5091 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5092 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5093 		}
5094 
5095 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5096 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5097 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5098 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5099 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5100 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5101 	}
5102 
5103 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5104 	if (extend) {
5105 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5106 
5107 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5108 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5109 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5110 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5111 		scmd->satacmd_lba_high_msb = lba >> 40;
5112 	} else {
5113 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5114 
5115 		scmd->satacmd_features_reg_ext = 0;
5116 		scmd->satacmd_sec_count_msb = 0;
5117 		scmd->satacmd_lba_low_msb = 0;
5118 		scmd->satacmd_lba_mid_msb = 0;
5119 		scmd->satacmd_lba_high_msb = 0;
5120 	}
5121 
5122 	scmd->satacmd_features_reg = feature & 0xff;
5123 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5124 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5125 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5126 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5127 
5128 	/* Determine transfer length */
5129 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5130 	case 1:
5131 		t_len = feature;
5132 		break;
5133 	case 2:
5134 		t_len = sec_count;
5135 		break;
5136 	default:
5137 		t_len = 0;
5138 		break;
5139 	}
5140 
5141 	/* Adjust transfer length for the Byte Block bit */
5142 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5143 		t_len *= SATA_DISK_SECTOR_SIZE;
5144 
5145 	/* Start processing command */
5146 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5147 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5148 		synch = FALSE;
5149 	} else {
5150 		synch = TRUE;
5151 	}
5152 
5153 	if (sata_hba_start(spx, &rval) != 0) {
5154 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5155 		return (rval);
5156 	}
5157 
5158 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5159 
5160 	if (synch) {
5161 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5162 	}
5163 
5164 	return (TRAN_ACCEPT);
5165 }
5166 
5167 /*
5168  * Translate command: Log Sense
5169  */
5170 static 	int
5171 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5172 {
5173 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5174 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5175 	sata_drive_info_t *sdinfo;
5176 	struct scsi_extended_sense *sense;
5177 	int 		len, count, alc_len;
5178 	int		pc;	/* Page Control code */
5179 	int		page_code;	/* Page code */
5180 	uint8_t		*buf;	/* log sense buffer */
5181 	int		rval, reason;
5182 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5183 
5184 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5185 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5186 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5187 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5188 
5189 	buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5190 
5191 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5192 
5193 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5194 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5195 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5196 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5197 		return (rval);
5198 	}
5199 	/*
5200 	 * If in interrupt context, reject this packet because it may result
5201 	 * in issuing a synchronous command to HBA.
5202 	 */
5203 	if (servicing_interrupt()) {
5204 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
5205 		    "sata_log_sense: rejecting command because "
5206 		    "of interrupt context\n", NULL);
5207 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5208 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5209 		return (TRAN_BUSY);
5210 	}
5211 
5212 	scsipkt->pkt_reason = CMD_CMPLT;
5213 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5214 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5215 
5216 	pc = scsipkt->pkt_cdbp[2] >> 6;
5217 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5218 
5219 	/* Reject not supported request for all but cumulative values */
5220 	switch (pc) {
5221 	case PC_CUMULATIVE_VALUES:
5222 		break;
5223 	default:
5224 		*scsipkt->pkt_scbp = STATUS_CHECK;
5225 		sense = sata_arq_sense(spx);
5226 		sense->es_key = KEY_ILLEGAL_REQUEST;
5227 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5228 		goto done;
5229 	}
5230 
5231 	switch (page_code) {
5232 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5233 	case PAGE_CODE_SELF_TEST_RESULTS:
5234 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5235 	case PAGE_CODE_SMART_READ_DATA:
5236 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5237 		break;
5238 	default:
5239 		*scsipkt->pkt_scbp = STATUS_CHECK;
5240 		sense = sata_arq_sense(spx);
5241 		sense->es_key = KEY_ILLEGAL_REQUEST;
5242 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5243 		goto done;
5244 	}
5245 
5246 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5247 		/*
5248 		 * Because log sense uses local buffers for data retrieval from
5249 		 * the devices and sets the data programatically in the
5250 		 * original specified buffer, release preallocated DMA
5251 		 * resources before storing data in the original buffer,
5252 		 * so no unwanted DMA sync would take place.
5253 		 */
5254 		sata_id_t *sata_id;
5255 
5256 		sata_scsi_dmafree(NULL, scsipkt);
5257 
5258 		len = 0;
5259 
5260 		/* Build log parameter header */
5261 		buf[len++] = page_code;	/* page code as in the CDB */
5262 		buf[len++] = 0;		/* reserved */
5263 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5264 		buf[len++] = 0;		/* (LSB) */
5265 
5266 		sdinfo = sata_get_device_info(
5267 		    spx->txlt_sata_hba_inst,
5268 		    &spx->txlt_sata_pkt->satapkt_device);
5269 
5270 		/*
5271 		 * Add requested pages.
5272 		 */
5273 		switch (page_code) {
5274 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5275 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5276 			break;
5277 		case PAGE_CODE_SELF_TEST_RESULTS:
5278 			sata_id = &sdinfo->satadrv_id;
5279 			if ((! (sata_id->ai_cmdset84 &
5280 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5281 			    (! (sata_id->ai_features87 &
5282 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5283 				*scsipkt->pkt_scbp = STATUS_CHECK;
5284 				sense = sata_arq_sense(spx);
5285 				sense->es_key = KEY_ILLEGAL_REQUEST;
5286 				sense->es_add_code =
5287 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5288 
5289 				goto done;
5290 			}
5291 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5292 			    spx->txlt_sata_hba_inst);
5293 			break;
5294 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5295 			sata_id = &sdinfo->satadrv_id;
5296 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5297 				*scsipkt->pkt_scbp = STATUS_CHECK;
5298 				sense = sata_arq_sense(spx);
5299 				sense->es_key = KEY_ILLEGAL_REQUEST;
5300 				sense->es_add_code =
5301 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5302 
5303 				goto done;
5304 			}
5305 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5306 				*scsipkt->pkt_scbp = STATUS_CHECK;
5307 				sense = sata_arq_sense(spx);
5308 				sense->es_key = KEY_ABORTED_COMMAND;
5309 				sense->es_add_code =
5310 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5311 				sense->es_qual_code =
5312 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5313 
5314 				goto done;
5315 			}
5316 
5317 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5318 			    spx->txlt_sata_hba_inst);
5319 			break;
5320 		case PAGE_CODE_SMART_READ_DATA:
5321 			sata_id = &sdinfo->satadrv_id;
5322 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5323 				*scsipkt->pkt_scbp = STATUS_CHECK;
5324 				sense = sata_arq_sense(spx);
5325 				sense->es_key = KEY_ILLEGAL_REQUEST;
5326 				sense->es_add_code =
5327 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5328 
5329 				goto done;
5330 			}
5331 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5332 				*scsipkt->pkt_scbp = STATUS_CHECK;
5333 				sense = sata_arq_sense(spx);
5334 				sense->es_key = KEY_ABORTED_COMMAND;
5335 				sense->es_add_code =
5336 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5337 				sense->es_qual_code =
5338 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5339 
5340 				goto done;
5341 			}
5342 
5343 			/* This page doesn't include a page header */
5344 			len = sata_build_lsense_page_30(sdinfo, buf,
5345 			    spx->txlt_sata_hba_inst);
5346 			goto no_header;
5347 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5348 			sata_id = &sdinfo->satadrv_id;
5349 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5350 				*scsipkt->pkt_scbp = STATUS_CHECK;
5351 				sense = sata_arq_sense(spx);
5352 				sense->es_key = KEY_ILLEGAL_REQUEST;
5353 				sense->es_add_code =
5354 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5355 
5356 				goto done;
5357 			}
5358 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5359 				*scsipkt->pkt_scbp = STATUS_CHECK;
5360 				sense = sata_arq_sense(spx);
5361 				sense->es_key = KEY_ABORTED_COMMAND;
5362 				sense->es_add_code =
5363 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5364 				sense->es_qual_code =
5365 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5366 
5367 				goto done;
5368 			}
5369 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
5370 			goto no_header;
5371 		default:
5372 			/* Invalid request */
5373 			*scsipkt->pkt_scbp = STATUS_CHECK;
5374 			sense = sata_arq_sense(spx);
5375 			sense->es_key = KEY_ILLEGAL_REQUEST;
5376 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5377 			goto done;
5378 		}
5379 
5380 		/* set parameter log sense data length */
5381 		buf[2] = len >> 8;	/* log sense length (MSB) */
5382 		buf[3] = len & 0xff;	/* log sense length (LSB) */
5383 
5384 		len += SCSI_LOG_PAGE_HDR_LEN;
5385 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
5386 
5387 no_header:
5388 		/* Check allocation length */
5389 		alc_len = scsipkt->pkt_cdbp[7];
5390 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5391 
5392 		/*
5393 		 * We do not check for possible parameters truncation
5394 		 * (alc_len < len) assuming that the target driver works
5395 		 * correctly. Just avoiding overrun.
5396 		 * Copy no more than requested and possible, buffer-wise.
5397 		 */
5398 		count = MIN(alc_len, len);
5399 		count = MIN(bp->b_bcount, count);
5400 		bcopy(buf, bp->b_un.b_addr, count);
5401 
5402 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5403 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5404 	}
5405 	*scsipkt->pkt_scbp = STATUS_GOOD;
5406 done:
5407 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5408 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5409 
5410 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5411 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5412 
5413 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5414 	    scsipkt->pkt_comp != NULL)
5415 		/* scsi callback required */
5416 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5417 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5418 		    TQ_SLEEP) == NULL)
5419 			/* Scheduling the callback failed */
5420 			return (TRAN_BUSY);
5421 
5422 	return (TRAN_ACCEPT);
5423 }
5424 
5425 /*
5426  * Translate command: Log Select
5427  * Not implemented at this time - returns invalid command response.
5428  */
5429 static	int
5430 sata_txlt_log_select(sata_pkt_txlate_t *spx)
5431 {
5432 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5433 	    "sata_txlt_log_select\n", NULL);
5434 
5435 	return (sata_txlt_invalid_command(spx));
5436 }
5437 
5438 
5439 /*
5440  * Translate command: Read (various types).
5441  * Translated into appropriate type of ATA READ command
5442  * for SATA hard disks.
5443  * Both the device capabilities and requested operation mode are
5444  * considered.
5445  *
5446  * Following scsi cdb fields are ignored:
5447  * rdprotect, dpo, fua, fua_nv, group_number.
5448  *
5449  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5450  * enable variable sata_func_enable), the capability of the controller and
5451  * capability of a device are checked and if both support queueing, read
5452  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
5453  * command rather than plain READ_XXX command.
5454  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5455  * both the controller and device suport such functionality, the read
5456  * request will be translated to READ_FPDMA_QUEUED command.
5457  * In both cases the maximum queue depth is derived as minimum of:
5458  * HBA capability,device capability and sata_max_queue_depth variable setting.
5459  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5460  * used to pass max queue depth value, and the maximum possible queue depth
5461  * is 32.
5462  *
5463  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5464  * appropriate values in scsi_pkt fields.
5465  */
5466 static int
5467 sata_txlt_read(sata_pkt_txlate_t *spx)
5468 {
5469 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5470 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5471 	sata_drive_info_t *sdinfo;
5472 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5473 	int cport = SATA_TXLT_CPORT(spx);
5474 	uint16_t sec_count;
5475 	uint64_t lba;
5476 	int rval, reason;
5477 	int synch;
5478 
5479 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5480 
5481 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5482 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5483 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5484 		return (rval);
5485 	}
5486 
5487 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5488 	    &spx->txlt_sata_pkt->satapkt_device);
5489 
5490 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5491 	/*
5492 	 * Extract LBA and sector count from scsi CDB.
5493 	 */
5494 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5495 	case SCMD_READ:
5496 		/* 6-byte scsi read cmd : 0x08 */
5497 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5498 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5499 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5500 		sec_count = scsipkt->pkt_cdbp[4];
5501 		/* sec_count 0 will be interpreted as 256 by a device */
5502 		break;
5503 	case SCMD_READ_G1:
5504 		/* 10-bytes scsi read command : 0x28 */
5505 		lba = scsipkt->pkt_cdbp[2];
5506 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5507 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5508 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5509 		sec_count = scsipkt->pkt_cdbp[7];
5510 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5511 		break;
5512 	case SCMD_READ_G5:
5513 		/* 12-bytes scsi read command : 0xA8 */
5514 		lba = scsipkt->pkt_cdbp[2];
5515 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5516 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5517 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5518 		sec_count = scsipkt->pkt_cdbp[6];
5519 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5520 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5521 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5522 		break;
5523 	case SCMD_READ_G4:
5524 		/* 16-bytes scsi read command : 0x88 */
5525 		lba = scsipkt->pkt_cdbp[2];
5526 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5527 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5528 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5529 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5530 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5531 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5532 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5533 		sec_count = scsipkt->pkt_cdbp[10];
5534 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5535 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5536 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5537 		break;
5538 	default:
5539 		/* Unsupported command */
5540 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5541 		return (sata_txlt_invalid_command(spx));
5542 	}
5543 
5544 	/*
5545 	 * Check if specified address exceeds device capacity
5546 	 */
5547 	if ((lba >= sdinfo->satadrv_capacity) ||
5548 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5549 		/* LBA out of range */
5550 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5551 		return (sata_txlt_lba_out_of_range(spx));
5552 	}
5553 
5554 	/*
5555 	 * For zero-length transfer, emulate good completion of the command
5556 	 * (reasons for rejecting the command were already checked).
5557 	 * No DMA resources were allocated.
5558 	 */
5559 	if (spx->txlt_dma_cookie_list == NULL) {
5560 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5561 		return (sata_emul_rw_completion(spx));
5562 	}
5563 
5564 	/*
5565 	 * Build cmd block depending on the device capability and
5566 	 * requested operation mode.
5567 	 * Do not bother with non-dma mode - we are working only with
5568 	 * devices supporting DMA.
5569 	 */
5570 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5571 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5572 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
5573 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5574 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5575 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
5576 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5577 #ifndef __lock_lint
5578 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5579 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5580 		scmd->satacmd_lba_high_msb = lba >> 40;
5581 #endif
5582 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5583 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5584 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5585 	}
5586 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5587 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5588 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5589 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5590 	scmd->satacmd_features_reg = 0;
5591 	scmd->satacmd_status_reg = 0;
5592 	scmd->satacmd_error_reg = 0;
5593 
5594 	/*
5595 	 * Check if queueing commands should be used and switch
5596 	 * to appropriate command if possible
5597 	 */
5598 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5599 		boolean_t using_queuing;
5600 
5601 		/* Queuing supported by controller and device? */
5602 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5603 		    (sdinfo->satadrv_features_support &
5604 		    SATA_DEV_F_NCQ) &&
5605 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5606 		    SATA_CTLF_NCQ)) {
5607 			using_queuing = B_TRUE;
5608 
5609 			/* NCQ supported - use FPDMA READ */
5610 			scmd->satacmd_cmd_reg =
5611 			    SATAC_READ_FPDMA_QUEUED;
5612 			scmd->satacmd_features_reg_ext =
5613 			    scmd->satacmd_sec_count_msb;
5614 			scmd->satacmd_sec_count_msb = 0;
5615 		} else if ((sdinfo->satadrv_features_support &
5616 		    SATA_DEV_F_TCQ) &&
5617 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5618 		    SATA_CTLF_QCMD)) {
5619 			using_queuing = B_TRUE;
5620 
5621 			/* Legacy queueing */
5622 			if (sdinfo->satadrv_features_support &
5623 			    SATA_DEV_F_LBA48) {
5624 				scmd->satacmd_cmd_reg =
5625 				    SATAC_READ_DMA_QUEUED_EXT;
5626 				scmd->satacmd_features_reg_ext =
5627 				    scmd->satacmd_sec_count_msb;
5628 				scmd->satacmd_sec_count_msb = 0;
5629 			} else {
5630 				scmd->satacmd_cmd_reg =
5631 				    SATAC_READ_DMA_QUEUED;
5632 			}
5633 		} else	/* NCQ nor legacy queuing not supported */
5634 			using_queuing = B_FALSE;
5635 
5636 		/*
5637 		 * If queuing, the sector count goes in the features register
5638 		 * and the secount count will contain the tag.
5639 		 */
5640 		if (using_queuing) {
5641 			scmd->satacmd_features_reg =
5642 			    scmd->satacmd_sec_count_lsb;
5643 			scmd->satacmd_sec_count_lsb = 0;
5644 			scmd->satacmd_flags.sata_queued = B_TRUE;
5645 
5646 			/* Set-up maximum queue depth */
5647 			scmd->satacmd_flags.sata_max_queue_depth =
5648 			    sdinfo->satadrv_max_queue_depth - 1;
5649 		} else if (sdinfo->satadrv_features_enabled &
5650 		    SATA_DEV_F_E_UNTAGGED_QING) {
5651 			/*
5652 			 * Although NCQ/TCQ is not enabled, untagged queuing
5653 			 * may be still used.
5654 			 * Set-up the maximum untagged queue depth.
5655 			 * Use controller's queue depth from sata_hba_tran.
5656 			 * SATA HBA drivers may ignore this value and rely on
5657 			 * the internal limits.For drivers that do not
5658 			 * ignore untaged queue depth, limit the value to
5659 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5660 			 * largest value that can be passed via
5661 			 * satacmd_flags.sata_max_queue_depth.
5662 			 */
5663 			scmd->satacmd_flags.sata_max_queue_depth =
5664 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5665 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5666 
5667 		} else {
5668 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5669 		}
5670 	} else
5671 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5672 
5673 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
5674 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
5675 	    scmd->satacmd_cmd_reg, lba, sec_count);
5676 
5677 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5678 		/* Need callback function */
5679 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5680 		synch = FALSE;
5681 	} else
5682 		synch = TRUE;
5683 
5684 	/* Transfer command to HBA */
5685 	if (sata_hba_start(spx, &rval) != 0) {
5686 		/* Pkt not accepted for execution */
5687 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5688 		return (rval);
5689 	}
5690 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5691 	/*
5692 	 * If execution is non-synchronous,
5693 	 * a callback function will handle potential errors, translate
5694 	 * the response and will do a callback to a target driver.
5695 	 * If it was synchronous, check execution status using the same
5696 	 * framework callback.
5697 	 */
5698 	if (synch) {
5699 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5700 		    "synchronous execution status %x\n",
5701 		    spx->txlt_sata_pkt->satapkt_reason);
5702 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5703 	}
5704 	return (TRAN_ACCEPT);
5705 }
5706 
5707 
5708 /*
5709  * SATA translate command: Write (various types)
5710  * Translated into appropriate type of ATA WRITE command
5711  * for SATA hard disks.
5712  * Both the device capabilities and requested operation mode are
5713  * considered.
5714  *
5715  * Following scsi cdb fields are ignored:
5716  * rwprotect, dpo, fua, fua_nv, group_number.
5717  *
5718  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5719  * enable variable sata_func_enable), the capability of the controller and
5720  * capability of a device are checked and if both support queueing, write
5721  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
5722  * command rather than plain WRITE_XXX command.
5723  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5724  * both the controller and device suport such functionality, the write
5725  * request will be translated to WRITE_FPDMA_QUEUED command.
5726  * In both cases the maximum queue depth is derived as minimum of:
5727  * HBA capability,device capability and sata_max_queue_depth variable setting.
5728  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5729  * used to pass max queue depth value, and the maximum possible queue depth
5730  * is 32.
5731  *
5732  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5733  * appropriate values in scsi_pkt fields.
5734  */
5735 static int
5736 sata_txlt_write(sata_pkt_txlate_t *spx)
5737 {
5738 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5739 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5740 	sata_drive_info_t *sdinfo;
5741 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5742 	int cport = SATA_TXLT_CPORT(spx);
5743 	uint16_t sec_count;
5744 	uint64_t lba;
5745 	int rval, reason;
5746 	int synch;
5747 
5748 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5749 
5750 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5751 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5752 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5753 		return (rval);
5754 	}
5755 
5756 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5757 	    &spx->txlt_sata_pkt->satapkt_device);
5758 
5759 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5760 	/*
5761 	 * Extract LBA and sector count from scsi CDB
5762 	 */
5763 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5764 	case SCMD_WRITE:
5765 		/* 6-byte scsi read cmd : 0x0A */
5766 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5767 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5768 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5769 		sec_count = scsipkt->pkt_cdbp[4];
5770 		/* sec_count 0 will be interpreted as 256 by a device */
5771 		break;
5772 	case SCMD_WRITE_G1:
5773 		/* 10-bytes scsi write command : 0x2A */
5774 		lba = scsipkt->pkt_cdbp[2];
5775 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5776 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5777 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5778 		sec_count = scsipkt->pkt_cdbp[7];
5779 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5780 		break;
5781 	case SCMD_WRITE_G5:
5782 		/* 12-bytes scsi read command : 0xAA */
5783 		lba = scsipkt->pkt_cdbp[2];
5784 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5785 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5786 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5787 		sec_count = scsipkt->pkt_cdbp[6];
5788 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5789 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5790 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5791 		break;
5792 	case SCMD_WRITE_G4:
5793 		/* 16-bytes scsi write command : 0x8A */
5794 		lba = scsipkt->pkt_cdbp[2];
5795 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5796 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5797 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5798 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5799 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5800 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5801 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5802 		sec_count = scsipkt->pkt_cdbp[10];
5803 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5804 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5805 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5806 		break;
5807 	default:
5808 		/* Unsupported command */
5809 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5810 		return (sata_txlt_invalid_command(spx));
5811 	}
5812 
5813 	/*
5814 	 * Check if specified address and length exceeds device capacity
5815 	 */
5816 	if ((lba >= sdinfo->satadrv_capacity) ||
5817 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5818 		/* LBA out of range */
5819 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5820 		return (sata_txlt_lba_out_of_range(spx));
5821 	}
5822 
5823 	/*
5824 	 * For zero-length transfer, emulate good completion of the command
5825 	 * (reasons for rejecting the command were already checked).
5826 	 * No DMA resources were allocated.
5827 	 */
5828 	if (spx->txlt_dma_cookie_list == NULL) {
5829 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5830 		return (sata_emul_rw_completion(spx));
5831 	}
5832 
5833 	/*
5834 	 * Build cmd block depending on the device capability and
5835 	 * requested operation mode.
5836 	 * Do not bother with non-dma mode- we are working only with
5837 	 * devices supporting DMA.
5838 	 */
5839 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5840 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5841 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
5842 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5843 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5844 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
5845 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5846 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5847 #ifndef __lock_lint
5848 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5849 		scmd->satacmd_lba_high_msb = lba >> 40;
5850 #endif
5851 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5852 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5853 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5854 	}
5855 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5856 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5857 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5858 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5859 	scmd->satacmd_features_reg = 0;
5860 	scmd->satacmd_status_reg = 0;
5861 	scmd->satacmd_error_reg = 0;
5862 
5863 	/*
5864 	 * Check if queueing commands should be used and switch
5865 	 * to appropriate command if possible
5866 	 */
5867 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5868 		boolean_t using_queuing;
5869 
5870 		/* Queuing supported by controller and device? */
5871 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5872 		    (sdinfo->satadrv_features_support &
5873 		    SATA_DEV_F_NCQ) &&
5874 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5875 		    SATA_CTLF_NCQ)) {
5876 			using_queuing = B_TRUE;
5877 
5878 			/* NCQ supported - use FPDMA WRITE */
5879 			scmd->satacmd_cmd_reg =
5880 			    SATAC_WRITE_FPDMA_QUEUED;
5881 			scmd->satacmd_features_reg_ext =
5882 			    scmd->satacmd_sec_count_msb;
5883 			scmd->satacmd_sec_count_msb = 0;
5884 		} else if ((sdinfo->satadrv_features_support &
5885 		    SATA_DEV_F_TCQ) &&
5886 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5887 		    SATA_CTLF_QCMD)) {
5888 			using_queuing = B_TRUE;
5889 
5890 			/* Legacy queueing */
5891 			if (sdinfo->satadrv_features_support &
5892 			    SATA_DEV_F_LBA48) {
5893 				scmd->satacmd_cmd_reg =
5894 				    SATAC_WRITE_DMA_QUEUED_EXT;
5895 				scmd->satacmd_features_reg_ext =
5896 				    scmd->satacmd_sec_count_msb;
5897 				scmd->satacmd_sec_count_msb = 0;
5898 			} else {
5899 				scmd->satacmd_cmd_reg =
5900 				    SATAC_WRITE_DMA_QUEUED;
5901 			}
5902 		} else	/*  NCQ nor legacy queuing not supported */
5903 			using_queuing = B_FALSE;
5904 
5905 		if (using_queuing) {
5906 			scmd->satacmd_features_reg =
5907 			    scmd->satacmd_sec_count_lsb;
5908 			scmd->satacmd_sec_count_lsb = 0;
5909 			scmd->satacmd_flags.sata_queued = B_TRUE;
5910 			/* Set-up maximum queue depth */
5911 			scmd->satacmd_flags.sata_max_queue_depth =
5912 			    sdinfo->satadrv_max_queue_depth - 1;
5913 		} else if (sdinfo->satadrv_features_enabled &
5914 		    SATA_DEV_F_E_UNTAGGED_QING) {
5915 			/*
5916 			 * Although NCQ/TCQ is not enabled, untagged queuing
5917 			 * may be still used.
5918 			 * Set-up the maximum untagged queue depth.
5919 			 * Use controller's queue depth from sata_hba_tran.
5920 			 * SATA HBA drivers may ignore this value and rely on
5921 			 * the internal limits. For drivera that do not
5922 			 * ignore untaged queue depth, limit the value to
5923 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5924 			 * largest value that can be passed via
5925 			 * satacmd_flags.sata_max_queue_depth.
5926 			 */
5927 			scmd->satacmd_flags.sata_max_queue_depth =
5928 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5929 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5930 
5931 		} else {
5932 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5933 		}
5934 	} else
5935 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5936 
5937 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5938 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
5939 	    scmd->satacmd_cmd_reg, lba, sec_count);
5940 
5941 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5942 		/* Need callback function */
5943 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5944 		synch = FALSE;
5945 	} else
5946 		synch = TRUE;
5947 
5948 	/* Transfer command to HBA */
5949 	if (sata_hba_start(spx, &rval) != 0) {
5950 		/* Pkt not accepted for execution */
5951 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5952 		return (rval);
5953 	}
5954 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5955 
5956 	/*
5957 	 * If execution is non-synchronous,
5958 	 * a callback function will handle potential errors, translate
5959 	 * the response and will do a callback to a target driver.
5960 	 * If it was synchronous, check execution status using the same
5961 	 * framework callback.
5962 	 */
5963 	if (synch) {
5964 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5965 		    "synchronous execution status %x\n",
5966 		    spx->txlt_sata_pkt->satapkt_reason);
5967 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5968 	}
5969 	return (TRAN_ACCEPT);
5970 }
5971 
5972 
5973 /*
5974  * Implements SCSI SBC WRITE BUFFER command download microcode option
5975  */
5976 static int
5977 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
5978 {
5979 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
5980 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
5981 
5982 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
5983 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5984 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
5985 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5986 
5987 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5988 	struct scsi_extended_sense *sense;
5989 	int rval, mode, sector_count, reason;
5990 	int cport = SATA_TXLT_CPORT(spx);
5991 
5992 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
5993 
5994 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5995 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
5996 
5997 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5998 
5999 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason)) != TRAN_ACCEPT) {
6000 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6001 		return (rval);
6002 	}
6003 	/*
6004 	 * If in interrupt context, reject this packet because it would issue
6005 	 * a synchronous command to HBA.
6006 	 */
6007 	if (servicing_interrupt()) {
6008 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
6009 		    "sata_txlt_write_buffer: rejecting command because "
6010 		    "of interrupt context\n", NULL);
6011 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6012 		return (TRAN_BUSY);
6013 	}
6014 
6015 	/* Use synchronous mode */
6016 	spx->txlt_sata_pkt->satapkt_op_mode
6017 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
6018 
6019 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6020 
6021 	scsipkt->pkt_reason = CMD_CMPLT;
6022 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6023 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6024 
6025 	/*
6026 	 * The SCSI to ATA translation specification only calls
6027 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6028 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6029 	 * ATA 8 (draft) got rid of download microcode for temp
6030 	 * and it is even optional for ATA 7, so it may be aborted.
6031 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6032 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6033 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6034 	 * sectors.  Thus the offset really doesn't buy us anything.
6035 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6036 	 * is revised, this can be revisisted.
6037 	 */
6038 	/* Reject not supported request */
6039 	switch (mode) {
6040 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6041 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6042 		break;
6043 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6044 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6045 		break;
6046 	default:
6047 		goto bad_param;
6048 	}
6049 
6050 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6051 
6052 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6053 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6054 		goto bad_param;
6055 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6056 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6057 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6058 	scmd->satacmd_lba_mid_lsb = 0;
6059 	scmd->satacmd_lba_high_lsb = 0;
6060 	scmd->satacmd_device_reg = 0;
6061 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6062 	scmd->satacmd_addr_type = 0;
6063 
6064 	/* Transfer command to HBA */
6065 	if (sata_hba_start(spx, &rval) != 0) {
6066 		/* Pkt not accepted for execution */
6067 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6068 		return (rval);
6069 	}
6070 
6071 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6072 
6073 	/* Then we need synchronous check the status of the disk */
6074 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6075 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6076 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6077 		scsipkt->pkt_reason = CMD_CMPLT;
6078 
6079 		/* Download commmand succeed, so probe and identify device */
6080 		sata_reidentify_device(spx);
6081 	} else {
6082 		/* Something went wrong, microcode download command failed */
6083 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6084 		*scsipkt->pkt_scbp = STATUS_CHECK;
6085 		sense = sata_arq_sense(spx);
6086 		switch (sata_pkt->satapkt_reason) {
6087 		case SATA_PKT_PORT_ERROR:
6088 			/*
6089 			 * We have no device data. Assume no data transfered.
6090 			 */
6091 			sense->es_key = KEY_HARDWARE_ERROR;
6092 			break;
6093 
6094 		case SATA_PKT_DEV_ERROR:
6095 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6096 			    SATA_STATUS_ERR) {
6097 				/*
6098 				 * determine dev error reason from error
6099 				 * reg content
6100 				 */
6101 				sata_decode_device_error(spx, sense);
6102 				break;
6103 			}
6104 			/* No extended sense key - no info available */
6105 			break;
6106 
6107 		case SATA_PKT_TIMEOUT:
6108 			scsipkt->pkt_reason = CMD_TIMEOUT;
6109 			scsipkt->pkt_statistics |=
6110 			    STAT_TIMEOUT | STAT_DEV_RESET;
6111 			/* No extended sense key ? */
6112 			break;
6113 
6114 		case SATA_PKT_ABORTED:
6115 			scsipkt->pkt_reason = CMD_ABORTED;
6116 			scsipkt->pkt_statistics |= STAT_ABORTED;
6117 			/* No extended sense key ? */
6118 			break;
6119 
6120 		case SATA_PKT_RESET:
6121 			/* pkt aborted by an explicit reset from a host */
6122 			scsipkt->pkt_reason = CMD_RESET;
6123 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6124 			break;
6125 
6126 		default:
6127 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6128 			    "sata_txlt_nodata_cmd_completion: "
6129 			    "invalid packet completion reason %d",
6130 			    sata_pkt->satapkt_reason));
6131 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6132 			break;
6133 		}
6134 
6135 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6136 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6137 
6138 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6139 			/* scsi callback required */
6140 			scsi_hba_pkt_comp(scsipkt);
6141 	}
6142 	return (TRAN_ACCEPT);
6143 
6144 bad_param:
6145 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6146 	*scsipkt->pkt_scbp = STATUS_CHECK;
6147 	sense = sata_arq_sense(spx);
6148 	sense->es_key = KEY_ILLEGAL_REQUEST;
6149 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6150 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6151 	    scsipkt->pkt_comp != NULL) {
6152 		/* scsi callback required */
6153 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6154 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6155 		    TQ_SLEEP) == 0) {
6156 			/* Scheduling the callback failed */
6157 			rval = TRAN_BUSY;
6158 		}
6159 	}
6160 	return (rval);
6161 }
6162 
6163 /*
6164  * Re-identify device after doing a firmware download.
6165  */
6166 static void
6167 sata_reidentify_device(sata_pkt_txlate_t *spx)
6168 {
6169 #define	DOWNLOAD_WAIT_TIME_SECS	60
6170 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6171 	int rval;
6172 	int retry_cnt;
6173 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6174 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6175 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6176 	sata_drive_info_t *sdinfo;
6177 
6178 	/*
6179 	 * Before returning good status, probe device.
6180 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6181 	 * The assumption is that the new microcode is applied by the
6182 	 * device. It is a caller responsibility to verify this.
6183 	 */
6184 	for (retry_cnt = 0;
6185 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6186 	    retry_cnt++) {
6187 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6188 
6189 		if (rval == SATA_SUCCESS) { /* Set default features */
6190 			sdinfo = sata_get_device_info(sata_hba_inst,
6191 			    &sata_device);
6192 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6193 			    SATA_SUCCESS) {
6194 				/* retry */
6195 				rval = sata_initialize_device(sata_hba_inst,
6196 				    sdinfo);
6197 				if (rval == SATA_RETRY)
6198 					sata_log(sata_hba_inst, CE_WARN,
6199 					    "SATA device at port %d pmport %d -"
6200 					    " default device features could not"
6201 					    " be set. Device may not operate "
6202 					    "as expected.",
6203 					    sata_device.satadev_addr.cport,
6204 					    sata_device.satadev_addr.pmport);
6205 			}
6206 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6207 				scsi_hba_pkt_comp(scsipkt);
6208 			return;
6209 		} else if (rval == SATA_RETRY) {
6210 			delay(drv_usectohz(1000000 *
6211 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6212 			continue;
6213 		} else	/* failed - no reason to retry */
6214 			break;
6215 	}
6216 
6217 	/*
6218 	 * Something went wrong, device probing failed.
6219 	 */
6220 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6221 	    "Cannot probe device after downloading microcode\n"));
6222 
6223 	/* Reset device to force retrying the probe. */
6224 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6225 	    (SATA_DIP(sata_hba_inst), &sata_device);
6226 
6227 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6228 		scsi_hba_pkt_comp(scsipkt);
6229 }
6230 
6231 
6232 /*
6233  * Translate command: Synchronize Cache.
6234  * Translates into Flush Cache command for SATA hard disks.
6235  *
6236  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6237  * appropriate values in scsi_pkt fields.
6238  */
6239 static 	int
6240 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6241 {
6242 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6243 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6244 	int cport = SATA_TXLT_CPORT(spx);
6245 	int rval, reason;
6246 	int synch;
6247 
6248 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6249 
6250 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
6251 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6252 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6253 		return (rval);
6254 	}
6255 
6256 	scmd->satacmd_addr_type = 0;
6257 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6258 	scmd->satacmd_device_reg = 0;
6259 	scmd->satacmd_sec_count_lsb = 0;
6260 	scmd->satacmd_lba_low_lsb = 0;
6261 	scmd->satacmd_lba_mid_lsb = 0;
6262 	scmd->satacmd_lba_high_lsb = 0;
6263 	scmd->satacmd_features_reg = 0;
6264 	scmd->satacmd_status_reg = 0;
6265 	scmd->satacmd_error_reg = 0;
6266 
6267 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6268 	    "sata_txlt_synchronize_cache\n", NULL);
6269 
6270 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6271 		/* Need to set-up a callback function */
6272 		spx->txlt_sata_pkt->satapkt_comp =
6273 		    sata_txlt_nodata_cmd_completion;
6274 		synch = FALSE;
6275 	} else
6276 		synch = TRUE;
6277 
6278 	/* Transfer command to HBA */
6279 	if (sata_hba_start(spx, &rval) != 0) {
6280 		/* Pkt not accepted for execution */
6281 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6282 		return (rval);
6283 	}
6284 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6285 
6286 	/*
6287 	 * If execution non-synchronous, it had to be completed
6288 	 * a callback function will handle potential errors, translate
6289 	 * the response and will do a callback to a target driver.
6290 	 * If it was synchronous, check status, using the same
6291 	 * framework callback.
6292 	 */
6293 	if (synch) {
6294 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6295 		    "synchronous execution status %x\n",
6296 		    spx->txlt_sata_pkt->satapkt_reason);
6297 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6298 	}
6299 	return (TRAN_ACCEPT);
6300 }
6301 
6302 
6303 /*
6304  * Send pkt to SATA HBA driver
6305  *
6306  * This function may be called only if the operation is requested by scsi_pkt,
6307  * i.e. scsi_pkt is not NULL.
6308  *
6309  * This function has to be called with cport mutex held. It does release
6310  * the mutex when it calls HBA driver sata_tran_start function and
6311  * re-acquires it afterwards.
6312  *
6313  * If return value is 0, pkt was accepted, -1 otherwise
6314  * rval is set to appropriate sata_scsi_start return value.
6315  *
6316  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6317  * have called the sata_pkt callback function for this packet.
6318  *
6319  * The scsi callback has to be performed by the caller of this routine.
6320  */
6321 static int
6322 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6323 {
6324 	int stat;
6325 	uint8_t cport = SATA_TXLT_CPORT(spx);
6326 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6327 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6328 	sata_drive_info_t *sdinfo;
6329 	sata_pmult_info_t *pminfo;
6330 	sata_pmport_info_t *pmportinfo = NULL;
6331 	sata_device_t *sata_device = NULL;
6332 	uint8_t cmd;
6333 	struct sata_cmd_flags cmd_flags;
6334 
6335 	ASSERT(spx->txlt_sata_pkt != NULL);
6336 
6337 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6338 
6339 	sdinfo = sata_get_device_info(sata_hba_inst,
6340 	    &spx->txlt_sata_pkt->satapkt_device);
6341 	ASSERT(sdinfo != NULL);
6342 
6343 	/* Clear device reset state? */
6344 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6345 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6346 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6347 
6348 		/*
6349 		 * Get the pmult_info of the its parent port multiplier, all
6350 		 * sub-devices share a common device reset flags on in
6351 		 * pmult_info.
6352 		 */
6353 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
6354 		pmportinfo = pminfo->pmult_dev_port[pmport];
6355 		ASSERT(pminfo != NULL);
6356 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
6357 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6358 			    sata_clear_dev_reset = B_TRUE;
6359 			pminfo->pmult_event_flags &=
6360 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6361 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6362 			    "sata_hba_start: clearing device reset state"
6363 			    "on pmult.\n", NULL);
6364 		}
6365 	} else {
6366 		if (sdinfo->satadrv_event_flags &
6367 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
6368 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6369 			    sata_clear_dev_reset = B_TRUE;
6370 			sdinfo->satadrv_event_flags &=
6371 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6372 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6373 			    "sata_hba_start: clearing device reset state\n",
6374 			    NULL);
6375 		}
6376 	}
6377 
6378 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
6379 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
6380 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
6381 
6382 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6383 
6384 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6385 	    "Sata cmd 0x%2x\n", cmd);
6386 
6387 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
6388 	    spx->txlt_sata_pkt);
6389 
6390 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6391 	/*
6392 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
6393 	 * with the sata callback, the sata_pkt could be already destroyed
6394 	 * by the time we check ther return status from the hba_start()
6395 	 * function, because sata_scsi_destroy_pkt() could have been already
6396 	 * called (perhaps in the interrupt context). So, in such case, there
6397 	 * should be no references to it. In other cases, sata_pkt still
6398 	 * exists.
6399 	 */
6400 	if (stat == SATA_TRAN_ACCEPTED) {
6401 		/*
6402 		 * pkt accepted for execution.
6403 		 * If it was executed synchronously, it is already completed
6404 		 * and pkt completion_reason indicates completion status.
6405 		 */
6406 		*rval = TRAN_ACCEPT;
6407 		return (0);
6408 	}
6409 
6410 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6411 	switch (stat) {
6412 	case SATA_TRAN_QUEUE_FULL:
6413 		/*
6414 		 * Controller detected queue full condition.
6415 		 */
6416 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
6417 		    "sata_hba_start: queue full\n", NULL);
6418 
6419 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6420 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
6421 
6422 		*rval = TRAN_BUSY;
6423 		break;
6424 
6425 	case SATA_TRAN_PORT_ERROR:
6426 		/*
6427 		 * Communication/link with device or general port error
6428 		 * detected before pkt execution begun.
6429 		 */
6430 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6431 		    SATA_ADDR_CPORT ||
6432 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6433 		    SATA_ADDR_DCPORT)
6434 			sata_log(sata_hba_inst, CE_CONT,
6435 			    "SATA port %d error",
6436 			    sata_device->satadev_addr.cport);
6437 		else
6438 			sata_log(sata_hba_inst, CE_CONT,
6439 			    "SATA port %d:%d error\n",
6440 			    sata_device->satadev_addr.cport,
6441 			    sata_device->satadev_addr.pmport);
6442 
6443 		/*
6444 		 * Update the port/device structure.
6445 		 * sata_pkt should be still valid. Since port error is
6446 		 * returned, sata_device content should reflect port
6447 		 * state - it means, that sata address have been changed,
6448 		 * because original packet's sata address refered to a device
6449 		 * attached to some port.
6450 		 */
6451 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
6452 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
6453 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6454 			mutex_enter(&pmportinfo->pmport_mutex);
6455 			sata_update_pmport_info(sata_hba_inst, sata_device);
6456 			mutex_exit(&pmportinfo->pmport_mutex);
6457 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6458 		} else {
6459 			sata_update_port_info(sata_hba_inst, sata_device);
6460 		}
6461 
6462 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6463 		*rval = TRAN_FATAL_ERROR;
6464 		break;
6465 
6466 	case SATA_TRAN_CMD_UNSUPPORTED:
6467 		/*
6468 		 * Command rejected by HBA as unsupported. It was HBA driver
6469 		 * that rejected the command, command was not sent to
6470 		 * an attached device.
6471 		 */
6472 		if ((sdinfo != NULL) &&
6473 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
6474 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6475 			    "sat_hba_start: cmd 0x%2x rejected "
6476 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
6477 
6478 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6479 		(void) sata_txlt_invalid_command(spx);
6480 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6481 
6482 		*rval = TRAN_ACCEPT;
6483 		break;
6484 
6485 	case SATA_TRAN_BUSY:
6486 		/*
6487 		 * Command rejected by HBA because other operation prevents
6488 		 * accepting the packet, or device is in RESET condition.
6489 		 */
6490 		if (sdinfo != NULL) {
6491 			sdinfo->satadrv_state =
6492 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
6493 
6494 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
6495 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6496 				    "sata_hba_start: cmd 0x%2x rejected "
6497 				    "because of device reset condition\n",
6498 				    cmd);
6499 			} else {
6500 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6501 				    "sata_hba_start: cmd 0x%2x rejected "
6502 				    "with SATA_TRAN_BUSY status\n",
6503 				    cmd);
6504 			}
6505 		}
6506 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6507 		*rval = TRAN_BUSY;
6508 		break;
6509 
6510 	default:
6511 		/* Unrecognized HBA response */
6512 		SATA_LOG_D((sata_hba_inst, CE_WARN,
6513 		    "sata_hba_start: unrecognized HBA response "
6514 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
6515 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6516 		*rval = TRAN_FATAL_ERROR;
6517 		break;
6518 	}
6519 
6520 	/*
6521 	 * If we got here, the packet was rejected.
6522 	 * Check if we need to remember reset state clearing request
6523 	 */
6524 	if (cmd_flags.sata_clear_dev_reset) {
6525 		/*
6526 		 * Check if device is still configured - it may have
6527 		 * disapeared from the configuration
6528 		 */
6529 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6530 		if (sdinfo != NULL) {
6531 			/*
6532 			 * Restore the flag that requests clearing of
6533 			 * the device reset state,
6534 			 * so the next sata packet may carry it to HBA.
6535 			 */
6536 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
6537 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
6538 				pminfo->pmult_event_flags |=
6539 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6540 			} else {
6541 				sdinfo->satadrv_event_flags |=
6542 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6543 			}
6544 		}
6545 	}
6546 	return (-1);
6547 }
6548 
6549 /*
6550  * Scsi response setup for invalid LBA
6551  *
6552  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
6553  */
6554 static int
6555 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
6556 {
6557 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6558 	struct scsi_extended_sense *sense;
6559 
6560 	scsipkt->pkt_reason = CMD_CMPLT;
6561 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6562 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6563 	*scsipkt->pkt_scbp = STATUS_CHECK;
6564 
6565 	*scsipkt->pkt_scbp = STATUS_CHECK;
6566 	sense = sata_arq_sense(spx);
6567 	sense->es_key = KEY_ILLEGAL_REQUEST;
6568 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6569 
6570 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6571 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6572 
6573 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6574 	    scsipkt->pkt_comp != NULL)
6575 		/* scsi callback required */
6576 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6577 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6578 		    TQ_SLEEP) == NULL)
6579 			/* Scheduling the callback failed */
6580 			return (TRAN_BUSY);
6581 	return (TRAN_ACCEPT);
6582 }
6583 
6584 
6585 /*
6586  * Analyze device status and error registers and translate them into
6587  * appropriate scsi sense codes.
6588  * NOTE: non-packet commands only for now
6589  */
6590 static void
6591 sata_decode_device_error(sata_pkt_txlate_t *spx,
6592     struct scsi_extended_sense *sense)
6593 {
6594 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
6595 
6596 	ASSERT(sense != NULL);
6597 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
6598 	    SATA_STATUS_ERR);
6599 
6600 
6601 	if (err_reg & SATA_ERROR_ICRC) {
6602 		sense->es_key = KEY_ABORTED_COMMAND;
6603 		sense->es_add_code = 0x08; /* Communication failure */
6604 		return;
6605 	}
6606 
6607 	if (err_reg & SATA_ERROR_UNC) {
6608 		sense->es_key = KEY_MEDIUM_ERROR;
6609 		/* Information bytes (LBA) need to be set by a caller */
6610 		return;
6611 	}
6612 
6613 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
6614 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
6615 		sense->es_key = KEY_UNIT_ATTENTION;
6616 		sense->es_add_code = 0x3a; /* No media present */
6617 		return;
6618 	}
6619 
6620 	if (err_reg & SATA_ERROR_IDNF) {
6621 		if (err_reg & SATA_ERROR_ABORT) {
6622 			sense->es_key = KEY_ABORTED_COMMAND;
6623 		} else {
6624 			sense->es_key = KEY_ILLEGAL_REQUEST;
6625 			sense->es_add_code = 0x21; /* LBA out of range */
6626 		}
6627 		return;
6628 	}
6629 
6630 	if (err_reg & SATA_ERROR_ABORT) {
6631 		ASSERT(spx->txlt_sata_pkt != NULL);
6632 		sense->es_key = KEY_ABORTED_COMMAND;
6633 		return;
6634 	}
6635 }
6636 
6637 /*
6638  * Extract error LBA from sata_pkt.satapkt_cmd register fields
6639  */
6640 static void
6641 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
6642 {
6643 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
6644 
6645 	*lba = 0;
6646 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
6647 		*lba = sata_cmd->satacmd_lba_high_msb;
6648 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
6649 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
6650 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
6651 		*lba = sata_cmd->satacmd_device_reg & 0xf;
6652 	}
6653 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
6654 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
6655 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
6656 }
6657 
6658 /*
6659  * This is fixed sense format - if LBA exceeds the info field size,
6660  * no valid info will be returned (valid bit in extended sense will
6661  * be set to 0).
6662  */
6663 static struct scsi_extended_sense *
6664 sata_arq_sense(sata_pkt_txlate_t *spx)
6665 {
6666 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6667 	struct scsi_arq_status *arqs;
6668 	struct scsi_extended_sense *sense;
6669 
6670 	/* Fill ARQ sense data */
6671 	scsipkt->pkt_state |= STATE_ARQ_DONE;
6672 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
6673 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
6674 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
6675 	arqs->sts_rqpkt_reason = CMD_CMPLT;
6676 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6677 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
6678 	arqs->sts_rqpkt_resid = 0;
6679 	sense = &arqs->sts_sensedata;
6680 	bzero(sense, sizeof (struct scsi_extended_sense));
6681 	sata_fixed_sense_data_preset(sense);
6682 	return (sense);
6683 }
6684 
6685 /*
6686  * ATA Pass Through support
6687  * Sets flags indicating that an invalid value was found in some
6688  * field in the command.  It could be something illegal according to
6689  * the SAT-2 spec or it could be a feature that is not (yet?)
6690  * supported.
6691  */
6692 static int
6693 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
6694 {
6695 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6696 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
6697 
6698 	scsipkt->pkt_reason = CMD_CMPLT;
6699 	*scsipkt->pkt_scbp = STATUS_CHECK;
6700 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6701 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6702 
6703 	sense = sata_arq_sense(spx);
6704 	sense->es_key = KEY_ILLEGAL_REQUEST;
6705 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6706 
6707 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6708 	    scsipkt->pkt_comp != NULL)
6709 		/* scsi callback required */
6710 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6711 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6712 		    TQ_SLEEP) == NULL)
6713 			/* Scheduling the callback failed */
6714 			return (TRAN_BUSY);
6715 
6716 	return (TRAN_ACCEPT);
6717 }
6718 
6719 /*
6720  * Emulated SATA Read/Write command completion for zero-length requests.
6721  * This request always succedes, so in synchronous mode it always returns
6722  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
6723  * callback cannot be scheduled.
6724  */
6725 static int
6726 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
6727 {
6728 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6729 
6730 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6731 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6732 	scsipkt->pkt_reason = CMD_CMPLT;
6733 	*scsipkt->pkt_scbp = STATUS_GOOD;
6734 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6735 		/* scsi callback required - have to schedule it */
6736 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6737 		    (task_func_t *)scsipkt->pkt_comp,
6738 		    (void *)scsipkt, TQ_SLEEP) == NULL)
6739 			/* Scheduling the callback failed */
6740 			return (TRAN_BUSY);
6741 	}
6742 	return (TRAN_ACCEPT);
6743 }
6744 
6745 
6746 /*
6747  * Translate completion status of SATA read/write commands into scsi response.
6748  * pkt completion_reason is checked to determine the completion status.
6749  * Do scsi callback if necessary.
6750  *
6751  * Note: this function may be called also for synchronously executed
6752  * commands.
6753  * This function may be used only if scsi_pkt is non-NULL.
6754  */
6755 static void
6756 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
6757 {
6758 	sata_pkt_txlate_t *spx =
6759 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6760 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6761 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6762 	struct scsi_extended_sense *sense;
6763 	uint64_t lba;
6764 	struct buf *bp;
6765 	int rval;
6766 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6767 		/* Normal completion */
6768 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6769 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6770 		scsipkt->pkt_reason = CMD_CMPLT;
6771 		*scsipkt->pkt_scbp = STATUS_GOOD;
6772 		if (spx->txlt_tmp_buf != NULL) {
6773 			/* Temporary buffer was used */
6774 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6775 			if (bp->b_flags & B_READ) {
6776 				rval = ddi_dma_sync(
6777 				    spx->txlt_buf_dma_handle, 0, 0,
6778 				    DDI_DMA_SYNC_FORCPU);
6779 				ASSERT(rval == DDI_SUCCESS);
6780 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6781 				    bp->b_bcount);
6782 			}
6783 		}
6784 	} else {
6785 		/*
6786 		 * Something went wrong - analyze return
6787 		 */
6788 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6789 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6790 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6791 		*scsipkt->pkt_scbp = STATUS_CHECK;
6792 		sense = sata_arq_sense(spx);
6793 		ASSERT(sense != NULL);
6794 
6795 		/*
6796 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
6797 		 * extract from device registers the failing LBA.
6798 		 */
6799 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
6800 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
6801 			    (scmd->satacmd_lba_mid_msb != 0 ||
6802 			    scmd->satacmd_lba_high_msb != 0)) {
6803 				/*
6804 				 * We have problem reporting this cmd LBA
6805 				 * in fixed sense data format, because of
6806 				 * the size of the scsi LBA fields.
6807 				 */
6808 				sense->es_valid = 0;
6809 			} else {
6810 				sata_extract_error_lba(spx, &lba);
6811 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
6812 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
6813 				sense->es_info_3 = (lba & 0xFF00) >> 8;
6814 				sense->es_info_4 = lba & 0xFF;
6815 			}
6816 		} else {
6817 			/* Invalid extended sense info */
6818 			sense->es_valid = 0;
6819 		}
6820 
6821 		switch (sata_pkt->satapkt_reason) {
6822 		case SATA_PKT_PORT_ERROR:
6823 			/* We may want to handle DEV GONE state as well */
6824 			/*
6825 			 * We have no device data. Assume no data transfered.
6826 			 */
6827 			sense->es_key = KEY_HARDWARE_ERROR;
6828 			break;
6829 
6830 		case SATA_PKT_DEV_ERROR:
6831 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6832 			    SATA_STATUS_ERR) {
6833 				/*
6834 				 * determine dev error reason from error
6835 				 * reg content
6836 				 */
6837 				sata_decode_device_error(spx, sense);
6838 				if (sense->es_key == KEY_MEDIUM_ERROR) {
6839 					switch (scmd->satacmd_cmd_reg) {
6840 					case SATAC_READ_DMA:
6841 					case SATAC_READ_DMA_EXT:
6842 					case SATAC_READ_DMA_QUEUED:
6843 					case SATAC_READ_DMA_QUEUED_EXT:
6844 					case SATAC_READ_FPDMA_QUEUED:
6845 						/* Unrecovered read error */
6846 						sense->es_add_code =
6847 						    SD_SCSI_ASC_UNREC_READ_ERR;
6848 						break;
6849 					case SATAC_WRITE_DMA:
6850 					case SATAC_WRITE_DMA_EXT:
6851 					case SATAC_WRITE_DMA_QUEUED:
6852 					case SATAC_WRITE_DMA_QUEUED_EXT:
6853 					case SATAC_WRITE_FPDMA_QUEUED:
6854 						/* Write error */
6855 						sense->es_add_code =
6856 						    SD_SCSI_ASC_WRITE_ERR;
6857 						break;
6858 					default:
6859 						/* Internal error */
6860 						SATA_LOG_D((
6861 						    spx->txlt_sata_hba_inst,
6862 						    CE_WARN,
6863 						    "sata_txlt_rw_completion :"
6864 						    "internal error - invalid "
6865 						    "command 0x%2x",
6866 						    scmd->satacmd_cmd_reg));
6867 						break;
6868 					}
6869 				}
6870 				break;
6871 			}
6872 			/* No extended sense key - no info available */
6873 			scsipkt->pkt_reason = CMD_INCOMPLETE;
6874 			break;
6875 
6876 		case SATA_PKT_TIMEOUT:
6877 			scsipkt->pkt_reason = CMD_TIMEOUT;
6878 			scsipkt->pkt_statistics |=
6879 			    STAT_TIMEOUT | STAT_DEV_RESET;
6880 			sense->es_key = KEY_ABORTED_COMMAND;
6881 			break;
6882 
6883 		case SATA_PKT_ABORTED:
6884 			scsipkt->pkt_reason = CMD_ABORTED;
6885 			scsipkt->pkt_statistics |= STAT_ABORTED;
6886 			sense->es_key = KEY_ABORTED_COMMAND;
6887 			break;
6888 
6889 		case SATA_PKT_RESET:
6890 			scsipkt->pkt_reason = CMD_RESET;
6891 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6892 			sense->es_key = KEY_ABORTED_COMMAND;
6893 			break;
6894 
6895 		default:
6896 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6897 			    "sata_txlt_rw_completion: "
6898 			    "invalid packet completion reason"));
6899 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6900 			break;
6901 		}
6902 	}
6903 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6904 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6905 
6906 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6907 		/* scsi callback required */
6908 		scsi_hba_pkt_comp(scsipkt);
6909 }
6910 
6911 
6912 /*
6913  * Translate completion status of non-data commands (i.e. commands returning
6914  * no data).
6915  * pkt completion_reason is checked to determine the completion status.
6916  * Do scsi callback if necessary (FLAG_NOINTR == 0)
6917  *
6918  * Note: this function may be called also for synchronously executed
6919  * commands.
6920  * This function may be used only if scsi_pkt is non-NULL.
6921  */
6922 
6923 static	void
6924 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
6925 {
6926 	sata_pkt_txlate_t *spx =
6927 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6928 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6929 
6930 	sata_set_arq_data(sata_pkt);
6931 
6932 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6933 		/* scsi callback required */
6934 		scsi_hba_pkt_comp(scsipkt);
6935 }
6936 
6937 /*
6938  * Completion handler for ATA Pass Through command
6939  */
6940 static void
6941 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
6942 {
6943 	sata_pkt_txlate_t *spx =
6944 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6945 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6946 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6947 	struct buf *bp;
6948 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
6949 
6950 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6951 		/* Normal completion */
6952 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6953 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6954 		scsipkt->pkt_reason = CMD_CMPLT;
6955 		*scsipkt->pkt_scbp = STATUS_GOOD;
6956 
6957 		/*
6958 		 * If the command has CK_COND set
6959 		 */
6960 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
6961 			*scsipkt->pkt_scbp = STATUS_CHECK;
6962 			sata_fill_ata_return_desc(sata_pkt,
6963 			    KEY_RECOVERABLE_ERROR,
6964 			    SD_SCSI_ASC_ATP_INFO_AVAIL, 0);
6965 		}
6966 
6967 		if (spx->txlt_tmp_buf != NULL) {
6968 			/* Temporary buffer was used */
6969 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6970 			if (bp->b_flags & B_READ) {
6971 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6972 				    bp->b_bcount);
6973 			}
6974 		}
6975 	} else {
6976 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6977 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6978 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6979 		*scsipkt->pkt_scbp = STATUS_CHECK;
6980 
6981 		/*
6982 		 * If DF or ERR was set, the HBA should have copied out the
6983 		 * status and error registers to the satacmd structure.
6984 		 */
6985 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
6986 			sense_key = KEY_HARDWARE_ERROR;
6987 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
6988 			addl_sense_qual = 0;
6989 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
6990 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
6991 				sense_key = KEY_NOT_READY;
6992 				addl_sense_code =
6993 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
6994 				addl_sense_qual = 0;
6995 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
6996 				sense_key = KEY_MEDIUM_ERROR;
6997 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
6998 				addl_sense_qual = 0;
6999 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7000 				sense_key = KEY_DATA_PROTECT;
7001 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7002 				addl_sense_qual = 0;
7003 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7004 				sense_key = KEY_ILLEGAL_REQUEST;
7005 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7006 				addl_sense_qual = 0;
7007 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7008 				sense_key = KEY_ABORTED_COMMAND;
7009 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7010 				addl_sense_qual = 0;
7011 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7012 				sense_key = KEY_UNIT_ATTENTION;
7013 				addl_sense_code =
7014 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7015 				addl_sense_qual = 0;
7016 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7017 				sense_key = KEY_UNIT_ATTENTION;
7018 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7019 				addl_sense_qual = 0;
7020 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7021 				sense_key = KEY_ABORTED_COMMAND;
7022 				addl_sense_code =
7023 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7024 				addl_sense_qual = 0;
7025 			}
7026 		}
7027 
7028 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7029 		    addl_sense_qual);
7030 	}
7031 
7032 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7033 		/* scsi callback required */
7034 		scsi_hba_pkt_comp(scsipkt);
7035 }
7036 
7037 /*
7038  * j
7039  */
7040 static void
7041 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7042     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7043 {
7044 	sata_pkt_txlate_t *spx =
7045 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7046 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7047 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7048 	struct sata_apt_sense_data *apt_sd =
7049 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7050 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7051 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7052 	    &(apt_sd->apt_sd_sense);
7053 	int extend = 0;
7054 
7055 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7056 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7057 		extend = 1;
7058 
7059 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7060 
7061 	/* update the residual count */
7062 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7063 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7064 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7065 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7066 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7067 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7068 	    sizeof (struct sata_apt_sense_data);
7069 
7070 	/*
7071 	 * Fill in the Descriptor sense header
7072 	 */
7073 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7074 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7075 	sds->ds_class = CLASS_EXTENDED_SENSE;
7076 	sds->ds_key = sense_key & 0xf;
7077 	sds->ds_add_code = addl_sense_code;
7078 	sds->ds_qual_code = addl_sense_qual;
7079 	sds->ds_addl_sense_length =
7080 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7081 
7082 	/*
7083 	 * Fill in the ATA Return descriptor sense data
7084 	 */
7085 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7086 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7087 	ata_ret_desc->ars_addl_length = 0xc;
7088 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7089 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7090 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7091 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7092 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7093 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7094 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7095 
7096 	if (extend == 1) {
7097 		ata_ret_desc->ars_extend = 1;
7098 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7099 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7100 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7101 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7102 	} else {
7103 		ata_ret_desc->ars_extend = 0;
7104 		ata_ret_desc->ars_sec_count_msb = 0;
7105 		ata_ret_desc->ars_lba_low_msb = 0;
7106 		ata_ret_desc->ars_lba_mid_msb = 0;
7107 		ata_ret_desc->ars_lba_high_msb = 0;
7108 	}
7109 }
7110 
7111 static	void
7112 sata_set_arq_data(sata_pkt_t *sata_pkt)
7113 {
7114 	sata_pkt_txlate_t *spx =
7115 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7116 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7117 	struct scsi_extended_sense *sense;
7118 
7119 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7120 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7121 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7122 		/* Normal completion */
7123 		scsipkt->pkt_reason = CMD_CMPLT;
7124 		*scsipkt->pkt_scbp = STATUS_GOOD;
7125 	} else {
7126 		/* Something went wrong */
7127 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7128 		*scsipkt->pkt_scbp = STATUS_CHECK;
7129 		sense = sata_arq_sense(spx);
7130 		switch (sata_pkt->satapkt_reason) {
7131 		case SATA_PKT_PORT_ERROR:
7132 			/*
7133 			 * We have no device data. Assume no data transfered.
7134 			 */
7135 			sense->es_key = KEY_HARDWARE_ERROR;
7136 			break;
7137 
7138 		case SATA_PKT_DEV_ERROR:
7139 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7140 			    SATA_STATUS_ERR) {
7141 				/*
7142 				 * determine dev error reason from error
7143 				 * reg content
7144 				 */
7145 				sata_decode_device_error(spx, sense);
7146 				break;
7147 			}
7148 			/* No extended sense key - no info available */
7149 			break;
7150 
7151 		case SATA_PKT_TIMEOUT:
7152 			scsipkt->pkt_reason = CMD_TIMEOUT;
7153 			scsipkt->pkt_statistics |=
7154 			    STAT_TIMEOUT | STAT_DEV_RESET;
7155 			/* No extended sense key ? */
7156 			break;
7157 
7158 		case SATA_PKT_ABORTED:
7159 			scsipkt->pkt_reason = CMD_ABORTED;
7160 			scsipkt->pkt_statistics |= STAT_ABORTED;
7161 			/* No extended sense key ? */
7162 			break;
7163 
7164 		case SATA_PKT_RESET:
7165 			/* pkt aborted by an explicit reset from a host */
7166 			scsipkt->pkt_reason = CMD_RESET;
7167 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7168 			break;
7169 
7170 		default:
7171 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7172 			    "sata_txlt_nodata_cmd_completion: "
7173 			    "invalid packet completion reason %d",
7174 			    sata_pkt->satapkt_reason));
7175 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7176 			break;
7177 		}
7178 
7179 	}
7180 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7181 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7182 }
7183 
7184 
7185 /*
7186  * Build Mode sense R/W recovery page
7187  * NOT IMPLEMENTED
7188  */
7189 
7190 static int
7191 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7192 {
7193 #ifndef __lock_lint
7194 	_NOTE(ARGUNUSED(sdinfo))
7195 	_NOTE(ARGUNUSED(pcntrl))
7196 	_NOTE(ARGUNUSED(buf))
7197 #endif
7198 	return (0);
7199 }
7200 
7201 /*
7202  * Build Mode sense caching page  -  scsi-3 implementation.
7203  * Page length distinguishes previous format from scsi-3 format.
7204  * buf must have space for 0x12 bytes.
7205  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
7206  *
7207  */
7208 static int
7209 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7210 {
7211 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
7212 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7213 
7214 	/*
7215 	 * Most of the fields are set to 0, being not supported and/or disabled
7216 	 */
7217 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
7218 
7219 	/* Saved paramters not supported */
7220 	if (pcntrl == 3)
7221 		return (0);
7222 	if (pcntrl == 0 || pcntrl == 2) {
7223 		/*
7224 		 * For now treat current and default parameters as same
7225 		 * That may have to change, if target driver will complain
7226 		 */
7227 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
7228 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7229 
7230 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
7231 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
7232 			page->dra = 1;		/* Read Ahead disabled */
7233 			page->rcd = 1;		/* Read Cache disabled */
7234 		}
7235 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
7236 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
7237 			page->wce = 1;		/* Write Cache enabled */
7238 	} else {
7239 		/* Changeable parameters */
7240 		page->mode_page.code = MODEPAGE_CACHING;
7241 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7242 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7243 			page->dra = 1;
7244 			page->rcd = 1;
7245 		}
7246 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
7247 			page->wce = 1;
7248 	}
7249 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7250 	    sizeof (struct mode_page));
7251 }
7252 
7253 /*
7254  * Build Mode sense exception cntrl page
7255  */
7256 static int
7257 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7258 {
7259 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
7260 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7261 
7262 	/*
7263 	 * Most of the fields are set to 0, being not supported and/or disabled
7264 	 */
7265 	bzero(buf, PAGELENGTH_INFO_EXCPT);
7266 
7267 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
7268 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
7269 
7270 	/* Indicate that this is page is saveable */
7271 	page->mode_page.ps = 1;
7272 
7273 	/*
7274 	 * We will return the same data for default, current and saved page.
7275 	 * The only changeable bit is dexcpt and that bit is required
7276 	 * by the ATA specification to be preserved across power cycles.
7277 	 */
7278 	if (pcntrl != 1) {
7279 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
7280 		page->mrie = MRIE_ONLY_ON_REQUEST;
7281 	}
7282 	else
7283 		page->dexcpt = 1;	/* Only changeable parameter */
7284 
7285 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
7286 }
7287 
7288 
7289 static int
7290 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7291 {
7292 	struct mode_acoustic_management *page =
7293 	    (struct mode_acoustic_management *)buf;
7294 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7295 
7296 	/*
7297 	 * Most of the fields are set to 0, being not supported and/or disabled
7298 	 */
7299 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
7300 
7301 	switch (pcntrl) {
7302 	case P_CNTRL_DEFAULT:
7303 		/*  default paramters not supported */
7304 		return (0);
7305 
7306 	case P_CNTRL_CURRENT:
7307 	case P_CNTRL_SAVED:
7308 		/* Saved and current are supported and are identical */
7309 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7310 		page->mode_page.length =
7311 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7312 		page->mode_page.ps = 1;
7313 
7314 		/* Word 83 indicates if feature is supported */
7315 		/* If feature is not supported */
7316 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
7317 			page->acoustic_manag_enable =
7318 			    ACOUSTIC_DISABLED;
7319 		} else {
7320 			page->acoustic_manag_enable =
7321 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
7322 			    != 0);
7323 			/* Word 94 inidicates the value */
7324 #ifdef	_LITTLE_ENDIAN
7325 			page->acoustic_manag_level =
7326 			    (uchar_t)sata_id->ai_acoustic;
7327 			page->vendor_recommended_value =
7328 			    sata_id->ai_acoustic >> 8;
7329 #else
7330 			page->acoustic_manag_level =
7331 			    sata_id->ai_acoustic >> 8;
7332 			page->vendor_recommended_value =
7333 			    (uchar_t)sata_id->ai_acoustic;
7334 #endif
7335 		}
7336 		break;
7337 
7338 	case P_CNTRL_CHANGEABLE:
7339 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7340 		page->mode_page.length =
7341 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7342 		page->mode_page.ps = 1;
7343 
7344 		/* Word 83 indicates if the feature is supported */
7345 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
7346 			page->acoustic_manag_enable =
7347 			    ACOUSTIC_ENABLED;
7348 			page->acoustic_manag_level = 0xff;
7349 		}
7350 		break;
7351 	}
7352 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7353 	    sizeof (struct mode_page));
7354 }
7355 
7356 
7357 /*
7358  * Build Mode sense power condition page.
7359  */
7360 static int
7361 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7362 {
7363 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
7364 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7365 
7366 	/*
7367 	 * Most of the fields are set to 0, being not supported and/or disabled
7368 	 * power condition page length was 0x0a
7369 	 */
7370 	bzero(buf, sizeof (struct mode_info_power_cond));
7371 
7372 	if (pcntrl == P_CNTRL_DEFAULT) {
7373 		/*  default paramters not supported */
7374 		return (0);
7375 	}
7376 
7377 	page->mode_page.code = MODEPAGE_POWER_COND;
7378 	page->mode_page.length = sizeof (struct mode_info_power_cond);
7379 
7380 	if (sata_id->ai_cap && SATA_STANDBYTIMER) {
7381 		page->standby = 1;
7382 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
7383 		    sizeof (uchar_t) * 4);
7384 	}
7385 
7386 	return (sizeof (struct mode_info_power_cond));
7387 }
7388 
7389 /*
7390  * Process mode select caching page 8 (scsi3 format only).
7391  * Read Ahead (same as read cache) and Write Cache may be turned on and off
7392  * if these features are supported by the device. If these features are not
7393  * supported, the command will be terminated with STATUS_CHECK.
7394  * This function fails only if the SET FEATURE command sent to
7395  * the device fails. The page format is not varified, assuming that the
7396  * target driver operates correctly - if parameters length is too short,
7397  * we just drop the page.
7398  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
7399  * setting have to be changed.
7400  * SET FEATURE command is executed synchronously, i.e. we wait here until
7401  * it is completed, regardless of the scsi pkt directives.
7402  *
7403  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
7404  * changing DRA will change RCD.
7405  *
7406  * More than one SATA command may be executed to perform operations specified
7407  * by mode select pages. The first error terminates further execution.
7408  * Operations performed successully are not backed-up in such case.
7409  *
7410  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7411  * If operation resulted in changing device setup, dmod flag should be set to
7412  * one (1). If parameters were not changed, dmod flag should be set to 0.
7413  * Upon return, if operation required sending command to the device, the rval
7414  * should be set to the value returned by sata_hba_start. If operation
7415  * did not require device access, rval should be set to TRAN_ACCEPT.
7416  * The pagelen should be set to the length of the page.
7417  *
7418  * This function has to be called with a port mutex held.
7419  *
7420  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7421  */
7422 int
7423 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
7424     int parmlen, int *pagelen, int *rval, int *dmod)
7425 {
7426 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7427 	sata_drive_info_t *sdinfo;
7428 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7429 	sata_id_t *sata_id;
7430 	struct scsi_extended_sense *sense;
7431 	int wce, dra;	/* Current settings */
7432 
7433 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7434 	    &spx->txlt_sata_pkt->satapkt_device);
7435 	sata_id = &sdinfo->satadrv_id;
7436 	*dmod = 0;
7437 
7438 	/* Verify parameters length. If too short, drop it */
7439 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7440 	    sizeof (struct mode_page)) > parmlen) {
7441 		*scsipkt->pkt_scbp = STATUS_CHECK;
7442 		sense = sata_arq_sense(spx);
7443 		sense->es_key = KEY_ILLEGAL_REQUEST;
7444 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7445 		*pagelen = parmlen;
7446 		*rval = TRAN_ACCEPT;
7447 		return (SATA_FAILURE);
7448 	}
7449 
7450 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
7451 
7452 	/* Current setting of Read Ahead (and Read Cache) */
7453 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
7454 		dra = 0;	/* 0 == not disabled */
7455 	else
7456 		dra = 1;
7457 	/* Current setting of Write Cache */
7458 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
7459 		wce = 1;
7460 	else
7461 		wce = 0;
7462 
7463 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
7464 		/* nothing to do */
7465 		*rval = TRAN_ACCEPT;
7466 		return (SATA_SUCCESS);
7467 	}
7468 
7469 	/*
7470 	 * Need to flip some setting
7471 	 * Set-up Internal SET FEATURES command(s)
7472 	 */
7473 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7474 	scmd->satacmd_addr_type = 0;
7475 	scmd->satacmd_device_reg = 0;
7476 	scmd->satacmd_status_reg = 0;
7477 	scmd->satacmd_error_reg = 0;
7478 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7479 	if (page->dra != dra || page->rcd != dra) {
7480 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7481 			/* Need to flip read ahead setting */
7482 			if (dra == 0)
7483 				/* Disable read ahead / read cache */
7484 				scmd->satacmd_features_reg =
7485 				    SATAC_SF_DISABLE_READ_AHEAD;
7486 			else
7487 				/* Enable read ahead  / read cache */
7488 				scmd->satacmd_features_reg =
7489 				    SATAC_SF_ENABLE_READ_AHEAD;
7490 
7491 			/* Transfer command to HBA */
7492 			if (sata_hba_start(spx, rval) != 0)
7493 				/*
7494 				 * Pkt not accepted for execution.
7495 				 */
7496 				return (SATA_FAILURE);
7497 
7498 			*dmod = 1;
7499 
7500 			/* Now process return */
7501 			if (spx->txlt_sata_pkt->satapkt_reason !=
7502 			    SATA_PKT_COMPLETED) {
7503 				goto failure;	/* Terminate */
7504 			}
7505 		} else {
7506 			*scsipkt->pkt_scbp = STATUS_CHECK;
7507 			sense = sata_arq_sense(spx);
7508 			sense->es_key = KEY_ILLEGAL_REQUEST;
7509 			sense->es_add_code =
7510 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7511 			*pagelen = parmlen;
7512 			*rval = TRAN_ACCEPT;
7513 			return (SATA_FAILURE);
7514 		}
7515 	}
7516 
7517 	/* Note that the packet is not removed, so it could be re-used */
7518 	if (page->wce != wce) {
7519 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
7520 			/* Need to flip Write Cache setting */
7521 			if (page->wce == 1)
7522 				/* Enable write cache */
7523 				scmd->satacmd_features_reg =
7524 				    SATAC_SF_ENABLE_WRITE_CACHE;
7525 			else
7526 				/* Disable write cache */
7527 				scmd->satacmd_features_reg =
7528 				    SATAC_SF_DISABLE_WRITE_CACHE;
7529 
7530 			/* Transfer command to HBA */
7531 			if (sata_hba_start(spx, rval) != 0)
7532 				/*
7533 				 * Pkt not accepted for execution.
7534 				 */
7535 				return (SATA_FAILURE);
7536 
7537 			*dmod = 1;
7538 
7539 			/* Now process return */
7540 			if (spx->txlt_sata_pkt->satapkt_reason !=
7541 			    SATA_PKT_COMPLETED) {
7542 				goto failure;
7543 			}
7544 		} else {
7545 			*scsipkt->pkt_scbp = STATUS_CHECK;
7546 			sense = sata_arq_sense(spx);
7547 			sense->es_key = KEY_ILLEGAL_REQUEST;
7548 			sense->es_add_code =
7549 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7550 			*pagelen = parmlen;
7551 			*rval = TRAN_ACCEPT;
7552 			return (SATA_FAILURE);
7553 		}
7554 	}
7555 	return (SATA_SUCCESS);
7556 
7557 failure:
7558 	sata_xlate_errors(spx);
7559 
7560 	return (SATA_FAILURE);
7561 }
7562 
7563 /*
7564  * Process mode select informational exceptions control page 0x1c
7565  *
7566  * The only changeable bit is dexcpt (disable exceptions).
7567  * MRIE (method of reporting informational exceptions) must be
7568  * "only on request".
7569  * This page applies to informational exceptions that report
7570  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
7571  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
7572  * Informational exception conditions occur as the result of background scan
7573  * errors, background self-test errors, or vendor specific events within a
7574  * logical unit. An informational exception condition may occur asynchronous
7575  * to any commands.
7576  *
7577  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7578  * If operation resulted in changing device setup, dmod flag should be set to
7579  * one (1). If parameters were not changed, dmod flag should be set to 0.
7580  * Upon return, if operation required sending command to the device, the rval
7581  * should be set to the value returned by sata_hba_start. If operation
7582  * did not require device access, rval should be set to TRAN_ACCEPT.
7583  * The pagelen should be set to the length of the page.
7584  *
7585  * This function has to be called with a port mutex held.
7586  *
7587  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7588  *
7589  * Cannot be called in the interrupt context.
7590  */
7591 static	int
7592 sata_mode_select_page_1c(
7593 	sata_pkt_txlate_t *spx,
7594 	struct mode_info_excpt_page *page,
7595 	int parmlen,
7596 	int *pagelen,
7597 	int *rval,
7598 	int *dmod)
7599 {
7600 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7601 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7602 	sata_drive_info_t *sdinfo;
7603 	sata_id_t *sata_id;
7604 	struct scsi_extended_sense *sense;
7605 
7606 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7607 	    &spx->txlt_sata_pkt->satapkt_device);
7608 	sata_id = &sdinfo->satadrv_id;
7609 
7610 	*dmod = 0;
7611 
7612 	/* Verify parameters length. If too short, drop it */
7613 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
7614 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
7615 		*scsipkt->pkt_scbp = STATUS_CHECK;
7616 		sense = sata_arq_sense(spx);
7617 		sense->es_key = KEY_ILLEGAL_REQUEST;
7618 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7619 		*pagelen = parmlen;
7620 		*rval = TRAN_ACCEPT;
7621 		return (SATA_FAILURE);
7622 	}
7623 
7624 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
7625 
7626 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
7627 		*scsipkt->pkt_scbp = STATUS_CHECK;
7628 		sense = sata_arq_sense(spx);
7629 		sense->es_key = KEY_ILLEGAL_REQUEST;
7630 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7631 		*pagelen = parmlen;
7632 		*rval = TRAN_ACCEPT;
7633 		return (SATA_FAILURE);
7634 	}
7635 
7636 	/* If already in the state requested, we are done */
7637 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
7638 		/* nothing to do */
7639 		*rval = TRAN_ACCEPT;
7640 		return (SATA_SUCCESS);
7641 	}
7642 
7643 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7644 
7645 	/* Build SMART_ENABLE or SMART_DISABLE command */
7646 	scmd->satacmd_addr_type = 0;		/* N/A */
7647 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
7648 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
7649 	scmd->satacmd_features_reg = page->dexcpt ?
7650 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
7651 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
7652 	scmd->satacmd_cmd_reg = SATAC_SMART;
7653 
7654 	/* Transfer command to HBA */
7655 	if (sata_hba_start(spx, rval) != 0)
7656 		/*
7657 		 * Pkt not accepted for execution.
7658 		 */
7659 		return (SATA_FAILURE);
7660 
7661 	*dmod = 1;	/* At least may have been modified */
7662 
7663 	/* Now process return */
7664 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
7665 		return (SATA_SUCCESS);
7666 
7667 	/* Packet did not complete successfully */
7668 	sata_xlate_errors(spx);
7669 
7670 	return (SATA_FAILURE);
7671 }
7672 
7673 /*
7674  * Process mode select acoustic management control page 0x30
7675  *
7676  *
7677  * This function has to be called with a port mutex held.
7678  *
7679  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7680  *
7681  * Cannot be called in the interrupt context.
7682  */
7683 int
7684 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
7685     mode_acoustic_management *page, int parmlen, int *pagelen,
7686     int *rval, int *dmod)
7687 {
7688 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7689 	sata_drive_info_t *sdinfo;
7690 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7691 	sata_id_t *sata_id;
7692 	struct scsi_extended_sense *sense;
7693 
7694 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7695 	    &spx->txlt_sata_pkt->satapkt_device);
7696 	sata_id = &sdinfo->satadrv_id;
7697 	*dmod = 0;
7698 
7699 	/* If parmlen is too short or the feature is not supported, drop it */
7700 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7701 	    sizeof (struct mode_page)) > parmlen) ||
7702 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
7703 		*scsipkt->pkt_scbp = STATUS_CHECK;
7704 		sense = sata_arq_sense(spx);
7705 		sense->es_key = KEY_ILLEGAL_REQUEST;
7706 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7707 		*pagelen = parmlen;
7708 		*rval = TRAN_ACCEPT;
7709 		return (SATA_FAILURE);
7710 	}
7711 
7712 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7713 	    sizeof (struct mode_page);
7714 
7715 	/*
7716 	 * We can enable and disable acoustice management and
7717 	 * set the acoustic management level.
7718 	 */
7719 
7720 	/*
7721 	 * Set-up Internal SET FEATURES command(s)
7722 	 */
7723 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7724 	scmd->satacmd_addr_type = 0;
7725 	scmd->satacmd_device_reg = 0;
7726 	scmd->satacmd_status_reg = 0;
7727 	scmd->satacmd_error_reg = 0;
7728 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7729 	if (page->acoustic_manag_enable) {
7730 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
7731 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
7732 	} else {	/* disabling acoustic management */
7733 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
7734 	}
7735 
7736 	/* Transfer command to HBA */
7737 	if (sata_hba_start(spx, rval) != 0)
7738 		/*
7739 		 * Pkt not accepted for execution.
7740 		 */
7741 		return (SATA_FAILURE);
7742 
7743 	/* Now process return */
7744 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
7745 		sata_xlate_errors(spx);
7746 		return (SATA_FAILURE);
7747 	}
7748 
7749 	*dmod = 1;
7750 
7751 	return (SATA_SUCCESS);
7752 }
7753 
7754 /*
7755  * Process mode select power condition page 0x1a
7756  *
7757  * This function has to be called with a port mutex held.
7758  *
7759  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7760  *
7761  * Cannot be called in the interrupt context.
7762  */
7763 int
7764 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
7765     mode_info_power_cond *page, int parmlen, int *pagelen,
7766     int *rval, int *dmod)
7767 {
7768 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7769 	sata_drive_info_t *sdinfo;
7770 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7771 	sata_id_t *sata_id;
7772 	struct scsi_extended_sense *sense;
7773 	uint8_t ata_count;
7774 	int i, len;
7775 
7776 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7777 	    &spx->txlt_sata_pkt->satapkt_device);
7778 	sata_id = &sdinfo->satadrv_id;
7779 	*dmod = 0;
7780 
7781 	len = sizeof (struct mode_info_power_cond);
7782 	len += sizeof (struct mode_page);
7783 
7784 	/* If parmlen is too short or the feature is not supported, drop it */
7785 	if ((len < parmlen) || (page->idle == 1) ||
7786 	    (!(sata_id->ai_cap && SATA_STANDBYTIMER) && page->standby == 1)) {
7787 		*scsipkt->pkt_scbp = STATUS_CHECK;
7788 		sense = sata_arq_sense(spx);
7789 		sense->es_key = KEY_ILLEGAL_REQUEST;
7790 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7791 		*pagelen = parmlen;
7792 		*rval = TRAN_ACCEPT;
7793 		return (SATA_FAILURE);
7794 	}
7795 
7796 	*pagelen = len;
7797 
7798 	/*
7799 	 * Set-up Internal STANDBY command(s)
7800 	 */
7801 	if (page->standby == 0)
7802 		goto out;
7803 
7804 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
7805 
7806 	scmd->satacmd_addr_type = 0;
7807 	scmd->satacmd_sec_count_lsb = ata_count;
7808 	scmd->satacmd_lba_low_lsb = 0;
7809 	scmd->satacmd_lba_mid_lsb = 0;
7810 	scmd->satacmd_lba_high_lsb = 0;
7811 	scmd->satacmd_features_reg = 0;
7812 	scmd->satacmd_device_reg = 0;
7813 	scmd->satacmd_status_reg = 0;
7814 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
7815 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
7816 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
7817 
7818 	/* Transfer command to HBA */
7819 	if (sata_hba_start(spx, rval) != 0) {
7820 		return (SATA_FAILURE);
7821 	} else {
7822 		if ((scmd->satacmd_error_reg != 0) ||
7823 		    (spx->txlt_sata_pkt->satapkt_reason !=
7824 		    SATA_PKT_COMPLETED)) {
7825 			sata_xlate_errors(spx);
7826 			return (SATA_FAILURE);
7827 		}
7828 	}
7829 
7830 	for (i = 0; i < 4; i++) {
7831 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
7832 	}
7833 out:
7834 	*dmod = 1;
7835 	return (SATA_SUCCESS);
7836 }
7837 
7838 /*
7839  * sata_build_lsense_page0() is used to create the
7840  * SCSI LOG SENSE page 0 (supported log pages)
7841  *
7842  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
7843  * (supported log pages, self-test results, informational exceptions
7844  * Sun vendor specific ATA SMART data, and start stop cycle counter).
7845  *
7846  * Takes a sata_drive_info t * and the address of a buffer
7847  * in which to create the page information.
7848  *
7849  * Returns the number of bytes valid in the buffer.
7850  */
7851 static	int
7852 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
7853 {
7854 	struct log_parameter *lpp = (struct log_parameter *)buf;
7855 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
7856 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
7857 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7858 
7859 	lpp->param_code[0] = 0;
7860 	lpp->param_code[1] = 0;
7861 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
7862 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
7863 
7864 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
7865 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
7866 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
7867 			++num_pages_supported;
7868 		}
7869 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
7870 		++num_pages_supported;
7871 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
7872 		++num_pages_supported;
7873 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
7874 		++num_pages_supported;
7875 	}
7876 
7877 	lpp->param_len = num_pages_supported;
7878 
7879 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
7880 	    num_pages_supported);
7881 }
7882 
7883 /*
7884  * sata_build_lsense_page_10() is used to create the
7885  * SCSI LOG SENSE page 0x10 (self-test results)
7886  *
7887  * Takes a sata_drive_info t * and the address of a buffer
7888  * in which to create the page information as well as a sata_hba_inst_t *.
7889  *
7890  * Returns the number of bytes valid in the buffer.
7891  *
7892  * Note: Self test and SMART data is accessible in device log pages.
7893  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
7894  * of data can be transferred by a single command), or by the General Purpose
7895  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
7896  * - approximately 33MB - can be transferred by a single command.
7897  * The SCT Command response (either error or command) is the same for both
7898  * the SMART and GPL methods of issuing commands.
7899  * This function uses READ LOG EXT command when drive supports LBA48, and
7900  * SMART READ command otherwise.
7901  *
7902  * Since above commands are executed in a synchronous mode, this function
7903  * should not be called in an interrupt context.
7904  */
7905 static	int
7906 sata_build_lsense_page_10(
7907 	sata_drive_info_t *sdinfo,
7908 	uint8_t *buf,
7909 	sata_hba_inst_t *sata_hba_inst)
7910 {
7911 	struct log_parameter *lpp = (struct log_parameter *)buf;
7912 	int rval;
7913 
7914 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
7915 		struct smart_ext_selftest_log *ext_selftest_log;
7916 
7917 		ext_selftest_log = kmem_zalloc(
7918 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
7919 
7920 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
7921 		    ext_selftest_log, 0);
7922 		if (rval == 0) {
7923 			int index, start_index;
7924 			struct smart_ext_selftest_log_entry *entry;
7925 			static const struct smart_ext_selftest_log_entry empty =
7926 			    {0};
7927 			uint16_t block_num;
7928 			int count;
7929 			boolean_t only_one_block = B_FALSE;
7930 
7931 			index = ext_selftest_log->
7932 			    smart_ext_selftest_log_index[0];
7933 			index |= ext_selftest_log->
7934 			    smart_ext_selftest_log_index[1] << 8;
7935 			if (index == 0)
7936 				goto out;
7937 
7938 			--index;	/* Correct for 0 origin */
7939 			start_index = index;	/* remember where we started */
7940 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7941 			if (block_num != 0) {
7942 				rval = sata_ext_smart_selftest_read_log(
7943 				    sata_hba_inst, sdinfo, ext_selftest_log,
7944 				    block_num);
7945 				if (rval != 0)
7946 					goto out;
7947 			}
7948 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7949 			entry =
7950 			    &ext_selftest_log->
7951 			    smart_ext_selftest_log_entries[index];
7952 
7953 			for (count = 1;
7954 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
7955 			    ++count) {
7956 				uint8_t status;
7957 				uint8_t code;
7958 				uint8_t sense_key;
7959 				uint8_t add_sense_code;
7960 				uint8_t add_sense_code_qual;
7961 
7962 				/* If this is an unused entry, we are done */
7963 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
7964 					/* Broken firmware on some disks */
7965 					if (index + 1 ==
7966 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
7967 						--entry;
7968 						--index;
7969 						if (bcmp(entry, &empty,
7970 						    sizeof (empty)) == 0)
7971 							goto out;
7972 					} else
7973 						goto out;
7974 				}
7975 
7976 				if (only_one_block &&
7977 				    start_index == index)
7978 					goto out;
7979 
7980 				lpp->param_code[0] = 0;
7981 				lpp->param_code[1] = count;
7982 				lpp->param_ctrl_flags =
7983 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
7984 				lpp->param_len =
7985 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
7986 
7987 				status = entry->smart_ext_selftest_log_status;
7988 				status >>= 4;
7989 				switch (status) {
7990 				case 0:
7991 				default:
7992 					sense_key = KEY_NO_SENSE;
7993 					add_sense_code =
7994 					    SD_SCSI_ASC_NO_ADD_SENSE;
7995 					add_sense_code_qual = 0;
7996 					break;
7997 				case 1:
7998 					sense_key = KEY_ABORTED_COMMAND;
7999 					add_sense_code =
8000 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8001 					add_sense_code_qual = SCSI_COMPONENT_81;
8002 					break;
8003 				case 2:
8004 					sense_key = KEY_ABORTED_COMMAND;
8005 					add_sense_code =
8006 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8007 					add_sense_code_qual = SCSI_COMPONENT_82;
8008 					break;
8009 				case 3:
8010 					sense_key = KEY_ABORTED_COMMAND;
8011 					add_sense_code =
8012 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8013 					add_sense_code_qual = SCSI_COMPONENT_83;
8014 					break;
8015 				case 4:
8016 					sense_key = KEY_HARDWARE_ERROR;
8017 					add_sense_code =
8018 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8019 					add_sense_code_qual = SCSI_COMPONENT_84;
8020 					break;
8021 				case 5:
8022 					sense_key = KEY_HARDWARE_ERROR;
8023 					add_sense_code =
8024 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8025 					add_sense_code_qual = SCSI_COMPONENT_85;
8026 					break;
8027 				case 6:
8028 					sense_key = KEY_HARDWARE_ERROR;
8029 					add_sense_code =
8030 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8031 					add_sense_code_qual = SCSI_COMPONENT_86;
8032 					break;
8033 				case 7:
8034 					sense_key = KEY_MEDIUM_ERROR;
8035 					add_sense_code =
8036 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8037 					add_sense_code_qual = SCSI_COMPONENT_87;
8038 					break;
8039 				case 8:
8040 					sense_key = KEY_HARDWARE_ERROR;
8041 					add_sense_code =
8042 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8043 					add_sense_code_qual = SCSI_COMPONENT_88;
8044 					break;
8045 				}
8046 				code = 0;	/* unspecified */
8047 				status |= (code << 4);
8048 				lpp->param_values[0] = status;
8049 				lpp->param_values[1] = 0; /* unspecified */
8050 				lpp->param_values[2] = entry->
8051 				    smart_ext_selftest_log_timestamp[1];
8052 				lpp->param_values[3] = entry->
8053 				    smart_ext_selftest_log_timestamp[0];
8054 				if (status != 0) {
8055 					lpp->param_values[4] = 0;
8056 					lpp->param_values[5] = 0;
8057 					lpp->param_values[6] = entry->
8058 					    smart_ext_selftest_log_failing_lba
8059 					    [5];
8060 					lpp->param_values[7] = entry->
8061 					    smart_ext_selftest_log_failing_lba
8062 					    [4];
8063 					lpp->param_values[8] = entry->
8064 					    smart_ext_selftest_log_failing_lba
8065 					    [3];
8066 					lpp->param_values[9] = entry->
8067 					    smart_ext_selftest_log_failing_lba
8068 					    [2];
8069 					lpp->param_values[10] = entry->
8070 					    smart_ext_selftest_log_failing_lba
8071 					    [1];
8072 					lpp->param_values[11] = entry->
8073 					    smart_ext_selftest_log_failing_lba
8074 					    [0];
8075 				} else {	/* No bad block address */
8076 					lpp->param_values[4] = 0xff;
8077 					lpp->param_values[5] = 0xff;
8078 					lpp->param_values[6] = 0xff;
8079 					lpp->param_values[7] = 0xff;
8080 					lpp->param_values[8] = 0xff;
8081 					lpp->param_values[9] = 0xff;
8082 					lpp->param_values[10] = 0xff;
8083 					lpp->param_values[11] = 0xff;
8084 				}
8085 
8086 				lpp->param_values[12] = sense_key;
8087 				lpp->param_values[13] = add_sense_code;
8088 				lpp->param_values[14] = add_sense_code_qual;
8089 				lpp->param_values[15] = 0; /* undefined */
8090 
8091 				lpp = (struct log_parameter *)
8092 				    (((uint8_t *)lpp) +
8093 				    SCSI_LOG_PARAM_HDR_LEN +
8094 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8095 
8096 				--index;	/* Back up to previous entry */
8097 				if (index < 0) {
8098 					if (block_num > 0) {
8099 						--block_num;
8100 					} else {
8101 						struct read_log_ext_directory
8102 						    logdir;
8103 
8104 						rval =
8105 						    sata_read_log_ext_directory(
8106 						    sata_hba_inst, sdinfo,
8107 						    &logdir);
8108 						if (rval == -1)
8109 							goto out;
8110 						if ((logdir.read_log_ext_vers
8111 						    [0] == 0) &&
8112 						    (logdir.read_log_ext_vers
8113 						    [1] == 0))
8114 							goto out;
8115 						block_num =
8116 						    logdir.read_log_ext_nblks
8117 						    [EXT_SMART_SELFTEST_LOG_PAGE
8118 						    - 1][0];
8119 						block_num |= logdir.
8120 						    read_log_ext_nblks
8121 						    [EXT_SMART_SELFTEST_LOG_PAGE
8122 						    - 1][1] << 8;
8123 						--block_num;
8124 						only_one_block =
8125 						    (block_num == 0);
8126 					}
8127 					rval = sata_ext_smart_selftest_read_log(
8128 					    sata_hba_inst, sdinfo,
8129 					    ext_selftest_log, block_num);
8130 					if (rval != 0)
8131 						goto out;
8132 
8133 					index =
8134 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8135 					    1;
8136 				}
8137 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8138 				entry = &ext_selftest_log->
8139 				    smart_ext_selftest_log_entries[index];
8140 			}
8141 		}
8142 out:
8143 		kmem_free(ext_selftest_log,
8144 		    sizeof (struct smart_ext_selftest_log));
8145 	} else {
8146 		struct smart_selftest_log *selftest_log;
8147 
8148 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8149 		    KM_SLEEP);
8150 
8151 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8152 		    selftest_log);
8153 
8154 		if (rval == 0) {
8155 			int index;
8156 			int count;
8157 			struct smart_selftest_log_entry *entry;
8158 			static const struct smart_selftest_log_entry empty =
8159 			    { 0 };
8160 
8161 			index = selftest_log->smart_selftest_log_index;
8162 			if (index == 0)
8163 				goto done;
8164 			--index;	/* Correct for 0 origin */
8165 			entry = &selftest_log->
8166 			    smart_selftest_log_entries[index];
8167 			for (count = 1;
8168 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8169 			    ++count) {
8170 				uint8_t status;
8171 				uint8_t code;
8172 				uint8_t sense_key;
8173 				uint8_t add_sense_code;
8174 				uint8_t add_sense_code_qual;
8175 
8176 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8177 					goto done;
8178 
8179 				lpp->param_code[0] = 0;
8180 				lpp->param_code[1] = count;
8181 				lpp->param_ctrl_flags =
8182 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8183 				lpp->param_len =
8184 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8185 
8186 				status = entry->smart_selftest_log_status;
8187 				status >>= 4;
8188 				switch (status) {
8189 				case 0:
8190 				default:
8191 					sense_key = KEY_NO_SENSE;
8192 					add_sense_code =
8193 					    SD_SCSI_ASC_NO_ADD_SENSE;
8194 					break;
8195 				case 1:
8196 					sense_key = KEY_ABORTED_COMMAND;
8197 					add_sense_code =
8198 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8199 					add_sense_code_qual = SCSI_COMPONENT_81;
8200 					break;
8201 				case 2:
8202 					sense_key = KEY_ABORTED_COMMAND;
8203 					add_sense_code =
8204 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8205 					add_sense_code_qual = SCSI_COMPONENT_82;
8206 					break;
8207 				case 3:
8208 					sense_key = KEY_ABORTED_COMMAND;
8209 					add_sense_code =
8210 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8211 					add_sense_code_qual = SCSI_COMPONENT_83;
8212 					break;
8213 				case 4:
8214 					sense_key = KEY_HARDWARE_ERROR;
8215 					add_sense_code =
8216 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8217 					add_sense_code_qual = SCSI_COMPONENT_84;
8218 					break;
8219 				case 5:
8220 					sense_key = KEY_HARDWARE_ERROR;
8221 					add_sense_code =
8222 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8223 					add_sense_code_qual = SCSI_COMPONENT_85;
8224 					break;
8225 				case 6:
8226 					sense_key = KEY_HARDWARE_ERROR;
8227 					add_sense_code =
8228 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8229 					add_sense_code_qual = SCSI_COMPONENT_86;
8230 					break;
8231 				case 7:
8232 					sense_key = KEY_MEDIUM_ERROR;
8233 					add_sense_code =
8234 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8235 					add_sense_code_qual = SCSI_COMPONENT_87;
8236 					break;
8237 				case 8:
8238 					sense_key = KEY_HARDWARE_ERROR;
8239 					add_sense_code =
8240 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8241 					add_sense_code_qual = SCSI_COMPONENT_88;
8242 					break;
8243 				}
8244 				code = 0;	/* unspecified */
8245 				status |= (code << 4);
8246 				lpp->param_values[0] = status;
8247 				lpp->param_values[1] = 0; /* unspecified */
8248 				lpp->param_values[2] = entry->
8249 				    smart_selftest_log_timestamp[1];
8250 				lpp->param_values[3] = entry->
8251 				    smart_selftest_log_timestamp[0];
8252 				if (status != 0) {
8253 					lpp->param_values[4] = 0;
8254 					lpp->param_values[5] = 0;
8255 					lpp->param_values[6] = 0;
8256 					lpp->param_values[7] = 0;
8257 					lpp->param_values[8] = entry->
8258 					    smart_selftest_log_failing_lba[3];
8259 					lpp->param_values[9] = entry->
8260 					    smart_selftest_log_failing_lba[2];
8261 					lpp->param_values[10] = entry->
8262 					    smart_selftest_log_failing_lba[1];
8263 					lpp->param_values[11] = entry->
8264 					    smart_selftest_log_failing_lba[0];
8265 				} else {	/* No block address */
8266 					lpp->param_values[4] = 0xff;
8267 					lpp->param_values[5] = 0xff;
8268 					lpp->param_values[6] = 0xff;
8269 					lpp->param_values[7] = 0xff;
8270 					lpp->param_values[8] = 0xff;
8271 					lpp->param_values[9] = 0xff;
8272 					lpp->param_values[10] = 0xff;
8273 					lpp->param_values[11] = 0xff;
8274 				}
8275 				lpp->param_values[12] = sense_key;
8276 				lpp->param_values[13] = add_sense_code;
8277 				lpp->param_values[14] = add_sense_code_qual;
8278 				lpp->param_values[15] = 0; /* undefined */
8279 
8280 				lpp = (struct log_parameter *)
8281 				    (((uint8_t *)lpp) +
8282 				    SCSI_LOG_PARAM_HDR_LEN +
8283 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8284 				--index;	/* back up to previous entry */
8285 				if (index < 0) {
8286 					index =
8287 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
8288 				}
8289 				entry = &selftest_log->
8290 				    smart_selftest_log_entries[index];
8291 			}
8292 		}
8293 done:
8294 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
8295 	}
8296 
8297 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
8298 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
8299 }
8300 
8301 /*
8302  * sata_build_lsense_page_2f() is used to create the
8303  * SCSI LOG SENSE page 0x2f (informational exceptions)
8304  *
8305  * Takes a sata_drive_info t * and the address of a buffer
8306  * in which to create the page information as well as a sata_hba_inst_t *.
8307  *
8308  * Returns the number of bytes valid in the buffer.
8309  *
8310  * Because it invokes function(s) that send synchronously executed command
8311  * to the HBA, it cannot be called in the interrupt context.
8312  */
8313 static	int
8314 sata_build_lsense_page_2f(
8315 	sata_drive_info_t *sdinfo,
8316 	uint8_t *buf,
8317 	sata_hba_inst_t *sata_hba_inst)
8318 {
8319 	struct log_parameter *lpp = (struct log_parameter *)buf;
8320 	int rval;
8321 	uint8_t *smart_data;
8322 	uint8_t temp;
8323 	sata_id_t *sata_id;
8324 #define	SMART_NO_TEMP	0xff
8325 
8326 	lpp->param_code[0] = 0;
8327 	lpp->param_code[1] = 0;
8328 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8329 
8330 	/* Now get the SMART status w.r.t. threshold exceeded */
8331 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
8332 	switch (rval) {
8333 	case 1:
8334 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
8335 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
8336 		break;
8337 	case 0:
8338 	case -1:	/* failed to get data */
8339 		lpp->param_values[0] = 0;	/* No failure predicted */
8340 		lpp->param_values[1] = 0;
8341 		break;
8342 #if defined(SATA_DEBUG)
8343 	default:
8344 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
8345 		/* NOTREACHED */
8346 #endif
8347 	}
8348 
8349 	sata_id = &sdinfo->satadrv_id;
8350 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
8351 		temp = SMART_NO_TEMP;
8352 	else {
8353 		/* Now get the temperature */
8354 		smart_data = kmem_zalloc(512, KM_SLEEP);
8355 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
8356 		    SCT_STATUS_LOG_PAGE, 1);
8357 		if (rval == -1)
8358 			temp = SMART_NO_TEMP;
8359 		else {
8360 			temp = smart_data[200];
8361 			if (temp & 0x80) {
8362 				if (temp & 0x7f)
8363 					temp = 0;
8364 				else
8365 					temp = SMART_NO_TEMP;
8366 			}
8367 		}
8368 		kmem_free(smart_data, 512);
8369 	}
8370 
8371 	lpp->param_values[2] = temp;	/* most recent temperature */
8372 	lpp->param_values[3] = 0;	/* required vendor specific byte */
8373 
8374 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
8375 
8376 
8377 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
8378 }
8379 
8380 /*
8381  * sata_build_lsense_page_30() is used to create the
8382  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
8383  *
8384  * Takes a sata_drive_info t * and the address of a buffer
8385  * in which to create the page information as well as a sata_hba_inst_t *.
8386  *
8387  * Returns the number of bytes valid in the buffer.
8388  */
8389 static int
8390 sata_build_lsense_page_30(
8391 	sata_drive_info_t *sdinfo,
8392 	uint8_t *buf,
8393 	sata_hba_inst_t *sata_hba_inst)
8394 {
8395 	struct smart_data *smart_data = (struct smart_data *)buf;
8396 	int rval;
8397 
8398 	/* Now do the SMART READ DATA */
8399 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
8400 	if (rval == -1)
8401 		return (0);
8402 
8403 	return (sizeof (struct smart_data));
8404 }
8405 
8406 /*
8407  * sata_build_lsense_page_0e() is used to create the
8408  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
8409  *
8410  * Date of Manufacture (0x0001)
8411  *	YEAR = "0000"
8412  *	WEEK = "00"
8413  * Accounting Date (0x0002)
8414  *	6 ASCII space character(20h)
8415  * Specified cycle count over device lifetime
8416  *	VALUE - THRESH - the delta between max and min;
8417  * Accumulated start-stop cycles
8418  *	VALUE - WORST - the accumulated cycles;
8419  *
8420  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
8421  *
8422  * Takes a sata_drive_info t * and the address of a buffer
8423  * in which to create the page information as well as a sata_hba_inst_t *.
8424  *
8425  * Returns the number of bytes valid in the buffer.
8426  */
8427 static	int
8428 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
8429 	sata_pkt_txlate_t *spx)
8430 {
8431 	struct start_stop_cycle_counter_log *log_page;
8432 	int i, rval, index;
8433 	uint8_t smart_data[512], id, value, worst, thresh;
8434 	uint32_t max_count, cycles;
8435 
8436 	/* Now do the SMART READ DATA */
8437 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
8438 	    (struct smart_data *)smart_data);
8439 	if (rval == -1)
8440 		return (0);
8441 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
8442 		index = (i * 12) + 2;
8443 		id = smart_data[index];
8444 		if (id != SMART_START_STOP_COUNT_ID)
8445 			continue;
8446 		else {
8447 			thresh = smart_data[index + 2];
8448 			value = smart_data[index + 3];
8449 			worst = smart_data[index + 4];
8450 			break;
8451 		}
8452 	}
8453 	if (id != SMART_START_STOP_COUNT_ID)
8454 		return (0);
8455 	max_count = value - thresh;
8456 	cycles = value - worst;
8457 
8458 	log_page = (struct start_stop_cycle_counter_log *)buf;
8459 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
8460 	log_page->code = 0x0e;
8461 	log_page->page_len_low = 0x24;
8462 
8463 	log_page->manufactor_date_low = 0x1;
8464 	log_page->param_1.fmt_link = 0x1; /* 01b */
8465 	log_page->param_len_1 = 0x06;
8466 	for (i = 0; i < 4; i++) {
8467 		log_page->year_manu[i] = 0x30;
8468 		if (i < 2)
8469 			log_page->week_manu[i] = 0x30;
8470 	}
8471 
8472 	log_page->account_date_low = 0x02;
8473 	log_page->param_2.fmt_link = 0x01; /* 01b */
8474 	log_page->param_len_2 = 0x06;
8475 	for (i = 0; i < 4; i++) {
8476 		log_page->year_account[i] = 0x20;
8477 		if (i < 2)
8478 			log_page->week_account[i] = 0x20;
8479 	}
8480 
8481 	log_page->lifetime_code_low = 0x03;
8482 	log_page->param_3.fmt_link = 0x03; /* 11b */
8483 	log_page->param_len_3 = 0x04;
8484 	/* VALUE - THRESH - the delta between max and min */
8485 	log_page->cycle_code_low = 0x04;
8486 	log_page->param_4.fmt_link = 0x03; /* 11b */
8487 	log_page->param_len_4 = 0x04;
8488 	/* WORST - THRESH - the distance from 'now' to min */
8489 
8490 	for (i = 0; i < 4; i++) {
8491 		log_page->cycle_lifetime[i] =
8492 		    (max_count >> (8 * (3 - i))) & 0xff;
8493 		log_page->cycle_accumulated[i] =
8494 		    (cycles >> (8 * (3 - i))) & 0xff;
8495 	}
8496 
8497 	return (sizeof (struct start_stop_cycle_counter_log));
8498 }
8499 
8500 /*
8501  * This function was used for build a ATA read verify sector command
8502  */
8503 static void
8504 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
8505 {
8506 	scmd->satacmd_cmd_reg = SATAC_RDVER;
8507 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
8508 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8509 
8510 	scmd->satacmd_sec_count_lsb = sec & 0xff;
8511 	scmd->satacmd_lba_low_lsb = lba & 0xff;
8512 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
8513 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
8514 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
8515 	scmd->satacmd_features_reg = 0;
8516 	scmd->satacmd_status_reg = 0;
8517 	scmd->satacmd_error_reg = 0;
8518 }
8519 
8520 /*
8521  * This function was used for building an ATA
8522  * command, and only command register need to
8523  * be defined, other register will be zero or na.
8524  */
8525 static void
8526 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
8527 {
8528 	scmd->satacmd_addr_type = 0;
8529 	scmd->satacmd_cmd_reg = cmd;
8530 	scmd->satacmd_device_reg = 0;
8531 	scmd->satacmd_sec_count_lsb = 0;
8532 	scmd->satacmd_lba_low_lsb = 0;
8533 	scmd->satacmd_lba_mid_lsb = 0;
8534 	scmd->satacmd_lba_high_lsb = 0;
8535 	scmd->satacmd_features_reg = 0;
8536 	scmd->satacmd_status_reg = 0;
8537 	scmd->satacmd_error_reg = 0;
8538 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8539 }
8540 
8541 /*
8542  * This function was used for changing the standby
8543  * timer format from SCSI to ATA.
8544  */
8545 static uint8_t
8546 sata_get_standby_timer(uint8_t *timer)
8547 {
8548 	uint32_t i = 0, count = 0;
8549 	uint8_t ata_count;
8550 
8551 	for (i = 0; i < 4; i++) {
8552 		count = count << 8 | timer[i];
8553 	}
8554 
8555 	if (count == 0)
8556 		return (0);
8557 
8558 	if (count >= 1 && count <= 12000)
8559 		ata_count = (count -1) / 50 + 1;
8560 	else if (count > 12000 && count <= 12600)
8561 		ata_count = 0xfc;
8562 	else if (count > 12601 && count <= 12750)
8563 		ata_count = 0xff;
8564 	else if (count > 12750 && count <= 17999)
8565 		ata_count = 0xf1;
8566 	else if (count > 18000 && count <= 198000)
8567 		ata_count = count / 18000 + 240;
8568 	else
8569 		ata_count = 0xfd;
8570 	return (ata_count);
8571 }
8572 
8573 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
8574 
8575 /*
8576  * Start command for ATAPI device.
8577  * This function processes scsi_pkt requests.
8578  * Now CD/DVD, tape and ATAPI disk devices are supported.
8579  * Most commands are packet without any translation into Packet Command.
8580  * Some may be trapped and executed as SATA commands (not clear which one).
8581  *
8582  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
8583  * execution).
8584  * Returns other TRAN_XXXX codes if command is not accepted or completed
8585  * (see return values for sata_hba_start()).
8586  *
8587  * Note:
8588  * Inquiry cdb format differs between transport version 2 and 3.
8589  * However, the transport version 3 devices that were checked did not adhere
8590  * to the specification (ignored MSB of the allocation length). Therefore,
8591  * the transport version is not checked, but Inquiry allocation length is
8592  * truncated to 255 bytes if the original allocation length set-up by the
8593  * target driver is greater than 255 bytes.
8594  */
8595 static int
8596 sata_txlt_atapi(sata_pkt_txlate_t *spx)
8597 {
8598 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8599 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8600 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8601 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
8602 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
8603 	    &spx->txlt_sata_pkt->satapkt_device);
8604 	int cport = SATA_TXLT_CPORT(spx);
8605 	int cdblen;
8606 	int rval, reason;
8607 	int synch;
8608 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
8609 
8610 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8611 
8612 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
8613 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
8614 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8615 		return (rval);
8616 	}
8617 
8618 	/*
8619 	 * ATAPI device executes some ATA commands in addition to those
8620 	 * commands sent via PACKET command. These ATA commands may be
8621 	 * executed by the regular SATA translation functions. None needs
8622 	 * to be captured now.
8623 	 *
8624 	 * Commands sent via PACKET command include:
8625 	 *	MMC command set for ATAPI CD/DVD device
8626 	 *	SSC command set for ATAPI TAPE device
8627 	 *	SBC command set for ATAPI disk device
8628 	 *
8629 	 */
8630 
8631 	/* Check the size of cdb */
8632 	cdblen = scsi_cdb_size[GETGROUP(cdbp)];
8633 	if (cdblen > sdinfo->satadrv_atapi_cdb_len) {
8634 		sata_log(NULL, CE_WARN,
8635 		    "sata: invalid ATAPI cdb length %d",
8636 		    scsipkt->pkt_cdblen);
8637 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8638 		return (TRAN_BADPKT);
8639 	}
8640 
8641 	SATAATAPITRACE(spx, cdblen);
8642 
8643 	/*
8644 	 * For non-read/write commands we need to
8645 	 * map buffer
8646 	 */
8647 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
8648 	case SCMD_READ:
8649 	case SCMD_READ_G1:
8650 	case SCMD_READ_G5:
8651 	case SCMD_READ_G4:
8652 	case SCMD_WRITE:
8653 	case SCMD_WRITE_G1:
8654 	case SCMD_WRITE_G5:
8655 	case SCMD_WRITE_G4:
8656 		break;
8657 	default:
8658 		if (bp != NULL) {
8659 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
8660 				bp_mapin(bp);
8661 		}
8662 		break;
8663 	}
8664 	/*
8665 	 * scmd->satacmd_flags.sata_data_direction default -
8666 	 * SATA_DIR_NODATA_XFER - is set by
8667 	 * sata_txlt_generic_pkt_info().
8668 	 */
8669 	if (scmd->satacmd_bp) {
8670 		if (scmd->satacmd_bp->b_flags & B_READ) {
8671 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8672 		} else {
8673 			scmd->satacmd_flags.sata_data_direction =
8674 			    SATA_DIR_WRITE;
8675 		}
8676 	}
8677 
8678 	/*
8679 	 * Set up ATAPI packet command.
8680 	 */
8681 
8682 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8683 
8684 	/* Copy cdb into sata_cmd */
8685 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8686 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
8687 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
8688 
8689 	/* See note in the command header */
8690 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
8691 		if (scmd->satacmd_acdb[3] != 0)
8692 			scmd->satacmd_acdb[4] = 255;
8693 	}
8694 
8695 #ifdef SATA_DEBUG
8696 	if (sata_debug_flags & SATA_DBG_ATAPI) {
8697 		uint8_t *p = scmd->satacmd_acdb;
8698 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
8699 
8700 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
8701 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
8702 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
8703 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
8704 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
8705 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
8706 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
8707 	}
8708 #endif
8709 
8710 	/*
8711 	 * Preset request sense data to NO SENSE.
8712 	 * If there is no way to get error information via Request Sense,
8713 	 * the packet request sense data would not have to be modified by HBA,
8714 	 * but it could be returned as is.
8715 	 */
8716 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8717 	sata_fixed_sense_data_preset(
8718 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8719 
8720 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
8721 		/* Need callback function */
8722 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
8723 		synch = FALSE;
8724 	} else
8725 		synch = TRUE;
8726 
8727 	/* Transfer command to HBA */
8728 	if (sata_hba_start(spx, &rval) != 0) {
8729 		/* Pkt not accepted for execution */
8730 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8731 		return (rval);
8732 	}
8733 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8734 	/*
8735 	 * If execution is non-synchronous,
8736 	 * a callback function will handle potential errors, translate
8737 	 * the response and will do a callback to a target driver.
8738 	 * If it was synchronous, use the same framework callback to check
8739 	 * an execution status.
8740 	 */
8741 	if (synch) {
8742 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
8743 		    "synchronous execution status %x\n",
8744 		    spx->txlt_sata_pkt->satapkt_reason);
8745 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
8746 	}
8747 	return (TRAN_ACCEPT);
8748 }
8749 
8750 
8751 /*
8752  * ATAPI Packet command completion.
8753  *
8754  * Failure of the command passed via Packet command are considered device
8755  * error. SATA HBA driver would have to retrieve error data (via Request
8756  * Sense command delivered via error retrieval sata packet) and copy it
8757  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
8758  */
8759 static void
8760 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
8761 {
8762 	sata_pkt_txlate_t *spx =
8763 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
8764 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8765 	struct scsi_extended_sense *sense;
8766 	struct buf *bp;
8767 	int rval;
8768 
8769 #ifdef SATA_DEBUG
8770 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
8771 #endif
8772 
8773 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
8774 	    STATE_SENT_CMD | STATE_GOT_STATUS;
8775 
8776 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
8777 		/* Normal completion */
8778 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
8779 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
8780 		scsipkt->pkt_reason = CMD_CMPLT;
8781 		*scsipkt->pkt_scbp = STATUS_GOOD;
8782 		if (spx->txlt_tmp_buf != NULL) {
8783 			/* Temporary buffer was used */
8784 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8785 			if (bp->b_flags & B_READ) {
8786 				rval = ddi_dma_sync(
8787 				    spx->txlt_buf_dma_handle, 0, 0,
8788 				    DDI_DMA_SYNC_FORCPU);
8789 				ASSERT(rval == DDI_SUCCESS);
8790 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
8791 				    bp->b_bcount);
8792 			}
8793 		}
8794 	} else {
8795 		/*
8796 		 * Something went wrong - analyze return
8797 		 */
8798 		*scsipkt->pkt_scbp = STATUS_CHECK;
8799 		sense = sata_arq_sense(spx);
8800 
8801 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
8802 			/*
8803 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
8804 			 * Under this condition ERR bit is set for ATA command,
8805 			 * and CHK bit set for ATAPI command.
8806 			 *
8807 			 * Please check st_intr & sdintr about how pkt_reason
8808 			 * is used.
8809 			 */
8810 			scsipkt->pkt_reason = CMD_CMPLT;
8811 
8812 			/*
8813 			 * We may not have ARQ data if there was a double
8814 			 * error. But sense data in sata packet was pre-set
8815 			 * with NO SENSE so it is valid even if HBA could
8816 			 * not retrieve a real sense data.
8817 			 * Just copy this sense data into scsi pkt sense area.
8818 			 */
8819 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
8820 			    SATA_ATAPI_MIN_RQSENSE_LEN);
8821 #ifdef SATA_DEBUG
8822 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
8823 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
8824 				    "sata_txlt_atapi_completion: %02x\n"
8825 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
8826 				    "          %02x %02x %02x %02x %02x %02x "
8827 				    "          %02x %02x %02x %02x %02x %02x\n",
8828 				    scsipkt->pkt_reason,
8829 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
8830 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
8831 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
8832 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
8833 				    rqsp[16], rqsp[17]);
8834 			}
8835 #endif
8836 		} else {
8837 			switch (sata_pkt->satapkt_reason) {
8838 			case SATA_PKT_PORT_ERROR:
8839 				/*
8840 				 * We have no device data.
8841 				 */
8842 				scsipkt->pkt_reason = CMD_INCOMPLETE;
8843 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8844 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8845 				    STATE_GOT_STATUS);
8846 				sense->es_key = KEY_HARDWARE_ERROR;
8847 				break;
8848 
8849 			case SATA_PKT_TIMEOUT:
8850 				scsipkt->pkt_reason = CMD_TIMEOUT;
8851 				scsipkt->pkt_statistics |=
8852 				    STAT_TIMEOUT | STAT_DEV_RESET;
8853 				/*
8854 				 * Need to check if HARDWARE_ERROR/
8855 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
8856 				 * appropriate.
8857 				 */
8858 				break;
8859 
8860 			case SATA_PKT_ABORTED:
8861 				scsipkt->pkt_reason = CMD_ABORTED;
8862 				scsipkt->pkt_statistics |= STAT_ABORTED;
8863 				/* Should we set key COMMAND_ABPRTED? */
8864 				break;
8865 
8866 			case SATA_PKT_RESET:
8867 				scsipkt->pkt_reason = CMD_RESET;
8868 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
8869 				/*
8870 				 * May be we should set Unit Attention /
8871 				 * Reset. Perhaps the same should be
8872 				 * returned for disks....
8873 				 */
8874 				sense->es_key = KEY_UNIT_ATTENTION;
8875 				sense->es_add_code = SD_SCSI_ASC_RESET;
8876 				break;
8877 
8878 			default:
8879 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8880 				    "sata_txlt_atapi_completion: "
8881 				    "invalid packet completion reason"));
8882 				scsipkt->pkt_reason = CMD_TRAN_ERR;
8883 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8884 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8885 				    STATE_GOT_STATUS);
8886 				break;
8887 			}
8888 		}
8889 	}
8890 
8891 	SATAATAPITRACE(spx, 0);
8892 
8893 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
8894 	    scsipkt->pkt_comp != NULL) {
8895 		/* scsi callback required */
8896 		(*scsipkt->pkt_comp)(scsipkt);
8897 	}
8898 }
8899 
8900 /*
8901  * Set up error retrieval sata command for ATAPI Packet Command error data
8902  * recovery.
8903  *
8904  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
8905  * returns SATA_FAILURE otherwise.
8906  */
8907 
8908 static int
8909 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
8910 {
8911 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
8912 	sata_cmd_t *scmd;
8913 	struct buf *bp;
8914 
8915 	/*
8916 	 * Allocate dma-able buffer error data.
8917 	 * Buffer allocation will take care of buffer alignment and other DMA
8918 	 * attributes.
8919 	 */
8920 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
8921 	if (bp == NULL) {
8922 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
8923 		    "sata_get_err_retrieval_pkt: "
8924 		    "cannot allocate buffer for error data", NULL);
8925 		return (SATA_FAILURE);
8926 	}
8927 	bp_mapin(bp); /* make data buffer accessible */
8928 
8929 	/* Operation modes are up to the caller */
8930 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
8931 
8932 	/* Synchronous mode, no callback - may be changed by the caller */
8933 	spkt->satapkt_comp = NULL;
8934 	spkt->satapkt_time = sata_default_pkt_time;
8935 
8936 	scmd = &spkt->satapkt_cmd;
8937 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8938 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
8939 
8940 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8941 
8942 	/*
8943 	 * Set-up acdb. Request Sense CDB (packet command content) is
8944 	 * not in DMA-able buffer. Its handling is HBA-specific (how
8945 	 * it is transfered into packet FIS).
8946 	 */
8947 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8948 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
8949 	/* Following zeroing of pad bytes may not be necessary */
8950 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
8951 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
8952 
8953 	/*
8954 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
8955 	 * before accessing it. Handle is in usual place in translate struct.
8956 	 */
8957 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
8958 
8959 	/*
8960 	 * Preset request sense data to NO SENSE.
8961 	 * Here it is redundant, only for a symetry with scsi-originated
8962 	 * packets. It should not be used for anything but debugging.
8963 	 */
8964 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8965 	sata_fixed_sense_data_preset(
8966 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8967 
8968 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
8969 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
8970 
8971 	return (SATA_SUCCESS);
8972 }
8973 
8974 /*
8975  * Set-up ATAPI packet command.
8976  * Data transfer direction has to be set-up in sata_cmd structure prior to
8977  * calling this function.
8978  *
8979  * Returns void
8980  */
8981 
8982 static void
8983 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
8984 {
8985 	scmd->satacmd_addr_type = 0;		/* N/A */
8986 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
8987 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
8988 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
8989 	scmd->satacmd_lba_high_lsb =
8990 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
8991 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
8992 
8993 	/*
8994 	 * We want all data to be transfered via DMA.
8995 	 * But specify it only if drive supports DMA and DMA mode is
8996 	 * selected - some drives are sensitive about it.
8997 	 * Hopefully it wil work for all drives....
8998 	 */
8999 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
9000 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
9001 
9002 	/*
9003 	 * Features register requires special care for devices that use
9004 	 * Serial ATA bridge - they need an explicit specification of
9005 	 * the data transfer direction for Packet DMA commands.
9006 	 * Setting this bit is harmless if DMA is not used.
9007 	 *
9008 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
9009 	 * spec they follow.
9010 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
9011 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
9012 	 * ATA/ATAPI-7 support is explicitly indicated.
9013 	 */
9014 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9015 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
9016 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
9017 		/*
9018 		 * Specification of major version is valid and version 7
9019 		 * is supported. It does automatically imply that all
9020 		 * spec features are supported. For now, we assume that
9021 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
9022 		 */
9023 		if ((sdinfo->satadrv_id.ai_dirdma &
9024 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
9025 			if (scmd->satacmd_flags.sata_data_direction ==
9026 			    SATA_DIR_READ)
9027 			scmd->satacmd_features_reg |=
9028 			    SATA_ATAPI_F_DATA_DIR_READ;
9029 		}
9030 	}
9031 }
9032 
9033 
9034 #ifdef SATA_DEBUG
9035 
9036 /* Display 18 bytes of Inquiry data */
9037 static void
9038 sata_show_inqry_data(uint8_t *buf)
9039 {
9040 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9041 	uint8_t *p;
9042 
9043 	cmn_err(CE_NOTE, "Inquiry data:");
9044 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9045 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9046 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9047 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9048 	    SATA_ATAPI_TRANS_VERSION(inq));
9049 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9050 	    inq->inq_rdf, inq->inq_aenc);
9051 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9052 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9053 	p = (uint8_t *)inq->inq_vid;
9054 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9055 	    "%02x %02x %02x %02x",
9056 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9057 	p = (uint8_t *)inq->inq_vid;
9058 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9059 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9060 
9061 	p = (uint8_t *)inq->inq_pid;
9062 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9063 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9064 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9065 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9066 	p = (uint8_t *)inq->inq_pid;
9067 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9068 	    "%c %c %c %c %c %c %c %c",
9069 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9070 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9071 
9072 	p = (uint8_t *)inq->inq_revision;
9073 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9074 	    p[0], p[1], p[2], p[3]);
9075 	p = (uint8_t *)inq->inq_revision;
9076 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9077 	    p[0], p[1], p[2], p[3]);
9078 
9079 }
9080 
9081 
9082 static void
9083 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9084 {
9085 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9086 
9087 	if (scsi_pkt == NULL)
9088 		return;
9089 	if (count != 0) {
9090 		/* saving cdb */
9091 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9092 		    SATA_ATAPI_MAX_CDB_LEN);
9093 		bcopy(scsi_pkt->pkt_cdbp,
9094 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9095 	} else {
9096 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9097 		    sts_sensedata,
9098 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9099 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9100 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9101 		    scsi_pkt->pkt_reason;
9102 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9103 		    spx->txlt_sata_pkt->satapkt_reason;
9104 
9105 		if (++sata_atapi_trace_index >= 64)
9106 			sata_atapi_trace_index = 0;
9107 	}
9108 }
9109 
9110 #endif
9111 
9112 /*
9113  * Fetch inquiry data from ATAPI device
9114  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
9115  *
9116  * Note:
9117  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9118  * where the caller expects to see the inquiry data.
9119  *
9120  */
9121 
9122 static int
9123 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9124     sata_address_t *saddr, struct scsi_inquiry *inq)
9125 {
9126 	sata_pkt_txlate_t *spx;
9127 	sata_pkt_t *spkt;
9128 	struct buf *bp;
9129 	sata_drive_info_t *sdinfo;
9130 	sata_cmd_t *scmd;
9131 	int rval;
9132 	uint8_t *rqsp;
9133 #ifdef SATA_DEBUG
9134 	char msg_buf[MAXPATHLEN];
9135 #endif
9136 
9137 	ASSERT(sata_hba != NULL);
9138 
9139 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9140 	spx->txlt_sata_hba_inst = sata_hba;
9141 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9142 	spkt = sata_pkt_alloc(spx, NULL);
9143 	if (spkt == NULL) {
9144 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9145 		return (SATA_FAILURE);
9146 	}
9147 	/* address is needed now */
9148 	spkt->satapkt_device.satadev_addr = *saddr;
9149 
9150 	/* scsi_inquiry size buffer */
9151 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9152 	if (bp == NULL) {
9153 		sata_pkt_free(spx);
9154 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9155 		SATA_LOG_D((sata_hba, CE_WARN,
9156 		    "sata_get_atapi_inquiry_data: "
9157 		    "cannot allocate data buffer"));
9158 		return (SATA_FAILURE);
9159 	}
9160 	bp_mapin(bp); /* make data buffer accessible */
9161 
9162 	scmd = &spkt->satapkt_cmd;
9163 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9164 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9165 
9166 	/* Use synchronous mode */
9167 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9168 	spkt->satapkt_comp = NULL;
9169 	spkt->satapkt_time = sata_default_pkt_time;
9170 
9171 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9172 
9173 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9174 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9175 
9176 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
9177 	sdinfo = sata_get_device_info(sata_hba,
9178 	    &spx->txlt_sata_pkt->satapkt_device);
9179 	if (sdinfo == NULL) {
9180 		/* we have to be carefull about the disapearing device */
9181 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9182 		rval = SATA_FAILURE;
9183 		goto cleanup;
9184 	}
9185 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9186 
9187 	/*
9188 	 * Set-up acdb. This works for atapi transport version 2 and later.
9189 	 */
9190 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9191 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9192 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9193 	scmd->satacmd_acdb[1] = 0x00;
9194 	scmd->satacmd_acdb[2] = 0x00;
9195 	scmd->satacmd_acdb[3] = 0x00;
9196 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9197 	scmd->satacmd_acdb[5] = 0x00;
9198 
9199 	sata_fixed_sense_data_preset(
9200 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9201 
9202 	/* Transfer command to HBA */
9203 	if (sata_hba_start(spx, &rval) != 0) {
9204 		/* Pkt not accepted for execution */
9205 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9206 		    "sata_get_atapi_inquiry_data: "
9207 		    "Packet not accepted for execution - ret: %02x", rval);
9208 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9209 		rval = SATA_FAILURE;
9210 		goto cleanup;
9211 	}
9212 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9213 
9214 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9215 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9216 		    "sata_get_atapi_inquiry_data: "
9217 		    "Packet completed successfully - ret: %02x", rval);
9218 		if (spx->txlt_buf_dma_handle != NULL) {
9219 			/*
9220 			 * Sync buffer. Handle is in usual place in translate
9221 			 * struct.
9222 			 */
9223 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9224 			    DDI_DMA_SYNC_FORCPU);
9225 			ASSERT(rval == DDI_SUCCESS);
9226 		}
9227 		/*
9228 		 * Normal completion - copy data into caller's buffer
9229 		 */
9230 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
9231 		    sizeof (struct scsi_inquiry));
9232 #ifdef SATA_DEBUG
9233 		if (sata_debug_flags & SATA_DBG_ATAPI) {
9234 			sata_show_inqry_data((uint8_t *)inq);
9235 		}
9236 #endif
9237 		rval = SATA_SUCCESS;
9238 	} else {
9239 		/*
9240 		 * Something went wrong - analyze return - check rqsense data
9241 		 */
9242 		rval = SATA_FAILURE;
9243 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9244 			/*
9245 			 * ARQ data hopefull show something other than NO SENSE
9246 			 */
9247 			rqsp = scmd->satacmd_rqsense;
9248 #ifdef SATA_DEBUG
9249 			if (sata_debug_flags & SATA_DBG_ATAPI) {
9250 				msg_buf[0] = '\0';
9251 				(void) snprintf(msg_buf, MAXPATHLEN,
9252 				    "ATAPI packet completion reason: %02x\n"
9253 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
9254 				    "          %02x %02x %02x %02x %02x %02x\n"
9255 				    "          %02x %02x %02x %02x %02x %02x",
9256 				    spkt->satapkt_reason,
9257 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9258 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9259 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9260 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9261 				    rqsp[16], rqsp[17]);
9262 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9263 				    "%s", msg_buf);
9264 			}
9265 #endif
9266 		} else {
9267 			switch (spkt->satapkt_reason) {
9268 			case SATA_PKT_PORT_ERROR:
9269 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9270 				    "sata_get_atapi_inquiry_data: "
9271 				    "packet reason: port error", NULL);
9272 				break;
9273 
9274 			case SATA_PKT_TIMEOUT:
9275 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9276 				    "sata_get_atapi_inquiry_data: "
9277 				    "packet reason: timeout", NULL);
9278 				break;
9279 
9280 			case SATA_PKT_ABORTED:
9281 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9282 				    "sata_get_atapi_inquiry_data: "
9283 				    "packet reason: aborted", NULL);
9284 				break;
9285 
9286 			case SATA_PKT_RESET:
9287 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9288 				    "sata_get_atapi_inquiry_data: "
9289 				    "packet reason: reset\n", NULL);
9290 				break;
9291 			default:
9292 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9293 				    "sata_get_atapi_inquiry_data: "
9294 				    "invalid packet reason: %02x\n",
9295 				    spkt->satapkt_reason);
9296 				break;
9297 			}
9298 		}
9299 	}
9300 cleanup:
9301 	sata_free_local_buffer(spx);
9302 	sata_pkt_free(spx);
9303 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9304 	return (rval);
9305 }
9306 
9307 
9308 
9309 
9310 
9311 #if 0
9312 #ifdef SATA_DEBUG
9313 
9314 /*
9315  * Test ATAPI packet command.
9316  * Single threaded test: send packet command in synch mode, process completion
9317  *
9318  */
9319 static void
9320 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
9321 {
9322 	sata_pkt_txlate_t *spx;
9323 	sata_pkt_t *spkt;
9324 	struct buf *bp;
9325 	sata_device_t sata_device;
9326 	sata_drive_info_t *sdinfo;
9327 	sata_cmd_t *scmd;
9328 	int rval;
9329 	uint8_t *rqsp;
9330 
9331 	ASSERT(sata_hba_inst != NULL);
9332 	sata_device.satadev_addr.cport = cport;
9333 	sata_device.satadev_addr.pmport = 0;
9334 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
9335 	sata_device.satadev_rev = SATA_DEVICE_REV;
9336 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9337 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
9338 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9339 	if (sdinfo == NULL) {
9340 		sata_log(sata_hba_inst, CE_WARN,
9341 		    "sata_test_atapi_packet_command: "
9342 		    "no device info for cport %d",
9343 		    sata_device.satadev_addr.cport);
9344 		return;
9345 	}
9346 
9347 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9348 	spx->txlt_sata_hba_inst = sata_hba_inst;
9349 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9350 	spkt = sata_pkt_alloc(spx, NULL);
9351 	if (spkt == NULL) {
9352 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9353 		return;
9354 	}
9355 	/* address is needed now */
9356 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
9357 
9358 	/* 1024k buffer */
9359 	bp = sata_alloc_local_buffer(spx, 1024);
9360 	if (bp == NULL) {
9361 		sata_pkt_free(spx);
9362 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9363 		sata_log(sata_hba_inst, CE_WARN,
9364 		    "sata_test_atapi_packet_command: "
9365 		    "cannot allocate data buffer");
9366 		return;
9367 	}
9368 	bp_mapin(bp); /* make data buffer accessible */
9369 
9370 	scmd = &spkt->satapkt_cmd;
9371 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9372 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9373 
9374 	/* Use synchronous mode */
9375 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9376 
9377 	/* Synchronous mode, no callback - may be changed by the caller */
9378 	spkt->satapkt_comp = NULL;
9379 	spkt->satapkt_time = sata_default_pkt_time;
9380 
9381 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9382 
9383 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9384 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9385 
9386 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9387 
9388 	/* Set-up acdb. */
9389 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9390 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9391 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9392 	scmd->satacmd_acdb[1] = 0x00;
9393 	scmd->satacmd_acdb[2] = 0x00;
9394 	scmd->satacmd_acdb[3] = 0x00;
9395 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9396 	scmd->satacmd_acdb[5] = 0x00;
9397 
9398 	sata_fixed_sense_data_preset(
9399 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9400 
9401 	/* Transfer command to HBA */
9402 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9403 	if (sata_hba_start(spx, &rval) != 0) {
9404 		/* Pkt not accepted for execution */
9405 		sata_log(sata_hba_inst, CE_WARN,
9406 		    "sata_test_atapi_packet_command: "
9407 		    "Packet not accepted for execution - ret: %02x", rval);
9408 		mutex_exit(
9409 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9410 		goto cleanup;
9411 	}
9412 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9413 
9414 	if (spx->txlt_buf_dma_handle != NULL) {
9415 		/*
9416 		 * Sync buffer. Handle is in usual place in translate struct.
9417 		 */
9418 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9419 		    DDI_DMA_SYNC_FORCPU);
9420 		ASSERT(rval == DDI_SUCCESS);
9421 	}
9422 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9423 		sata_log(sata_hba_inst, CE_WARN,
9424 		    "sata_test_atapi_packet_command: "
9425 		    "Packet completed successfully");
9426 		/*
9427 		 * Normal completion - show inquiry data
9428 		 */
9429 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
9430 	} else {
9431 		/*
9432 		 * Something went wrong - analyze return - check rqsense data
9433 		 */
9434 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9435 			/*
9436 			 * ARQ data hopefull show something other than NO SENSE
9437 			 */
9438 			rqsp = scmd->satacmd_rqsense;
9439 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9440 			    "ATAPI packet completion reason: %02x\n"
9441 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9442 			    "          %02x %02x %02x %02x %02x %02x "
9443 			    "          %02x %02x %02x %02x %02x %02x\n",
9444 			    spkt->satapkt_reason,
9445 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9446 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9447 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9448 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9449 			    rqsp[16], rqsp[17]);
9450 		} else {
9451 			switch (spkt->satapkt_reason) {
9452 			case SATA_PKT_PORT_ERROR:
9453 				sata_log(sata_hba_inst, CE_WARN,
9454 				    "sata_test_atapi_packet_command: "
9455 				    "packet reason: port error\n");
9456 				break;
9457 
9458 			case SATA_PKT_TIMEOUT:
9459 				sata_log(sata_hba_inst, CE_WARN,
9460 				    "sata_test_atapi_packet_command: "
9461 				    "packet reason: timeout\n");
9462 				break;
9463 
9464 			case SATA_PKT_ABORTED:
9465 				sata_log(sata_hba_inst, CE_WARN,
9466 				    "sata_test_atapi_packet_command: "
9467 				    "packet reason: aborted\n");
9468 				break;
9469 
9470 			case SATA_PKT_RESET:
9471 				sata_log(sata_hba_inst, CE_WARN,
9472 				    "sata_test_atapi_packet_command: "
9473 				    "packet reason: reset\n");
9474 				break;
9475 			default:
9476 				sata_log(sata_hba_inst, CE_WARN,
9477 				    "sata_test_atapi_packet_command: "
9478 				    "invalid packet reason: %02x\n",
9479 				    spkt->satapkt_reason);
9480 				break;
9481 			}
9482 		}
9483 	}
9484 cleanup:
9485 	sata_free_local_buffer(spx);
9486 	sata_pkt_free(spx);
9487 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9488 }
9489 
9490 #endif /* SATA_DEBUG */
9491 #endif /* 1 */
9492 
9493 
9494 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
9495 
9496 /*
9497  * Validate sata_tran info
9498  * SATA_FAILURE returns if structure is inconsistent or structure revision
9499  * does not match one used by the framework.
9500  *
9501  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
9502  * required function pointers.
9503  * Returns SATA_FAILURE otherwise.
9504  */
9505 static int
9506 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
9507 {
9508 	/*
9509 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
9510 	 * of the SATA interface.
9511 	 */
9512 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
9513 		sata_log(NULL, CE_WARN,
9514 		    "sata: invalid sata_hba_tran version %d for driver %s",
9515 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
9516 		return (SATA_FAILURE);
9517 	}
9518 
9519 	if (dip != sata_tran->sata_tran_hba_dip) {
9520 		SATA_LOG_D((NULL, CE_WARN,
9521 		    "sata: inconsistent sata_tran_hba_dip "
9522 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
9523 		return (SATA_FAILURE);
9524 	}
9525 
9526 	if (sata_tran->sata_tran_probe_port == NULL ||
9527 	    sata_tran->sata_tran_start == NULL ||
9528 	    sata_tran->sata_tran_abort == NULL ||
9529 	    sata_tran->sata_tran_reset_dport == NULL ||
9530 	    sata_tran->sata_tran_hotplug_ops == NULL ||
9531 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
9532 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
9533 	    NULL) {
9534 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
9535 		    "required functions"));
9536 	}
9537 	return (SATA_SUCCESS);
9538 }
9539 
9540 /*
9541  * Remove HBA instance from sata_hba_list.
9542  */
9543 static void
9544 sata_remove_hba_instance(dev_info_t *dip)
9545 {
9546 	sata_hba_inst_t	*sata_hba_inst;
9547 
9548 	mutex_enter(&sata_mutex);
9549 	for (sata_hba_inst = sata_hba_list;
9550 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
9551 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9552 		if (sata_hba_inst->satahba_dip == dip)
9553 			break;
9554 	}
9555 
9556 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
9557 #ifdef SATA_DEBUG
9558 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
9559 		    "unknown HBA instance\n");
9560 #endif
9561 		ASSERT(FALSE);
9562 	}
9563 	if (sata_hba_inst == sata_hba_list) {
9564 		sata_hba_list = sata_hba_inst->satahba_next;
9565 		if (sata_hba_list) {
9566 			sata_hba_list->satahba_prev =
9567 			    (struct sata_hba_inst *)NULL;
9568 		}
9569 		if (sata_hba_inst == sata_hba_list_tail) {
9570 			sata_hba_list_tail = NULL;
9571 		}
9572 	} else if (sata_hba_inst == sata_hba_list_tail) {
9573 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
9574 		if (sata_hba_list_tail) {
9575 			sata_hba_list_tail->satahba_next =
9576 			    (struct sata_hba_inst *)NULL;
9577 		}
9578 	} else {
9579 		sata_hba_inst->satahba_prev->satahba_next =
9580 		    sata_hba_inst->satahba_next;
9581 		sata_hba_inst->satahba_next->satahba_prev =
9582 		    sata_hba_inst->satahba_prev;
9583 	}
9584 	mutex_exit(&sata_mutex);
9585 }
9586 
9587 /*
9588  * Probe all SATA ports of the specified HBA instance.
9589  * The assumption is that there are no target and attachment point minor nodes
9590  * created by the boot subsystems, so we do not need to prune device tree.
9591  *
9592  * This function is called only from sata_hba_attach(). It does not have to
9593  * be protected by controller mutex, because the hba_attached flag is not set
9594  * yet and no one would be touching this HBA instance other than this thread.
9595  * Determines if port is active and what type of the device is attached
9596  * (if any). Allocates necessary structures for each port.
9597  *
9598  * An AP (Attachement Point) node is created for each SATA device port even
9599  * when there is no device attached.
9600  */
9601 
9602 static 	void
9603 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
9604 {
9605 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9606 	int			ncport;
9607 	sata_cport_info_t 	*cportinfo;
9608 	sata_drive_info_t	*drive;
9609 	sata_device_t		sata_device;
9610 	int			rval;
9611 	dev_t			minor_number;
9612 	char			name[16];
9613 	clock_t			start_time, cur_time;
9614 
9615 	/*
9616 	 * Probe controller ports first, to find port status and
9617 	 * any port multiplier attached.
9618 	 */
9619 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
9620 		/* allocate cport structure */
9621 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
9622 		ASSERT(cportinfo != NULL);
9623 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
9624 
9625 		mutex_enter(&cportinfo->cport_mutex);
9626 
9627 		cportinfo->cport_addr.cport = ncport;
9628 		cportinfo->cport_addr.pmport = 0;
9629 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
9630 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
9631 		cportinfo->cport_state |= SATA_STATE_PROBING;
9632 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
9633 
9634 		/*
9635 		 * Regardless if a port is usable or not, create
9636 		 * an attachment point
9637 		 */
9638 		mutex_exit(&cportinfo->cport_mutex);
9639 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
9640 		    ncport, 0, SATA_ADDR_CPORT);
9641 		(void) sprintf(name, "%d", ncport);
9642 		if (ddi_create_minor_node(dip, name, S_IFCHR,
9643 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
9644 		    DDI_SUCCESS) {
9645 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
9646 			    "cannot create SATA attachment point for port %d",
9647 			    ncport);
9648 		}
9649 
9650 		/* Probe port */
9651 		start_time = ddi_get_lbolt();
9652 	reprobe_cport:
9653 		sata_device.satadev_addr.cport = ncport;
9654 		sata_device.satadev_addr.pmport = 0;
9655 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
9656 		sata_device.satadev_rev = SATA_DEVICE_REV;
9657 
9658 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9659 		    (dip, &sata_device);
9660 
9661 		mutex_enter(&cportinfo->cport_mutex);
9662 		cportinfo->cport_scr = sata_device.satadev_scr;
9663 		if (rval != SATA_SUCCESS) {
9664 			/* Something went wrong? Fail the port */
9665 			cportinfo->cport_state = SATA_PSTATE_FAILED;
9666 			mutex_exit(&cportinfo->cport_mutex);
9667 			continue;
9668 		}
9669 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
9670 		cportinfo->cport_state |= SATA_STATE_PROBED;
9671 		cportinfo->cport_dev_type = sata_device.satadev_type;
9672 
9673 		cportinfo->cport_state |= SATA_STATE_READY;
9674 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
9675 			mutex_exit(&cportinfo->cport_mutex);
9676 			continue;
9677 		}
9678 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
9679 			/*
9680 			 * There is some device attached.
9681 			 * Allocate device info structure
9682 			 */
9683 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
9684 				mutex_exit(&cportinfo->cport_mutex);
9685 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
9686 				    kmem_zalloc(sizeof (sata_drive_info_t),
9687 				    KM_SLEEP);
9688 				mutex_enter(&cportinfo->cport_mutex);
9689 			}
9690 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
9691 			drive->satadrv_addr = cportinfo->cport_addr;
9692 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
9693 			drive->satadrv_type = cportinfo->cport_dev_type;
9694 			drive->satadrv_state = SATA_STATE_UNKNOWN;
9695 
9696 			mutex_exit(&cportinfo->cport_mutex);
9697 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
9698 			    SATA_SUCCESS) {
9699 				/*
9700 				 * Plugged device was not correctly identified.
9701 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
9702 				 */
9703 				cur_time = ddi_get_lbolt();
9704 				if ((cur_time - start_time) <
9705 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
9706 					/* sleep for a while */
9707 					delay(drv_usectohz(
9708 					    SATA_DEV_RETRY_DLY));
9709 					goto reprobe_cport;
9710 				}
9711 			}
9712 		} else { /* SATA_DTYPE_PMULT */
9713 			mutex_exit(&cportinfo->cport_mutex);
9714 
9715 			/* Allocate sata_pmult_info and sata_pmport_info */
9716 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
9717 			    SATA_SUCCESS)
9718 				continue;
9719 
9720 			/* Log the information of the port multiplier */
9721 			sata_show_pmult_info(sata_hba_inst, &sata_device);
9722 
9723 			/* Probe its pmports */
9724 			sata_probe_pmports(sata_hba_inst, ncport);
9725 		}
9726 	}
9727 }
9728 
9729 /*
9730  * Probe all device ports behind a port multiplier.
9731  *
9732  * PMult-related structure should be allocated before by sata_alloc_pmult().
9733  *
9734  * NOTE1: Only called from sata_probe_ports()
9735  * NOTE2: No mutex should be hold.
9736  */
9737 static void
9738 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
9739 {
9740 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9741 	sata_pmult_info_t	*pmultinfo = NULL;
9742 	sata_pmport_info_t 	*pmportinfo = NULL;
9743 	sata_drive_info_t	*drive = NULL;
9744 	sata_device_t		sata_device;
9745 
9746 	clock_t			start_time, cur_time;
9747 	int			npmport;
9748 	int			rval;
9749 
9750 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
9751 
9752 	/* Probe Port Multiplier ports */
9753 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
9754 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
9755 		start_time = ddi_get_lbolt();
9756 reprobe_pmport:
9757 		sata_device.satadev_addr.cport = ncport;
9758 		sata_device.satadev_addr.pmport = npmport;
9759 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
9760 		sata_device.satadev_rev = SATA_DEVICE_REV;
9761 
9762 		/* Let HBA driver probe it. */
9763 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9764 		    (dip, &sata_device);
9765 		mutex_enter(&pmportinfo->pmport_mutex);
9766 
9767 		pmportinfo->pmport_scr = sata_device.satadev_scr;
9768 
9769 		if (rval != SATA_SUCCESS) {
9770 			pmportinfo->pmport_state =
9771 			    SATA_PSTATE_FAILED;
9772 			mutex_exit(&pmportinfo->pmport_mutex);
9773 			continue;
9774 		}
9775 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
9776 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
9777 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
9778 
9779 		pmportinfo->pmport_state |= SATA_STATE_READY;
9780 		if (pmportinfo->pmport_dev_type ==
9781 		    SATA_DTYPE_NONE) {
9782 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
9783 			    "no device found at port %d:%d", ncport, npmport);
9784 			mutex_exit(&pmportinfo->pmport_mutex);
9785 			continue;
9786 		}
9787 		/* Port multipliers cannot be chained */
9788 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
9789 		/*
9790 		 * There is something attached to Port
9791 		 * Multiplier device port
9792 		 * Allocate device info structure
9793 		 */
9794 		if (pmportinfo->pmport_sata_drive == NULL) {
9795 			mutex_exit(&pmportinfo->pmport_mutex);
9796 			pmportinfo->pmport_sata_drive =
9797 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
9798 			mutex_enter(&pmportinfo->pmport_mutex);
9799 		}
9800 		drive = pmportinfo->pmport_sata_drive;
9801 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
9802 		drive->satadrv_addr.pmport = npmport;
9803 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
9804 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
9805 		drive->satadrv_state = SATA_STATE_UNKNOWN;
9806 
9807 		mutex_exit(&pmportinfo->pmport_mutex);
9808 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
9809 
9810 		if (rval != SATA_SUCCESS) {
9811 			/*
9812 			 * Plugged device was not correctly identified.
9813 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
9814 			 */
9815 			cur_time = ddi_get_lbolt();
9816 			if ((cur_time - start_time) < drv_usectohz(
9817 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
9818 				/* sleep for a while */
9819 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
9820 				goto reprobe_pmport;
9821 			}
9822 		}
9823 	}
9824 }
9825 
9826 /*
9827  * Add SATA device for specified HBA instance & port (SCSI target
9828  * device nodes).
9829  * This function is called (indirectly) only from sata_hba_attach().
9830  * A target node is created when there is a supported type device attached,
9831  * but may be removed if it cannot be put online.
9832  *
9833  * This function cannot be called from an interrupt context.
9834  *
9835  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
9836  *
9837  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
9838  * device identification failed - adding a device could be retried.
9839  *
9840  */
9841 static 	int
9842 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
9843     sata_device_t *sata_device)
9844 {
9845 	sata_cport_info_t 	*cportinfo;
9846 	sata_pmult_info_t	*pminfo;
9847 	sata_pmport_info_t	*pmportinfo;
9848 	dev_info_t		*cdip;		/* child dip */
9849 	sata_address_t		*saddr = &sata_device->satadev_addr;
9850 	uint8_t			cport, pmport;
9851 	int			rval;
9852 
9853 	cport = saddr->cport;
9854 	pmport = saddr->pmport;
9855 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
9856 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
9857 
9858 	/*
9859 	 * Some device is attached to a controller port.
9860 	 * We rely on controllers distinquishing between no-device,
9861 	 * attached port multiplier and other kind of attached device.
9862 	 * We need to get Identify Device data and determine
9863 	 * positively the dev type before trying to attach
9864 	 * the target driver.
9865 	 */
9866 	sata_device->satadev_rev = SATA_DEVICE_REV;
9867 	switch (saddr->qual) {
9868 	case SATA_ADDR_CPORT:
9869 		/*
9870 		 * Add a non-port-multiplier device at controller port.
9871 		 */
9872 		saddr->qual = SATA_ADDR_DCPORT;
9873 
9874 		rval = sata_probe_device(sata_hba_inst, sata_device);
9875 		if (rval != SATA_SUCCESS ||
9876 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
9877 			return (SATA_FAILURE);
9878 
9879 		mutex_enter(&cportinfo->cport_mutex);
9880 		sata_show_drive_info(sata_hba_inst,
9881 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
9882 
9883 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
9884 			/*
9885 			 * Could not determine device type or
9886 			 * a device is not supported.
9887 			 * Degrade this device to unknown.
9888 			 */
9889 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
9890 			mutex_exit(&cportinfo->cport_mutex);
9891 			return (SATA_SUCCESS);
9892 		}
9893 		cportinfo->cport_dev_type = sata_device->satadev_type;
9894 		cportinfo->cport_tgtnode_clean = B_TRUE;
9895 		mutex_exit(&cportinfo->cport_mutex);
9896 
9897 		/*
9898 		 * Initialize device to the desired state. Even if it
9899 		 * fails, the device will still attach but syslog
9900 		 * will show the warning.
9901 		 */
9902 		if (sata_initialize_device(sata_hba_inst,
9903 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
9904 			/* Retry */
9905 			rval = sata_initialize_device(sata_hba_inst,
9906 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
9907 
9908 			if (rval == SATA_RETRY)
9909 				sata_log(sata_hba_inst, CE_WARN,
9910 				    "SATA device at port %d - "
9911 				    "default device features could not be set."
9912 				    " Device may not operate as expected.",
9913 				    cport);
9914 		}
9915 
9916 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
9917 		if (cdip == NULL) {
9918 			/*
9919 			 * Attaching target node failed.
9920 			 * We retain sata_drive_info structure...
9921 			 */
9922 			return (SATA_SUCCESS);
9923 		}
9924 
9925 		mutex_enter(&cportinfo->cport_mutex);
9926 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
9927 		    satadrv_state = SATA_STATE_READY;
9928 		mutex_exit(&cportinfo->cport_mutex);
9929 
9930 		break;
9931 
9932 	case SATA_ADDR_PMPORT:
9933 		saddr->qual = SATA_ADDR_DPMPORT;
9934 
9935 		mutex_enter(&cportinfo->cport_mutex);
9936 		/* It must be a Port Multiplier at the controller port */
9937 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
9938 
9939 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
9940 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
9941 		mutex_exit(&cportinfo->cport_mutex);
9942 
9943 		rval = sata_probe_device(sata_hba_inst, sata_device);
9944 		if (rval != SATA_SUCCESS ||
9945 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
9946 			return (SATA_FAILURE);
9947 		}
9948 
9949 		mutex_enter(&pmportinfo->pmport_mutex);
9950 		sata_show_drive_info(sata_hba_inst,
9951 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
9952 
9953 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
9954 			/*
9955 			 * Could not determine device type.
9956 			 * Degrade this device to unknown.
9957 			 */
9958 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
9959 			mutex_exit(&pmportinfo->pmport_mutex);
9960 			return (SATA_SUCCESS);
9961 		}
9962 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
9963 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
9964 		mutex_exit(&pmportinfo->pmport_mutex);
9965 
9966 		/*
9967 		 * Initialize device to the desired state.
9968 		 * Even if it fails, the device will still
9969 		 * attach but syslog will show the warning.
9970 		 */
9971 		if (sata_initialize_device(sata_hba_inst,
9972 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
9973 			/* Retry */
9974 			rval = sata_initialize_device(sata_hba_inst,
9975 			    pmportinfo->pmport_sata_drive);
9976 
9977 			if (rval == SATA_RETRY)
9978 				sata_log(sata_hba_inst, CE_WARN,
9979 				    "SATA device at port %d:%d - "
9980 				    "default device features could not be set."
9981 				    " Device may not operate as expected.",
9982 				    cport, pmport);
9983 		}
9984 
9985 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
9986 		if (cdip == NULL) {
9987 			/*
9988 			 * Attaching target node failed.
9989 			 * We retain sata_drive_info structure...
9990 			 */
9991 			return (SATA_SUCCESS);
9992 		}
9993 		mutex_enter(&pmportinfo->pmport_mutex);
9994 		pmportinfo->pmport_sata_drive->satadrv_state |=
9995 		    SATA_STATE_READY;
9996 		mutex_exit(&pmportinfo->pmport_mutex);
9997 
9998 		break;
9999 
10000 	default:
10001 		return (SATA_FAILURE);
10002 	}
10003 
10004 	return (SATA_SUCCESS);
10005 }
10006 
10007 /*
10008  * Clean up target node at specific address.
10009  *
10010  * NOTE: No Mutex should be hold.
10011  */
10012 static int
10013 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
10014     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
10015 {
10016 	uint8_t cport, pmport, qual;
10017 	dev_info_t *tdip;
10018 
10019 	cport = sata_device->satadev_addr.cport;
10020 	pmport = sata_device->satadev_addr.pmport;
10021 	qual = sata_device->satadev_addr.qual;
10022 
10023 	if (qual == SATA_ADDR_DCPORT) {
10024 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10025 		    "sata_hba_ioctl: disconnect device at port %d", cport));
10026 	} else {
10027 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10028 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10029 		    cport, pmport));
10030 	}
10031 
10032 	/* We are addressing attached device, not a port */
10033 	sata_device->satadev_addr.qual =
10034 	    sdinfo->satadrv_addr.qual;
10035 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10036 	    &sata_device->satadev_addr);
10037 	if (tdip != NULL && ndi_devi_offline(tdip,
10038 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10039 		/*
10040 		 * Problem :
10041 		 * The target node remained attached.
10042 		 * This happens when the device file was open
10043 		 * or a node was waiting for resources.
10044 		 * Cannot do anything about it.
10045 		 */
10046 		if (qual == SATA_ADDR_DCPORT) {
10047 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10048 			    "sata_hba_ioctl: disconnect: could "
10049 			    "not unconfigure device before "
10050 			    "disconnecting the SATA port %d",
10051 			    cport));
10052 		} else {
10053 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10054 			    "sata_hba_ioctl: disconnect: could "
10055 			    "not unconfigure device before "
10056 			    "disconnecting the SATA port %d:%d",
10057 			    cport, pmport));
10058 		}
10059 		/*
10060 		 * Set DEVICE REMOVED state in the target
10061 		 * node. It will prevent access to the device
10062 		 * even when a new device is attached, until
10063 		 * the old target node is released, removed and
10064 		 * recreated for a new  device.
10065 		 */
10066 		sata_set_device_removed(tdip);
10067 
10068 		/*
10069 		 * Instruct event daemon to try the target
10070 		 * node cleanup later.
10071 		 */
10072 		sata_set_target_node_cleanup(
10073 		    sata_hba_inst, &sata_device->satadev_addr);
10074 	}
10075 
10076 
10077 	return (SATA_SUCCESS);
10078 }
10079 
10080 
10081 /*
10082  * Create scsi target node for attached device, create node properties and
10083  * attach the node.
10084  * The node could be removed if the device onlining fails.
10085  *
10086  * A dev_info_t pointer is returned if operation is successful, NULL is
10087  * returned otherwise.
10088  */
10089 
10090 static dev_info_t *
10091 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10092 			sata_address_t *sata_addr)
10093 {
10094 	dev_info_t *cdip = NULL;
10095 	int rval;
10096 	char *nname = NULL;
10097 	char **compatible = NULL;
10098 	int ncompatible;
10099 	struct scsi_inquiry inq;
10100 	sata_device_t sata_device;
10101 	sata_drive_info_t *sdinfo;
10102 	int target;
10103 	int i;
10104 
10105 	sata_device.satadev_rev = SATA_DEVICE_REV;
10106 	sata_device.satadev_addr = *sata_addr;
10107 
10108 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10109 
10110 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10111 
10112 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10113 	    sata_addr->pmport, sata_addr->qual);
10114 
10115 	if (sdinfo == NULL) {
10116 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10117 		    sata_addr->cport)));
10118 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10119 		    "sata_create_target_node: no sdinfo for target %x",
10120 		    target));
10121 		return (NULL);
10122 	}
10123 
10124 	/*
10125 	 * create or get scsi inquiry data, expected by
10126 	 * scsi_hba_nodename_compatible_get()
10127 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10128 	 * ATAPI devices respond directly to Inquiry request.
10129 	 */
10130 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10131 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10132 		    (uint8_t *)&inq);
10133 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10134 		    sata_addr->cport)));
10135 	} else { /* Assume supported ATAPI device */
10136 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10137 		    sata_addr->cport)));
10138 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10139 		    &inq) == SATA_FAILURE)
10140 			return (NULL);
10141 		/*
10142 		 * Save supported ATAPI transport version
10143 		 */
10144 		sdinfo->satadrv_atapi_trans_ver =
10145 		    SATA_ATAPI_TRANS_VERSION(&inq);
10146 	}
10147 
10148 	/* determine the node name and compatible */
10149 	scsi_hba_nodename_compatible_get(&inq, NULL,
10150 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10151 
10152 #ifdef SATA_DEBUG
10153 	if (sata_debug_flags & SATA_DBG_NODES) {
10154 		if (nname == NULL) {
10155 			cmn_err(CE_NOTE, "sata_create_target_node: "
10156 			    "cannot determine nodename for target %d\n",
10157 			    target);
10158 		} else {
10159 			cmn_err(CE_WARN, "sata_create_target_node: "
10160 			    "target %d nodename: %s\n", target, nname);
10161 		}
10162 		if (compatible == NULL) {
10163 			cmn_err(CE_WARN,
10164 			    "sata_create_target_node: no compatible name\n");
10165 		} else {
10166 			for (i = 0; i < ncompatible; i++) {
10167 				cmn_err(CE_WARN, "sata_create_target_node: "
10168 				    "compatible name: %s\n", compatible[i]);
10169 			}
10170 		}
10171 	}
10172 #endif
10173 
10174 	/* if nodename can't be determined, log error and exit */
10175 	if (nname == NULL) {
10176 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10177 		    "sata_create_target_node: cannot determine nodename "
10178 		    "for target %d\n", target));
10179 		scsi_hba_nodename_compatible_free(nname, compatible);
10180 		return (NULL);
10181 	}
10182 	/*
10183 	 * Create scsi target node
10184 	 */
10185 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
10186 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10187 	    "device-type", "scsi");
10188 
10189 	if (rval != DDI_PROP_SUCCESS) {
10190 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10191 		    "updating device_type prop failed %d", rval));
10192 		goto fail;
10193 	}
10194 
10195 	/*
10196 	 * Create target node properties: target & lun
10197 	 */
10198 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
10199 	if (rval != DDI_PROP_SUCCESS) {
10200 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10201 		    "updating target prop failed %d", rval));
10202 		goto fail;
10203 	}
10204 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
10205 	if (rval != DDI_PROP_SUCCESS) {
10206 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10207 		    "updating target prop failed %d", rval));
10208 		goto fail;
10209 	}
10210 
10211 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10212 		/*
10213 		 * Add "variant" property
10214 		 */
10215 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10216 		    "variant", "atapi");
10217 		if (rval != DDI_PROP_SUCCESS) {
10218 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10219 			    "sata_create_target_node: variant atapi "
10220 			    "property could not be created: %d", rval));
10221 			goto fail;
10222 		}
10223 	}
10224 	/* decorate the node with compatible */
10225 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
10226 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
10227 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10228 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
10229 		    (void *)cdip));
10230 		goto fail;
10231 	}
10232 
10233 
10234 	/*
10235 	 * Now, try to attach the driver. If probing of the device fails,
10236 	 * the target node may be removed
10237 	 */
10238 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
10239 
10240 	scsi_hba_nodename_compatible_free(nname, compatible);
10241 
10242 	if (rval == NDI_SUCCESS)
10243 		return (cdip);
10244 
10245 	/* target node was removed - are we sure? */
10246 	return (NULL);
10247 
10248 fail:
10249 	scsi_hba_nodename_compatible_free(nname, compatible);
10250 	ddi_prop_remove_all(cdip);
10251 	rval = ndi_devi_free(cdip);
10252 	if (rval != NDI_SUCCESS) {
10253 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10254 		    "node removal failed %d", rval));
10255 	}
10256 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
10257 	    "cannot create target node for SATA device at port %d",
10258 	    sata_addr->cport);
10259 	return (NULL);
10260 }
10261 
10262 /*
10263  * Remove a target node.
10264  */
10265 static void
10266 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
10267 			sata_address_t *sata_addr)
10268 {
10269 	dev_info_t *tdip;
10270 	uint8_t cport = sata_addr->cport;
10271 	uint8_t pmport = sata_addr->pmport;
10272 	uint8_t qual = sata_addr->qual;
10273 
10274 	/* Note the sata daemon uses the address of the port/pmport */
10275 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10276 
10277 	/* Remove target node */
10278 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
10279 	if (tdip != NULL) {
10280 		/*
10281 		 * Target node exists.  Unconfigure device
10282 		 * then remove the target node (one ndi
10283 		 * operation).
10284 		 */
10285 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10286 			/*
10287 			 * PROBLEM - no device, but target node remained. This
10288 			 * happens when the file was open or node was waiting
10289 			 * for resources.
10290 			 */
10291 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10292 			    "sata_remove_target_node: "
10293 			    "Failed to remove target node for "
10294 			    "detached SATA device."));
10295 			/*
10296 			 * Set target node state to DEVI_DEVICE_REMOVED. But
10297 			 * re-check first that the node still exists.
10298 			 */
10299 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
10300 			    cport, pmport);
10301 			if (tdip != NULL) {
10302 				sata_set_device_removed(tdip);
10303 				/*
10304 				 * Instruct event daemon to retry the cleanup
10305 				 * later.
10306 				 */
10307 				sata_set_target_node_cleanup(sata_hba_inst,
10308 				    sata_addr);
10309 			}
10310 		}
10311 
10312 		if (qual == SATA_ADDR_CPORT)
10313 			sata_log(sata_hba_inst, CE_WARN,
10314 			    "SATA device detached at port %d", cport);
10315 		else
10316 			sata_log(sata_hba_inst, CE_WARN,
10317 			    "SATA device detached at port %d:%d",
10318 			    cport, pmport);
10319 	}
10320 #ifdef SATA_DEBUG
10321 	else {
10322 		if (qual == SATA_ADDR_CPORT)
10323 			sata_log(sata_hba_inst, CE_WARN,
10324 			    "target node not found at port %d", cport);
10325 		else
10326 			sata_log(sata_hba_inst, CE_WARN,
10327 			    "target node not found at port %d:%d",
10328 			    cport, pmport);
10329 	}
10330 #endif
10331 }
10332 
10333 
10334 /*
10335  * Re-probe sata port, check for a device and attach info
10336  * structures when necessary. Identify Device data is fetched, if possible.
10337  * Assumption: sata address is already validated.
10338  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10339  * the presence of a device and its type.
10340  *
10341  * flag arg specifies that the function should try multiple times to identify
10342  * device type and to initialize it, or it should return immediately on failure.
10343  * SATA_DEV_IDENTIFY_RETRY - retry
10344  * SATA_DEV_IDENTIFY_NORETRY - no retry
10345  *
10346  * SATA_FAILURE is returned if one of the operations failed.
10347  *
10348  * This function cannot be called in interrupt context - it may sleep.
10349  *
10350  * Note: Port multiplier is supported.
10351  */
10352 static int
10353 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10354     int flag)
10355 {
10356 	sata_cport_info_t *cportinfo;
10357 	sata_pmult_info_t *pmultinfo;
10358 	sata_drive_info_t *sdinfo, *osdinfo;
10359 	boolean_t init_device = B_FALSE;
10360 	int prev_device_type = SATA_DTYPE_NONE;
10361 	int prev_device_settings = 0;
10362 	int prev_device_state = 0;
10363 	clock_t start_time;
10364 	int retry = B_FALSE;
10365 	uint8_t cport = sata_device->satadev_addr.cport;
10366 	int rval_probe, rval_init;
10367 
10368 	/*
10369 	 * If target is pmport, sata_reprobe_pmport() will handle it.
10370 	 */
10371 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
10372 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
10373 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
10374 
10375 	/* We only care about host sata cport for now */
10376 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10377 	    sata_device->satadev_addr.cport);
10378 
10379 	/*
10380 	 * If a port multiplier was previously attached (we have no idea it
10381 	 * still there or not), sata_reprobe_pmult() will handle it.
10382 	 */
10383 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
10384 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
10385 
10386 	/* Store sata_drive_info when a non-pmult device was attached. */
10387 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10388 	if (osdinfo != NULL) {
10389 		/*
10390 		 * We are re-probing port with a previously attached device.
10391 		 * Save previous device type and settings.
10392 		 */
10393 		prev_device_type = cportinfo->cport_dev_type;
10394 		prev_device_settings = osdinfo->satadrv_settings;
10395 		prev_device_state = osdinfo->satadrv_state;
10396 	}
10397 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
10398 		start_time = ddi_get_lbolt();
10399 		retry = B_TRUE;
10400 	}
10401 retry_probe:
10402 
10403 	/* probe port */
10404 	mutex_enter(&cportinfo->cport_mutex);
10405 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10406 	cportinfo->cport_state |= SATA_STATE_PROBING;
10407 	mutex_exit(&cportinfo->cport_mutex);
10408 
10409 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10410 	    (SATA_DIP(sata_hba_inst), sata_device);
10411 
10412 	mutex_enter(&cportinfo->cport_mutex);
10413 	if (rval_probe != SATA_SUCCESS) {
10414 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10415 		mutex_exit(&cportinfo->cport_mutex);
10416 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
10417 		    "SATA port %d probing failed",
10418 		    cportinfo->cport_addr.cport));
10419 		return (SATA_FAILURE);
10420 	}
10421 
10422 	/*
10423 	 * update sata port state and set device type
10424 	 */
10425 	sata_update_port_info(sata_hba_inst, sata_device);
10426 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10427 
10428 	/*
10429 	 * Sanity check - Port is active? Is the link active?
10430 	 * Is there any device attached?
10431 	 */
10432 	if ((cportinfo->cport_state &
10433 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10434 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10435 	    SATA_PORT_DEVLINK_UP) {
10436 		/*
10437 		 * Port in non-usable state or no link active/no device.
10438 		 * Free info structure if necessary (direct attached drive
10439 		 * only, for now!
10440 		 */
10441 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10442 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10443 		/* Add here differentiation for device attached or not */
10444 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10445 		mutex_exit(&cportinfo->cport_mutex);
10446 		if (sdinfo != NULL)
10447 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10448 		return (SATA_SUCCESS);
10449 	}
10450 
10451 	cportinfo->cport_state |= SATA_STATE_READY;
10452 	cportinfo->cport_state |= SATA_STATE_PROBED;
10453 
10454 	cportinfo->cport_dev_type = sata_device->satadev_type;
10455 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10456 
10457 	/*
10458 	 * If we are re-probing the port, there may be
10459 	 * sata_drive_info structure attached
10460 	 */
10461 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10462 
10463 		/*
10464 		 * There is no device, so remove device info structure,
10465 		 * if necessary.
10466 		 */
10467 		/* Device change: Drive -> None */
10468 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10469 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10470 		if (sdinfo != NULL) {
10471 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10472 			sata_log(sata_hba_inst, CE_WARN,
10473 			    "SATA device detached "
10474 			    "from port %d", cportinfo->cport_addr.cport);
10475 		}
10476 		mutex_exit(&cportinfo->cport_mutex);
10477 		return (SATA_SUCCESS);
10478 
10479 	}
10480 
10481 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10482 
10483 		/* Device (may) change: Drive -> Drive */
10484 		if (sdinfo == NULL) {
10485 			/*
10486 			 * There is some device attached, but there is
10487 			 * no sata_drive_info structure - allocate one
10488 			 */
10489 			mutex_exit(&cportinfo->cport_mutex);
10490 			sdinfo = kmem_zalloc(
10491 			    sizeof (sata_drive_info_t), KM_SLEEP);
10492 			mutex_enter(&cportinfo->cport_mutex);
10493 			/*
10494 			 * Recheck, that the port state did not change when we
10495 			 * released mutex.
10496 			 */
10497 			if (cportinfo->cport_state & SATA_STATE_READY) {
10498 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
10499 				sdinfo->satadrv_addr = cportinfo->cport_addr;
10500 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
10501 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10502 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10503 			} else {
10504 				/*
10505 				 * Port is not in ready state, we
10506 				 * cannot attach a device.
10507 				 */
10508 				mutex_exit(&cportinfo->cport_mutex);
10509 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
10510 				return (SATA_SUCCESS);
10511 			}
10512 			/*
10513 			 * Since we are adding device, presumably new one,
10514 			 * indicate that it  should be initalized,
10515 			 * as well as some internal framework states).
10516 			 */
10517 			init_device = B_TRUE;
10518 		}
10519 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10520 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10521 	} else {
10522 		/* Device change: Drive -> PMult */
10523 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10524 		if (sdinfo != NULL) {
10525 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10526 			sata_log(sata_hba_inst, CE_WARN,
10527 			    "SATA device detached "
10528 			    "from port %d", cportinfo->cport_addr.cport);
10529 		}
10530 
10531 		sata_log(sata_hba_inst, CE_WARN,
10532 		    "SATA port multiplier detected at port %d",
10533 		    cportinfo->cport_addr.cport);
10534 
10535 		mutex_exit(&cportinfo->cport_mutex);
10536 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
10537 		    SATA_SUCCESS)
10538 			return (SATA_FAILURE);
10539 		sata_show_pmult_info(sata_hba_inst, sata_device);
10540 		mutex_enter(&cportinfo->cport_mutex);
10541 
10542 		/*
10543 		 * Mark all the port multiplier port behind the port
10544 		 * multiplier behind with link events, so that the sata daemon
10545 		 * will update their status.
10546 		 */
10547 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10548 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10549 		mutex_exit(&cportinfo->cport_mutex);
10550 		return (SATA_SUCCESS);
10551 	}
10552 	mutex_exit(&cportinfo->cport_mutex);
10553 
10554 	/*
10555 	 * Figure out what kind of device we are really
10556 	 * dealing with. Failure of identifying device does not fail this
10557 	 * function.
10558 	 */
10559 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
10560 	rval_init = SATA_FAILURE;
10561 	mutex_enter(&cportinfo->cport_mutex);
10562 	if (rval_probe == SATA_SUCCESS) {
10563 		/*
10564 		 * If we are dealing with the same type of a device as before,
10565 		 * restore its settings flags.
10566 		 */
10567 		if (osdinfo != NULL &&
10568 		    sata_device->satadev_type == prev_device_type)
10569 			sdinfo->satadrv_settings = prev_device_settings;
10570 
10571 		mutex_exit(&cportinfo->cport_mutex);
10572 		rval_init = SATA_SUCCESS;
10573 		/* Set initial device features, if necessary */
10574 		if (init_device == B_TRUE) {
10575 			rval_init = sata_initialize_device(sata_hba_inst,
10576 			    sdinfo);
10577 		}
10578 		if (rval_init == SATA_SUCCESS)
10579 			return (rval_init);
10580 		/* else we will retry if retry was asked for */
10581 
10582 	} else {
10583 		/*
10584 		 * If there was some device info before we probe the device,
10585 		 * restore previous device setting, so we can retry from scratch
10586 		 * later. Providing, of course, that device has not disapear
10587 		 * during probing process.
10588 		 */
10589 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10590 			if (osdinfo != NULL) {
10591 				cportinfo->cport_dev_type = prev_device_type;
10592 				sdinfo->satadrv_type = prev_device_type;
10593 				sdinfo->satadrv_state = prev_device_state;
10594 			}
10595 		} else {
10596 			/* device is gone */
10597 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10598 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10599 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10600 			mutex_exit(&cportinfo->cport_mutex);
10601 			return (SATA_SUCCESS);
10602 		}
10603 		mutex_exit(&cportinfo->cport_mutex);
10604 	}
10605 
10606 	if (retry) {
10607 		clock_t cur_time = ddi_get_lbolt();
10608 		/*
10609 		 * A device was not successfully identified or initialized.
10610 		 * Track retry time for device identification.
10611 		 */
10612 		if ((cur_time - start_time) <
10613 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10614 			/* sleep for a while */
10615 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10616 			goto retry_probe;
10617 		}
10618 		/* else no more retries */
10619 		mutex_enter(&cportinfo->cport_mutex);
10620 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10621 			if (rval_init == SATA_RETRY) {
10622 				/*
10623 				 * Setting drive features have failed, but
10624 				 * because the drive is still accessible,
10625 				 * keep it and emit a warning message.
10626 				 */
10627 				sata_log(sata_hba_inst, CE_WARN,
10628 				    "SATA device at port %d - desired "
10629 				    "drive features could not be set. "
10630 				    "Device may not operate as expected.",
10631 				    cportinfo->cport_addr.cport);
10632 			} else {
10633 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
10634 				    satadrv_state = SATA_DSTATE_FAILED;
10635 			}
10636 		}
10637 		mutex_exit(&cportinfo->cport_mutex);
10638 	}
10639 	return (SATA_SUCCESS);
10640 }
10641 
10642 /*
10643  * Reprobe a controller port that connected to a port multiplier.
10644  *
10645  * NOTE: No Mutex should be hold.
10646  */
10647 static int
10648 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10649     int flag)
10650 {
10651 	_NOTE(ARGUNUSED(flag))
10652 	sata_cport_info_t *cportinfo;
10653 	sata_pmult_info_t *pmultinfo;
10654 	uint8_t cport = sata_device->satadev_addr.cport;
10655 	int rval_probe;
10656 
10657 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10658 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10659 
10660 	/* probe port */
10661 	mutex_enter(&cportinfo->cport_mutex);
10662 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10663 	cportinfo->cport_state |= SATA_STATE_PROBING;
10664 	mutex_exit(&cportinfo->cport_mutex);
10665 
10666 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10667 	    (SATA_DIP(sata_hba_inst), sata_device);
10668 
10669 	mutex_enter(&cportinfo->cport_mutex);
10670 	if (rval_probe != SATA_SUCCESS) {
10671 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10672 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
10673 		    "SATA port %d probing failed", cport));
10674 		sata_log(sata_hba_inst, CE_WARN,
10675 		    "SATA port multiplier detached at port %d", cport);
10676 		mutex_exit(&cportinfo->cport_mutex);
10677 		sata_free_pmult(sata_hba_inst, sata_device);
10678 		return (SATA_FAILURE);
10679 	}
10680 
10681 	/*
10682 	 * update sata port state and set device type
10683 	 */
10684 	sata_update_port_info(sata_hba_inst, sata_device);
10685 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10686 	cportinfo->cport_state |= SATA_STATE_PROBED;
10687 
10688 	/*
10689 	 * Sanity check - Port is active? Is the link active?
10690 	 * Is there any device attached?
10691 	 */
10692 	if ((cportinfo->cport_state &
10693 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10694 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10695 	    SATA_PORT_DEVLINK_UP ||
10696 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
10697 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10698 		mutex_exit(&cportinfo->cport_mutex);
10699 		sata_free_pmult(sata_hba_inst, sata_device);
10700 		sata_log(sata_hba_inst, CE_WARN,
10701 		    "SATA port multiplier detached at port %d", cport);
10702 		return (SATA_SUCCESS);
10703 	}
10704 
10705 	/*
10706 	 * Device changed: PMult -> Non-PMult
10707 	 *
10708 	 * This situation is uncommon, most possibly being caused by errors
10709 	 * after which the port multiplier is not correct initialized and
10710 	 * recognized. In that case the new device will be marked as unknown
10711 	 * and will not be automatically probed in this routine. Instead
10712 	 * system administrator could manually restart it via cfgadm(1M).
10713 	 */
10714 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10715 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10716 		mutex_exit(&cportinfo->cport_mutex);
10717 		sata_free_pmult(sata_hba_inst, sata_device);
10718 		sata_log(sata_hba_inst, CE_WARN,
10719 		    "SATA port multiplier detached at port %d", cport);
10720 		return (SATA_FAILURE);
10721 	}
10722 
10723 	/*
10724 	 * Now we know it is a port multiplier. However, if this is not the
10725 	 * previously attached port multiplier - they may have different
10726 	 * pmport numbers - we need to re-allocate data structures for every
10727 	 * pmport and drive.
10728 	 *
10729 	 * Port multipliers of the same model have identical values in these
10730 	 * registers, so it is still necessary to update the information of
10731 	 * all drives attached to the previous port multiplier afterwards.
10732 	 */
10733 	/* Device changed: PMult -> another PMult */
10734 	mutex_exit(&cportinfo->cport_mutex);
10735 	sata_free_pmult(sata_hba_inst, sata_device);
10736 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
10737 		return (SATA_FAILURE);
10738 	mutex_enter(&cportinfo->cport_mutex);
10739 
10740 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
10741 	    "SATA port multiplier [changed] at port %d", cport);
10742 	sata_log(sata_hba_inst, CE_WARN,
10743 	    "SATA port multiplier detected at port %d", cport);
10744 
10745 	/*
10746 	 * Mark all the port multiplier port behind the port
10747 	 * multiplier behind with link events, so that the sata daemon
10748 	 * will update their status.
10749 	 */
10750 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10751 	mutex_exit(&cportinfo->cport_mutex);
10752 
10753 	return (SATA_SUCCESS);
10754 }
10755 
10756 /*
10757  * Re-probe a port multiplier port, check for a device and attach info
10758  * structures when necessary. Identify Device data is fetched, if possible.
10759  * Assumption: sata address is already validated as port multiplier port.
10760  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10761  * the presence of a device and its type.
10762  *
10763  * flag arg specifies that the function should try multiple times to identify
10764  * device type and to initialize it, or it should return immediately on failure.
10765  * SATA_DEV_IDENTIFY_RETRY - retry
10766  * SATA_DEV_IDENTIFY_NORETRY - no retry
10767  *
10768  * SATA_FAILURE is returned if one of the operations failed.
10769  *
10770  * This function cannot be called in interrupt context - it may sleep.
10771  *
10772  * NOTE: Should be only called by sata_probe_port() in case target port is a
10773  *       port multiplier port.
10774  * NOTE: No Mutex should be hold.
10775  */
10776 static int
10777 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10778     int flag)
10779 {
10780 	sata_cport_info_t *cportinfo = NULL;
10781 	sata_pmport_info_t *pmportinfo = NULL;
10782 	sata_drive_info_t *sdinfo, *osdinfo;
10783 	sata_device_t sdevice;
10784 	boolean_t init_device = B_FALSE;
10785 	int prev_device_type = SATA_DTYPE_NONE;
10786 	int prev_device_settings = 0;
10787 	int prev_device_state = 0;
10788 	clock_t start_time;
10789 	uint8_t cport = sata_device->satadev_addr.cport;
10790 	uint8_t pmport = sata_device->satadev_addr.pmport;
10791 	int rval;
10792 
10793 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10794 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
10795 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10796 
10797 	if (osdinfo != NULL) {
10798 		/*
10799 		 * We are re-probing port with a previously attached device.
10800 		 * Save previous device type and settings.
10801 		 */
10802 		prev_device_type = pmportinfo->pmport_dev_type;
10803 		prev_device_settings = osdinfo->satadrv_settings;
10804 		prev_device_state = osdinfo->satadrv_state;
10805 	}
10806 
10807 	start_time = ddi_get_lbolt();
10808 
10809 	/* check parent status */
10810 	mutex_enter(&cportinfo->cport_mutex);
10811 	if ((cportinfo->cport_state &
10812 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10813 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10814 	    SATA_PORT_DEVLINK_UP) {
10815 		mutex_exit(&cportinfo->cport_mutex);
10816 		return (SATA_FAILURE);
10817 	}
10818 	mutex_exit(&cportinfo->cport_mutex);
10819 
10820 retry_probe_pmport:
10821 
10822 	/* probe port */
10823 	mutex_enter(&pmportinfo->pmport_mutex);
10824 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10825 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
10826 	mutex_exit(&pmportinfo->pmport_mutex);
10827 
10828 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10829 	    (SATA_DIP(sata_hba_inst), sata_device);
10830 
10831 	/* might need retry because we cannot touch registers. */
10832 	if (rval == SATA_FAILURE) {
10833 		mutex_enter(&pmportinfo->pmport_mutex);
10834 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
10835 		mutex_exit(&pmportinfo->pmport_mutex);
10836 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10837 		    "SATA port %d:%d probing failed",
10838 		    cport, pmport));
10839 		return (SATA_FAILURE);
10840 	} else if (rval == SATA_RETRY) {
10841 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10842 		    "SATA port %d:%d probing failed, retrying...",
10843 		    cport, pmport));
10844 		clock_t cur_time = ddi_get_lbolt();
10845 		/*
10846 		 * A device was not successfully identified or initialized.
10847 		 * Track retry time for device identification.
10848 		 */
10849 		if ((cur_time - start_time) <
10850 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10851 			/* sleep for a while */
10852 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10853 			goto retry_probe_pmport;
10854 		} else {
10855 			mutex_enter(&pmportinfo->pmport_mutex);
10856 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
10857 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
10858 				    satadrv_state = SATA_DSTATE_FAILED;
10859 			mutex_exit(&pmportinfo->pmport_mutex);
10860 			return (SATA_SUCCESS);
10861 		}
10862 	}
10863 
10864 	/*
10865 	 * Sanity check - Controller port is active? Is the link active?
10866 	 * Is it still a port multiplier?
10867 	 */
10868 	if ((cportinfo->cport_state &
10869 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10870 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10871 	    SATA_PORT_DEVLINK_UP ||
10872 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
10873 		/*
10874 		 * Port in non-usable state or no link active/no
10875 		 * device. Free info structure.
10876 		 */
10877 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10878 
10879 		sdevice.satadev_addr.cport = cport;
10880 		sdevice.satadev_addr.pmport = pmport;
10881 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
10882 		mutex_exit(&cportinfo->cport_mutex);
10883 
10884 		sata_free_pmult(sata_hba_inst, &sdevice);
10885 		return (SATA_FAILURE);
10886 	}
10887 
10888 	/* SATA_SUCCESS NOW */
10889 	/*
10890 	 * update sata port state and set device type
10891 	 */
10892 	mutex_enter(&pmportinfo->pmport_mutex);
10893 	sata_update_pmport_info(sata_hba_inst, sata_device);
10894 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
10895 
10896 	/*
10897 	 * Sanity check - Port is active? Is the link active?
10898 	 * Is there any device attached?
10899 	 */
10900 	if ((pmportinfo->pmport_state &
10901 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10902 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10903 	    SATA_PORT_DEVLINK_UP) {
10904 		/*
10905 		 * Port in non-usable state or no link active/no device.
10906 		 * Free info structure if necessary (direct attached drive
10907 		 * only, for now!
10908 		 */
10909 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10910 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10911 		/* Add here differentiation for device attached or not */
10912 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10913 		mutex_exit(&pmportinfo->pmport_mutex);
10914 		if (sdinfo != NULL)
10915 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10916 		return (SATA_SUCCESS);
10917 	}
10918 
10919 	pmportinfo->pmport_state |= SATA_STATE_READY;
10920 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
10921 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10922 
10923 	/*
10924 	 * If we are re-probing the port, there may be
10925 	 * sata_drive_info structure attached
10926 	 * (or sata_pm_info, if PMult is supported).
10927 	 */
10928 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10929 		/*
10930 		 * There is no device, so remove device info structure,
10931 		 * if necessary.
10932 		 */
10933 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10934 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10935 		if (sdinfo != NULL) {
10936 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10937 			sata_log(sata_hba_inst, CE_WARN,
10938 			    "SATA device detached from port %d:%d",
10939 			    cport, pmport);
10940 		}
10941 		mutex_exit(&pmportinfo->pmport_mutex);
10942 		return (SATA_SUCCESS);
10943 	}
10944 
10945 	/* this should not be a pmult */
10946 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
10947 	if (sdinfo == NULL) {
10948 		/*
10949 		 * There is some device attached, but there is
10950 		 * no sata_drive_info structure - allocate one
10951 		 */
10952 		mutex_exit(&pmportinfo->pmport_mutex);
10953 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
10954 		    KM_SLEEP);
10955 		mutex_enter(&pmportinfo->pmport_mutex);
10956 		/*
10957 		 * Recheck, that the port state did not change when we
10958 		 * released mutex.
10959 		 */
10960 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
10961 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
10962 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
10963 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
10964 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10965 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10966 		} else {
10967 			/*
10968 			 * Port is not in ready state, we
10969 			 * cannot attach a device.
10970 			 */
10971 			mutex_exit(&pmportinfo->pmport_mutex);
10972 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10973 			return (SATA_SUCCESS);
10974 		}
10975 		/*
10976 		 * Since we are adding device, presumably new one,
10977 		 * indicate that it  should be initalized,
10978 		 * as well as some internal framework states).
10979 		 */
10980 		init_device = B_TRUE;
10981 	}
10982 
10983 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10984 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10985 
10986 	mutex_exit(&pmportinfo->pmport_mutex);
10987 	/*
10988 	 * Figure out what kind of device we are really
10989 	 * dealing with.
10990 	 */
10991 	rval = sata_probe_device(sata_hba_inst, sata_device);
10992 
10993 	mutex_enter(&pmportinfo->pmport_mutex);
10994 	if (rval == SATA_SUCCESS) {
10995 		/*
10996 		 * If we are dealing with the same type of a device as before,
10997 		 * restore its settings flags.
10998 		 */
10999 		if (osdinfo != NULL &&
11000 		    sata_device->satadev_type == prev_device_type)
11001 			sdinfo->satadrv_settings = prev_device_settings;
11002 
11003 		mutex_exit(&pmportinfo->pmport_mutex);
11004 		/* Set initial device features, if necessary */
11005 		if (init_device == B_TRUE) {
11006 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
11007 		}
11008 		if (rval == SATA_SUCCESS)
11009 			return (rval);
11010 	} else {
11011 		/*
11012 		 * If there was some device info before we probe the device,
11013 		 * restore previous device setting, so we can retry from scratch
11014 		 * later. Providing, of course, that device has not disappeared
11015 		 * during probing process.
11016 		 */
11017 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11018 			if (osdinfo != NULL) {
11019 				pmportinfo->pmport_dev_type = prev_device_type;
11020 				sdinfo->satadrv_type = prev_device_type;
11021 				sdinfo->satadrv_state = prev_device_state;
11022 			}
11023 		} else {
11024 			/* device is gone */
11025 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11026 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11027 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11028 			mutex_exit(&pmportinfo->pmport_mutex);
11029 			return (SATA_SUCCESS);
11030 		}
11031 		mutex_exit(&pmportinfo->pmport_mutex);
11032 	}
11033 
11034 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11035 		clock_t cur_time = ddi_get_lbolt();
11036 		/*
11037 		 * A device was not successfully identified or initialized.
11038 		 * Track retry time for device identification.
11039 		 */
11040 		if ((cur_time - start_time) <
11041 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11042 			/* sleep for a while */
11043 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11044 			goto retry_probe_pmport;
11045 		} else {
11046 			mutex_enter(&pmportinfo->pmport_mutex);
11047 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11048 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11049 				    satadrv_state = SATA_DSTATE_FAILED;
11050 			mutex_exit(&pmportinfo->pmport_mutex);
11051 		}
11052 	}
11053 	return (SATA_SUCCESS);
11054 }
11055 
11056 /*
11057  * Allocated related structure for a port multiplier and its device ports
11058  *
11059  * Port multiplier should be ready and probed, and related information like
11060  * the number of the device ports should be store in sata_device_t.
11061  *
11062  * NOTE: No Mutex should be hold.
11063  */
11064 static int
11065 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11066 {
11067 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11068 	sata_cport_info_t *cportinfo = NULL;
11069 	sata_pmult_info_t *pmultinfo = NULL;
11070 	sata_pmport_info_t *pmportinfo = NULL;
11071 	sata_device_t sd;
11072 	dev_t minor_number;
11073 	char name[16];
11074 	uint8_t cport = sata_device->satadev_addr.cport;
11075 	int rval;
11076 	int npmport;
11077 
11078 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11079 
11080 	/* This function might be called while a port-mult is hot-plugged. */
11081 	mutex_enter(&cportinfo->cport_mutex);
11082 
11083 	/* dev_type's not updated when get called from sata_reprobe_port() */
11084 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11085 		/* Create a pmult_info structure */
11086 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11087 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11088 	}
11089 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11090 
11091 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11092 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11093 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11094 
11095 	/*
11096 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11097 	 * The HBA driver should initialize and register the port multiplier,
11098 	 * sata_register_pmult() will fill following fields,
11099 	 *   + sata_pmult_info.pmult_gscr
11100 	 *   + sata_pmult_info.pmult_num_dev_ports
11101 	 */
11102 	sd.satadev_addr = sata_device->satadev_addr;
11103 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11104 	mutex_exit(&cportinfo->cport_mutex);
11105 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11106 	    (SATA_DIP(sata_hba_inst), &sd);
11107 	mutex_enter(&cportinfo->cport_mutex);
11108 
11109 	if (rval != SATA_SUCCESS ||
11110 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11111 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11112 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11113 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11114 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11115 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11116 		mutex_exit(&cportinfo->cport_mutex);
11117 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11118 		    "sata_alloc_pmult: failed to initialize pmult "
11119 		    "at port %d.", cport)
11120 		return (SATA_FAILURE);
11121 	}
11122 
11123 	/* Initialize pmport_info structure */
11124 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11125 	    npmport++) {
11126 
11127 		/* if everything is allocated, skip */
11128 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11129 			continue;
11130 
11131 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11132 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11133 		mutex_exit(&cportinfo->cport_mutex);
11134 
11135 		mutex_enter(&pmportinfo->pmport_mutex);
11136 		pmportinfo->pmport_addr.cport = cport;
11137 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11138 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11139 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11140 		mutex_exit(&pmportinfo->pmport_mutex);
11141 
11142 		mutex_enter(&cportinfo->cport_mutex);
11143 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11144 
11145 		/* Create an attachment point */
11146 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
11147 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
11148 		(void) sprintf(name, "%d.%d", cport, npmport);
11149 
11150 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
11151 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
11152 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
11153 			    "cannot create SATA attachment point for "
11154 			    "port %d:%d", cport, npmport);
11155 		}
11156 	}
11157 
11158 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
11159 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
11160 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
11161 
11162 	mutex_exit(&cportinfo->cport_mutex);
11163 	return (SATA_SUCCESS);
11164 }
11165 
11166 /*
11167  * Free data structures when a port multiplier is removed.
11168  *
11169  * NOTE: No Mutex should be hold.
11170  */
11171 static void
11172 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11173 {
11174 	sata_cport_info_t *cportinfo;
11175 	sata_pmult_info_t *pmultinfo;
11176 	sata_pmport_info_t *pmportinfo;
11177 	sata_device_t pmport_device;
11178 	sata_drive_info_t *sdinfo;
11179 	dev_info_t *tdip;
11180 	char name[16];
11181 	uint8_t cport = sata_device->satadev_addr.cport;
11182 	int npmport;
11183 
11184 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11185 
11186 	/* This function might be called while port-mult is hot plugged. */
11187 	mutex_enter(&cportinfo->cport_mutex);
11188 
11189 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11190 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11191 	ASSERT(pmultinfo != NULL);
11192 
11193 	/* Free pmport_info structure */
11194 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11195 	    npmport++) {
11196 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
11197 		if (pmportinfo == NULL)
11198 			continue;
11199 		mutex_exit(&cportinfo->cport_mutex);
11200 
11201 		mutex_enter(&pmportinfo->pmport_mutex);
11202 		sdinfo = pmportinfo->pmport_sata_drive;
11203 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11204 		mutex_exit(&pmportinfo->pmport_mutex);
11205 
11206 		/* Remove attachment point. */
11207 		name[0] = '\0';
11208 		(void) sprintf(name, "%d.%d", cport, npmport);
11209 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
11210 		sata_log(sata_hba_inst, CE_NOTE,
11211 		    "Remove attachment point of port %d:%d",
11212 		    cport, npmport);
11213 
11214 		/*
11215 		 * Rumove target node
11216 		 */
11217 		bzero(&pmport_device, sizeof (sata_device_t));
11218 		pmport_device.satadev_rev = SATA_DEVICE_REV;
11219 		pmport_device.satadev_addr.cport = cport;
11220 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
11221 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
11222 
11223 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11224 		    &(pmport_device.satadev_addr));
11225 		if (tdip != NULL && ndi_devi_offline(tdip,
11226 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11227 			/*
11228 			 * Problem :
11229 			 * The target node remained attached.
11230 			 * This happens when the device file was open
11231 			 * or a node was waiting for resources.
11232 			 * Cannot do anything about it.
11233 			 */
11234 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11235 			    "sata_free_pmult: could not unconfigure device "
11236 			    "before disconnecting the SATA port %d:%d",
11237 			    cport, npmport));
11238 
11239 			/*
11240 			 * Set DEVICE REMOVED state in the target
11241 			 * node. It will prevent access to the device
11242 			 * even when a new device is attached, until
11243 			 * the old target node is released, removed and
11244 			 * recreated for a new  device.
11245 			 */
11246 			sata_set_device_removed(tdip);
11247 
11248 			/*
11249 			 * Instruct event daemon to try the target
11250 			 * node cleanup later.
11251 			 */
11252 			sata_set_target_node_cleanup(
11253 			    sata_hba_inst, &(pmport_device.satadev_addr));
11254 
11255 		}
11256 		mutex_enter(&cportinfo->cport_mutex);
11257 
11258 		/*
11259 		 * Add here differentiation for device attached or not
11260 		 */
11261 		if (sdinfo != NULL)  {
11262 			sata_log(sata_hba_inst, CE_WARN,
11263 			    "SATA device detached from port %d:%d",
11264 			    cport, npmport);
11265 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11266 		}
11267 
11268 		mutex_destroy(&pmportinfo->pmport_mutex);
11269 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
11270 	}
11271 
11272 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11273 
11274 	cportinfo->cport_devp.cport_sata_pmult = NULL;
11275 
11276 	sata_log(sata_hba_inst, CE_WARN,
11277 	    "SATA port multiplier detached at port %d", cport);
11278 
11279 	mutex_exit(&cportinfo->cport_mutex);
11280 }
11281 
11282 /*
11283  * Initialize device
11284  * Specified device is initialized to a default state.
11285  *
11286  * Returns SATA_SUCCESS if all device features are set successfully,
11287  * SATA_RETRY if device is accessible but device features were not set
11288  * successfully, and SATA_FAILURE otherwise.
11289  */
11290 static int
11291 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
11292     sata_drive_info_t *sdinfo)
11293 {
11294 	int rval;
11295 
11296 	sata_save_drive_settings(sdinfo);
11297 
11298 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
11299 
11300 	sata_init_write_cache_mode(sdinfo);
11301 
11302 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
11303 
11304 	/* Determine current data transfer mode */
11305 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
11306 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11307 	} else if ((sdinfo->satadrv_id.ai_validinfo &
11308 	    SATA_VALIDINFO_88) != 0 &&
11309 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
11310 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11311 	} else if ((sdinfo->satadrv_id.ai_dworddma &
11312 	    SATA_MDMA_SEL_MASK) != 0) {
11313 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11314 	} else
11315 		/* DMA supported, not no DMA transfer mode is selected !? */
11316 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11317 
11318 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
11319 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
11320 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
11321 	else
11322 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
11323 
11324 	return (rval);
11325 }
11326 
11327 
11328 /*
11329  * Initialize write cache mode.
11330  *
11331  * The default write cache setting for SATA HDD is provided by sata_write_cache
11332  * static variable. ATAPI CD/DVDs devices have write cache default is
11333  * determined by sata_atapicdvd_write_cache static variable.
11334  * ATAPI tape devices have write cache default is determined by
11335  * sata_atapitape_write_cache static variable.
11336  * ATAPI disk devices have write cache default is determined by
11337  * sata_atapidisk_write_cache static variable.
11338  * 1 - enable
11339  * 0 - disable
11340  * any other value - current drive setting
11341  *
11342  * Although there is not reason to disable write cache on CD/DVD devices,
11343  * tape devices and ATAPI disk devices, the default setting control is provided
11344  * for the maximun flexibility.
11345  *
11346  * In the future, it may be overridden by the
11347  * disk-write-cache-enable property setting, if it is defined.
11348  * Returns SATA_SUCCESS if all device features are set successfully,
11349  * SATA_FAILURE otherwise.
11350  */
11351 static void
11352 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
11353 {
11354 	switch (sdinfo->satadrv_type) {
11355 	case SATA_DTYPE_ATADISK:
11356 		if (sata_write_cache == 1)
11357 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11358 		else if (sata_write_cache == 0)
11359 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11360 		/*
11361 		 * When sata_write_cache value is not 0 or 1,
11362 		 * a current setting of the drive's write cache is used.
11363 		 */
11364 		break;
11365 	case SATA_DTYPE_ATAPICD:
11366 		if (sata_atapicdvd_write_cache == 1)
11367 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11368 		else if (sata_atapicdvd_write_cache == 0)
11369 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11370 		/*
11371 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
11372 		 * a current setting of the drive's write cache is used.
11373 		 */
11374 		break;
11375 	case SATA_DTYPE_ATAPITAPE:
11376 		if (sata_atapitape_write_cache == 1)
11377 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11378 		else if (sata_atapitape_write_cache == 0)
11379 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11380 		/*
11381 		 * When sata_atapitape_write_cache value is not 0 or 1,
11382 		 * a current setting of the drive's write cache is used.
11383 		 */
11384 		break;
11385 	case SATA_DTYPE_ATAPIDISK:
11386 		if (sata_atapidisk_write_cache == 1)
11387 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11388 		else if (sata_atapidisk_write_cache == 0)
11389 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11390 		/*
11391 		 * When sata_atapidisk_write_cache value is not 0 or 1,
11392 		 * a current setting of the drive's write cache is used.
11393 		 */
11394 		break;
11395 	}
11396 }
11397 
11398 
11399 /*
11400  * Validate sata address.
11401  * Specified cport, pmport and qualifier has to match
11402  * passed sata_scsi configuration info.
11403  * The presence of an attached device is not verified.
11404  *
11405  * Returns 0 when address is valid, -1 otherwise.
11406  */
11407 static int
11408 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
11409 	int pmport, int qual)
11410 {
11411 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
11412 		goto invalid_address;
11413 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11414 		goto invalid_address;
11415 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
11416 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
11417 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
11418 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
11419 		goto invalid_address;
11420 
11421 	return (0);
11422 
11423 invalid_address:
11424 	return (-1);
11425 
11426 }
11427 
11428 /*
11429  * Validate scsi address
11430  * SCSI target address is translated into SATA cport/pmport and compared
11431  * with a controller port/device configuration. LUN has to be 0.
11432  * Returns 0 if a scsi target refers to an attached device,
11433  * returns 1 if address is valid but no valid device is attached,
11434  * returns 2 if address is valid but device type is unknown (not valid device),
11435  * returns -1 if bad address or device is of an unsupported type.
11436  * Upon return sata_device argument is set.
11437  *
11438  * Port multiplier is supported now.
11439  */
11440 static int
11441 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
11442 	struct scsi_address *ap, sata_device_t *sata_device)
11443 {
11444 	int cport, pmport, qual, rval;
11445 
11446 	rval = -1;	/* Invalid address */
11447 	if (ap->a_lun != 0)
11448 		goto out;
11449 
11450 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
11451 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
11452 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
11453 
11454 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
11455 		goto out;
11456 
11457 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
11458 	    0) {
11459 
11460 		sata_cport_info_t *cportinfo;
11461 		sata_pmult_info_t *pmultinfo;
11462 		sata_drive_info_t *sdinfo = NULL;
11463 
11464 		sata_device->satadev_addr.qual = qual;
11465 		sata_device->satadev_addr.cport = cport;
11466 		sata_device->satadev_addr.pmport = pmport;
11467 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
11468 
11469 		rval = 1;	/* Valid sata address */
11470 
11471 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11472 		if (qual == SATA_ADDR_DCPORT) {
11473 			if (cportinfo == NULL ||
11474 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11475 				goto out;
11476 
11477 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11478 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
11479 			    sdinfo != NULL) {
11480 				rval = 2;
11481 				goto out;
11482 			}
11483 
11484 			if ((cportinfo->cport_dev_type &
11485 			    SATA_VALID_DEV_TYPE) == 0) {
11486 				rval = -1;
11487 				goto out;
11488 			}
11489 
11490 		} else if (qual == SATA_ADDR_DPMPORT) {
11491 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11492 			if (pmultinfo == NULL) {
11493 				rval = -1;
11494 				goto out;
11495 			}
11496 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
11497 			    NULL ||
11498 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11499 			    pmport) == SATA_DTYPE_NONE)
11500 				goto out;
11501 
11502 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
11503 			    pmport);
11504 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11505 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
11506 				rval = 2;
11507 				goto out;
11508 			}
11509 
11510 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11511 			    pmport) && SATA_VALID_DEV_TYPE) == 0) {
11512 				rval = -1;
11513 				goto out;
11514 			}
11515 
11516 		} else {
11517 			rval = -1;
11518 			goto out;
11519 		}
11520 		if ((sdinfo == NULL) ||
11521 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
11522 			goto out;
11523 
11524 		sata_device->satadev_type = sdinfo->satadrv_type;
11525 
11526 		return (0);
11527 	}
11528 out:
11529 	if (rval > 0) {
11530 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
11531 		    "sata_validate_scsi_address: no valid target %x lun %x",
11532 		    ap->a_target, ap->a_lun);
11533 	}
11534 	return (rval);
11535 }
11536 
11537 /*
11538  * Find dip corresponding to passed device number
11539  *
11540  * Returns NULL if invalid device number is passed or device cannot be found,
11541  * Returns dip is device is found.
11542  */
11543 static dev_info_t *
11544 sata_devt_to_devinfo(dev_t dev)
11545 {
11546 	dev_info_t *dip;
11547 #ifndef __lock_lint
11548 	struct devnames *dnp;
11549 	major_t major = getmajor(dev);
11550 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
11551 
11552 	if (major >= devcnt)
11553 		return (NULL);
11554 
11555 	dnp = &devnamesp[major];
11556 	LOCK_DEV_OPS(&(dnp->dn_lock));
11557 	dip = dnp->dn_head;
11558 	while (dip && (ddi_get_instance(dip) != instance)) {
11559 		dip = ddi_get_next(dip);
11560 	}
11561 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
11562 #endif
11563 
11564 	return (dip);
11565 }
11566 
11567 
11568 /*
11569  * Probe device.
11570  * This function issues Identify Device command and initializes local
11571  * sata_drive_info structure if the device can be identified.
11572  * The device type is determined by examining Identify Device
11573  * command response.
11574  * If the sata_hba_inst has linked drive info structure for this
11575  * device address, the Identify Device data is stored into sata_drive_info
11576  * structure linked to the port info structure.
11577  *
11578  * sata_device has to refer to the valid sata port(s) for HBA described
11579  * by sata_hba_inst structure.
11580  *
11581  * Returns:
11582  *	SATA_SUCCESS if device type was successfully probed and port-linked
11583  *		drive info structure was updated;
11584  * 	SATA_FAILURE if there is no device, or device was not probed
11585  *		successully;
11586  *	SATA_RETRY if device probe can be retried later.
11587  * If a device cannot be identified, sata_device's dev_state and dev_type
11588  * fields are set to unknown.
11589  * There are no retries in this function. Any retries should be managed by
11590  * the caller.
11591  */
11592 
11593 
11594 static int
11595 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11596 {
11597 	sata_pmport_info_t *pmportinfo;
11598 	sata_drive_info_t *sdinfo;
11599 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
11600 	int rval;
11601 
11602 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
11603 	    sata_device->satadev_addr.cport) &
11604 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
11605 
11606 	sata_device->satadev_type = SATA_DTYPE_NONE;
11607 
11608 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11609 	    sata_device->satadev_addr.cport)));
11610 
11611 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
11612 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
11613 		    sata_device->satadev_addr.cport,
11614 		    sata_device->satadev_addr.pmport);
11615 		ASSERT(pmportinfo != NULL);
11616 	}
11617 
11618 	/* Get pointer to port-linked sata device info structure */
11619 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11620 	if (sdinfo != NULL) {
11621 		sdinfo->satadrv_state &=
11622 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
11623 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
11624 	} else {
11625 		/* No device to probe */
11626 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11627 		    sata_device->satadev_addr.cport)));
11628 		sata_device->satadev_type = SATA_DTYPE_NONE;
11629 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
11630 		return (SATA_FAILURE);
11631 	}
11632 	/*
11633 	 * Need to issue both types of identify device command and
11634 	 * determine device type by examining retreived data/status.
11635 	 * First, ATA Identify Device.
11636 	 */
11637 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
11638 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
11639 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11640 	    sata_device->satadev_addr.cport)));
11641 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
11642 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11643 	if (rval == SATA_RETRY) {
11644 		/* We may try to check for ATAPI device */
11645 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
11646 			/*
11647 			 * HBA supports ATAPI - try to issue Identify Packet
11648 			 * Device command.
11649 			 */
11650 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
11651 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11652 		}
11653 	}
11654 	if (rval == SATA_SUCCESS) {
11655 		/*
11656 		 * Got something responding positively to ATA Identify Device
11657 		 * or to Identify Packet Device cmd.
11658 		 * Save last used device type.
11659 		 */
11660 		sata_device->satadev_type = new_sdinfo.satadrv_type;
11661 
11662 		/* save device info, if possible */
11663 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11664 		    sata_device->satadev_addr.cport)));
11665 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11666 		if (sdinfo == NULL) {
11667 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11668 			    sata_device->satadev_addr.cport)));
11669 			return (SATA_FAILURE);
11670 		}
11671 		/*
11672 		 * Copy drive info into the port-linked drive info structure.
11673 		 */
11674 		*sdinfo = new_sdinfo;
11675 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11676 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11677 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11678 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11679 			    sata_device->satadev_addr.cport) =
11680 			    sdinfo->satadrv_type;
11681 		else { /* SATA_ADDR_DPMPORT */
11682 			mutex_enter(&pmportinfo->pmport_mutex);
11683 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11684 			    sata_device->satadev_addr.cport,
11685 			    sata_device->satadev_addr.pmport) =
11686 			    sdinfo->satadrv_type;
11687 			mutex_exit(&pmportinfo->pmport_mutex);
11688 		}
11689 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11690 		    sata_device->satadev_addr.cport)));
11691 		return (SATA_SUCCESS);
11692 	}
11693 
11694 	/*
11695 	 * It may be SATA_RETRY or SATA_FAILURE return.
11696 	 * Looks like we cannot determine the device type at this time.
11697 	 */
11698 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11699 	    sata_device->satadev_addr.cport)));
11700 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11701 	if (sdinfo != NULL) {
11702 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
11703 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11704 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11705 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11706 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11707 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11708 			    sata_device->satadev_addr.cport) =
11709 			    SATA_DTYPE_UNKNOWN;
11710 		else {
11711 			/* SATA_ADDR_DPMPORT */
11712 			mutex_enter(&pmportinfo->pmport_mutex);
11713 			if ((SATA_PMULT_INFO(sata_hba_inst,
11714 			    sata_device->satadev_addr.cport) != NULL) &&
11715 			    (SATA_PMPORT_INFO(sata_hba_inst,
11716 			    sata_device->satadev_addr.cport,
11717 			    sata_device->satadev_addr.pmport) != NULL))
11718 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11719 				    sata_device->satadev_addr.cport,
11720 				    sata_device->satadev_addr.pmport) =
11721 				    SATA_DTYPE_UNKNOWN;
11722 			mutex_exit(&pmportinfo->pmport_mutex);
11723 		}
11724 	}
11725 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11726 	    sata_device->satadev_addr.cport)));
11727 	return (rval);
11728 }
11729 
11730 
11731 /*
11732  * Get pointer to sata_drive_info structure.
11733  *
11734  * The sata_device has to contain address (cport, pmport and qualifier) for
11735  * specified sata_scsi structure.
11736  *
11737  * Returns NULL if device address is not valid for this HBA configuration.
11738  * Otherwise, returns a pointer to sata_drive_info structure.
11739  *
11740  * This function should be called with a port mutex held.
11741  */
11742 static sata_drive_info_t *
11743 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
11744     sata_device_t *sata_device)
11745 {
11746 	uint8_t cport = sata_device->satadev_addr.cport;
11747 	uint8_t pmport = sata_device->satadev_addr.pmport;
11748 	uint8_t qual = sata_device->satadev_addr.qual;
11749 
11750 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11751 		return (NULL);
11752 
11753 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
11754 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
11755 		/* Port not probed yet */
11756 		return (NULL);
11757 
11758 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
11759 		return (NULL);
11760 
11761 	if (qual == SATA_ADDR_DCPORT) {
11762 		/* Request for a device on a controller port */
11763 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
11764 		    SATA_DTYPE_PMULT)
11765 			/* Port multiplier attached */
11766 			return (NULL);
11767 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
11768 	}
11769 	if (qual == SATA_ADDR_DPMPORT) {
11770 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
11771 		    SATA_DTYPE_PMULT)
11772 			return (NULL);
11773 
11774 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
11775 			return (NULL);
11776 
11777 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
11778 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
11779 			/* Port multiplier port not probed yet */
11780 			return (NULL);
11781 
11782 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
11783 	}
11784 
11785 	/* we should not get here */
11786 	return (NULL);
11787 }
11788 
11789 
11790 /*
11791  * sata_identify_device.
11792  * Send Identify Device command to SATA HBA driver.
11793  * If command executes successfully, update sata_drive_info structure pointed
11794  * to by sdinfo argument, including Identify Device data.
11795  * If command fails, invalidate data in sata_drive_info.
11796  *
11797  * Cannot be called from interrupt level.
11798  *
11799  * Returns:
11800  * SATA_SUCCESS if the device was identified as a supported device,
11801  * SATA_RETRY if the device was not identified but could be retried,
11802  * SATA_FAILURE if the device was not identified and identify attempt
11803  *	should not be retried.
11804  */
11805 static int
11806 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
11807     sata_drive_info_t *sdinfo)
11808 {
11809 	uint16_t cfg_word;
11810 	int rval;
11811 
11812 	/* fetch device identify data */
11813 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
11814 	    sdinfo)) != SATA_SUCCESS)
11815 		goto fail_unknown;
11816 
11817 	cfg_word = sdinfo->satadrv_id.ai_config;
11818 
11819 	/* Set the correct device type */
11820 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
11821 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11822 	} else if (cfg_word == SATA_CFA_TYPE) {
11823 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
11824 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11825 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
11826 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
11827 		case SATA_ATAPI_CDROM_DEV:
11828 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
11829 			break;
11830 		case SATA_ATAPI_SQACC_DEV:
11831 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
11832 			break;
11833 		case SATA_ATAPI_DIRACC_DEV:
11834 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
11835 			break;
11836 		default:
11837 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11838 		}
11839 	} else {
11840 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11841 	}
11842 
11843 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11844 		if (sdinfo->satadrv_capacity == 0) {
11845 			/* Non-LBA disk. Too bad... */
11846 			sata_log(sata_hba_inst, CE_WARN,
11847 			    "SATA disk device at port %d does not support LBA",
11848 			    sdinfo->satadrv_addr.cport);
11849 			rval = SATA_FAILURE;
11850 			goto fail_unknown;
11851 		}
11852 	}
11853 #if 0
11854 	/* Left for historical reason */
11855 	/*
11856 	 * Some initial version of SATA spec indicated that at least
11857 	 * UDMA mode 4 has to be supported. It is not metioned in
11858 	 * SerialATA 2.6, so this restriction is removed.
11859 	 */
11860 	/* Check for Ultra DMA modes 6 through 0 being supported */
11861 	for (i = 6; i >= 0; --i) {
11862 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
11863 			break;
11864 	}
11865 
11866 	/*
11867 	 * At least UDMA 4 mode has to be supported. If mode 4 or
11868 	 * higher are not supported by the device, fail this
11869 	 * device.
11870 	 */
11871 	if (i < 4) {
11872 		/* No required Ultra DMA mode supported */
11873 		sata_log(sata_hba_inst, CE_WARN,
11874 		    "SATA disk device at port %d does not support UDMA "
11875 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
11876 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11877 		    "mode 4 or higher required, %d supported", i));
11878 		rval = SATA_FAILURE;
11879 		goto fail_unknown;
11880 	}
11881 #endif
11882 
11883 	/*
11884 	 * For Disk devices, if it doesn't support UDMA mode, we would
11885 	 * like to return failure directly.
11886 	 */
11887 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
11888 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
11889 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
11890 		sata_log(sata_hba_inst, CE_WARN,
11891 		    "SATA disk device at port %d does not support UDMA",
11892 		    sdinfo->satadrv_addr.cport);
11893 		rval = SATA_FAILURE;
11894 		goto fail_unknown;
11895 	}
11896 
11897 	return (SATA_SUCCESS);
11898 
11899 fail_unknown:
11900 	/* Invalidate sata_drive_info ? */
11901 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11902 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11903 	return (rval);
11904 }
11905 
11906 /*
11907  * Log/display device information
11908  */
11909 static void
11910 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
11911     sata_drive_info_t *sdinfo)
11912 {
11913 	int valid_version;
11914 	char msg_buf[MAXPATHLEN];
11915 	int i;
11916 
11917 	/* Show HBA path */
11918 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
11919 
11920 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
11921 
11922 	switch (sdinfo->satadrv_type) {
11923 	case SATA_DTYPE_ATADISK:
11924 		(void) sprintf(msg_buf, "SATA disk device at");
11925 		break;
11926 
11927 	case SATA_DTYPE_ATAPICD:
11928 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
11929 		break;
11930 
11931 	case SATA_DTYPE_ATAPITAPE:
11932 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
11933 		break;
11934 
11935 	case SATA_DTYPE_ATAPIDISK:
11936 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
11937 		break;
11938 
11939 	case SATA_DTYPE_UNKNOWN:
11940 		(void) sprintf(msg_buf,
11941 		    "Unsupported SATA device type (cfg 0x%x) at ",
11942 		    sdinfo->satadrv_id.ai_config);
11943 		break;
11944 	}
11945 
11946 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
11947 		cmn_err(CE_CONT, "?\t%s port %d\n",
11948 		    msg_buf, sdinfo->satadrv_addr.cport);
11949 	else
11950 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
11951 		    msg_buf, sdinfo->satadrv_addr.cport,
11952 		    sdinfo->satadrv_addr.pmport);
11953 
11954 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
11955 	    sizeof (sdinfo->satadrv_id.ai_model));
11956 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
11957 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
11958 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
11959 
11960 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
11961 	    sizeof (sdinfo->satadrv_id.ai_fw));
11962 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
11963 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
11964 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
11965 
11966 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
11967 	    sizeof (sdinfo->satadrv_id.ai_drvser));
11968 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
11969 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
11970 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11971 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
11972 	} else {
11973 		/*
11974 		 * Some drives do not implement serial number and may
11975 		 * violate the spec by providing spaces rather than zeros
11976 		 * in serial number field. Scan the buffer to detect it.
11977 		 */
11978 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
11979 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
11980 				break;
11981 		}
11982 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
11983 			cmn_err(CE_CONT, "?\tserial number - none\n");
11984 		} else {
11985 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
11986 		}
11987 	}
11988 
11989 #ifdef SATA_DEBUG
11990 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
11991 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
11992 		int i;
11993 		for (i = 14; i >= 2; i--) {
11994 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
11995 				valid_version = i;
11996 				break;
11997 			}
11998 		}
11999 		cmn_err(CE_CONT,
12000 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
12001 		    valid_version,
12002 		    sdinfo->satadrv_id.ai_majorversion,
12003 		    sdinfo->satadrv_id.ai_minorversion);
12004 	}
12005 #endif
12006 	/* Log some info */
12007 	cmn_err(CE_CONT, "?\tsupported features:\n");
12008 	msg_buf[0] = '\0';
12009 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12010 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
12011 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
12012 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
12013 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
12014 	}
12015 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
12016 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
12017 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
12018 		(void) strlcat(msg_buf, ", Native Command Queueing",
12019 		    MAXPATHLEN);
12020 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
12021 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
12022 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
12023 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
12024 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
12025 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
12026 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
12027 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12028 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12029 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12030 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12031 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12032 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12033 	if (sdinfo->satadrv_features_support &
12034 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12035 		msg_buf[0] = '\0';
12036 		(void) snprintf(msg_buf, MAXPATHLEN,
12037 		    "Supported queue depth %d",
12038 		    sdinfo->satadrv_queue_depth);
12039 		if (!(sata_func_enable &
12040 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12041 			(void) strlcat(msg_buf,
12042 			    " - queueing disabled globally", MAXPATHLEN);
12043 		else if (sdinfo->satadrv_queue_depth >
12044 		    sdinfo->satadrv_max_queue_depth) {
12045 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12046 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12047 			    (int)sdinfo->satadrv_max_queue_depth);
12048 		}
12049 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12050 	}
12051 
12052 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12053 #ifdef __i386
12054 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12055 		    sdinfo->satadrv_capacity);
12056 #else
12057 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12058 		    sdinfo->satadrv_capacity);
12059 #endif
12060 		cmn_err(CE_CONT, "?%s", msg_buf);
12061 	}
12062 }
12063 
12064 /*
12065  * Log/display port multiplier information
12066  * No Mutex should be hold.
12067  */
12068 static void
12069 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12070     sata_device_t *sata_device)
12071 {
12072 	_NOTE(ARGUNUSED(sata_hba_inst))
12073 
12074 	int cport = sata_device->satadev_addr.cport;
12075 	sata_pmult_info_t *pmultinfo;
12076 	char msg_buf[MAXPATHLEN];
12077 	uint32_t gscr0, gscr1, gscr2, gscr64;
12078 
12079 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12080 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12081 	if (pmultinfo == NULL) {
12082 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12083 		return;
12084 	}
12085 
12086 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12087 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12088 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12089 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12090 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12091 
12092 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12093 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12094 
12095 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12096 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12097 	cmn_err(CE_CONT, "?%s", msg_buf);
12098 
12099 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12100 	if (gscr1 & (1 << 3))
12101 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12102 	else if (gscr1 & (1 << 2))
12103 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12104 	else if (gscr1 & (1 << 1))
12105 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12106 	else
12107 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12108 	cmn_err(CE_CONT, "?%s", msg_buf);
12109 
12110 	(void) strcpy(msg_buf, "\tSupport ");
12111 	if (gscr64 & (1 << 3))
12112 		(void) strlcat(msg_buf, "Asy-Notif, ",
12113 		    MAXPATHLEN);
12114 	if (gscr64 & (1 << 2))
12115 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12116 	if (gscr64 & (1 << 1))
12117 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12118 	if (gscr64 & (1 << 0))
12119 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12120 	if ((gscr64 & 0xf) == 0)
12121 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12122 	cmn_err(CE_CONT, "?%s", msg_buf);
12123 
12124 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12125 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12126 	cmn_err(CE_CONT, "?%s", msg_buf);
12127 }
12128 
12129 /*
12130  * sata_save_drive_settings extracts current setting of the device and stores
12131  * it for future reference, in case the device setup would need to be restored
12132  * after the device reset.
12133  *
12134  * For all devices read ahead and write cache settings are saved, if the
12135  * device supports these features at all.
12136  * For ATAPI devices the Removable Media Status Notification setting is saved.
12137  */
12138 static void
12139 sata_save_drive_settings(sata_drive_info_t *sdinfo)
12140 {
12141 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
12142 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
12143 
12144 		/* Current setting of Read Ahead (and Read Cache) */
12145 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
12146 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12147 		else
12148 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
12149 
12150 		/* Current setting of Write Cache */
12151 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
12152 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12153 		else
12154 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12155 	}
12156 
12157 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
12158 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
12159 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
12160 		else
12161 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
12162 	}
12163 }
12164 
12165 
12166 /*
12167  * sata_check_capacity function determines a disk capacity
12168  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
12169  *
12170  * NOTE: CHS mode is not supported! If a device does not support LBA,
12171  * this function is not called.
12172  *
12173  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
12174  */
12175 static uint64_t
12176 sata_check_capacity(sata_drive_info_t *sdinfo)
12177 {
12178 	uint64_t capacity = 0;
12179 	int i;
12180 
12181 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
12182 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
12183 		/* Capacity valid only for LBA-addressable disk devices */
12184 		return (0);
12185 
12186 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
12187 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
12188 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
12189 		/* LBA48 mode supported and enabled */
12190 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
12191 		    SATA_DEV_F_LBA28;
12192 		for (i = 3;  i >= 0;  --i) {
12193 			capacity <<= 16;
12194 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
12195 		}
12196 	} else {
12197 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
12198 		capacity <<= 16;
12199 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
12200 		if (capacity >= 0x1000000)
12201 			/* LBA28 mode */
12202 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
12203 	}
12204 	return (capacity);
12205 }
12206 
12207 
12208 /*
12209  * Allocate consistent buffer for DMA transfer
12210  *
12211  * Cannot be called from interrupt level or with mutex held - it may sleep.
12212  *
12213  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
12214  */
12215 static struct buf *
12216 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
12217 {
12218 	struct scsi_address ap;
12219 	struct buf *bp;
12220 	ddi_dma_attr_t	cur_dma_attr;
12221 
12222 	ASSERT(spx->txlt_sata_pkt != NULL);
12223 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
12224 	ap.a_target = SATA_TO_SCSI_TARGET(
12225 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
12226 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
12227 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
12228 	ap.a_lun = 0;
12229 
12230 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
12231 	    B_READ, SLEEP_FUNC, NULL);
12232 
12233 	if (bp != NULL) {
12234 		/* Allocate DMA resources for this buffer */
12235 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
12236 		/*
12237 		 * We use a local version of the dma_attr, to account
12238 		 * for a device addressing limitations.
12239 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
12240 		 * will cause dma attributes to be adjusted to a lowest
12241 		 * acceptable level.
12242 		 */
12243 		sata_adjust_dma_attr(NULL,
12244 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
12245 
12246 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
12247 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
12248 			scsi_free_consistent_buf(bp);
12249 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12250 			bp = NULL;
12251 		}
12252 	}
12253 	return (bp);
12254 }
12255 
12256 /*
12257  * Release local buffer (consistent buffer for DMA transfer) allocated
12258  * via sata_alloc_local_buffer().
12259  */
12260 static void
12261 sata_free_local_buffer(sata_pkt_txlate_t *spx)
12262 {
12263 	ASSERT(spx->txlt_sata_pkt != NULL);
12264 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
12265 
12266 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
12267 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
12268 
12269 	sata_common_free_dma_rsrcs(spx);
12270 
12271 	/* Free buffer */
12272 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
12273 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12274 }
12275 
12276 /*
12277  * Allocate sata_pkt
12278  * Pkt structure version and embedded strcutures version are initialized.
12279  * sata_pkt and sata_pkt_txlate structures are cross-linked.
12280  *
12281  * Since this may be called in interrupt context by sata_scsi_init_pkt,
12282  * callback argument determines if it can sleep or not.
12283  * Hence, it should not be called from interrupt context.
12284  *
12285  * If successful, non-NULL pointer to a sata pkt is returned.
12286  * Upon failure, NULL pointer is returned.
12287  */
12288 static sata_pkt_t *
12289 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
12290 {
12291 	sata_pkt_t *spkt;
12292 	int kmsflag;
12293 
12294 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
12295 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
12296 	if (spkt == NULL) {
12297 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12298 		    "sata_pkt_alloc: failed"));
12299 		return (NULL);
12300 	}
12301 	spkt->satapkt_rev = SATA_PKT_REV;
12302 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
12303 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
12304 	spkt->satapkt_framework_private = spx;
12305 	spx->txlt_sata_pkt = spkt;
12306 	return (spkt);
12307 }
12308 
12309 /*
12310  * Free sata pkt allocated via sata_pkt_alloc()
12311  */
12312 static void
12313 sata_pkt_free(sata_pkt_txlate_t *spx)
12314 {
12315 	ASSERT(spx->txlt_sata_pkt != NULL);
12316 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
12317 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
12318 	spx->txlt_sata_pkt = NULL;
12319 }
12320 
12321 
12322 /*
12323  * Adjust DMA attributes.
12324  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
12325  * from 8 bits to 16 bits, depending on a command being used.
12326  * Limiting max block count arbitrarily to 256 for all read/write
12327  * commands may affects performance, so check both the device and
12328  * controller capability before adjusting dma attributes.
12329  */
12330 void
12331 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
12332     ddi_dma_attr_t *adj_dma_attr)
12333 {
12334 	uint32_t count_max;
12335 
12336 	/* Copy original attributes */
12337 	*adj_dma_attr = *dma_attr;
12338 	/*
12339 	 * Things to consider: device addressing capability,
12340 	 * "excessive" controller DMA capabilities.
12341 	 * If a device is being probed/initialized, there are
12342 	 * no device info - use default limits then.
12343 	 */
12344 	if (sdinfo == NULL) {
12345 		count_max = dma_attr->dma_attr_granular * 0x100;
12346 		if (dma_attr->dma_attr_count_max > count_max)
12347 			adj_dma_attr->dma_attr_count_max = count_max;
12348 		if (dma_attr->dma_attr_maxxfer > count_max)
12349 			adj_dma_attr->dma_attr_maxxfer = count_max;
12350 		return;
12351 	}
12352 
12353 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12354 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
12355 			/*
12356 			 * 16-bit sector count may be used - we rely on
12357 			 * the assumption that only read and write cmds
12358 			 * will request more than 256 sectors worth of data
12359 			 */
12360 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
12361 		} else {
12362 			/*
12363 			 * 8-bit sector count will be used - default limits
12364 			 * for dma attributes
12365 			 */
12366 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
12367 		}
12368 		/*
12369 		 * Adjust controler dma attributes, if necessary
12370 		 */
12371 		if (dma_attr->dma_attr_count_max > count_max)
12372 			adj_dma_attr->dma_attr_count_max = count_max;
12373 		if (dma_attr->dma_attr_maxxfer > count_max)
12374 			adj_dma_attr->dma_attr_maxxfer = count_max;
12375 	}
12376 }
12377 
12378 
12379 /*
12380  * Allocate DMA resources for the buffer
12381  * This function handles initial DMA resource allocation as well as
12382  * DMA window shift and may be called repeatedly for the same DMA window
12383  * until all DMA cookies in the DMA window are processed.
12384  * To guarantee that there is always a coherent set of cookies to process
12385  * by SATA HBA driver (observing alignment, device granularity, etc.),
12386  * the number of slots for DMA cookies is equal to lesser of  a number of
12387  * cookies in a DMA window and a max number of scatter/gather entries.
12388  *
12389  * Returns DDI_SUCCESS upon successful operation.
12390  * Return failure code of a failing command or DDI_FAILURE when
12391  * internal cleanup failed.
12392  */
12393 static int
12394 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
12395     int (*callback)(caddr_t), caddr_t arg,
12396     ddi_dma_attr_t *cur_dma_attr)
12397 {
12398 	int	rval;
12399 	off_t	offset;
12400 	size_t	size;
12401 	int	max_sg_len, req_len, i;
12402 	uint_t	dma_flags;
12403 	struct buf	*bp;
12404 	uint64_t	cur_txfer_len;
12405 
12406 
12407 	ASSERT(spx->txlt_sata_pkt != NULL);
12408 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
12409 	ASSERT(bp != NULL);
12410 
12411 
12412 	if (spx->txlt_buf_dma_handle == NULL) {
12413 		/*
12414 		 * No DMA resources allocated so far - this is a first call
12415 		 * for this sata pkt.
12416 		 */
12417 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
12418 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
12419 
12420 		if (rval != DDI_SUCCESS) {
12421 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12422 			    "sata_dma_buf_setup: no buf DMA resources %x",
12423 			    rval));
12424 			return (rval);
12425 		}
12426 
12427 		if (bp->b_flags & B_READ)
12428 			dma_flags = DDI_DMA_READ;
12429 		else
12430 			dma_flags = DDI_DMA_WRITE;
12431 
12432 		if (flags & PKT_CONSISTENT)
12433 			dma_flags |= DDI_DMA_CONSISTENT;
12434 
12435 		if (flags & PKT_DMA_PARTIAL)
12436 			dma_flags |= DDI_DMA_PARTIAL;
12437 
12438 		/*
12439 		 * Check buffer alignment and size against dma attributes
12440 		 * Consider dma_attr_align only. There may be requests
12441 		 * with the size lower than device granularity, but they
12442 		 * will not read/write from/to the device, so no adjustment
12443 		 * is necessary. The dma_attr_minxfer theoretically should
12444 		 * be considered, but no HBA driver is checking it.
12445 		 */
12446 		if (IS_P2ALIGNED(bp->b_un.b_addr,
12447 		    cur_dma_attr->dma_attr_align)) {
12448 			rval = ddi_dma_buf_bind_handle(
12449 			    spx->txlt_buf_dma_handle,
12450 			    bp, dma_flags, callback, arg,
12451 			    &spx->txlt_dma_cookie,
12452 			    &spx->txlt_curwin_num_dma_cookies);
12453 		} else { /* Buffer is not aligned */
12454 
12455 			int	(*ddicallback)(caddr_t);
12456 			size_t	bufsz;
12457 
12458 			/* Check id sleeping is allowed */
12459 			ddicallback = (callback == NULL_FUNC) ?
12460 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
12461 
12462 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12463 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
12464 			    (void *)bp->b_un.b_addr, bp->b_bcount);
12465 
12466 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
12467 				/*
12468 				 * CPU will need to access data in the buffer
12469 				 * (for copying) so map it.
12470 				 */
12471 				bp_mapin(bp);
12472 
12473 			ASSERT(spx->txlt_tmp_buf == NULL);
12474 
12475 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
12476 			rval = ddi_dma_mem_alloc(
12477 			    spx->txlt_buf_dma_handle,
12478 			    bp->b_bcount,
12479 			    &sata_acc_attr,
12480 			    DDI_DMA_STREAMING,
12481 			    ddicallback, NULL,
12482 			    &spx->txlt_tmp_buf,
12483 			    &bufsz,
12484 			    &spx->txlt_tmp_buf_handle);
12485 
12486 			if (rval != DDI_SUCCESS) {
12487 				/* DMA mapping failed */
12488 				(void) ddi_dma_free_handle(
12489 				    &spx->txlt_buf_dma_handle);
12490 				spx->txlt_buf_dma_handle = NULL;
12491 #ifdef SATA_DEBUG
12492 				mbuffail_count++;
12493 #endif
12494 				SATADBG1(SATA_DBG_DMA_SETUP,
12495 				    spx->txlt_sata_hba_inst,
12496 				    "sata_dma_buf_setup: "
12497 				    "buf dma mem alloc failed %x\n", rval);
12498 				return (rval);
12499 			}
12500 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
12501 			    cur_dma_attr->dma_attr_align));
12502 
12503 #ifdef SATA_DEBUG
12504 			mbuf_count++;
12505 
12506 			if (bp->b_bcount != bufsz)
12507 				/*
12508 				 * This will require special handling, because
12509 				 * DMA cookies will be based on the temporary
12510 				 * buffer size, not the original buffer
12511 				 * b_bcount, so the residue may have to
12512 				 * be counted differently.
12513 				 */
12514 				SATADBG2(SATA_DBG_DMA_SETUP,
12515 				    spx->txlt_sata_hba_inst,
12516 				    "sata_dma_buf_setup: bp size %x != "
12517 				    "bufsz %x\n", bp->b_bcount, bufsz);
12518 #endif
12519 			if (dma_flags & DDI_DMA_WRITE) {
12520 				/*
12521 				 * Write operation - copy data into
12522 				 * an aligned temporary buffer. Buffer will be
12523 				 * synced for device by ddi_dma_addr_bind_handle
12524 				 */
12525 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
12526 				    bp->b_bcount);
12527 			}
12528 
12529 			rval = ddi_dma_addr_bind_handle(
12530 			    spx->txlt_buf_dma_handle,
12531 			    NULL,
12532 			    spx->txlt_tmp_buf,
12533 			    bufsz, dma_flags, ddicallback, 0,
12534 			    &spx->txlt_dma_cookie,
12535 			    &spx->txlt_curwin_num_dma_cookies);
12536 		}
12537 
12538 		switch (rval) {
12539 		case DDI_DMA_PARTIAL_MAP:
12540 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12541 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
12542 			/*
12543 			 * Partial DMA mapping.
12544 			 * Retrieve number of DMA windows for this request.
12545 			 */
12546 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
12547 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
12548 				if (spx->txlt_tmp_buf != NULL) {
12549 					ddi_dma_mem_free(
12550 					    &spx->txlt_tmp_buf_handle);
12551 					spx->txlt_tmp_buf = NULL;
12552 				}
12553 				(void) ddi_dma_unbind_handle(
12554 				    spx->txlt_buf_dma_handle);
12555 				(void) ddi_dma_free_handle(
12556 				    &spx->txlt_buf_dma_handle);
12557 				spx->txlt_buf_dma_handle = NULL;
12558 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12559 				    "sata_dma_buf_setup: numwin failed\n"));
12560 				return (DDI_FAILURE);
12561 			}
12562 			SATADBG2(SATA_DBG_DMA_SETUP,
12563 			    spx->txlt_sata_hba_inst,
12564 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
12565 			    spx->txlt_num_dma_win,
12566 			    spx->txlt_curwin_num_dma_cookies);
12567 			spx->txlt_cur_dma_win = 0;
12568 			break;
12569 
12570 		case DDI_DMA_MAPPED:
12571 			/* DMA fully mapped */
12572 			spx->txlt_num_dma_win = 1;
12573 			spx->txlt_cur_dma_win = 0;
12574 			SATADBG1(SATA_DBG_DMA_SETUP,
12575 			    spx->txlt_sata_hba_inst,
12576 			    "sata_dma_buf_setup: windows: 1 "
12577 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
12578 			break;
12579 
12580 		default:
12581 			/* DMA mapping failed */
12582 			if (spx->txlt_tmp_buf != NULL) {
12583 				ddi_dma_mem_free(
12584 				    &spx->txlt_tmp_buf_handle);
12585 				spx->txlt_tmp_buf = NULL;
12586 			}
12587 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12588 			spx->txlt_buf_dma_handle = NULL;
12589 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12590 			    "sata_dma_buf_setup: buf dma handle binding "
12591 			    "failed %x\n", rval));
12592 			return (rval);
12593 		}
12594 		spx->txlt_curwin_processed_dma_cookies = 0;
12595 		spx->txlt_dma_cookie_list = NULL;
12596 	} else {
12597 		/*
12598 		 * DMA setup is reused. Check if we need to process more
12599 		 * cookies in current window, or to get next window, if any.
12600 		 */
12601 
12602 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
12603 		    spx->txlt_curwin_num_dma_cookies);
12604 
12605 		if (spx->txlt_curwin_processed_dma_cookies ==
12606 		    spx->txlt_curwin_num_dma_cookies) {
12607 			/*
12608 			 * All cookies from current DMA window were processed.
12609 			 * Get next DMA window.
12610 			 */
12611 			spx->txlt_cur_dma_win++;
12612 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
12613 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
12614 				    spx->txlt_cur_dma_win, &offset, &size,
12615 				    &spx->txlt_dma_cookie,
12616 				    &spx->txlt_curwin_num_dma_cookies);
12617 				spx->txlt_curwin_processed_dma_cookies = 0;
12618 			} else {
12619 				/* No more windows! End of request! */
12620 				/* What to do? - panic for now */
12621 				ASSERT(spx->txlt_cur_dma_win >=
12622 				    spx->txlt_num_dma_win);
12623 
12624 				spx->txlt_curwin_num_dma_cookies = 0;
12625 				spx->txlt_curwin_processed_dma_cookies = 0;
12626 				spx->txlt_sata_pkt->
12627 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
12628 				return (DDI_SUCCESS);
12629 			}
12630 		}
12631 	}
12632 	/* There better be at least one DMA cookie outstanding */
12633 	ASSERT((spx->txlt_curwin_num_dma_cookies -
12634 	    spx->txlt_curwin_processed_dma_cookies) > 0);
12635 
12636 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
12637 		/* The default cookie slot was used in previous run */
12638 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
12639 		spx->txlt_dma_cookie_list = NULL;
12640 		spx->txlt_dma_cookie_list_len = 0;
12641 	}
12642 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
12643 		/*
12644 		 * Processing a new DMA window - set-up dma cookies list.
12645 		 * We may reuse previously allocated cookie array if it is
12646 		 * possible.
12647 		 */
12648 		if (spx->txlt_dma_cookie_list != NULL &&
12649 		    spx->txlt_dma_cookie_list_len <
12650 		    spx->txlt_curwin_num_dma_cookies) {
12651 			/*
12652 			 * New DMA window contains more cookies than
12653 			 * the previous one. We need larger cookie list - free
12654 			 * the old one.
12655 			 */
12656 			(void) kmem_free(spx->txlt_dma_cookie_list,
12657 			    spx->txlt_dma_cookie_list_len *
12658 			    sizeof (ddi_dma_cookie_t));
12659 			spx->txlt_dma_cookie_list = NULL;
12660 			spx->txlt_dma_cookie_list_len = 0;
12661 		}
12662 		if (spx->txlt_dma_cookie_list == NULL) {
12663 			/*
12664 			 * Calculate lesser of number of cookies in this
12665 			 * DMA window and number of s/g entries.
12666 			 */
12667 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
12668 			req_len = MIN(max_sg_len,
12669 			    spx->txlt_curwin_num_dma_cookies);
12670 
12671 			/* Allocate new dma cookie array if necessary */
12672 			if (req_len == 1) {
12673 				/* Only one cookie - no need for a list */
12674 				spx->txlt_dma_cookie_list =
12675 				    &spx->txlt_dma_cookie;
12676 				spx->txlt_dma_cookie_list_len = 1;
12677 			} else {
12678 				/*
12679 				 * More than one cookie - try to allocate space.
12680 				 */
12681 				spx->txlt_dma_cookie_list = kmem_zalloc(
12682 				    sizeof (ddi_dma_cookie_t) * req_len,
12683 				    callback == NULL_FUNC ? KM_NOSLEEP :
12684 				    KM_SLEEP);
12685 				if (spx->txlt_dma_cookie_list == NULL) {
12686 					SATADBG1(SATA_DBG_DMA_SETUP,
12687 					    spx->txlt_sata_hba_inst,
12688 					    "sata_dma_buf_setup: cookie list "
12689 					    "allocation failed\n", NULL);
12690 					/*
12691 					 * We could not allocate space for
12692 					 * neccessary number of dma cookies in
12693 					 * this window, so we fail this request.
12694 					 * Next invocation would try again to
12695 					 * allocate space for cookie list.
12696 					 * Note:Packet residue was not modified.
12697 					 */
12698 					return (DDI_DMA_NORESOURCES);
12699 				} else {
12700 					spx->txlt_dma_cookie_list_len = req_len;
12701 				}
12702 			}
12703 		}
12704 		/*
12705 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
12706 		 * First cookie was already fetched.
12707 		 */
12708 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
12709 		cur_txfer_len =
12710 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
12711 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
12712 		spx->txlt_curwin_processed_dma_cookies++;
12713 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
12714 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
12715 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12716 			    &spx->txlt_dma_cookie_list[i]);
12717 			cur_txfer_len +=
12718 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12719 			spx->txlt_curwin_processed_dma_cookies++;
12720 			spx->txlt_sata_pkt->
12721 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
12722 		}
12723 	} else {
12724 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12725 		    "sata_dma_buf_setup: sliding within DMA window, "
12726 		    "cur cookie %d, total cookies %d\n",
12727 		    spx->txlt_curwin_processed_dma_cookies,
12728 		    spx->txlt_curwin_num_dma_cookies);
12729 
12730 		/*
12731 		 * Not all cookies from the current dma window were used because
12732 		 * of s/g limitation.
12733 		 * There is no need to re-size the list - it was set at
12734 		 * optimal size, or only default entry is used (s/g = 1).
12735 		 */
12736 		if (spx->txlt_dma_cookie_list == NULL) {
12737 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
12738 			spx->txlt_dma_cookie_list_len = 1;
12739 		}
12740 		/*
12741 		 * Since we are processing remaining cookies in a DMA window,
12742 		 * there may be less of them than the number of entries in the
12743 		 * current dma cookie list.
12744 		 */
12745 		req_len = MIN(spx->txlt_dma_cookie_list_len,
12746 		    (spx->txlt_curwin_num_dma_cookies -
12747 		    spx->txlt_curwin_processed_dma_cookies));
12748 
12749 		/* Fetch the next batch of cookies */
12750 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
12751 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12752 			    &spx->txlt_dma_cookie_list[i]);
12753 			cur_txfer_len +=
12754 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12755 			spx->txlt_sata_pkt->
12756 			    satapkt_cmd.satacmd_num_dma_cookies++;
12757 			spx->txlt_curwin_processed_dma_cookies++;
12758 		}
12759 	}
12760 
12761 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
12762 
12763 	/* Point sata_cmd to the cookie list */
12764 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
12765 	    &spx->txlt_dma_cookie_list[0];
12766 
12767 	/* Remember number of DMA cookies passed in sata packet */
12768 	spx->txlt_num_dma_cookies =
12769 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
12770 
12771 	ASSERT(cur_txfer_len != 0);
12772 	if (cur_txfer_len <= bp->b_bcount)
12773 		spx->txlt_total_residue -= cur_txfer_len;
12774 	else {
12775 		/*
12776 		 * Temporary DMA buffer has been padded by
12777 		 * ddi_dma_mem_alloc()!
12778 		 * This requires special handling, because DMA cookies are
12779 		 * based on the temporary buffer size, not the b_bcount,
12780 		 * and we have extra bytes to transfer - but the packet
12781 		 * residue has to stay correct because we will copy only
12782 		 * the requested number of bytes.
12783 		 */
12784 		spx->txlt_total_residue -= bp->b_bcount;
12785 	}
12786 
12787 	return (DDI_SUCCESS);
12788 }
12789 
12790 /*
12791  * Common routine for releasing DMA resources
12792  */
12793 static void
12794 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
12795 {
12796 	if (spx->txlt_buf_dma_handle != NULL) {
12797 		if (spx->txlt_tmp_buf != NULL)  {
12798 			/*
12799 			 * Intermediate DMA buffer was allocated.
12800 			 * Free allocated buffer and associated access handle.
12801 			 */
12802 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
12803 			spx->txlt_tmp_buf = NULL;
12804 		}
12805 		/*
12806 		 * Free DMA resources - cookies and handles
12807 		 */
12808 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
12809 		if (spx->txlt_dma_cookie_list != NULL) {
12810 			if (spx->txlt_dma_cookie_list !=
12811 			    &spx->txlt_dma_cookie) {
12812 				(void) kmem_free(spx->txlt_dma_cookie_list,
12813 				    spx->txlt_dma_cookie_list_len *
12814 				    sizeof (ddi_dma_cookie_t));
12815 				spx->txlt_dma_cookie_list = NULL;
12816 			}
12817 		}
12818 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
12819 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12820 		spx->txlt_buf_dma_handle = NULL;
12821 	}
12822 }
12823 
12824 /*
12825  * Free DMA resources
12826  * Used by the HBA driver to release DMA resources that it does not use.
12827  *
12828  * Returns Void
12829  */
12830 void
12831 sata_free_dma_resources(sata_pkt_t *sata_pkt)
12832 {
12833 	sata_pkt_txlate_t *spx;
12834 
12835 	if (sata_pkt == NULL)
12836 		return;
12837 
12838 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
12839 
12840 	sata_common_free_dma_rsrcs(spx);
12841 }
12842 
12843 /*
12844  * Fetch Device Identify data.
12845  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
12846  * command to a device and get the device identify data.
12847  * The device_info structure has to be set to device type (for selecting proper
12848  * device identify command).
12849  *
12850  * Returns:
12851  * SATA_SUCCESS if cmd succeeded
12852  * SATA_RETRY if cmd was rejected and could be retried,
12853  * SATA_FAILURE if cmd failed and should not be retried (port error)
12854  *
12855  * Cannot be called in an interrupt context.
12856  */
12857 
12858 static int
12859 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
12860     sata_drive_info_t *sdinfo)
12861 {
12862 	struct buf *bp;
12863 	sata_pkt_t *spkt;
12864 	sata_cmd_t *scmd;
12865 	sata_pkt_txlate_t *spx;
12866 	int rval;
12867 
12868 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12869 	spx->txlt_sata_hba_inst = sata_hba_inst;
12870 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
12871 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12872 	if (spkt == NULL) {
12873 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12874 		return (SATA_RETRY); /* may retry later */
12875 	}
12876 	/* address is needed now */
12877 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12878 
12879 	/*
12880 	 * Allocate buffer for Identify Data return data
12881 	 */
12882 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
12883 	if (bp == NULL) {
12884 		sata_pkt_free(spx);
12885 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12886 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12887 		    "sata_fetch_device_identify_data: "
12888 		    "cannot allocate buffer for ID"));
12889 		return (SATA_RETRY); /* may retry later */
12890 	}
12891 
12892 	/* Fill sata_pkt */
12893 	sdinfo->satadrv_state = SATA_STATE_PROBING;
12894 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12895 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12896 	/* Synchronous mode, no callback */
12897 	spkt->satapkt_comp = NULL;
12898 	/* Timeout 30s */
12899 	spkt->satapkt_time = sata_default_pkt_time;
12900 
12901 	scmd = &spkt->satapkt_cmd;
12902 	scmd->satacmd_bp = bp;
12903 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
12904 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
12905 
12906 	/* Build Identify Device cmd in the sata_pkt */
12907 	scmd->satacmd_addr_type = 0;		/* N/A */
12908 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
12909 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
12910 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
12911 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
12912 	scmd->satacmd_features_reg = 0;		/* N/A */
12913 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
12914 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
12915 		/* Identify Packet Device cmd */
12916 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
12917 	} else {
12918 		/* Identify Device cmd - mandatory for all other devices */
12919 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
12920 	}
12921 
12922 	/* Send pkt to SATA HBA driver */
12923 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
12924 
12925 #ifdef SATA_INJECT_FAULTS
12926 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
12927 #endif
12928 
12929 	if (rval == SATA_TRAN_ACCEPTED &&
12930 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
12931 		if (spx->txlt_buf_dma_handle != NULL) {
12932 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
12933 			    DDI_DMA_SYNC_FORKERNEL);
12934 			ASSERT(rval == DDI_SUCCESS);
12935 		}
12936 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
12937 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
12938 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12939 			    "SATA disk device at port %d - "
12940 			    "partial Identify Data",
12941 			    sdinfo->satadrv_addr.cport));
12942 			rval = SATA_RETRY; /* may retry later */
12943 			goto fail;
12944 		}
12945 		/* Update sata_drive_info */
12946 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
12947 		    sizeof (sata_id_t));
12948 
12949 		sdinfo->satadrv_features_support = 0;
12950 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12951 			/*
12952 			 * Retrieve capacity (disks only) and addressing mode
12953 			 */
12954 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
12955 		} else {
12956 			/*
12957 			 * For ATAPI devices one would have to issue
12958 			 * Get Capacity cmd for media capacity. Not here.
12959 			 */
12960 			sdinfo->satadrv_capacity = 0;
12961 			/*
12962 			 * Check what cdb length is supported
12963 			 */
12964 			if ((sdinfo->satadrv_id.ai_config &
12965 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
12966 				sdinfo->satadrv_atapi_cdb_len = 16;
12967 			else
12968 				sdinfo->satadrv_atapi_cdb_len = 12;
12969 		}
12970 		/* Setup supported features flags */
12971 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
12972 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
12973 
12974 		/* Check for SATA GEN and NCQ support */
12975 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
12976 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
12977 			/* SATA compliance */
12978 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
12979 				sdinfo->satadrv_features_support |=
12980 				    SATA_DEV_F_NCQ;
12981 			if (sdinfo->satadrv_id.ai_satacap &
12982 			    (SATA_1_SPEED | SATA_2_SPEED)) {
12983 				if (sdinfo->satadrv_id.ai_satacap &
12984 				    SATA_2_SPEED)
12985 					sdinfo->satadrv_features_support |=
12986 					    SATA_DEV_F_SATA2;
12987 				if (sdinfo->satadrv_id.ai_satacap &
12988 				    SATA_1_SPEED)
12989 					sdinfo->satadrv_features_support |=
12990 					    SATA_DEV_F_SATA1;
12991 			} else {
12992 				sdinfo->satadrv_features_support |=
12993 				    SATA_DEV_F_SATA1;
12994 			}
12995 		}
12996 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
12997 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
12998 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
12999 
13000 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
13001 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
13002 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
13003 			++sdinfo->satadrv_queue_depth;
13004 			/* Adjust according to controller capabilities */
13005 			sdinfo->satadrv_max_queue_depth = MIN(
13006 			    sdinfo->satadrv_queue_depth,
13007 			    SATA_QDEPTH(sata_hba_inst));
13008 			/* Adjust according to global queue depth limit */
13009 			sdinfo->satadrv_max_queue_depth = MIN(
13010 			    sdinfo->satadrv_max_queue_depth,
13011 			    sata_current_max_qdepth);
13012 			if (sdinfo->satadrv_max_queue_depth == 0)
13013 				sdinfo->satadrv_max_queue_depth = 1;
13014 		} else
13015 			sdinfo->satadrv_max_queue_depth = 1;
13016 
13017 		rval = SATA_SUCCESS;
13018 	} else {
13019 		/*
13020 		 * Woops, no Identify Data.
13021 		 */
13022 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
13023 			rval = SATA_RETRY; /* may retry later */
13024 		} else if (rval == SATA_TRAN_ACCEPTED) {
13025 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
13026 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
13027 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13028 			    spkt->satapkt_reason == SATA_PKT_RESET)
13029 				rval = SATA_RETRY; /* may retry later */
13030 			else
13031 				rval = SATA_FAILURE;
13032 		} else {
13033 			rval = SATA_FAILURE;
13034 		}
13035 	}
13036 fail:
13037 	/* Free allocated resources */
13038 	sata_free_local_buffer(spx);
13039 	sata_pkt_free(spx);
13040 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13041 
13042 	return (rval);
13043 }
13044 
13045 
13046 /*
13047  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13048  * UDMA mode is checked first, followed by MWDMA mode.
13049  * set correctly, so this function is setting it to the highest supported level.
13050  * Older SATA spec required that the device supports at least DMA 4 mode and
13051  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13052  * restriction has been removed.
13053  *
13054  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13055  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13056  *
13057  * NOTE: This function should be called only if DMA mode is supported.
13058  */
13059 static int
13060 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13061 {
13062 	sata_pkt_t *spkt;
13063 	sata_cmd_t *scmd;
13064 	sata_pkt_txlate_t *spx;
13065 	int i, mode;
13066 	uint8_t subcmd;
13067 	int rval = SATA_SUCCESS;
13068 
13069 	ASSERT(sdinfo != NULL);
13070 	ASSERT(sata_hba_inst != NULL);
13071 
13072 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13073 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13074 		/* Find highest Ultra DMA mode supported */
13075 		for (mode = 6; mode >= 0; --mode) {
13076 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13077 				break;
13078 		}
13079 #if 0
13080 		/* Left for historical reasons */
13081 		/*
13082 		 * Some initial version of SATA spec indicated that at least
13083 		 * UDMA mode 4 has to be supported. It is not mentioned in
13084 		 * SerialATA 2.6, so this restriction is removed.
13085 		 */
13086 		if (mode < 4)
13087 			return (SATA_FAILURE);
13088 #endif
13089 
13090 		/*
13091 		 * For disk, we're still going to set DMA mode whatever is
13092 		 * selected by default
13093 		 *
13094 		 * We saw an old maxtor sata drive will select Ultra DMA and
13095 		 * Multi-Word DMA simultaneouly by default, which is going
13096 		 * to cause DMA command timed out, so we need to select DMA
13097 		 * mode even when it's already done by default
13098 		 */
13099 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13100 
13101 			/* Find UDMA mode currently selected */
13102 			for (i = 6; i >= 0; --i) {
13103 				if (sdinfo->satadrv_id.ai_ultradma &
13104 				    (1 << (i + 8)))
13105 					break;
13106 			}
13107 			if (i >= mode)
13108 				/* Nothing to do */
13109 				return (SATA_SUCCESS);
13110 		}
13111 
13112 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13113 
13114 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13115 		/* Find highest MultiWord DMA mode supported */
13116 		for (mode = 2; mode >= 0; --mode) {
13117 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13118 				break;
13119 		}
13120 
13121 		/*
13122 		 * For disk, We're still going to set DMA mode whatever is
13123 		 * selected by default
13124 		 *
13125 		 * We saw an old maxtor sata drive will select Ultra DMA and
13126 		 * Multi-Word DMA simultaneouly by default, which is going
13127 		 * to cause DMA command timed out, so we need to select DMA
13128 		 * mode even when it's already done by default
13129 		 */
13130 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13131 
13132 			/* Find highest MultiWord DMA mode selected */
13133 			for (i = 2; i >= 0; --i) {
13134 				if (sdinfo->satadrv_id.ai_dworddma &
13135 				    (1 << (i + 8)))
13136 					break;
13137 			}
13138 			if (i >= mode)
13139 				/* Nothing to do */
13140 				return (SATA_SUCCESS);
13141 		}
13142 
13143 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
13144 	} else
13145 		return (SATA_SUCCESS);
13146 
13147 	/*
13148 	 * Set DMA mode via SET FEATURES COMMAND.
13149 	 * Prepare packet for SET FEATURES COMMAND.
13150 	 */
13151 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13152 	spx->txlt_sata_hba_inst = sata_hba_inst;
13153 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13154 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13155 	if (spkt == NULL) {
13156 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13157 		    "sata_set_dma_mode: could not set DMA mode %", mode));
13158 		rval = SATA_FAILURE;
13159 		goto done;
13160 	}
13161 	/* Fill sata_pkt */
13162 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13163 	/* Timeout 30s */
13164 	spkt->satapkt_time = sata_default_pkt_time;
13165 	/* Synchronous mode, no callback, interrupts */
13166 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13167 	spkt->satapkt_comp = NULL;
13168 	scmd = &spkt->satapkt_cmd;
13169 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13170 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13171 	scmd->satacmd_addr_type = 0;
13172 	scmd->satacmd_device_reg = 0;
13173 	scmd->satacmd_status_reg = 0;
13174 	scmd->satacmd_error_reg = 0;
13175 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13176 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
13177 	scmd->satacmd_sec_count_lsb = subcmd | mode;
13178 
13179 	/* Transfer command to HBA */
13180 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
13181 	    spkt) != SATA_TRAN_ACCEPTED ||
13182 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13183 		/* Pkt execution failed */
13184 		rval = SATA_FAILURE;
13185 	}
13186 done:
13187 
13188 	/* Free allocated resources */
13189 	if (spkt != NULL)
13190 		sata_pkt_free(spx);
13191 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13192 
13193 	return (rval);
13194 }
13195 
13196 
13197 /*
13198  * Set device caching mode.
13199  * One of the following operations should be specified:
13200  * SATAC_SF_ENABLE_READ_AHEAD
13201  * SATAC_SF_DISABLE_READ_AHEAD
13202  * SATAC_SF_ENABLE_WRITE_CACHE
13203  * SATAC_SF_DISABLE_WRITE_CACHE
13204  *
13205  * If operation fails, system log messgage is emitted.
13206  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
13207  * command was sent but did not succeed, and SATA_FAILURE otherwise.
13208  */
13209 
13210 static int
13211 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13212     int cache_op)
13213 {
13214 	sata_pkt_t *spkt;
13215 	sata_cmd_t *scmd;
13216 	sata_pkt_txlate_t *spx;
13217 	int rval = SATA_SUCCESS;
13218 	int hba_rval;
13219 	char *infop;
13220 
13221 	ASSERT(sdinfo != NULL);
13222 	ASSERT(sata_hba_inst != NULL);
13223 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
13224 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
13225 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
13226 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
13227 
13228 
13229 	/* Prepare packet for SET FEATURES COMMAND */
13230 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13231 	spx->txlt_sata_hba_inst = sata_hba_inst;
13232 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13233 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13234 	if (spkt == NULL) {
13235 		rval = SATA_FAILURE;
13236 		goto failure;
13237 	}
13238 	/* Fill sata_pkt */
13239 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13240 	/* Timeout 30s */
13241 	spkt->satapkt_time = sata_default_pkt_time;
13242 	/* Synchronous mode, no callback, interrupts */
13243 	spkt->satapkt_op_mode =
13244 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13245 	spkt->satapkt_comp = NULL;
13246 	scmd = &spkt->satapkt_cmd;
13247 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13248 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13249 	scmd->satacmd_addr_type = 0;
13250 	scmd->satacmd_device_reg = 0;
13251 	scmd->satacmd_status_reg = 0;
13252 	scmd->satacmd_error_reg = 0;
13253 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13254 	scmd->satacmd_features_reg = cache_op;
13255 
13256 	/* Transfer command to HBA */
13257 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
13258 	    SATA_DIP(sata_hba_inst), spkt);
13259 
13260 #ifdef SATA_INJECT_FAULTS
13261 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13262 #endif
13263 
13264 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
13265 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13266 		/* Pkt execution failed */
13267 		switch (cache_op) {
13268 		case SATAC_SF_ENABLE_READ_AHEAD:
13269 			infop = "enabling read ahead failed";
13270 			break;
13271 		case SATAC_SF_DISABLE_READ_AHEAD:
13272 			infop = "disabling read ahead failed";
13273 			break;
13274 		case SATAC_SF_ENABLE_WRITE_CACHE:
13275 			infop = "enabling write cache failed";
13276 			break;
13277 		case SATAC_SF_DISABLE_WRITE_CACHE:
13278 			infop = "disabling write cache failed";
13279 			break;
13280 		}
13281 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13282 		rval = SATA_RETRY;
13283 	}
13284 failure:
13285 	/* Free allocated resources */
13286 	if (spkt != NULL)
13287 		sata_pkt_free(spx);
13288 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13289 	return (rval);
13290 }
13291 
13292 /*
13293  * Set Removable Media Status Notification (enable/disable)
13294  * state == 0 , disable
13295  * state != 0 , enable
13296  *
13297  * If operation fails, system log messgage is emitted.
13298  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
13299  */
13300 
13301 static int
13302 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13303     int state)
13304 {
13305 	sata_pkt_t *spkt;
13306 	sata_cmd_t *scmd;
13307 	sata_pkt_txlate_t *spx;
13308 	int rval = SATA_SUCCESS;
13309 	char *infop;
13310 
13311 	ASSERT(sdinfo != NULL);
13312 	ASSERT(sata_hba_inst != NULL);
13313 
13314 	/* Prepare packet for SET FEATURES COMMAND */
13315 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13316 	spx->txlt_sata_hba_inst = sata_hba_inst;
13317 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13318 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13319 	if (spkt == NULL) {
13320 		rval = SATA_FAILURE;
13321 		goto failure;
13322 	}
13323 	/* Fill sata_pkt */
13324 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13325 	/* Timeout 30s */
13326 	spkt->satapkt_time = sata_default_pkt_time;
13327 	/* Synchronous mode, no callback, interrupts */
13328 	spkt->satapkt_op_mode =
13329 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13330 	spkt->satapkt_comp = NULL;
13331 	scmd = &spkt->satapkt_cmd;
13332 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13333 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13334 	scmd->satacmd_addr_type = 0;
13335 	scmd->satacmd_device_reg = 0;
13336 	scmd->satacmd_status_reg = 0;
13337 	scmd->satacmd_error_reg = 0;
13338 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13339 	if (state == 0)
13340 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
13341 	else
13342 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
13343 
13344 	/* Transfer command to HBA */
13345 	if (((*SATA_START_FUNC(sata_hba_inst))(
13346 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
13347 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13348 		/* Pkt execution failed */
13349 		if (state == 0)
13350 			infop = "disabling Removable Media Status "
13351 			    "Notification failed";
13352 		else
13353 			infop = "enabling Removable Media Status "
13354 			    "Notification failed";
13355 
13356 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13357 		rval = SATA_FAILURE;
13358 	}
13359 failure:
13360 	/* Free allocated resources */
13361 	if (spkt != NULL)
13362 		sata_pkt_free(spx);
13363 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13364 	return (rval);
13365 }
13366 
13367 
13368 /*
13369  * Update state and copy port ss* values from passed sata_device structure.
13370  * sata_address is validated - if not valid, nothing is changed in sata_scsi
13371  * configuration struct.
13372  *
13373  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
13374  * regardless of the state in device argument.
13375  *
13376  * Port mutex should be held while calling this function.
13377  */
13378 static void
13379 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
13380     sata_device_t *sata_device)
13381 {
13382 	sata_cport_info_t *cportinfo;
13383 
13384 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
13385 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
13386 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
13387 		    sata_device->satadev_addr.cport)
13388 			return;
13389 
13390 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
13391 		    sata_device->satadev_addr.cport);
13392 
13393 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
13394 		cportinfo->cport_scr = sata_device->satadev_scr;
13395 
13396 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
13397 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
13398 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13399 		cportinfo->cport_state |=
13400 		    sata_device->satadev_state & SATA_PSTATE_VALID;
13401 	}
13402 }
13403 
13404 void
13405 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
13406     sata_device_t *sata_device)
13407 {
13408 	sata_pmport_info_t *pmportinfo;
13409 
13410 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
13411 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
13412 	    SATA_NUM_PMPORTS(sata_hba_inst,
13413 	    sata_device->satadev_addr.cport) <
13414 	    sata_device->satadev_addr.pmport) {
13415 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
13416 		    "sata_update_port_info: error address %p.",
13417 		    &sata_device->satadev_addr);
13418 		return;
13419 	}
13420 
13421 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
13422 	    sata_device->satadev_addr.cport,
13423 	    sata_device->satadev_addr.pmport);
13424 
13425 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
13426 	pmportinfo->pmport_scr = sata_device->satadev_scr;
13427 
13428 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
13429 	pmportinfo->pmport_state &=
13430 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13431 	pmportinfo->pmport_state |=
13432 	    sata_device->satadev_state & SATA_PSTATE_VALID;
13433 }
13434 
13435 /*
13436  * Extract SATA port specification from an IOCTL argument.
13437  *
13438  * This function return the port the user land send us as is, unless it
13439  * cannot retrieve port spec, then -1 is returned.
13440  *
13441  * Support port multiplier.
13442  */
13443 static int32_t
13444 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
13445 {
13446 	int32_t port;
13447 
13448 	/* Extract port number from nvpair in dca structure  */
13449 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
13450 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
13451 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
13452 		    port));
13453 		port = -1;
13454 	}
13455 
13456 	return (port);
13457 }
13458 
13459 /*
13460  * Get dev_info_t pointer to the device node pointed to by port argument.
13461  * NOTE: target argument is a value used in ioctls to identify
13462  * the AP - it is not a sata_address.
13463  * It is a combination of cport, pmport and address qualifier, encodded same
13464  * way as a scsi target number.
13465  * At this moment it carries only cport number.
13466  *
13467  * PMult hotplug is supported now.
13468  *
13469  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13470  */
13471 
13472 static dev_info_t *
13473 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
13474 {
13475 	dev_info_t	*cdip = NULL;
13476 	int		target, tgt;
13477 	int 		circ;
13478 	uint8_t		qual;
13479 
13480 	sata_hba_inst_t	*sata_hba_inst;
13481 	scsi_hba_tran_t *scsi_hba_tran;
13482 
13483 	/* Get target id */
13484 	scsi_hba_tran = ddi_get_driver_private(dip);
13485 	if (scsi_hba_tran == NULL)
13486 		return (NULL);
13487 
13488 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
13489 
13490 	if (sata_hba_inst == NULL)
13491 		return (NULL);
13492 
13493 	/* Identify a port-mult by cport_info.cport_dev_type */
13494 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
13495 		qual = SATA_ADDR_DPMPORT;
13496 	else
13497 		qual = SATA_ADDR_DCPORT;
13498 
13499 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
13500 
13501 	/* Retrieve target dip */
13502 	ndi_devi_enter(dip, &circ);
13503 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13504 		dev_info_t *next = ddi_get_next_sibling(cdip);
13505 
13506 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13507 		    DDI_PROP_DONTPASS, "target", -1);
13508 		if (tgt == -1) {
13509 			/*
13510 			 * This is actually an error condition, but not
13511 			 * a fatal one. Just continue the search.
13512 			 */
13513 			cdip = next;
13514 			continue;
13515 		}
13516 
13517 		if (tgt == target)
13518 			break;
13519 
13520 		cdip = next;
13521 	}
13522 	ndi_devi_exit(dip, circ);
13523 
13524 	return (cdip);
13525 }
13526 
13527 /*
13528  * Get dev_info_t pointer to the device node pointed to by port argument.
13529  * NOTE: target argument is a value used in ioctls to identify
13530  * the AP - it is not a sata_address.
13531  * It is a combination of cport, pmport and address qualifier, encoded same
13532  * way as a scsi target number.
13533  *
13534  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13535  */
13536 
13537 static dev_info_t *
13538 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
13539 {
13540 	dev_info_t	*cdip = NULL;
13541 	int		target, tgt;
13542 	int 		circ;
13543 
13544 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
13545 
13546 	ndi_devi_enter(dip, &circ);
13547 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13548 		dev_info_t *next = ddi_get_next_sibling(cdip);
13549 
13550 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13551 		    DDI_PROP_DONTPASS, "target", -1);
13552 		if (tgt == -1) {
13553 			/*
13554 			 * This is actually an error condition, but not
13555 			 * a fatal one. Just continue the search.
13556 			 */
13557 			cdip = next;
13558 			continue;
13559 		}
13560 
13561 		if (tgt == target)
13562 			break;
13563 
13564 		cdip = next;
13565 	}
13566 	ndi_devi_exit(dip, circ);
13567 
13568 	return (cdip);
13569 }
13570 
13571 /*
13572  * Process sata port disconnect request.
13573  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
13574  * before this request. Nevertheless, if a device is still configured,
13575  * we need to attempt to offline and unconfigure device.
13576  * Regardless of the unconfigure operation results the port is marked as
13577  * deactivated and no access to the attached device is possible.
13578  * If the target node remains because unconfigure operation failed, its state
13579  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
13580  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
13581  * the device and remove old target node.
13582  *
13583  * This function invokes sata_hba_inst->satahba_tran->
13584  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13585  * If successful, the device structure (if any) attached to the specified port
13586  * is removed and state of the port marked appropriately.
13587  * Failure of the port_deactivate may keep port in the physically active state,
13588  * or may fail the port.
13589  *
13590  * NOTE: Port multiplier is supported.
13591  */
13592 
13593 static int
13594 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
13595     sata_device_t *sata_device)
13596 {
13597 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
13598 	sata_cport_info_t *cportinfo = NULL;
13599 	sata_pmport_info_t *pmportinfo = NULL;
13600 	sata_pmult_info_t *pmultinfo = NULL;
13601 	sata_device_t subsdevice;
13602 	int cport, pmport, qual;
13603 	int rval = SATA_SUCCESS;
13604 	int npmport = 0;
13605 	int rv = 0;
13606 
13607 	cport = sata_device->satadev_addr.cport;
13608 	pmport = sata_device->satadev_addr.pmport;
13609 	qual = sata_device->satadev_addr.qual;
13610 
13611 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13612 	if (qual == SATA_ADDR_DCPORT)
13613 		qual = SATA_ADDR_CPORT;
13614 	else
13615 		qual = SATA_ADDR_PMPORT;
13616 
13617 	/*
13618 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
13619 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13620 	 * Do the sanity check.
13621 	 */
13622 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
13623 		/* No physical port deactivation supported. */
13624 		return (EINVAL);
13625 	}
13626 
13627 	/* Check the current state of the port */
13628 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
13629 	    (SATA_DIP(sata_hba_inst), sata_device);
13630 
13631 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13632 
13633 	/*
13634 	 * Processing port mulitiplier
13635 	 */
13636 	if (qual == SATA_ADDR_CPORT &&
13637 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
13638 		mutex_enter(&cportinfo->cport_mutex);
13639 
13640 		/* Check controller port status */
13641 		sata_update_port_info(sata_hba_inst, sata_device);
13642 		if (rval != SATA_SUCCESS ||
13643 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13644 			/*
13645 			 * Device port status is unknown or it is in failed
13646 			 * state
13647 			 */
13648 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13649 			    SATA_PSTATE_FAILED;
13650 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13651 			    "sata_hba_ioctl: connect: failed to deactivate "
13652 			    "SATA port %d", cport);
13653 			mutex_exit(&cportinfo->cport_mutex);
13654 			return (EIO);
13655 		}
13656 
13657 		/* Disconnect all sub-devices. */
13658 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13659 		if (pmultinfo != NULL) {
13660 
13661 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
13662 			    sata_hba_inst, cport); npmport ++) {
13663 				subsdinfo = SATA_PMPORT_DRV_INFO(
13664 				    sata_hba_inst, cport, npmport);
13665 				if (subsdinfo == NULL)
13666 					continue;
13667 
13668 				subsdevice.satadev_addr = subsdinfo->
13669 				    satadrv_addr;
13670 
13671 				mutex_exit(&cportinfo->cport_mutex);
13672 				if (sata_ioctl_disconnect(sata_hba_inst,
13673 				    &subsdevice) == SATA_SUCCESS) {
13674 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
13675 					"[Remove] device at port %d:%d "
13676 					"successfully.", cport, npmport);
13677 				}
13678 				mutex_enter(&cportinfo->cport_mutex);
13679 			}
13680 		}
13681 
13682 		/* Disconnect the port multiplier */
13683 		cportinfo->cport_state &= ~SATA_STATE_READY;
13684 		mutex_exit(&cportinfo->cport_mutex);
13685 
13686 		sata_device->satadev_addr.qual = qual;
13687 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13688 		    (SATA_DIP(sata_hba_inst), sata_device);
13689 
13690 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13691 		    SE_NO_HINT);
13692 
13693 		mutex_enter(&cportinfo->cport_mutex);
13694 		sata_update_port_info(sata_hba_inst, sata_device);
13695 		if (rval != SATA_SUCCESS &&
13696 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13697 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13698 			rv = EIO;
13699 		} else {
13700 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13701 		}
13702 		mutex_exit(&cportinfo->cport_mutex);
13703 
13704 		return (rv);
13705 	}
13706 
13707 	/*
13708 	 * Process non-port-multiplier device - it could be a drive connected
13709 	 * to a port multiplier port or a controller port.
13710 	 */
13711 	if (qual == SATA_ADDR_PMPORT) {
13712 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13713 		mutex_enter(&pmportinfo->pmport_mutex);
13714 		sata_update_pmport_info(sata_hba_inst, sata_device);
13715 		if (rval != SATA_SUCCESS ||
13716 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13717 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
13718 			    SATA_PSTATE_FAILED;
13719 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13720 			    "sata_hba_ioctl: connect: failed to deactivate "
13721 			    "SATA port %d:%d", cport, pmport);
13722 			mutex_exit(&pmportinfo->pmport_mutex);
13723 			return (EIO);
13724 		}
13725 
13726 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
13727 			sdinfo = pmportinfo->pmport_sata_drive;
13728 			ASSERT(sdinfo != NULL);
13729 		}
13730 
13731 		/*
13732 		 * Set port's dev_state to not ready - this will disable
13733 		 * an access to a potentially attached device.
13734 		 */
13735 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
13736 
13737 		/* Remove and release sata_drive info structure. */
13738 		if (sdinfo != NULL) {
13739 			if ((sdinfo->satadrv_type &
13740 			    SATA_VALID_DEV_TYPE) != 0) {
13741 				/*
13742 				 * If a target node exists, try to offline
13743 				 * a device and remove target node.
13744 				 */
13745 				mutex_exit(&pmportinfo->pmport_mutex);
13746 				(void) sata_offline_device(sata_hba_inst,
13747 				    sata_device, sdinfo);
13748 				mutex_enter(&pmportinfo->pmport_mutex);
13749 			}
13750 
13751 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
13752 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
13753 			(void) kmem_free((void *)sdinfo,
13754 			    sizeof (sata_drive_info_t));
13755 		}
13756 		mutex_exit(&pmportinfo->pmport_mutex);
13757 
13758 	} else if (qual == SATA_ADDR_CPORT) {
13759 		mutex_enter(&cportinfo->cport_mutex);
13760 		sata_update_port_info(sata_hba_inst, sata_device);
13761 		if (rval != SATA_SUCCESS ||
13762 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13763 			/*
13764 			 * Device port status is unknown or it is in failed
13765 			 * state
13766 			 */
13767 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13768 			    SATA_PSTATE_FAILED;
13769 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13770 			    "sata_hba_ioctl: connect: failed to deactivate "
13771 			    "SATA port %d", cport);
13772 			mutex_exit(&cportinfo->cport_mutex);
13773 			return (EIO);
13774 		}
13775 
13776 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
13777 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13778 			ASSERT(pmultinfo != NULL);
13779 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
13780 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
13781 			ASSERT(sdinfo != NULL);
13782 		}
13783 		cportinfo->cport_state &= ~SATA_STATE_READY;
13784 
13785 		if (sdinfo != NULL) {
13786 			if ((sdinfo->satadrv_type &
13787 			    SATA_VALID_DEV_TYPE) != 0) {
13788 				/*
13789 				 * If a target node exists, try to offline
13790 				 * a device and remove target node.
13791 				 */
13792 				mutex_exit(&cportinfo->cport_mutex);
13793 				(void) sata_offline_device(sata_hba_inst,
13794 				    sata_device, sdinfo);
13795 				mutex_enter(&cportinfo->cport_mutex);
13796 			}
13797 
13798 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
13799 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
13800 			(void) kmem_free((void *)sdinfo,
13801 			    sizeof (sata_drive_info_t));
13802 		}
13803 		mutex_exit(&cportinfo->cport_mutex);
13804 	}
13805 
13806 	/* Just ask HBA driver to deactivate port */
13807 	sata_device->satadev_addr.qual = qual;
13808 
13809 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13810 	    (SATA_DIP(sata_hba_inst), sata_device);
13811 
13812 	/*
13813 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13814 	 * without the hint (to force listener to investivate the state).
13815 	 */
13816 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13817 	    SE_NO_HINT);
13818 
13819 	if (qual == SATA_ADDR_PMPORT) {
13820 		mutex_enter(&pmportinfo->pmport_mutex);
13821 		sata_update_pmport_info(sata_hba_inst, sata_device);
13822 
13823 		if (rval != SATA_SUCCESS &&
13824 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13825 			/*
13826 			 * Port deactivation failure - do not change port
13827 			 * state unless the state returned by HBA indicates a
13828 			 * port failure.
13829 			 *
13830 			 * NOTE: device structures were released, so devices
13831 			 * now are invisible! Port reset is needed to
13832 			 * re-enumerate devices.
13833 			 */
13834 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
13835 			rv = EIO;
13836 		} else {
13837 			/*
13838 			 * Deactivation succeded. From now on the sata framework
13839 			 * will not care what is happening to the device, until
13840 			 * the port is activated again.
13841 			 */
13842 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
13843 		}
13844 		mutex_exit(&pmportinfo->pmport_mutex);
13845 	} else if (qual == SATA_ADDR_CPORT) {
13846 		mutex_enter(&cportinfo->cport_mutex);
13847 		sata_update_port_info(sata_hba_inst, sata_device);
13848 
13849 		if (rval != SATA_SUCCESS &&
13850 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13851 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13852 			rv = EIO;
13853 		} else {
13854 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13855 		}
13856 		mutex_exit(&cportinfo->cport_mutex);
13857 	}
13858 
13859 	return (rv);
13860 }
13861 
13862 
13863 
13864 /*
13865  * Process sata port connect request
13866  * The sata cfgadm pluging will invoke this operation only if port was found
13867  * in the disconnect state (failed state is also treated as the disconnected
13868  * state).
13869  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
13870  * sata_tran_hotplug_ops->sata_tran_port_activate().
13871  * If successful and a device is found attached to the port,
13872  * the initialization sequence is executed to attach a device structure to
13873  * a port structure. The state of the port and a device would be set
13874  * appropriately.
13875  * The device is not set in configured state (system-wise) by this operation.
13876  *
13877  * Note, that activating the port may generate link events,
13878  * so it is important that following processing and the
13879  * event processing does not interfere with each other!
13880  *
13881  * This operation may remove port failed state and will
13882  * try to make port active and in good standing.
13883  *
13884  * NOTE: Port multiplier is supported.
13885  */
13886 
13887 static int
13888 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
13889     sata_device_t *sata_device)
13890 {
13891 	sata_pmport_info_t	*pmportinfo = NULL;
13892 	uint8_t cport, pmport, qual;
13893 	int rv = 0;
13894 
13895 	cport = sata_device->satadev_addr.cport;
13896 	pmport = sata_device->satadev_addr.pmport;
13897 	qual = sata_device->satadev_addr.qual;
13898 
13899 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13900 	if (qual == SATA_ADDR_DCPORT)
13901 		qual = SATA_ADDR_CPORT;
13902 	else
13903 		qual = SATA_ADDR_PMPORT;
13904 
13905 	if (qual == SATA_ADDR_PMPORT)
13906 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13907 
13908 	/*
13909 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
13910 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
13911 	 * Perform sanity check now.
13912 	 */
13913 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
13914 		/* No physical port activation supported. */
13915 		return (EINVAL);
13916 	}
13917 
13918 	/* Just ask HBA driver to activate port */
13919 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
13920 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
13921 		/*
13922 		 * Port activation failure.
13923 		 */
13924 		if (qual == SATA_ADDR_CPORT) {
13925 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13926 			    cport)->cport_mutex);
13927 			sata_update_port_info(sata_hba_inst, sata_device);
13928 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13929 				SATA_CPORT_STATE(sata_hba_inst, cport) =
13930 				    SATA_PSTATE_FAILED;
13931 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13932 				    "sata_hba_ioctl: connect: failed to "
13933 				    "activate SATA port %d", cport);
13934 			}
13935 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13936 			    cport)->cport_mutex);
13937 		} else { /* port multiplier device port */
13938 			mutex_enter(&pmportinfo->pmport_mutex);
13939 			sata_update_pmport_info(sata_hba_inst, sata_device);
13940 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13941 				SATA_PMPORT_STATE(sata_hba_inst, cport,
13942 				    pmport) = SATA_PSTATE_FAILED;
13943 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13944 				    "sata_hba_ioctl: connect: failed to "
13945 				    "activate SATA port %d:%d", cport, pmport);
13946 			}
13947 			mutex_exit(&pmportinfo->pmport_mutex);
13948 		}
13949 		return (EIO);
13950 	}
13951 
13952 	/* Virgin port state - will be updated by the port re-probe. */
13953 	if (qual == SATA_ADDR_CPORT) {
13954 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13955 		    cport)->cport_mutex);
13956 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
13957 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13958 		    cport)->cport_mutex);
13959 	} else { /* port multiplier device port */
13960 		mutex_enter(&pmportinfo->pmport_mutex);
13961 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
13962 		mutex_exit(&pmportinfo->pmport_mutex);
13963 	}
13964 
13965 	/*
13966 	 * Probe the port to find its state and attached device.
13967 	 */
13968 	if (sata_reprobe_port(sata_hba_inst, sata_device,
13969 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
13970 		rv = EIO;
13971 
13972 	/*
13973 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13974 	 * without the hint
13975 	 */
13976 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13977 	    SE_NO_HINT);
13978 
13979 	/*
13980 	 * If there is a device attached to the port, emit
13981 	 * a message.
13982 	 */
13983 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
13984 
13985 		if (qual == SATA_ADDR_CPORT) {
13986 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
13987 				sata_log(sata_hba_inst, CE_WARN,
13988 				    "SATA port multiplier detected "
13989 				    "at port %d", cport);
13990 			} else {
13991 				sata_log(sata_hba_inst, CE_WARN,
13992 				    "SATA device detected at port %d", cport);
13993 				if (sata_device->satadev_type ==
13994 				    SATA_DTYPE_UNKNOWN) {
13995 				/*
13996 				 * A device was not successfully identified
13997 				 */
13998 				sata_log(sata_hba_inst, CE_WARN,
13999 				    "Could not identify SATA "
14000 				    "device at port %d", cport);
14001 				}
14002 			}
14003 		} else { /* port multiplier device port */
14004 			sata_log(sata_hba_inst, CE_WARN,
14005 			    "SATA device detected at port %d:%d",
14006 			    cport, pmport);
14007 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14008 				/*
14009 				 * A device was not successfully identified
14010 				 */
14011 				sata_log(sata_hba_inst, CE_WARN,
14012 				    "Could not identify SATA "
14013 				    "device at port %d:%d", cport, pmport);
14014 			}
14015 		}
14016 	}
14017 
14018 	return (rv);
14019 }
14020 
14021 
14022 /*
14023  * Process sata device unconfigure request.
14024  * The unconfigure operation uses generic nexus operation to
14025  * offline a device. It leaves a target device node attached.
14026  * and obviously sata_drive_info attached as well, because
14027  * from the hardware point of view nothing has changed.
14028  */
14029 static int
14030 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14031     sata_device_t *sata_device)
14032 {
14033 	int rv = 0;
14034 	dev_info_t *tdip;
14035 
14036 	/* We are addressing attached device, not a port */
14037 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14038 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14039 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14040 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14041 
14042 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14043 	    &sata_device->satadev_addr)) != NULL) {
14044 
14045 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14046 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14047 			    "sata_hba_ioctl: unconfigure: "
14048 			    "failed to unconfigure device at SATA port %d:%d",
14049 			    sata_device->satadev_addr.cport,
14050 			    sata_device->satadev_addr.pmport));
14051 			rv = EIO;
14052 		}
14053 		/*
14054 		 * The target node devi_state should be marked with
14055 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14056 		 * This would be the indication for cfgadm that
14057 		 * the AP node occupant state is 'unconfigured'.
14058 		 */
14059 
14060 	} else {
14061 		/*
14062 		 * This would indicate a failure on the part of cfgadm
14063 		 * to detect correct state of the node prior to this
14064 		 * call - one cannot unconfigure non-existing device.
14065 		 */
14066 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14067 		    "sata_hba_ioctl: unconfigure: "
14068 		    "attempt to unconfigure non-existing device "
14069 		    "at SATA port %d:%d",
14070 		    sata_device->satadev_addr.cport,
14071 		    sata_device->satadev_addr.pmport));
14072 		rv = ENXIO;
14073 	}
14074 	return (rv);
14075 }
14076 
14077 /*
14078  * Process sata device configure request
14079  * If port is in a failed state, operation is aborted - one has to use
14080  * an explicit connect or port activate request to try to get a port into
14081  * non-failed mode. Port reset wil also work in such situation.
14082  * If the port is in disconnected (shutdown) state, the connect operation is
14083  * attempted prior to any other action.
14084  * When port is in the active state, there is a device attached and the target
14085  * node exists, a device was most likely offlined.
14086  * If target node does not exist, a new target node is created. In both cases
14087  * an attempt is made to online (configure) the device.
14088  *
14089  * NOTE: Port multiplier is supported.
14090  */
14091 static int
14092 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14093     sata_device_t *sata_device)
14094 {
14095 	int cport, pmport, qual;
14096 	int rval;
14097 	boolean_t target = TRUE;
14098 	sata_cport_info_t *cportinfo;
14099 	sata_pmport_info_t *pmportinfo = NULL;
14100 	dev_info_t *tdip;
14101 	sata_drive_info_t *sdinfo;
14102 
14103 	cport = sata_device->satadev_addr.cport;
14104 	pmport = sata_device->satadev_addr.pmport;
14105 	qual = sata_device->satadev_addr.qual;
14106 
14107 	/* Get current port state */
14108 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14109 	    (SATA_DIP(sata_hba_inst), sata_device);
14110 
14111 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14112 	if (qual == SATA_ADDR_DPMPORT) {
14113 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14114 		mutex_enter(&pmportinfo->pmport_mutex);
14115 		sata_update_pmport_info(sata_hba_inst, sata_device);
14116 		if (rval != SATA_SUCCESS ||
14117 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14118 			/*
14119 			 * Obviously, device on a failed port is not visible
14120 			 */
14121 			mutex_exit(&pmportinfo->pmport_mutex);
14122 			return (ENXIO);
14123 		}
14124 		mutex_exit(&pmportinfo->pmport_mutex);
14125 	} else {
14126 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14127 		    cport)->cport_mutex);
14128 		sata_update_port_info(sata_hba_inst, sata_device);
14129 		if (rval != SATA_SUCCESS ||
14130 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14131 			/*
14132 			 * Obviously, device on a failed port is not visible
14133 			 */
14134 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14135 			    cport)->cport_mutex);
14136 			return (ENXIO);
14137 		}
14138 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14139 		    cport)->cport_mutex);
14140 	}
14141 
14142 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
14143 		/* need to activate port */
14144 		target = FALSE;
14145 
14146 		/* Sanity check */
14147 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14148 			return (ENXIO);
14149 
14150 		/* Just let HBA driver to activate port */
14151 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14152 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14153 			/*
14154 			 * Port activation failure - do not change port state
14155 			 * unless the state returned by HBA indicates a port
14156 			 * failure.
14157 			 */
14158 			if (qual == SATA_ADDR_DPMPORT) {
14159 				mutex_enter(&pmportinfo->pmport_mutex);
14160 				sata_update_pmport_info(sata_hba_inst,
14161 				    sata_device);
14162 				if (sata_device->satadev_state &
14163 				    SATA_PSTATE_FAILED)
14164 					pmportinfo->pmport_state =
14165 					    SATA_PSTATE_FAILED;
14166 				mutex_exit(&pmportinfo->pmport_mutex);
14167 			} else {
14168 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14169 				    cport)->cport_mutex);
14170 				sata_update_port_info(sata_hba_inst,
14171 				    sata_device);
14172 				if (sata_device->satadev_state &
14173 				    SATA_PSTATE_FAILED)
14174 					cportinfo->cport_state =
14175 					    SATA_PSTATE_FAILED;
14176 				mutex_exit(&SATA_CPORT_INFO(
14177 				    sata_hba_inst, cport)->cport_mutex);
14178 			}
14179 		}
14180 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14181 		    "sata_hba_ioctl: configure: "
14182 		    "failed to activate SATA port %d:%d",
14183 		    cport, pmport));
14184 		return (EIO);
14185 	}
14186 	/*
14187 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14188 	 * without the hint.
14189 	 */
14190 	sata_gen_sysevent(sata_hba_inst,
14191 	    &sata_device->satadev_addr, SE_NO_HINT);
14192 
14193 	/* Virgin port state */
14194 	if (qual == SATA_ADDR_DPMPORT) {
14195 		mutex_enter(&pmportinfo->pmport_mutex);
14196 		pmportinfo->pmport_state = 0;
14197 		mutex_exit(&pmportinfo->pmport_mutex);
14198 	} else {
14199 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14200 		    cport)-> cport_mutex);
14201 		cportinfo->cport_state = 0;
14202 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14203 		    cport)->cport_mutex);
14204 	}
14205 	/*
14206 	 * Always reprobe port, to get current device info.
14207 	 */
14208 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14209 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14210 		return (EIO);
14211 
14212 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
14213 		if (qual == SATA_ADDR_DPMPORT) {
14214 			/*
14215 			 * That's the transition from "inactive" port
14216 			 * to active one with device attached.
14217 			 */
14218 			sata_log(sata_hba_inst, CE_WARN,
14219 			    "SATA device detected at port %d:%d",
14220 			    cport, pmport);
14221 		} else {
14222 			/*
14223 			 * When PM is attached to the cport and cport is
14224 			 * activated, every PM device port needs to be reprobed.
14225 			 * We need to emit message for all devices detected
14226 			 * at port multiplier's device ports.
14227 			 * Add such code here.
14228 			 * For now, just inform about device attached to
14229 			 * cport.
14230 			 */
14231 			sata_log(sata_hba_inst, CE_WARN,
14232 			    "SATA device detected at port %d", cport);
14233 		}
14234 	}
14235 
14236 	/*
14237 	 * This is where real configuration operation starts.
14238 	 *
14239 	 * When PM is attached to the cport and cport is activated,
14240 	 * devices attached PM device ports may have to be configured
14241 	 * explicitly. This may change when port multiplier is supported.
14242 	 * For now, configure only disks and other valid target devices.
14243 	 */
14244 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
14245 		if (qual == SATA_ADDR_DCPORT) {
14246 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14247 				/*
14248 				 * A device was not successfully identified
14249 				 */
14250 				sata_log(sata_hba_inst, CE_WARN,
14251 				    "Could not identify SATA "
14252 				    "device at port %d", cport);
14253 			}
14254 		} else { /* port multiplier device port */
14255 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14256 				/*
14257 				 * A device was not successfully identified
14258 				 */
14259 				sata_log(sata_hba_inst, CE_WARN,
14260 				    "Could not identify SATA "
14261 				    "device at port %d:%d", cport, pmport);
14262 			}
14263 		}
14264 		return (ENXIO);		/* No device to configure */
14265 	}
14266 
14267 	/*
14268 	 * Here we may have a device in reset condition,
14269 	 * but because we are just configuring it, there is
14270 	 * no need to process the reset other than just
14271 	 * to clear device reset condition in the HBA driver.
14272 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
14273 	 * cause a first command sent the HBA driver with the request
14274 	 * to clear device reset condition.
14275 	 */
14276 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14277 	if (qual == SATA_ADDR_DPMPORT)
14278 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14279 	else
14280 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14281 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14282 	if (sdinfo == NULL) {
14283 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14284 		return (ENXIO);
14285 	}
14286 	if (sdinfo->satadrv_event_flags &
14287 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14288 		sdinfo->satadrv_event_flags = 0;
14289 	}
14290 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14291 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14292 
14293 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14294 	    &sata_device->satadev_addr)) != NULL) {
14295 		/*
14296 		 * Target node exists. Verify, that it belongs
14297 		 * to existing, attached device and not to
14298 		 * a removed device.
14299 		 */
14300 		if (sata_check_device_removed(tdip) == B_TRUE) {
14301 			if (qual == SATA_ADDR_DPMPORT)
14302 				sata_log(sata_hba_inst, CE_WARN,
14303 				    "SATA device at port %d cannot be "
14304 				    "configured. "
14305 				    "Application(s) accessing "
14306 				    "previously attached device "
14307 				    "have to release it before newly "
14308 				    "inserted device can be made accessible.",
14309 				    cport);
14310 			else
14311 				sata_log(sata_hba_inst, CE_WARN,
14312 				    "SATA device at port %d:%d cannot be"
14313 				    "configured. "
14314 				    "Application(s) accessing "
14315 				    "previously attached device "
14316 				    "have to release it before newly "
14317 				    "inserted device can be made accessible.",
14318 				    cport, pmport);
14319 			return (EIO);
14320 		}
14321 		/*
14322 		 * Device was not removed and re-inserted.
14323 		 * Try to online it.
14324 		 */
14325 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
14326 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14327 			    "sata_hba_ioctl: configure: "
14328 			    "onlining device at SATA port "
14329 			    "%d:%d failed", cport, pmport));
14330 			return (EIO);
14331 		}
14332 
14333 		if (qual == SATA_ADDR_DPMPORT) {
14334 			mutex_enter(&pmportinfo->pmport_mutex);
14335 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14336 			mutex_exit(&pmportinfo->pmport_mutex);
14337 		} else {
14338 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14339 			    cport)->cport_mutex);
14340 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14341 			mutex_exit(&SATA_CPORT_INFO(
14342 			    sata_hba_inst, cport)->cport_mutex);
14343 		}
14344 	} else {
14345 		/*
14346 		 * No target node - need to create a new target node.
14347 		 */
14348 		if (qual == SATA_ADDR_DPMPORT) {
14349 			mutex_enter(&pmportinfo->pmport_mutex);
14350 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14351 			mutex_exit(&pmportinfo->pmport_mutex);
14352 		} else {
14353 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14354 			    cport_mutex);
14355 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14356 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14357 			    cport_mutex);
14358 		}
14359 
14360 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
14361 		    sata_hba_inst, &sata_device->satadev_addr);
14362 		if (tdip == NULL) {
14363 			/* Configure operation failed */
14364 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14365 			    "sata_hba_ioctl: configure: "
14366 			    "configuring SATA device at port %d:%d "
14367 			    "failed", cport, pmport));
14368 			return (EIO);
14369 		}
14370 	}
14371 	return (0);
14372 }
14373 
14374 
14375 /*
14376  * Process ioctl deactivate port request.
14377  * Arbitrarily unconfigure attached device, if any.
14378  * Even if the unconfigure fails, proceed with the
14379  * port deactivation.
14380  *
14381  * NOTE: Port Multiplier is supported now.
14382  */
14383 
14384 static int
14385 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
14386     sata_device_t *sata_device)
14387 {
14388 	int cport, pmport, qual;
14389 	int rval, rv = 0;
14390 	int npmport;
14391 	sata_cport_info_t *cportinfo;
14392 	sata_pmport_info_t *pmportinfo;
14393 	sata_pmult_info_t *pmultinfo;
14394 	dev_info_t *tdip;
14395 	sata_drive_info_t *sdinfo = NULL;
14396 	sata_device_t subsdevice;
14397 
14398 	/* Sanity check */
14399 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
14400 		return (ENOTSUP);
14401 
14402 	cport = sata_device->satadev_addr.cport;
14403 	pmport = sata_device->satadev_addr.pmport;
14404 	qual = sata_device->satadev_addr.qual;
14405 
14406 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
14407 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14408 	if (qual == SATA_ADDR_DCPORT)
14409 		qual = SATA_ADDR_CPORT;
14410 	else
14411 		qual = SATA_ADDR_PMPORT;
14412 
14413 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14414 	if (qual == SATA_ADDR_PMPORT)
14415 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14416 
14417 	/*
14418 	 * Processing port multiplier
14419 	 */
14420 	if (qual == SATA_ADDR_CPORT &&
14421 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14422 		mutex_enter(&cportinfo->cport_mutex);
14423 
14424 		/* Deactivate all sub-deices */
14425 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14426 		if (pmultinfo != NULL) {
14427 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14428 			    sata_hba_inst, cport); npmport++) {
14429 
14430 				subsdevice.satadev_addr.cport = cport;
14431 				subsdevice.satadev_addr.pmport =
14432 				    (uint8_t)npmport;
14433 				subsdevice.satadev_addr.qual =
14434 				    SATA_ADDR_DPMPORT;
14435 
14436 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14437 				    "sata_hba_ioctl: deactivate: trying to "
14438 				    "deactivate SATA port %d:%d",
14439 				    cport, npmport);
14440 
14441 				mutex_exit(&cportinfo->cport_mutex);
14442 				if (sata_ioctl_deactivate(sata_hba_inst,
14443 				    &subsdevice) == SATA_SUCCESS) {
14444 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14445 					    "[Deactivate] device at port %d:%d "
14446 					    "successfully.", cport, npmport);
14447 				}
14448 				mutex_enter(&cportinfo->cport_mutex);
14449 			}
14450 		}
14451 
14452 		/* Deactivate the port multiplier now. */
14453 		cportinfo->cport_state &= ~SATA_STATE_READY;
14454 		mutex_exit(&cportinfo->cport_mutex);
14455 
14456 		sata_device->satadev_addr.qual = qual;
14457 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14458 		    (SATA_DIP(sata_hba_inst), sata_device);
14459 
14460 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14461 		    SE_NO_HINT);
14462 
14463 		mutex_enter(&cportinfo->cport_mutex);
14464 		sata_update_port_info(sata_hba_inst, sata_device);
14465 		if (rval != SATA_SUCCESS) {
14466 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14467 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14468 			}
14469 			rv = EIO;
14470 		} else {
14471 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14472 		}
14473 		mutex_exit(&cportinfo->cport_mutex);
14474 
14475 		return (rv);
14476 	}
14477 
14478 	/*
14479 	 * Process non-port-multiplier device - it could be a drive connected
14480 	 * to a port multiplier port or a controller port.
14481 	 */
14482 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14483 	if (qual == SATA_ADDR_CPORT) {
14484 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14485 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14486 			/* deal only with valid devices */
14487 			if ((cportinfo->cport_dev_type &
14488 			    SATA_VALID_DEV_TYPE) != 0)
14489 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14490 		}
14491 		cportinfo->cport_state &= ~SATA_STATE_READY;
14492 	} else {
14493 		/* Port multiplier device port */
14494 		mutex_enter(&pmportinfo->pmport_mutex);
14495 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14496 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
14497 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
14498 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
14499 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14500 		mutex_exit(&pmportinfo->pmport_mutex);
14501 	}
14502 
14503 	if (sdinfo != NULL) {
14504 		/*
14505 		 * If a target node exists, try to offline a device and
14506 		 * to remove a target node.
14507 		 */
14508 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14509 		    cport_mutex);
14510 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14511 		    &sata_device->satadev_addr);
14512 		if (tdip != NULL) {
14513 			/* target node exist */
14514 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14515 			    "sata_hba_ioctl: port deactivate: "
14516 			    "target node exists.", NULL);
14517 
14518 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
14519 			    NDI_SUCCESS) {
14520 				SATA_LOG_D((sata_hba_inst, CE_WARN,
14521 				    "sata_hba_ioctl: port deactivate: "
14522 				    "failed to unconfigure device at port "
14523 				    "%d:%d before deactivating the port",
14524 				    cport, pmport));
14525 				/*
14526 				 * Set DEVICE REMOVED state in the target
14527 				 * node. It will prevent an access to
14528 				 * the device even when a new device is
14529 				 * attached, until the old target node is
14530 				 * released, removed and recreated for a new
14531 				 * device.
14532 				 */
14533 				sata_set_device_removed(tdip);
14534 
14535 				/*
14536 				 * Instruct the event daemon to try the
14537 				 * target node cleanup later.
14538 				 */
14539 				sata_set_target_node_cleanup(sata_hba_inst,
14540 				    &sata_device->satadev_addr);
14541 			}
14542 		}
14543 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14544 		    cport_mutex);
14545 		/*
14546 		 * In any case, remove and release sata_drive_info
14547 		 * structure.
14548 		 */
14549 		if (qual == SATA_ADDR_CPORT) {
14550 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14551 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14552 		} else { /* port multiplier device port */
14553 			mutex_enter(&pmportinfo->pmport_mutex);
14554 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14555 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14556 			mutex_exit(&pmportinfo->pmport_mutex);
14557 		}
14558 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
14559 	}
14560 
14561 	if (qual == SATA_ADDR_CPORT) {
14562 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
14563 		    SATA_STATE_PROBING);
14564 	} else if (qual == SATA_ADDR_PMPORT) {
14565 		mutex_enter(&pmportinfo->pmport_mutex);
14566 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
14567 		    SATA_STATE_PROBING);
14568 		mutex_exit(&pmportinfo->pmport_mutex);
14569 	}
14570 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14571 
14572 	/* Just let HBA driver to deactivate port */
14573 	sata_device->satadev_addr.qual = qual;
14574 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14575 	    (SATA_DIP(sata_hba_inst), sata_device);
14576 
14577 	/*
14578 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14579 	 * without the hint
14580 	 */
14581 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14582 	    SE_NO_HINT);
14583 
14584 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14585 	sata_update_port_info(sata_hba_inst, sata_device);
14586 	if (qual == SATA_ADDR_CPORT) {
14587 		if (rval != SATA_SUCCESS) {
14588 			/*
14589 			 * Port deactivation failure - do not change port state
14590 			 * unless the state returned by HBA indicates a port
14591 			 * failure.
14592 			 */
14593 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14594 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14595 				    SATA_PSTATE_FAILED;
14596 			}
14597 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14598 			    "sata_hba_ioctl: port deactivate: "
14599 			    "cannot deactivate SATA port %d", cport));
14600 			rv = EIO;
14601 		} else {
14602 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14603 		}
14604 	} else {
14605 		mutex_enter(&pmportinfo->pmport_mutex);
14606 		if (rval != SATA_SUCCESS) {
14607 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14608 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14609 				    pmport) = SATA_PSTATE_FAILED;
14610 			}
14611 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14612 			    "sata_hba_ioctl: port deactivate: "
14613 			    "cannot deactivate SATA port %d:%d",
14614 			    cport, pmport));
14615 			rv = EIO;
14616 		} else {
14617 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14618 		}
14619 		mutex_exit(&pmportinfo->pmport_mutex);
14620 	}
14621 
14622 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14623 
14624 	return (rv);
14625 }
14626 
14627 /*
14628  * Process ioctl port activate request.
14629  *
14630  * NOTE: Port multiplier is supported now.
14631  */
14632 static int
14633 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
14634     sata_device_t *sata_device)
14635 {
14636 	int cport, pmport, qual;
14637 	sata_cport_info_t *cportinfo;
14638 	sata_pmport_info_t *pmportinfo = NULL;
14639 	boolean_t dev_existed = TRUE;
14640 
14641 	/* Sanity check */
14642 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14643 		return (ENOTSUP);
14644 
14645 	cport = sata_device->satadev_addr.cport;
14646 	pmport = sata_device->satadev_addr.pmport;
14647 	qual = sata_device->satadev_addr.qual;
14648 
14649 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14650 
14651 	/*
14652 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14653 	 * is a device. But what we are dealing with is port/pmport.
14654 	 */
14655 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14656 	if (qual == SATA_ADDR_DCPORT)
14657 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14658 	else
14659 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14660 
14661 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14662 	if (qual == SATA_ADDR_PMPORT) {
14663 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14664 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
14665 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
14666 			dev_existed = FALSE;
14667 	} else { /* cport */
14668 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
14669 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
14670 			dev_existed = FALSE;
14671 	}
14672 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14673 
14674 	/* Just let HBA driver to activate port, if necessary */
14675 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14676 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14677 		/*
14678 		 * Port activation failure - do not change port state unless
14679 		 * the state returned by HBA indicates a port failure.
14680 		 */
14681 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14682 		    cport)->cport_mutex);
14683 		sata_update_port_info(sata_hba_inst, sata_device);
14684 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14685 			if (qual == SATA_ADDR_PMPORT) {
14686 				mutex_enter(&pmportinfo->pmport_mutex);
14687 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14688 				mutex_exit(&pmportinfo->pmport_mutex);
14689 			} else
14690 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14691 
14692 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14693 			    cport)->cport_mutex);
14694 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14695 			    "sata_hba_ioctl: port activate: cannot activate "
14696 			    "SATA port %d:%d", cport, pmport));
14697 			return (EIO);
14698 		}
14699 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14700 	}
14701 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14702 	if (qual == SATA_ADDR_PMPORT) {
14703 		mutex_enter(&pmportinfo->pmport_mutex);
14704 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
14705 		mutex_exit(&pmportinfo->pmport_mutex);
14706 	} else
14707 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
14708 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14709 
14710 	/*
14711 	 * Re-probe port to find its current state and possibly attached device.
14712 	 * Port re-probing may change the cportinfo device type if device is
14713 	 * found attached.
14714 	 * If port probing failed, the device type would be set to
14715 	 * SATA_DTYPE_NONE.
14716 	 */
14717 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
14718 	    SATA_DEV_IDENTIFY_RETRY);
14719 
14720 	/*
14721 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14722 	 * without the hint.
14723 	 */
14724 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14725 	    SE_NO_HINT);
14726 
14727 	if (dev_existed == FALSE) {
14728 		if (qual == SATA_ADDR_PMPORT &&
14729 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14730 			/*
14731 			 * That's the transition from the "inactive" port state
14732 			 * or the active port without a device attached to the
14733 			 * active port state with a device attached.
14734 			 */
14735 			sata_log(sata_hba_inst, CE_WARN,
14736 			    "SATA device detected at port %d:%d",
14737 			    cport, pmport);
14738 		} else if (qual == SATA_ADDR_CPORT &&
14739 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14740 			/*
14741 			 * That's the transition from the "inactive" port state
14742 			 * or the active port without a device attached to the
14743 			 * active port state with a device attached.
14744 			 */
14745 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
14746 				sata_log(sata_hba_inst, CE_WARN,
14747 				    "SATA device detected at port %d", cport);
14748 			} else {
14749 				sata_log(sata_hba_inst, CE_WARN,
14750 				    "SATA port multiplier detected at port %d",
14751 				    cport);
14752 			}
14753 		}
14754 	}
14755 	return (0);
14756 }
14757 
14758 
14759 
14760 /*
14761  * Process ioctl reset port request.
14762  *
14763  * NOTE: Port-Multiplier is supported.
14764  */
14765 static int
14766 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
14767     sata_device_t *sata_device)
14768 {
14769 	int cport, pmport, qual;
14770 	int rv = 0;
14771 
14772 	cport = sata_device->satadev_addr.cport;
14773 	pmport = sata_device->satadev_addr.pmport;
14774 	qual = sata_device->satadev_addr.qual;
14775 
14776 	/*
14777 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14778 	 * is a device. But what we are dealing with is port/pmport.
14779 	 */
14780 	if (qual == SATA_ADDR_DCPORT)
14781 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14782 	else
14783 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14784 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
14785 
14786 	/* Sanity check */
14787 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14788 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14789 		    "sata_hba_ioctl: sata_hba_tran missing required "
14790 		    "function sata_tran_reset_dport"));
14791 		return (ENOTSUP);
14792 	}
14793 
14794 	/* Ask HBA to reset port */
14795 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
14796 	    sata_device) != SATA_SUCCESS) {
14797 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14798 		    "sata_hba_ioctl: reset port: failed %d:%d",
14799 		    cport, pmport));
14800 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14801 		    cport_mutex);
14802 		sata_update_port_info(sata_hba_inst, sata_device);
14803 		if (qual == SATA_ADDR_CPORT)
14804 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14805 			    SATA_PSTATE_FAILED;
14806 		else {
14807 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14808 			    pmport));
14809 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14810 			    SATA_PSTATE_FAILED;
14811 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14812 			    pmport));
14813 		}
14814 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14815 		    cport_mutex);
14816 		rv = EIO;
14817 	}
14818 	/*
14819 	 * Beacuse the port was reset, it should be probed and
14820 	 * attached device reinitialized. At this point the
14821 	 * port state is unknown - it's state is HBA-specific.
14822 	 * Re-probe port to get its state.
14823 	 */
14824 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14825 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
14826 		rv = EIO;
14827 	}
14828 	return (rv);
14829 }
14830 
14831 /*
14832  * Process ioctl reset device request.
14833  *
14834  * NOTE: Port multiplier is supported.
14835  */
14836 static int
14837 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
14838     sata_device_t *sata_device)
14839 {
14840 	sata_drive_info_t *sdinfo = NULL;
14841 	sata_pmult_info_t *pmultinfo = NULL;
14842 	int cport, pmport;
14843 	int rv = 0;
14844 
14845 	/* Sanity check */
14846 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14847 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14848 		    "sata_hba_ioctl: sata_hba_tran missing required "
14849 		    "function sata_tran_reset_dport"));
14850 		return (ENOTSUP);
14851 	}
14852 
14853 	cport = sata_device->satadev_addr.cport;
14854 	pmport = sata_device->satadev_addr.pmport;
14855 
14856 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14857 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
14858 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
14859 		    SATA_DTYPE_PMULT)
14860 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
14861 			    cport_devp.cport_sata_pmult;
14862 		else
14863 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
14864 			    sata_device->satadev_addr.cport);
14865 	} else { /* port multiplier */
14866 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14867 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
14868 		    sata_device->satadev_addr.cport,
14869 		    sata_device->satadev_addr.pmport);
14870 	}
14871 	if (sdinfo == NULL && pmultinfo == NULL) {
14872 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14873 		return (EINVAL);
14874 	}
14875 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14876 
14877 	/* Ask HBA to reset device */
14878 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
14879 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14880 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14881 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
14882 		    cport, pmport));
14883 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14884 		    cport_mutex);
14885 		sata_update_port_info(sata_hba_inst, sata_device);
14886 		/*
14887 		 * Device info structure remains attached. Another device reset
14888 		 * or port disconnect/connect and re-probing is
14889 		 * needed to change it's state
14890 		 */
14891 		if (sdinfo != NULL) {
14892 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
14893 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
14894 		} else if (pmultinfo != NULL) {
14895 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
14896 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
14897 		}
14898 
14899 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14900 		rv = EIO;
14901 	}
14902 	/*
14903 	 * If attached device was a port multiplier, some extra processing
14904 	 * may be needed to bring it back. SATA specification requies a
14905 	 * mandatory software reset on host port to reliably enumerate a port
14906 	 * multiplier, the HBA driver should handle that after reset
14907 	 * operation.
14908 	 */
14909 	return (rv);
14910 }
14911 
14912 
14913 /*
14914  * Process ioctl reset all request.
14915  */
14916 static int
14917 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
14918 {
14919 	sata_device_t sata_device;
14920 	int rv = 0;
14921 	int tcport;
14922 	int tpmport = 0;
14923 
14924 	sata_device.satadev_rev = SATA_DEVICE_REV;
14925 
14926 	/*
14927 	 * There is no protection here for configured devices.
14928 	 */
14929 	/* Sanity check */
14930 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14931 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14932 		    "sata_hba_ioctl: sata_hba_tran missing required "
14933 		    "function sata_tran_reset_dport"));
14934 		return (ENOTSUP);
14935 	}
14936 
14937 	/*
14938 	 * Need to lock all ports, not just one.
14939 	 * If any port is locked by event processing, fail the whole operation.
14940 	 * One port is already locked, but for simplicity lock it again.
14941 	 */
14942 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
14943 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14944 		    cport_mutex);
14945 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
14946 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
14947 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14948 			    cport_mutex);
14949 			rv = EBUSY;
14950 			break;
14951 		} else {
14952 			/*
14953 			 * It is enough to lock cport in command-based
14954 			 * switching mode.
14955 			 */
14956 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
14957 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
14958 		}
14959 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14960 		    cport_mutex);
14961 	}
14962 
14963 	if (rv == 0) {
14964 		/*
14965 		 * All cports were successfully locked.
14966 		 * Reset main SATA controller.
14967 		 * Set the device address to port 0, to have a valid device
14968 		 * address.
14969 		 */
14970 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
14971 		sata_device.satadev_addr.cport = 0;
14972 		sata_device.satadev_addr.pmport = 0;
14973 
14974 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
14975 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
14976 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14977 			    "sata_hba_ioctl: reset controller failed"));
14978 			return (EIO);
14979 		}
14980 		/*
14981 		 * Because ports were reset, port states are unknown.
14982 		 * They should be re-probed to get their state and
14983 		 * attached devices should be reinitialized.
14984 		 */
14985 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
14986 		    tcport++) {
14987 			sata_device.satadev_addr.cport = tcport;
14988 			sata_device.satadev_addr.pmport = tpmport;
14989 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
14990 
14991 			/*
14992 			 * The sata_reprobe_port() will mark a
14993 			 * SATA_EVNT_DEVICE_RESET event on the port
14994 			 * multiplier, all its sub-ports will be probed by
14995 			 * sata daemon afterwards.
14996 			 */
14997 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
14998 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14999 				rv = EIO;
15000 		}
15001 	}
15002 	/*
15003 	 * Unlock all ports
15004 	 */
15005 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15006 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15007 		    cport_mutex);
15008 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
15009 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
15010 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15011 		    cport_mutex);
15012 	}
15013 
15014 	/*
15015 	 * This operation returns EFAULT if either reset
15016 	 * controller failed or a re-probing of any port failed.
15017 	 */
15018 	return (rv);
15019 }
15020 
15021 
15022 /*
15023  * Process ioctl port self test request.
15024  *
15025  * NOTE: Port multiplier code is not completed nor tested.
15026  */
15027 static int
15028 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15029     sata_device_t *sata_device)
15030 {
15031 	int cport, pmport, qual;
15032 	int rv = 0;
15033 
15034 	/* Sanity check */
15035 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15036 		return (ENOTSUP);
15037 
15038 	cport = sata_device->satadev_addr.cport;
15039 	pmport = sata_device->satadev_addr.pmport;
15040 	qual = sata_device->satadev_addr.qual;
15041 
15042 	/*
15043 	 * There is no protection here for a configured
15044 	 * device attached to this port.
15045 	 */
15046 
15047 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15048 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15049 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15050 		    "sata_hba_ioctl: port selftest: "
15051 		    "failed port %d:%d", cport, pmport));
15052 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15053 		    cport_mutex);
15054 		sata_update_port_info(sata_hba_inst, sata_device);
15055 		if (qual == SATA_ADDR_CPORT)
15056 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15057 			    SATA_PSTATE_FAILED;
15058 		else { /* port multiplier device port */
15059 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15060 			    cport, pmport));
15061 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15062 			    SATA_PSTATE_FAILED;
15063 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15064 			    cport, pmport));
15065 		}
15066 
15067 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15068 		    cport_mutex);
15069 		return (EIO);
15070 	}
15071 	/*
15072 	 * Beacuse the port was reset in the course of testing, it should be
15073 	 * re-probed and attached device state should be restored. At this
15074 	 * point the port state is unknown - it's state is HBA-specific.
15075 	 * Force port re-probing to get it into a known state.
15076 	 */
15077 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15078 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15079 		rv = EIO;
15080 	return (rv);
15081 }
15082 
15083 
15084 /*
15085  * sata_cfgadm_state:
15086  * Use the sata port state and state of the target node to figure out
15087  * the cfgadm_state.
15088  *
15089  * The port argument is a value with encoded cport,
15090  * pmport and address qualifier, in the same manner as a scsi target number.
15091  * SCSI_TO_SATA_CPORT macro extracts cport number,
15092  * SCSI_TO_SATA_PMPORT extracts pmport number and
15093  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15094  *
15095  * Port multiplier is supported.
15096  */
15097 
15098 static void
15099 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15100     devctl_ap_state_t *ap_state)
15101 {
15102 	uint8_t		cport, pmport, qual;
15103 	uint32_t	port_state, pmult_state;
15104 	uint32_t	dev_type;
15105 	sata_drive_info_t *sdinfo;
15106 
15107 	cport = SCSI_TO_SATA_CPORT(port);
15108 	pmport = SCSI_TO_SATA_PMPORT(port);
15109 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15110 
15111 	/* Check cport state */
15112 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15113 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15114 	    port_state & SATA_PSTATE_FAILED) {
15115 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15116 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15117 		if (port_state & SATA_PSTATE_FAILED)
15118 			ap_state->ap_condition = AP_COND_FAILED;
15119 		else
15120 			ap_state->ap_condition = AP_COND_UNKNOWN;
15121 
15122 		return;
15123 	}
15124 
15125 	/* cport state is okay. Now check pmport state */
15126 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15127 		/* Sanity check */
15128 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15129 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15130 		    cport, pmport) == NULL)
15131 			return;
15132 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15133 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15134 		    port_state & SATA_PSTATE_FAILED) {
15135 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15136 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15137 			if (port_state & SATA_PSTATE_FAILED)
15138 				ap_state->ap_condition = AP_COND_FAILED;
15139 			else
15140 				ap_state->ap_condition = AP_COND_UNKNOWN;
15141 
15142 			return;
15143 		}
15144 	}
15145 
15146 	/* Port is enabled and ready */
15147 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15148 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15149 	else
15150 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15151 
15152 	switch (dev_type) {
15153 	case SATA_DTYPE_NONE:
15154 	{
15155 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15156 		ap_state->ap_condition = AP_COND_OK;
15157 		/* No device attached */
15158 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
15159 		break;
15160 	}
15161 	case SATA_DTYPE_PMULT:
15162 	{
15163 		/* Need to check port multiplier state */
15164 		ASSERT(qual == SATA_ADDR_DCPORT);
15165 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
15166 		    pmult_state;
15167 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
15168 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15169 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15170 			if (pmult_state & SATA_PSTATE_FAILED)
15171 				ap_state->ap_condition = AP_COND_FAILED;
15172 			else
15173 				ap_state->ap_condition = AP_COND_UNKNOWN;
15174 
15175 			return;
15176 		}
15177 
15178 		/* Port multiplier is not configurable */
15179 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
15180 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15181 		ap_state->ap_condition = AP_COND_OK;
15182 		break;
15183 	}
15184 
15185 	case SATA_DTYPE_ATADISK:
15186 	case SATA_DTYPE_ATAPICD:
15187 	case SATA_DTYPE_ATAPITAPE:
15188 	case SATA_DTYPE_ATAPIDISK:
15189 	{
15190 		dev_info_t *tdip = NULL;
15191 		dev_info_t *dip = NULL;
15192 		int circ;
15193 
15194 		dip = SATA_DIP(sata_hba_inst);
15195 		tdip = sata_get_target_dip(dip, cport, pmport);
15196 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15197 		if (tdip != NULL) {
15198 			ndi_devi_enter(dip, &circ);
15199 			mutex_enter(&(DEVI(tdip)->devi_lock));
15200 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
15201 				/*
15202 				 * There could be the case where previously
15203 				 * configured and opened device was removed
15204 				 * and unknown device was plugged.
15205 				 * In such case we want to show a device, and
15206 				 * its configured or unconfigured state but
15207 				 * indicate unusable condition untill the
15208 				 * old target node is released and removed.
15209 				 */
15210 				ap_state->ap_condition = AP_COND_UNUSABLE;
15211 			} else {
15212 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
15213 				    cport));
15214 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15215 				    cport);
15216 				if (sdinfo != NULL) {
15217 					if ((sdinfo->satadrv_state &
15218 					    SATA_DSTATE_FAILED) != 0)
15219 						ap_state->ap_condition =
15220 						    AP_COND_FAILED;
15221 					else
15222 						ap_state->ap_condition =
15223 						    AP_COND_OK;
15224 				} else {
15225 					ap_state->ap_condition =
15226 					    AP_COND_UNKNOWN;
15227 				}
15228 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
15229 				    cport));
15230 			}
15231 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
15232 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
15233 				ap_state->ap_ostate =
15234 				    AP_OSTATE_UNCONFIGURED;
15235 			} else {
15236 				ap_state->ap_ostate =
15237 				    AP_OSTATE_CONFIGURED;
15238 			}
15239 			mutex_exit(&(DEVI(tdip)->devi_lock));
15240 			ndi_devi_exit(dip, circ);
15241 		} else {
15242 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15243 			ap_state->ap_condition = AP_COND_UNKNOWN;
15244 		}
15245 		break;
15246 	}
15247 	default:
15248 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15249 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15250 		ap_state->ap_condition = AP_COND_UNKNOWN;
15251 		/*
15252 		 * This is actually internal error condition (non fatal),
15253 		 * because we have already checked all defined device types.
15254 		 */
15255 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15256 		    "sata_cfgadm_state: Internal error: "
15257 		    "unknown device type"));
15258 		break;
15259 	}
15260 }
15261 
15262 
15263 /*
15264  * Process ioctl get device path request.
15265  *
15266  * NOTE: Port multiplier has no target dip. Devices connected to port
15267  * multiplier have target node attached to the HBA node. The only difference
15268  * between them and the directly-attached device node is a target address.
15269  */
15270 static int
15271 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
15272     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15273 {
15274 	char path[MAXPATHLEN];
15275 	uint32_t size;
15276 	dev_info_t *tdip;
15277 
15278 	(void) strcpy(path, "/devices");
15279 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15280 	    &sata_device->satadev_addr)) == NULL) {
15281 		/*
15282 		 * No such device. If this is a request for a size, do not
15283 		 * return EINVAL for non-existing target, because cfgadm
15284 		 * will then indicate a meaningless ioctl failure.
15285 		 * If this is a request for a path, indicate invalid
15286 		 * argument.
15287 		 */
15288 		if (ioc->get_size == 0)
15289 			return (EINVAL);
15290 	} else {
15291 		(void) ddi_pathname(tdip, path + strlen(path));
15292 	}
15293 	size = strlen(path) + 1;
15294 
15295 	if (ioc->get_size != 0) {
15296 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
15297 		    mode) != 0)
15298 			return (EFAULT);
15299 	} else {
15300 		if (ioc->bufsiz != size)
15301 			return (EINVAL);
15302 
15303 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
15304 		    mode) != 0)
15305 			return (EFAULT);
15306 	}
15307 	return (0);
15308 }
15309 
15310 /*
15311  * Process ioctl get attachment point type request.
15312  *
15313  * NOTE: Port multiplier is supported.
15314  */
15315 static	int
15316 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
15317     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15318 {
15319 	uint32_t	type_len;
15320 	const char	*ap_type;
15321 	int		dev_type;
15322 
15323 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15324 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
15325 		    sata_device->satadev_addr.cport);
15326 	else /* pmport */
15327 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
15328 		    sata_device->satadev_addr.cport,
15329 		    sata_device->satadev_addr.pmport);
15330 
15331 	switch (dev_type) {
15332 	case SATA_DTYPE_NONE:
15333 		ap_type = "port";
15334 		break;
15335 
15336 	case SATA_DTYPE_ATADISK:
15337 	case SATA_DTYPE_ATAPIDISK:
15338 		ap_type = "disk";
15339 		break;
15340 
15341 	case SATA_DTYPE_ATAPICD:
15342 		ap_type = "cd/dvd";
15343 		break;
15344 
15345 	case SATA_DTYPE_ATAPITAPE:
15346 		ap_type = "tape";
15347 		break;
15348 
15349 	case SATA_DTYPE_PMULT:
15350 		ap_type = "sata-pmult";
15351 		break;
15352 
15353 	case SATA_DTYPE_UNKNOWN:
15354 		ap_type = "unknown";
15355 		break;
15356 
15357 	default:
15358 		ap_type = "unsupported";
15359 		break;
15360 
15361 	} /* end of dev_type switch */
15362 
15363 	type_len = strlen(ap_type) + 1;
15364 
15365 	if (ioc->get_size) {
15366 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
15367 		    mode) != 0)
15368 			return (EFAULT);
15369 	} else {
15370 		if (ioc->bufsiz != type_len)
15371 			return (EINVAL);
15372 
15373 		if (ddi_copyout((void *)ap_type, ioc->buf,
15374 		    ioc->bufsiz, mode) != 0)
15375 			return (EFAULT);
15376 	}
15377 	return (0);
15378 
15379 }
15380 
15381 /*
15382  * Process ioctl get device model info request.
15383  * This operation should return to cfgadm the device model
15384  * information string
15385  *
15386  * NOTE: Port multiplier is supported.
15387  */
15388 static	int
15389 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
15390     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15391 {
15392 	sata_drive_info_t *sdinfo;
15393 	uint32_t info_len;
15394 	char ap_info[SATA_ID_MODEL_LEN + 1];
15395 
15396 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15397 	    sata_device->satadev_addr.cport)->cport_mutex);
15398 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15399 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15400 		    sata_device->satadev_addr.cport);
15401 	else /* port multiplier */
15402 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15403 		    sata_device->satadev_addr.cport,
15404 		    sata_device->satadev_addr.pmport);
15405 	if (sdinfo == NULL) {
15406 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15407 		    sata_device->satadev_addr.cport)->cport_mutex);
15408 		return (EINVAL);
15409 	}
15410 
15411 #ifdef	_LITTLE_ENDIAN
15412 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15413 #else	/* _LITTLE_ENDIAN */
15414 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15415 #endif	/* _LITTLE_ENDIAN */
15416 
15417 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15418 	    sata_device->satadev_addr.cport)->cport_mutex);
15419 
15420 	ap_info[SATA_ID_MODEL_LEN] = '\0';
15421 
15422 	info_len = strlen(ap_info) + 1;
15423 
15424 	if (ioc->get_size) {
15425 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15426 		    mode) != 0)
15427 			return (EFAULT);
15428 	} else {
15429 		if (ioc->bufsiz < info_len)
15430 			return (EINVAL);
15431 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15432 		    mode) != 0)
15433 			return (EFAULT);
15434 	}
15435 	return (0);
15436 }
15437 
15438 
15439 /*
15440  * Process ioctl get device firmware revision info request.
15441  * This operation should return to cfgadm the device firmware revision
15442  * information string
15443  *
15444  * Port multiplier is supported.
15445  */
15446 static	int
15447 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
15448     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15449 {
15450 	sata_drive_info_t *sdinfo;
15451 	uint32_t info_len;
15452 	char ap_info[SATA_ID_FW_LEN + 1];
15453 
15454 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15455 	    sata_device->satadev_addr.cport)->cport_mutex);
15456 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15457 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15458 		    sata_device->satadev_addr.cport);
15459 	else /* port multiplier */
15460 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15461 		    sata_device->satadev_addr.cport,
15462 		    sata_device->satadev_addr.pmport);
15463 	if (sdinfo == NULL) {
15464 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15465 		    sata_device->satadev_addr.cport)->cport_mutex);
15466 		return (EINVAL);
15467 	}
15468 
15469 #ifdef	_LITTLE_ENDIAN
15470 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15471 #else	/* _LITTLE_ENDIAN */
15472 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15473 #endif	/* _LITTLE_ENDIAN */
15474 
15475 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15476 	    sata_device->satadev_addr.cport)->cport_mutex);
15477 
15478 	ap_info[SATA_ID_FW_LEN] = '\0';
15479 
15480 	info_len = strlen(ap_info) + 1;
15481 
15482 	if (ioc->get_size) {
15483 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15484 		    mode) != 0)
15485 			return (EFAULT);
15486 	} else {
15487 		if (ioc->bufsiz < info_len)
15488 			return (EINVAL);
15489 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15490 		    mode) != 0)
15491 			return (EFAULT);
15492 	}
15493 	return (0);
15494 }
15495 
15496 
15497 /*
15498  * Process ioctl get device serial number info request.
15499  * This operation should return to cfgadm the device serial number string.
15500  *
15501  * NOTE: Port multiplier is supported.
15502  */
15503 static	int
15504 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
15505     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15506 {
15507 	sata_drive_info_t *sdinfo;
15508 	uint32_t info_len;
15509 	char ap_info[SATA_ID_SERIAL_LEN + 1];
15510 
15511 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15512 	    sata_device->satadev_addr.cport)->cport_mutex);
15513 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15514 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15515 		    sata_device->satadev_addr.cport);
15516 	else /* port multiplier */
15517 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15518 		    sata_device->satadev_addr.cport,
15519 		    sata_device->satadev_addr.pmport);
15520 	if (sdinfo == NULL) {
15521 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15522 		    sata_device->satadev_addr.cport)->cport_mutex);
15523 		return (EINVAL);
15524 	}
15525 
15526 #ifdef	_LITTLE_ENDIAN
15527 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15528 #else	/* _LITTLE_ENDIAN */
15529 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15530 #endif	/* _LITTLE_ENDIAN */
15531 
15532 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15533 	    sata_device->satadev_addr.cport)->cport_mutex);
15534 
15535 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
15536 
15537 	info_len = strlen(ap_info) + 1;
15538 
15539 	if (ioc->get_size) {
15540 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15541 		    mode) != 0)
15542 			return (EFAULT);
15543 	} else {
15544 		if (ioc->bufsiz < info_len)
15545 			return (EINVAL);
15546 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15547 		    mode) != 0)
15548 			return (EFAULT);
15549 	}
15550 	return (0);
15551 }
15552 
15553 
15554 /*
15555  * Preset scsi extended sense data (to NO SENSE)
15556  * First 18 bytes of the sense data are preset to current valid sense
15557  * with a key NO SENSE data.
15558  *
15559  * Returns void
15560  */
15561 static void
15562 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
15563 {
15564 	sense->es_valid = 1;		/* Valid sense */
15565 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
15566 	sense->es_key = KEY_NO_SENSE;
15567 	sense->es_info_1 = 0;
15568 	sense->es_info_2 = 0;
15569 	sense->es_info_3 = 0;
15570 	sense->es_info_4 = 0;
15571 	sense->es_add_len = 10;	/* Additional length - replace with a def */
15572 	sense->es_cmd_info[0] = 0;
15573 	sense->es_cmd_info[1] = 0;
15574 	sense->es_cmd_info[2] = 0;
15575 	sense->es_cmd_info[3] = 0;
15576 	sense->es_add_code = 0;
15577 	sense->es_qual_code = 0;
15578 }
15579 
15580 /*
15581  * Register a legacy cmdk-style devid for the target (disk) device.
15582  *
15583  * Note: This function is called only when the HBA devinfo node has the
15584  * property "use-cmdk-devid-format" set. This property indicates that
15585  * devid compatible with old cmdk (target) driver is to be generated
15586  * for any target device attached to this controller. This will take
15587  * precedence over the devid generated by sd (target) driver.
15588  * This function is derived from cmdk_devid_setup() function in cmdk.c.
15589  */
15590 static void
15591 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
15592 {
15593 	char	*hwid;
15594 	int	modlen;
15595 	int	serlen;
15596 	int	rval;
15597 	ddi_devid_t	devid;
15598 
15599 	/*
15600 	 * device ID is a concatanation of model number, "=", serial number.
15601 	 */
15602 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
15603 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
15604 	    sizeof (sdinfo->satadrv_id.ai_model));
15605 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
15606 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
15607 	if (modlen == 0)
15608 		goto err;
15609 	hwid[modlen++] = '=';
15610 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
15611 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15612 	swab(&hwid[modlen], &hwid[modlen],
15613 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15614 	serlen = sata_check_modser(&hwid[modlen],
15615 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15616 	if (serlen == 0)
15617 		goto err;
15618 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
15619 
15620 	/* initialize/register devid */
15621 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
15622 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
15623 		rval = ddi_devid_register(dip, devid);
15624 		/*
15625 		 * Free up the allocated devid buffer.
15626 		 * NOTE: This doesn't mean unregistering devid.
15627 		 */
15628 		ddi_devid_free(devid);
15629 	}
15630 
15631 	if (rval != DDI_SUCCESS)
15632 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
15633 		    " on port %d", sdinfo->satadrv_addr.cport);
15634 err:
15635 	kmem_free(hwid, LEGACY_HWID_LEN);
15636 }
15637 
15638 /*
15639  * valid model/serial string must contain a non-zero non-space characters.
15640  * trim trailing spaces/NULLs.
15641  */
15642 static int
15643 sata_check_modser(char *buf, int buf_len)
15644 {
15645 	boolean_t ret;
15646 	char *s;
15647 	int i;
15648 	int tb;
15649 	char ch;
15650 
15651 	ret = B_FALSE;
15652 	s = buf;
15653 	for (i = 0; i < buf_len; i++) {
15654 		ch = *s++;
15655 		if (ch != ' ' && ch != '\0')
15656 			tb = i + 1;
15657 		if (ch != ' ' && ch != '\0' && ch != '0')
15658 			ret = B_TRUE;
15659 	}
15660 
15661 	if (ret == B_FALSE)
15662 		return (0); /* invalid string */
15663 
15664 	return (tb); /* return length */
15665 }
15666 
15667 /*
15668  * sata_set_drive_features function compares current device features setting
15669  * with the saved device features settings and, if there is a difference,
15670  * it restores device features setting to the previously saved state.
15671  * It also arbitrarily tries to select the highest supported DMA mode.
15672  * Device Identify or Identify Packet Device data has to be current.
15673  * At the moment read ahead and write cache are considered for all devices.
15674  * For atapi devices, Removable Media Status Notification is set in addition
15675  * to common features.
15676  *
15677  * This function cannot be called in the interrupt context (it may sleep).
15678  *
15679  * The input argument sdinfo should point to the drive info structure
15680  * to be updated after features are set. Note, that only
15681  * device (packet) identify data is updated, not the flags indicating the
15682  * supported features.
15683  *
15684  * Returns SATA_SUCCESS if successful or there was nothing to do.
15685  * Device Identify data in the drive info structure pointed to by the sdinfo
15686  * arguments is updated even when no features were set or changed.
15687  *
15688  * Returns SATA_FAILURE if device features could not be set or DMA mode
15689  * for a disk cannot be set and device identify data cannot be fetched.
15690  *
15691  * Returns SATA_RETRY if device features could not be set (other than disk
15692  * DMA mode) but the device identify data was fetched successfully.
15693  *
15694  * Note: This function may fail the port, making it inaccessible.
15695  * In such case the explicit port disconnect/connect or physical device
15696  * detach/attach is required to re-evaluate port state again.
15697  */
15698 
15699 static int
15700 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
15701     sata_drive_info_t *sdinfo, int restore)
15702 {
15703 	int rval = SATA_SUCCESS;
15704 	int rval_set;
15705 	sata_drive_info_t new_sdinfo;
15706 	char *finfo = "sata_set_drive_features: cannot";
15707 	char *finfox;
15708 	int cache_op;
15709 
15710 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
15711 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
15712 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
15713 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15714 		/*
15715 		 * Cannot get device identification - caller may retry later
15716 		 */
15717 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15718 		    "%s fetch device identify data\n", finfo);
15719 		return (SATA_FAILURE);
15720 	}
15721 	finfox = (restore != 0) ? " restore device features" :
15722 	    " initialize device features\n";
15723 
15724 	switch (sdinfo->satadrv_type) {
15725 	case SATA_DTYPE_ATADISK:
15726 		/* Arbitrarily set UDMA mode */
15727 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15728 		    SATA_SUCCESS) {
15729 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15730 			    "%s set UDMA mode\n", finfo));
15731 			return (SATA_FAILURE);
15732 		}
15733 		break;
15734 	case SATA_DTYPE_ATAPICD:
15735 	case SATA_DTYPE_ATAPITAPE:
15736 	case SATA_DTYPE_ATAPIDISK:
15737 		/*  Set Removable Media Status Notification, if necessary */
15738 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
15739 		    restore != 0) {
15740 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
15741 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
15742 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
15743 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
15744 				/* Current setting does not match saved one */
15745 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
15746 				    sdinfo->satadrv_settings &
15747 				    SATA_DEV_RMSN) != SATA_SUCCESS)
15748 					rval = SATA_FAILURE;
15749 			}
15750 		}
15751 		/*
15752 		 * We have to set Multiword DMA or UDMA, if it is supported, as
15753 		 * we want to use DMA transfer mode whenever possible.
15754 		 * Some devices require explicit setting of the DMA mode.
15755 		 */
15756 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
15757 			/* Set highest supported DMA mode */
15758 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15759 			    SATA_SUCCESS) {
15760 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15761 				    "%s set UDMA mode\n", finfo));
15762 				rval = SATA_FAILURE;
15763 			}
15764 		}
15765 		break;
15766 	}
15767 
15768 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
15769 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15770 		/*
15771 		 * neither READ AHEAD nor WRITE CACHE is supported
15772 		 * - do nothing
15773 		 */
15774 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15775 		    "settable features not supported\n", NULL);
15776 		goto update_sdinfo;
15777 	}
15778 
15779 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
15780 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
15781 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
15782 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
15783 		/*
15784 		 * both READ AHEAD and WRITE CACHE are enabled
15785 		 * - Nothing to do
15786 		 */
15787 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15788 		    "no device features to set\n", NULL);
15789 		goto update_sdinfo;
15790 	}
15791 
15792 	cache_op = 0;
15793 
15794 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
15795 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15796 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15797 			/* Enable read ahead / read cache */
15798 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
15799 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15800 			    "enabling read cache\n", NULL);
15801 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15802 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15803 			/* Disable read ahead  / read cache */
15804 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
15805 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15806 			    "disabling read cache\n", NULL);
15807 		}
15808 
15809 		if (cache_op != 0) {
15810 			/* Try to set read cache mode */
15811 			rval_set = sata_set_cache_mode(sata_hba_inst,
15812 			    &new_sdinfo, cache_op);
15813 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15814 				rval = rval_set;
15815 		}
15816 	}
15817 
15818 	cache_op = 0;
15819 
15820 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15821 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15822 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15823 			/* Enable write cache */
15824 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
15825 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15826 			    "enabling write cache\n", NULL);
15827 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15828 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15829 			/* Disable write cache */
15830 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
15831 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15832 			    "disabling write cache\n", NULL);
15833 		}
15834 
15835 		if (cache_op != 0) {
15836 			/* Try to set write cache mode */
15837 			rval_set = sata_set_cache_mode(sata_hba_inst,
15838 			    &new_sdinfo, cache_op);
15839 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15840 				rval = rval_set;
15841 		}
15842 	}
15843 	if (rval != SATA_SUCCESS)
15844 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15845 		    "%s %s", finfo, finfox));
15846 
15847 update_sdinfo:
15848 	/*
15849 	 * We need to fetch Device Identify data again
15850 	 */
15851 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15852 		/*
15853 		 * Cannot get device identification - retry later
15854 		 */
15855 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15856 		    "%s re-fetch device identify data\n", finfo));
15857 		rval = SATA_FAILURE;
15858 	}
15859 	/* Copy device sata info. */
15860 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
15861 
15862 	return (rval);
15863 }
15864 
15865 
15866 /*
15867  *
15868  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
15869  * unable to determine.
15870  *
15871  * Cannot be called in an interrupt context.
15872  *
15873  * Called by sata_build_lsense_page_2f()
15874  */
15875 
15876 static int
15877 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
15878     sata_drive_info_t *sdinfo)
15879 {
15880 	sata_pkt_t *spkt;
15881 	sata_cmd_t *scmd;
15882 	sata_pkt_txlate_t *spx;
15883 	int rval;
15884 
15885 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15886 	spx->txlt_sata_hba_inst = sata_hba_inst;
15887 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15888 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15889 	if (spkt == NULL) {
15890 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15891 		return (-1);
15892 	}
15893 	/* address is needed now */
15894 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15895 
15896 
15897 	/* Fill sata_pkt */
15898 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15899 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15900 	/* Synchronous mode, no callback */
15901 	spkt->satapkt_comp = NULL;
15902 	/* Timeout 30s */
15903 	spkt->satapkt_time = sata_default_pkt_time;
15904 
15905 	scmd = &spkt->satapkt_cmd;
15906 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
15907 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
15908 
15909 	/* Set up which registers need to be returned */
15910 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
15911 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
15912 
15913 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
15914 	scmd->satacmd_addr_type = 0;		/* N/A */
15915 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
15916 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
15917 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
15918 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
15919 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
15920 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
15921 	scmd->satacmd_cmd_reg = SATAC_SMART;
15922 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
15923 	    sdinfo->satadrv_addr.cport)));
15924 
15925 
15926 	/* Send pkt to SATA HBA driver */
15927 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
15928 	    SATA_TRAN_ACCEPTED ||
15929 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15930 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15931 		    sdinfo->satadrv_addr.cport)));
15932 		/*
15933 		 * Whoops, no SMART RETURN STATUS
15934 		 */
15935 		rval = -1;
15936 	} else {
15937 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15938 		    sdinfo->satadrv_addr.cport)));
15939 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
15940 			rval = -1;
15941 			goto fail;
15942 		}
15943 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
15944 			rval = -1;
15945 			goto fail;
15946 		}
15947 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
15948 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
15949 			rval = 0;
15950 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
15951 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
15952 			rval = 1;
15953 		else {
15954 			rval = -1;
15955 			goto fail;
15956 		}
15957 	}
15958 fail:
15959 	/* Free allocated resources */
15960 	sata_pkt_free(spx);
15961 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
15962 
15963 	return (rval);
15964 }
15965 
15966 /*
15967  *
15968  * Returns 0 if succeeded, -1 otherwise
15969  *
15970  * Cannot be called in an interrupt context.
15971  *
15972  */
15973 static int
15974 sata_fetch_smart_data(
15975 	sata_hba_inst_t *sata_hba_inst,
15976 	sata_drive_info_t *sdinfo,
15977 	struct smart_data *smart_data)
15978 {
15979 	sata_pkt_t *spkt;
15980 	sata_cmd_t *scmd;
15981 	sata_pkt_txlate_t *spx;
15982 	int rval;
15983 
15984 #if ! defined(lint)
15985 	ASSERT(sizeof (struct smart_data) == 512);
15986 #endif
15987 
15988 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15989 	spx->txlt_sata_hba_inst = sata_hba_inst;
15990 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15991 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15992 	if (spkt == NULL) {
15993 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15994 		return (-1);
15995 	}
15996 	/* address is needed now */
15997 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15998 
15999 
16000 	/* Fill sata_pkt */
16001 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16002 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16003 	/* Synchronous mode, no callback */
16004 	spkt->satapkt_comp = NULL;
16005 	/* Timeout 30s */
16006 	spkt->satapkt_time = sata_default_pkt_time;
16007 
16008 	scmd = &spkt->satapkt_cmd;
16009 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16010 
16011 	/*
16012 	 * Allocate buffer for SMART data
16013 	 */
16014 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16015 	    sizeof (struct smart_data));
16016 	if (scmd->satacmd_bp == NULL) {
16017 		sata_pkt_free(spx);
16018 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16019 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16020 		    "sata_fetch_smart_data: "
16021 		    "cannot allocate buffer"));
16022 		return (-1);
16023 	}
16024 
16025 
16026 	/* Build SMART_READ_DATA cmd in the sata_pkt */
16027 	scmd->satacmd_addr_type = 0;		/* N/A */
16028 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16029 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16030 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16031 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16032 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16033 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16034 	scmd->satacmd_cmd_reg = SATAC_SMART;
16035 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16036 	    sdinfo->satadrv_addr.cport)));
16037 
16038 	/* Send pkt to SATA HBA driver */
16039 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16040 	    SATA_TRAN_ACCEPTED ||
16041 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16042 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16043 		    sdinfo->satadrv_addr.cport)));
16044 		/*
16045 		 * Whoops, no SMART DATA available
16046 		 */
16047 		rval = -1;
16048 		goto fail;
16049 	} else {
16050 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16051 		    sdinfo->satadrv_addr.cport)));
16052 		if (spx->txlt_buf_dma_handle != NULL) {
16053 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16054 			    DDI_DMA_SYNC_FORKERNEL);
16055 			ASSERT(rval == DDI_SUCCESS);
16056 		}
16057 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16058 		    sizeof (struct smart_data));
16059 	}
16060 
16061 fail:
16062 	/* Free allocated resources */
16063 	sata_free_local_buffer(spx);
16064 	sata_pkt_free(spx);
16065 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16066 
16067 	return (rval);
16068 }
16069 
16070 /*
16071  * Used by LOG SENSE page 0x10
16072  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16073  * Note: cannot be called in the interrupt context.
16074  *
16075  * return 0 for success, -1 otherwise
16076  *
16077  */
16078 static int
16079 sata_ext_smart_selftest_read_log(
16080 	sata_hba_inst_t *sata_hba_inst,
16081 	sata_drive_info_t *sdinfo,
16082 	struct smart_ext_selftest_log *ext_selftest_log,
16083 	uint16_t block_num)
16084 {
16085 	sata_pkt_txlate_t *spx;
16086 	sata_pkt_t *spkt;
16087 	sata_cmd_t *scmd;
16088 	int rval;
16089 
16090 #if ! defined(lint)
16091 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16092 #endif
16093 
16094 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16095 	spx->txlt_sata_hba_inst = sata_hba_inst;
16096 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16097 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16098 	if (spkt == NULL) {
16099 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16100 		return (-1);
16101 	}
16102 	/* address is needed now */
16103 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16104 
16105 
16106 	/* Fill sata_pkt */
16107 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16108 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16109 	/* Synchronous mode, no callback */
16110 	spkt->satapkt_comp = NULL;
16111 	/* Timeout 30s */
16112 	spkt->satapkt_time = sata_default_pkt_time;
16113 
16114 	scmd = &spkt->satapkt_cmd;
16115 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16116 
16117 	/*
16118 	 * Allocate buffer for SMART extended self-test log
16119 	 */
16120 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16121 	    sizeof (struct smart_ext_selftest_log));
16122 	if (scmd->satacmd_bp == NULL) {
16123 		sata_pkt_free(spx);
16124 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16125 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16126 		    "sata_ext_smart_selftest_log: "
16127 		    "cannot allocate buffer"));
16128 		return (-1);
16129 	}
16130 
16131 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16132 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16133 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16134 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16135 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16136 	scmd->satacmd_lba_low_msb = 0;
16137 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16138 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16139 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16140 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16141 
16142 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16143 	    sdinfo->satadrv_addr.cport)));
16144 
16145 	/* Send pkt to SATA HBA driver */
16146 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16147 	    SATA_TRAN_ACCEPTED ||
16148 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16149 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16150 		    sdinfo->satadrv_addr.cport)));
16151 
16152 		/*
16153 		 * Whoops, no SMART selftest log info available
16154 		 */
16155 		rval = -1;
16156 		goto fail;
16157 	} else {
16158 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16159 		    sdinfo->satadrv_addr.cport)));
16160 
16161 		if (spx->txlt_buf_dma_handle != NULL) {
16162 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16163 			    DDI_DMA_SYNC_FORKERNEL);
16164 			ASSERT(rval == DDI_SUCCESS);
16165 		}
16166 		bcopy(scmd->satacmd_bp->b_un.b_addr,
16167 		    (uint8_t *)ext_selftest_log,
16168 		    sizeof (struct smart_ext_selftest_log));
16169 		rval = 0;
16170 	}
16171 
16172 fail:
16173 	/* Free allocated resources */
16174 	sata_free_local_buffer(spx);
16175 	sata_pkt_free(spx);
16176 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16177 
16178 	return (rval);
16179 }
16180 
16181 /*
16182  * Returns 0 for success, -1 otherwise
16183  *
16184  * SMART self-test log data is returned in buffer pointed to by selftest_log
16185  */
16186 static int
16187 sata_smart_selftest_log(
16188 	sata_hba_inst_t *sata_hba_inst,
16189 	sata_drive_info_t *sdinfo,
16190 	struct smart_selftest_log *selftest_log)
16191 {
16192 	sata_pkt_t *spkt;
16193 	sata_cmd_t *scmd;
16194 	sata_pkt_txlate_t *spx;
16195 	int rval;
16196 
16197 #if ! defined(lint)
16198 	ASSERT(sizeof (struct smart_selftest_log) == 512);
16199 #endif
16200 
16201 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16202 	spx->txlt_sata_hba_inst = sata_hba_inst;
16203 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16204 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16205 	if (spkt == NULL) {
16206 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16207 		return (-1);
16208 	}
16209 	/* address is needed now */
16210 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16211 
16212 
16213 	/* Fill sata_pkt */
16214 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16215 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16216 	/* Synchronous mode, no callback */
16217 	spkt->satapkt_comp = NULL;
16218 	/* Timeout 30s */
16219 	spkt->satapkt_time = sata_default_pkt_time;
16220 
16221 	scmd = &spkt->satapkt_cmd;
16222 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16223 
16224 	/*
16225 	 * Allocate buffer for SMART SELFTEST LOG
16226 	 */
16227 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16228 	    sizeof (struct smart_selftest_log));
16229 	if (scmd->satacmd_bp == NULL) {
16230 		sata_pkt_free(spx);
16231 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16232 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16233 		    "sata_smart_selftest_log: "
16234 		    "cannot allocate buffer"));
16235 		return (-1);
16236 	}
16237 
16238 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16239 	scmd->satacmd_addr_type = 0;		/* N/A */
16240 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
16241 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
16242 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16243 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16244 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16245 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16246 	scmd->satacmd_cmd_reg = SATAC_SMART;
16247 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16248 	    sdinfo->satadrv_addr.cport)));
16249 
16250 	/* Send pkt to SATA HBA driver */
16251 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16252 	    SATA_TRAN_ACCEPTED ||
16253 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16254 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16255 		    sdinfo->satadrv_addr.cport)));
16256 		/*
16257 		 * Whoops, no SMART DATA available
16258 		 */
16259 		rval = -1;
16260 		goto fail;
16261 	} else {
16262 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16263 		    sdinfo->satadrv_addr.cport)));
16264 		if (spx->txlt_buf_dma_handle != NULL) {
16265 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16266 			    DDI_DMA_SYNC_FORKERNEL);
16267 			ASSERT(rval == DDI_SUCCESS);
16268 		}
16269 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
16270 		    sizeof (struct smart_selftest_log));
16271 		rval = 0;
16272 	}
16273 
16274 fail:
16275 	/* Free allocated resources */
16276 	sata_free_local_buffer(spx);
16277 	sata_pkt_free(spx);
16278 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16279 
16280 	return (rval);
16281 }
16282 
16283 
16284 /*
16285  * Returns 0 for success, -1 otherwise
16286  *
16287  * SMART READ LOG data is returned in buffer pointed to by smart_log
16288  */
16289 static int
16290 sata_smart_read_log(
16291 	sata_hba_inst_t *sata_hba_inst,
16292 	sata_drive_info_t *sdinfo,
16293 	uint8_t *smart_log,		/* where the data should be returned */
16294 	uint8_t which_log,		/* which log should be returned */
16295 	uint8_t log_size)		/* # of 512 bytes in log */
16296 {
16297 	sata_pkt_t *spkt;
16298 	sata_cmd_t *scmd;
16299 	sata_pkt_txlate_t *spx;
16300 	int rval;
16301 
16302 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16303 	spx->txlt_sata_hba_inst = sata_hba_inst;
16304 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16305 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16306 	if (spkt == NULL) {
16307 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16308 		return (-1);
16309 	}
16310 	/* address is needed now */
16311 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16312 
16313 
16314 	/* Fill sata_pkt */
16315 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16316 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16317 	/* Synchronous mode, no callback */
16318 	spkt->satapkt_comp = NULL;
16319 	/* Timeout 30s */
16320 	spkt->satapkt_time = sata_default_pkt_time;
16321 
16322 	scmd = &spkt->satapkt_cmd;
16323 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16324 
16325 	/*
16326 	 * Allocate buffer for SMART READ LOG
16327 	 */
16328 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
16329 	if (scmd->satacmd_bp == NULL) {
16330 		sata_pkt_free(spx);
16331 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16332 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16333 		    "sata_smart_read_log: " "cannot allocate buffer"));
16334 		return (-1);
16335 	}
16336 
16337 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16338 	scmd->satacmd_addr_type = 0;		/* N/A */
16339 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
16340 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
16341 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16342 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16343 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16344 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16345 	scmd->satacmd_cmd_reg = SATAC_SMART;
16346 
16347 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16348 	    sdinfo->satadrv_addr.cport)));
16349 
16350 	/* Send pkt to SATA HBA driver */
16351 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16352 	    SATA_TRAN_ACCEPTED ||
16353 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16354 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16355 		    sdinfo->satadrv_addr.cport)));
16356 
16357 		/*
16358 		 * Whoops, no SMART DATA available
16359 		 */
16360 		rval = -1;
16361 		goto fail;
16362 	} else {
16363 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16364 		    sdinfo->satadrv_addr.cport)));
16365 
16366 		if (spx->txlt_buf_dma_handle != NULL) {
16367 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16368 			    DDI_DMA_SYNC_FORKERNEL);
16369 			ASSERT(rval == DDI_SUCCESS);
16370 		}
16371 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
16372 		rval = 0;
16373 	}
16374 
16375 fail:
16376 	/* Free allocated resources */
16377 	sata_free_local_buffer(spx);
16378 	sata_pkt_free(spx);
16379 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16380 
16381 	return (rval);
16382 }
16383 
16384 /*
16385  * Used by LOG SENSE page 0x10
16386  *
16387  * return 0 for success, -1 otherwise
16388  *
16389  */
16390 static int
16391 sata_read_log_ext_directory(
16392 	sata_hba_inst_t *sata_hba_inst,
16393 	sata_drive_info_t *sdinfo,
16394 	struct read_log_ext_directory *logdir)
16395 {
16396 	sata_pkt_txlate_t *spx;
16397 	sata_pkt_t *spkt;
16398 	sata_cmd_t *scmd;
16399 	int rval;
16400 
16401 #if ! defined(lint)
16402 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
16403 #endif
16404 
16405 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16406 	spx->txlt_sata_hba_inst = sata_hba_inst;
16407 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16408 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16409 	if (spkt == NULL) {
16410 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16411 		return (-1);
16412 	}
16413 
16414 	/* Fill sata_pkt */
16415 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16416 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16417 	/* Synchronous mode, no callback */
16418 	spkt->satapkt_comp = NULL;
16419 	/* Timeout 30s */
16420 	spkt->satapkt_time = sata_default_pkt_time;
16421 
16422 	scmd = &spkt->satapkt_cmd;
16423 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16424 
16425 	/*
16426 	 * Allocate buffer for SMART READ LOG EXTENDED command
16427 	 */
16428 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16429 	    sizeof (struct read_log_ext_directory));
16430 	if (scmd->satacmd_bp == NULL) {
16431 		sata_pkt_free(spx);
16432 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16433 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16434 		    "sata_read_log_ext_directory: "
16435 		    "cannot allocate buffer"));
16436 		return (-1);
16437 	}
16438 
16439 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
16440 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16441 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
16442 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
16443 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
16444 	scmd->satacmd_lba_low_msb = 0;
16445 	scmd->satacmd_lba_mid_lsb = 0;
16446 	scmd->satacmd_lba_mid_msb = 0;
16447 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16448 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16449 
16450 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16451 	    sdinfo->satadrv_addr.cport)));
16452 
16453 	/* Send pkt to SATA HBA driver */
16454 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16455 	    SATA_TRAN_ACCEPTED ||
16456 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16457 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16458 		    sdinfo->satadrv_addr.cport)));
16459 		/*
16460 		 * Whoops, no SMART selftest log info available
16461 		 */
16462 		rval = -1;
16463 		goto fail;
16464 	} else {
16465 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16466 		    sdinfo->satadrv_addr.cport)));
16467 		if (spx->txlt_buf_dma_handle != NULL) {
16468 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16469 			    DDI_DMA_SYNC_FORKERNEL);
16470 			ASSERT(rval == DDI_SUCCESS);
16471 		}
16472 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
16473 		    sizeof (struct read_log_ext_directory));
16474 		rval = 0;
16475 	}
16476 
16477 fail:
16478 	/* Free allocated resources */
16479 	sata_free_local_buffer(spx);
16480 	sata_pkt_free(spx);
16481 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16482 
16483 	return (rval);
16484 }
16485 
16486 /*
16487  * Set up error retrieval sata command for NCQ command error data
16488  * recovery.
16489  *
16490  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
16491  * returns SATA_FAILURE otherwise.
16492  */
16493 static int
16494 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
16495 {
16496 #ifndef __lock_lint
16497 	_NOTE(ARGUNUSED(sdinfo))
16498 #endif
16499 
16500 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
16501 	sata_cmd_t *scmd;
16502 	struct buf *bp;
16503 
16504 	/* Operation modes are up to the caller */
16505 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16506 
16507 	/* Synchronous mode, no callback - may be changed by the caller */
16508 	spkt->satapkt_comp = NULL;
16509 	spkt->satapkt_time = sata_default_pkt_time;
16510 
16511 	scmd = &spkt->satapkt_cmd;
16512 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
16513 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
16514 
16515 	/*
16516 	 * Allocate dma_able buffer error data.
16517 	 * Buffer allocation will take care of buffer alignment and other DMA
16518 	 * attributes.
16519 	 */
16520 	bp = sata_alloc_local_buffer(spx,
16521 	    sizeof (struct sata_ncq_error_recovery_page));
16522 	if (bp == NULL)
16523 		return (SATA_FAILURE);
16524 
16525 	bp_mapin(bp); /* make data buffer accessible */
16526 	scmd->satacmd_bp = bp;
16527 
16528 	/*
16529 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
16530 	 * before accessing it. Handle is in usual place in translate struct.
16531 	 */
16532 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
16533 
16534 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
16535 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
16536 
16537 	return (SATA_SUCCESS);
16538 }
16539 
16540 /*
16541  * sata_xlate_errors() is used to translate (S)ATA error
16542  * information to SCSI information returned in the SCSI
16543  * packet.
16544  */
16545 static void
16546 sata_xlate_errors(sata_pkt_txlate_t *spx)
16547 {
16548 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
16549 	struct scsi_extended_sense *sense;
16550 
16551 	scsipkt->pkt_reason = CMD_INCOMPLETE;
16552 	*scsipkt->pkt_scbp = STATUS_CHECK;
16553 	sense = sata_arq_sense(spx);
16554 
16555 	switch (spx->txlt_sata_pkt->satapkt_reason) {
16556 	case SATA_PKT_PORT_ERROR:
16557 		/*
16558 		 * We have no device data. Assume no data transfered.
16559 		 */
16560 		sense->es_key = KEY_HARDWARE_ERROR;
16561 		break;
16562 
16563 	case SATA_PKT_DEV_ERROR:
16564 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
16565 		    SATA_STATUS_ERR) {
16566 			/*
16567 			 * determine dev error reason from error
16568 			 * reg content
16569 			 */
16570 			sata_decode_device_error(spx, sense);
16571 			break;
16572 		}
16573 		/* No extended sense key - no info available */
16574 		break;
16575 
16576 	case SATA_PKT_TIMEOUT:
16577 		scsipkt->pkt_reason = CMD_TIMEOUT;
16578 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
16579 		/* No extended sense key */
16580 		break;
16581 
16582 	case SATA_PKT_ABORTED:
16583 		scsipkt->pkt_reason = CMD_ABORTED;
16584 		scsipkt->pkt_statistics |= STAT_ABORTED;
16585 		/* No extended sense key */
16586 		break;
16587 
16588 	case SATA_PKT_RESET:
16589 		/*
16590 		 * pkt aborted either by an explicit reset request from
16591 		 * a host, or due to error recovery
16592 		 */
16593 		scsipkt->pkt_reason = CMD_RESET;
16594 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
16595 		break;
16596 
16597 	default:
16598 		scsipkt->pkt_reason = CMD_TRAN_ERR;
16599 		break;
16600 	}
16601 }
16602 
16603 
16604 
16605 
16606 /*
16607  * Log sata message
16608  * dev pathname msg line preceeds the logged message.
16609  */
16610 
16611 static	void
16612 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
16613 {
16614 	char pathname[128];
16615 	dev_info_t *dip = NULL;
16616 	va_list ap;
16617 
16618 	mutex_enter(&sata_log_mutex);
16619 
16620 	va_start(ap, fmt);
16621 	(void) vsprintf(sata_log_buf, fmt, ap);
16622 	va_end(ap);
16623 
16624 	if (sata_hba_inst != NULL) {
16625 		dip = SATA_DIP(sata_hba_inst);
16626 		(void) ddi_pathname(dip, pathname);
16627 	} else {
16628 		pathname[0] = 0;
16629 	}
16630 	if (level == CE_CONT) {
16631 		if (sata_debug_flags == 0)
16632 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
16633 		else
16634 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
16635 	} else {
16636 		if (level != CE_NOTE) {
16637 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
16638 		} else if (sata_msg) {
16639 			cmn_err(level, "%s:\n %s", pathname,
16640 			    sata_log_buf);
16641 		}
16642 	}
16643 
16644 	/* sata trace debug */
16645 	sata_trace_debug(dip, sata_log_buf);
16646 
16647 	mutex_exit(&sata_log_mutex);
16648 }
16649 
16650 
16651 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
16652 
16653 /*
16654  * Start or terminate the thread, depending on flag arg and current state
16655  */
16656 static void
16657 sata_event_thread_control(int startstop)
16658 {
16659 	static 	int sata_event_thread_terminating = 0;
16660 	static 	int sata_event_thread_starting = 0;
16661 	int i;
16662 
16663 	mutex_enter(&sata_event_mutex);
16664 
16665 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
16666 	    sata_event_thread_terminating == 1)) {
16667 		mutex_exit(&sata_event_mutex);
16668 		return;
16669 	}
16670 	if (startstop == 1 && sata_event_thread_starting == 1) {
16671 		mutex_exit(&sata_event_mutex);
16672 		return;
16673 	}
16674 	if (startstop == 1 && sata_event_thread_terminating == 1) {
16675 		sata_event_thread_starting = 1;
16676 		/* wait til terminate operation completes */
16677 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16678 		while (sata_event_thread_terminating == 1) {
16679 			if (i-- <= 0) {
16680 				sata_event_thread_starting = 0;
16681 				mutex_exit(&sata_event_mutex);
16682 #ifdef SATA_DEBUG
16683 				cmn_err(CE_WARN, "sata_event_thread_control: "
16684 				    "timeout waiting for thread to terminate");
16685 #endif
16686 				return;
16687 			}
16688 			mutex_exit(&sata_event_mutex);
16689 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16690 			mutex_enter(&sata_event_mutex);
16691 		}
16692 	}
16693 	if (startstop == 1) {
16694 		if (sata_event_thread == NULL) {
16695 			sata_event_thread = thread_create(NULL, 0,
16696 			    (void (*)())sata_event_daemon,
16697 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
16698 		}
16699 		sata_event_thread_starting = 0;
16700 		mutex_exit(&sata_event_mutex);
16701 		return;
16702 	}
16703 
16704 	/*
16705 	 * If we got here, thread may need to be terminated
16706 	 */
16707 	if (sata_event_thread != NULL) {
16708 		int i;
16709 		/* Signal event thread to go away */
16710 		sata_event_thread_terminating = 1;
16711 		sata_event_thread_terminate = 1;
16712 		cv_signal(&sata_event_cv);
16713 		/*
16714 		 * Wait til daemon terminates.
16715 		 */
16716 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16717 		while (sata_event_thread_terminate == 1) {
16718 			mutex_exit(&sata_event_mutex);
16719 			if (i-- <= 0) {
16720 				/* Daemon did not go away !!! */
16721 #ifdef SATA_DEBUG
16722 				cmn_err(CE_WARN, "sata_event_thread_control: "
16723 				    "cannot terminate event daemon thread");
16724 #endif
16725 				mutex_enter(&sata_event_mutex);
16726 				break;
16727 			}
16728 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16729 			mutex_enter(&sata_event_mutex);
16730 		}
16731 		sata_event_thread_terminating = 0;
16732 	}
16733 	ASSERT(sata_event_thread_terminating == 0);
16734 	ASSERT(sata_event_thread_starting == 0);
16735 	mutex_exit(&sata_event_mutex);
16736 }
16737 
16738 
16739 /*
16740  * SATA HBA event notification function.
16741  * Events reported by SATA HBA drivers per HBA instance relate to a change in
16742  * a port and/or device state or a controller itself.
16743  * Events for different addresses/addr types cannot be combined.
16744  * A warning message is generated for each event type.
16745  * Events are not processed by this function, so only the
16746  * event flag(s)is set for an affected entity and the event thread is
16747  * waken up. Event daemon thread processes all events.
16748  *
16749  * NOTE: Since more than one event may be reported at the same time, one
16750  * cannot determine a sequence of events when opposite event are reported, eg.
16751  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
16752  * is taking precedence over reported events, i.e. may cause ignoring some
16753  * events.
16754  */
16755 #define	SATA_EVENT_MAX_MSG_LENGTH	79
16756 
16757 void
16758 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
16759 {
16760 	sata_hba_inst_t *sata_hba_inst = NULL;
16761 	sata_address_t *saddr;
16762 	sata_pmult_info_t *pmultinfo;
16763 	sata_drive_info_t *sdinfo;
16764 	sata_port_stats_t *pstats;
16765 	sata_cport_info_t *cportinfo;
16766 	sata_pmport_info_t *pmportinfo;
16767 	int cport, pmport;
16768 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
16769 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
16770 	char *lcp;
16771 	static char *err_msg_evnt_1 =
16772 	    "sata_hba_event_notify: invalid port event 0x%x ";
16773 	static char *err_msg_evnt_2 =
16774 	    "sata_hba_event_notify: invalid device event 0x%x ";
16775 	int linkevent;
16776 
16777 	/*
16778 	 * There is a possibility that an event will be generated on HBA
16779 	 * that has not completed attachment or is detaching. We still want
16780 	 * to process events until HBA is detached.
16781 	 */
16782 	mutex_enter(&sata_mutex);
16783 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
16784 	    sata_hba_inst = sata_hba_inst->satahba_next) {
16785 		if (SATA_DIP(sata_hba_inst) == dip)
16786 			if (sata_hba_inst->satahba_attached == 1)
16787 				break;
16788 	}
16789 	mutex_exit(&sata_mutex);
16790 	if (sata_hba_inst == NULL)
16791 		/* HBA not attached */
16792 		return;
16793 
16794 	ASSERT(sata_device != NULL);
16795 
16796 	/*
16797 	 * Validate address before - do not proceed with invalid address.
16798 	 */
16799 	saddr = &sata_device->satadev_addr;
16800 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
16801 		return;
16802 
16803 	cport = saddr->cport;
16804 	pmport = saddr->pmport;
16805 
16806 	buf1[0] = buf2[0] = '\0';
16807 
16808 	/*
16809 	 * If event relates to port or device, check port state.
16810 	 * Port has to be initialized, or we cannot accept an event.
16811 	 */
16812 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
16813 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
16814 		mutex_enter(&sata_hba_inst->satahba_mutex);
16815 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
16816 		mutex_exit(&sata_hba_inst->satahba_mutex);
16817 		if (cportinfo == NULL || cportinfo->cport_state == 0)
16818 			return;
16819 	}
16820 
16821 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
16822 	    SATA_ADDR_DPMPORT)) != 0) {
16823 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
16824 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16825 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
16826 			    "is attached to port %d, ignore pmult/pmport "
16827 			    "event 0x%x", cportinfo->cport_dev_type,
16828 			    cport, event));
16829 			return;
16830 		}
16831 
16832 		mutex_enter(&cportinfo->cport_mutex);
16833 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
16834 		mutex_exit(&cportinfo->cport_mutex);
16835 
16836 		/*
16837 		 * The daemon might be processing attachment of port
16838 		 * multiplier, in that case we should ignore events on its
16839 		 * sub-devices.
16840 		 *
16841 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
16842 		 * The pmport_state is checked by sata daemon.
16843 		 */
16844 		if (pmultinfo == NULL ||
16845 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
16846 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16847 			    "sata_hba_event_notify: pmult is not"
16848 			    "available at port %d:%d, ignore event 0x%x",
16849 			    cport, pmport, event));
16850 			return;
16851 		}
16852 	}
16853 
16854 	if ((saddr->qual &
16855 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
16856 
16857 		mutex_enter(&cportinfo->cport_mutex);
16858 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
16859 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16860 			    "sata_hba_event_notify: invalid/"
16861 			    "un-implemented port %d:%d (%d ports), "
16862 			    "ignore event 0x%x", cport, pmport,
16863 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
16864 			mutex_exit(&cportinfo->cport_mutex);
16865 			return;
16866 		}
16867 		mutex_exit(&cportinfo->cport_mutex);
16868 
16869 		mutex_enter(&sata_hba_inst->satahba_mutex);
16870 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
16871 		    cport, pmport);
16872 		mutex_exit(&sata_hba_inst->satahba_mutex);
16873 
16874 		/* pmport is implemented/valid? */
16875 		if (pmportinfo == NULL) {
16876 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16877 			    "sata_hba_event_notify: invalid/"
16878 			    "un-implemented port %d:%d, ignore "
16879 			    "event 0x%x", cport, pmport, event));
16880 			return;
16881 		}
16882 	}
16883 
16884 	/*
16885 	 * Events refer to devices, ports and controllers - each has
16886 	 * unique address. Events for different addresses cannot be combined.
16887 	 */
16888 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
16889 
16890 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16891 
16892 		/* qualify this event(s) */
16893 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
16894 			/* Invalid event for the device port */
16895 			(void) sprintf(buf2, err_msg_evnt_1,
16896 			    event & SATA_EVNT_PORT_EVENTS);
16897 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16898 			goto event_info;
16899 		}
16900 		if (saddr->qual == SATA_ADDR_CPORT) {
16901 			/* Controller's device port event */
16902 
16903 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
16904 			    cport_event_flags |=
16905 			    event & SATA_EVNT_PORT_EVENTS;
16906 			pstats =
16907 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
16908 			    cport_stats;
16909 		} else {
16910 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16911 			mutex_enter(&pmportinfo->pmport_mutex);
16912 			/* Port multiplier's device port event */
16913 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
16914 			    pmport_event_flags |=
16915 			    event & SATA_EVNT_PORT_EVENTS;
16916 			pstats =
16917 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
16918 			    pmport_stats;
16919 			mutex_exit(&pmportinfo->pmport_mutex);
16920 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16921 		}
16922 
16923 		/*
16924 		 * Add to statistics and log the message. We have to do it
16925 		 * here rather than in the event daemon, because there may be
16926 		 * multiple events occuring before they are processed.
16927 		 */
16928 		linkevent = event &
16929 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
16930 		if (linkevent) {
16931 			if (linkevent == (SATA_EVNT_LINK_LOST |
16932 			    SATA_EVNT_LINK_ESTABLISHED)) {
16933 				/* This is likely event combination */
16934 				(void) strlcat(buf1, "link lost/established, ",
16935 				    SATA_EVENT_MAX_MSG_LENGTH);
16936 
16937 				if (pstats->link_lost < 0xffffffffffffffffULL)
16938 					pstats->link_lost++;
16939 				if (pstats->link_established <
16940 				    0xffffffffffffffffULL)
16941 					pstats->link_established++;
16942 				linkevent = 0;
16943 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
16944 				(void) strlcat(buf1, "link lost, ",
16945 				    SATA_EVENT_MAX_MSG_LENGTH);
16946 
16947 				if (pstats->link_lost < 0xffffffffffffffffULL)
16948 					pstats->link_lost++;
16949 			} else {
16950 				(void) strlcat(buf1, "link established, ",
16951 				    SATA_EVENT_MAX_MSG_LENGTH);
16952 				if (pstats->link_established <
16953 				    0xffffffffffffffffULL)
16954 					pstats->link_established++;
16955 			}
16956 		}
16957 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
16958 			(void) strlcat(buf1, "device attached, ",
16959 			    SATA_EVENT_MAX_MSG_LENGTH);
16960 			if (pstats->device_attached < 0xffffffffffffffffULL)
16961 				pstats->device_attached++;
16962 		}
16963 		if (event & SATA_EVNT_DEVICE_DETACHED) {
16964 			(void) strlcat(buf1, "device detached, ",
16965 			    SATA_EVENT_MAX_MSG_LENGTH);
16966 			if (pstats->device_detached < 0xffffffffffffffffULL)
16967 				pstats->device_detached++;
16968 		}
16969 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
16970 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
16971 			    "port %d power level changed", cport);
16972 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
16973 				pstats->port_pwr_changed++;
16974 		}
16975 
16976 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
16977 			/* There should be no other events for this address */
16978 			(void) sprintf(buf2, err_msg_evnt_1,
16979 			    event & ~SATA_EVNT_PORT_EVENTS);
16980 		}
16981 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16982 
16983 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
16984 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16985 
16986 		/* qualify this event */
16987 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
16988 			/* Invalid event for a device */
16989 			(void) sprintf(buf2, err_msg_evnt_2,
16990 			    event & SATA_EVNT_DEVICE_RESET);
16991 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16992 			goto event_info;
16993 		}
16994 		/* drive event */
16995 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
16996 		if (sdinfo != NULL) {
16997 			if (event & SATA_EVNT_DEVICE_RESET) {
16998 				(void) strlcat(buf1, "device reset, ",
16999 				    SATA_EVENT_MAX_MSG_LENGTH);
17000 				if (sdinfo->satadrv_stats.drive_reset <
17001 				    0xffffffffffffffffULL)
17002 					sdinfo->satadrv_stats.drive_reset++;
17003 				sdinfo->satadrv_event_flags |=
17004 				    SATA_EVNT_DEVICE_RESET;
17005 			}
17006 		}
17007 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
17008 			/* Invalid event for a device */
17009 			(void) sprintf(buf2, err_msg_evnt_2,
17010 			    event & ~SATA_EVNT_DRIVE_EVENTS);
17011 		}
17012 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17013 	} else if (saddr->qual == SATA_ADDR_PMULT) {
17014 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17015 
17016 		/* qualify this event */
17017 		if ((event & (SATA_EVNT_DEVICE_RESET |
17018 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
17019 			/* Invalid event for a port multiplier */
17020 			(void) sprintf(buf2, err_msg_evnt_2,
17021 			    event & SATA_EVNT_DEVICE_RESET);
17022 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17023 			goto event_info;
17024 		}
17025 
17026 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17027 
17028 		if (event & SATA_EVNT_DEVICE_RESET) {
17029 
17030 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17031 			    "[Reset] port-mult on cport %d", cport);
17032 			pmultinfo->pmult_event_flags |=
17033 			    SATA_EVNT_DEVICE_RESET;
17034 			(void) strlcat(buf1, "pmult reset, ",
17035 			    SATA_EVENT_MAX_MSG_LENGTH);
17036 		}
17037 
17038 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17039 
17040 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17041 			    "pmult link changed on cport %d", cport);
17042 			pmultinfo->pmult_event_flags |=
17043 			    SATA_EVNT_PMULT_LINK_CHANGED;
17044 			(void) strlcat(buf1, "pmult link changed, ",
17045 			    SATA_EVENT_MAX_MSG_LENGTH);
17046 		}
17047 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17048 
17049 	} else {
17050 		if (saddr->qual != SATA_ADDR_NULL) {
17051 			/* Wrong address qualifier */
17052 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17053 			    "sata_hba_event_notify: invalid address 0x%x",
17054 			    *(uint32_t *)saddr));
17055 			return;
17056 		}
17057 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17058 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17059 			/* Invalid event for the controller */
17060 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17061 			    "sata_hba_event_notify: invalid event 0x%x for "
17062 			    "controller",
17063 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17064 			return;
17065 		}
17066 		buf1[0] = '\0';
17067 		/* This may be a frequent and not interesting event */
17068 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17069 		    "controller power level changed\n", NULL);
17070 
17071 		mutex_enter(&sata_hba_inst->satahba_mutex);
17072 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17073 		    0xffffffffffffffffULL)
17074 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17075 
17076 		sata_hba_inst->satahba_event_flags |=
17077 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17078 		mutex_exit(&sata_hba_inst->satahba_mutex);
17079 	}
17080 	/*
17081 	 * If we got here, there is something to do with this HBA
17082 	 * instance.
17083 	 */
17084 	mutex_enter(&sata_hba_inst->satahba_mutex);
17085 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17086 	mutex_exit(&sata_hba_inst->satahba_mutex);
17087 	mutex_enter(&sata_mutex);
17088 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17089 	mutex_exit(&sata_mutex);
17090 
17091 	/* Tickle event thread */
17092 	mutex_enter(&sata_event_mutex);
17093 	if (sata_event_thread_active == 0)
17094 		cv_signal(&sata_event_cv);
17095 	mutex_exit(&sata_event_mutex);
17096 
17097 event_info:
17098 	if (buf1[0] != '\0') {
17099 		lcp = strrchr(buf1, ',');
17100 		if (lcp != NULL)
17101 			*lcp = '\0';
17102 	}
17103 	if (saddr->qual == SATA_ADDR_CPORT ||
17104 	    saddr->qual == SATA_ADDR_DCPORT) {
17105 		if (buf1[0] != '\0') {
17106 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17107 			    cport, buf1);
17108 		}
17109 		if (buf2[0] != '\0') {
17110 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17111 			    cport, buf2);
17112 		}
17113 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
17114 	    saddr->qual == SATA_ADDR_DPMPORT) {
17115 		if (buf1[0] != '\0') {
17116 			sata_log(sata_hba_inst, CE_NOTE,
17117 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
17118 		}
17119 		if (buf2[0] != '\0') {
17120 			sata_log(sata_hba_inst, CE_NOTE,
17121 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
17122 		}
17123 	}
17124 }
17125 
17126 
17127 /*
17128  * Event processing thread.
17129  * Arg is a pointer to the sata_hba_list pointer.
17130  * It is not really needed, because sata_hba_list is global and static
17131  */
17132 static void
17133 sata_event_daemon(void *arg)
17134 {
17135 #ifndef __lock_lint
17136 	_NOTE(ARGUNUSED(arg))
17137 #endif
17138 	sata_hba_inst_t *sata_hba_inst;
17139 	clock_t delta;
17140 
17141 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17142 	    "SATA event daemon started\n", NULL);
17143 loop:
17144 	/*
17145 	 * Process events here. Walk through all registered HBAs
17146 	 */
17147 	mutex_enter(&sata_mutex);
17148 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17149 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17150 		ASSERT(sata_hba_inst != NULL);
17151 		mutex_enter(&sata_hba_inst->satahba_mutex);
17152 		if (sata_hba_inst->satahba_attached == 0 ||
17153 		    (sata_hba_inst->satahba_event_flags &
17154 		    SATA_EVNT_SKIP) != 0) {
17155 			mutex_exit(&sata_hba_inst->satahba_mutex);
17156 			continue;
17157 		}
17158 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
17159 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
17160 			mutex_exit(&sata_hba_inst->satahba_mutex);
17161 			mutex_exit(&sata_mutex);
17162 			/* Got the controller with pending event */
17163 			sata_process_controller_events(sata_hba_inst);
17164 			/*
17165 			 * Since global mutex was released, there is a
17166 			 * possibility that HBA list has changed, so start
17167 			 * over from the top. Just processed controller
17168 			 * will be passed-over because of the SKIP flag.
17169 			 */
17170 			goto loop;
17171 		}
17172 		mutex_exit(&sata_hba_inst->satahba_mutex);
17173 	}
17174 	/* Clear SKIP flag in all controllers */
17175 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17176 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17177 		mutex_enter(&sata_hba_inst->satahba_mutex);
17178 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
17179 		mutex_exit(&sata_hba_inst->satahba_mutex);
17180 	}
17181 	mutex_exit(&sata_mutex);
17182 
17183 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17184 	    "SATA EVENT DAEMON suspending itself", NULL);
17185 
17186 #ifdef SATA_DEBUG
17187 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
17188 		sata_log(sata_hba_inst, CE_WARN,
17189 		    "SATA EVENTS PROCESSING DISABLED\n");
17190 		thread_exit(); /* Daemon will not run again */
17191 	}
17192 #endif
17193 	mutex_enter(&sata_event_mutex);
17194 	sata_event_thread_active = 0;
17195 	mutex_exit(&sata_event_mutex);
17196 	/*
17197 	 * Go to sleep/suspend itself and wake up either because new event or
17198 	 * wait timeout. Exit if there is a termination request (driver
17199 	 * unload).
17200 	 */
17201 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
17202 	do {
17203 		mutex_enter(&sata_event_mutex);
17204 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
17205 		    delta, TR_CLOCK_TICK);
17206 
17207 		if (sata_event_thread_active != 0) {
17208 			mutex_exit(&sata_event_mutex);
17209 			continue;
17210 		}
17211 
17212 		/* Check if it is time to go away */
17213 		if (sata_event_thread_terminate == 1) {
17214 			/*
17215 			 * It is up to the thread setting above flag to make
17216 			 * sure that this thread is not killed prematurely.
17217 			 */
17218 			sata_event_thread_terminate = 0;
17219 			sata_event_thread = NULL;
17220 			mutex_exit(&sata_event_mutex);
17221 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17222 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
17223 			thread_exit();  { _NOTE(NOT_REACHED) }
17224 		}
17225 		mutex_exit(&sata_event_mutex);
17226 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
17227 
17228 	mutex_enter(&sata_event_mutex);
17229 	sata_event_thread_active = 1;
17230 	mutex_exit(&sata_event_mutex);
17231 
17232 	mutex_enter(&sata_mutex);
17233 	sata_event_pending &= ~SATA_EVNT_MAIN;
17234 	mutex_exit(&sata_mutex);
17235 
17236 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17237 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
17238 
17239 	goto loop;
17240 }
17241 
17242 /*
17243  * Specific HBA instance event processing.
17244  *
17245  * NOTE: At the moment, device event processing is limited to hard disks
17246  * only.
17247  * Port multiplier is supported now.
17248  */
17249 static void
17250 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
17251 {
17252 	int ncport;
17253 	uint32_t event_flags;
17254 	sata_address_t *saddr;
17255 	sata_cport_info_t *cportinfo;
17256 	sata_pmult_info_t *pmultinfo;
17257 
17258 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
17259 	    "Processing controller %d event(s)",
17260 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
17261 
17262 	mutex_enter(&sata_hba_inst->satahba_mutex);
17263 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
17264 	event_flags = sata_hba_inst->satahba_event_flags;
17265 	mutex_exit(&sata_hba_inst->satahba_mutex);
17266 	/*
17267 	 * Process controller power change first
17268 	 * HERE
17269 	 */
17270 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
17271 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
17272 
17273 	/*
17274 	 * Search through ports/devices to identify affected port/device.
17275 	 * We may have to process events for more than one port/device.
17276 	 */
17277 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
17278 		/*
17279 		 * Not all ports may be processed in attach by the time we
17280 		 * get an event. Check if port info is initialized.
17281 		 */
17282 		mutex_enter(&sata_hba_inst->satahba_mutex);
17283 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
17284 		mutex_exit(&sata_hba_inst->satahba_mutex);
17285 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
17286 			continue;
17287 
17288 		/* We have initialized controller port info */
17289 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17290 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
17291 		    cport_event_flags;
17292 		/* Check if port was locked by IOCTL processing */
17293 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
17294 			/*
17295 			 * We ignore port events because port is busy
17296 			 * with AP control processing. Set again
17297 			 * controller and main event flag, so that
17298 			 * events may be processed by the next daemon
17299 			 * run.
17300 			 */
17301 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17302 			mutex_enter(&sata_hba_inst->satahba_mutex);
17303 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17304 			mutex_exit(&sata_hba_inst->satahba_mutex);
17305 			mutex_enter(&sata_mutex);
17306 			sata_event_pending |= SATA_EVNT_MAIN;
17307 			mutex_exit(&sata_mutex);
17308 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
17309 			    "Event processing postponed until "
17310 			    "AP control processing completes",
17311 			    NULL);
17312 			/* Check other ports */
17313 			continue;
17314 		} else {
17315 			/*
17316 			 * Set BSY flag so that AP control would not
17317 			 * interfere with events processing for
17318 			 * this port.
17319 			 */
17320 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17321 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
17322 		}
17323 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17324 
17325 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
17326 
17327 		if ((event_flags &
17328 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17329 			/*
17330 			 * Got port event.
17331 			 * We need some hierarchy of event processing as they
17332 			 * are affecting each other:
17333 			 * 1. port failed
17334 			 * 2. device detached/attached
17335 			 * 3. link events - link events may trigger device
17336 			 *    detached or device attached events in some
17337 			 *    circumstances.
17338 			 * 4. port power level changed
17339 			 */
17340 			if (event_flags & SATA_EVNT_PORT_FAILED) {
17341 				sata_process_port_failed_event(sata_hba_inst,
17342 				    saddr);
17343 			}
17344 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17345 				sata_process_device_detached(sata_hba_inst,
17346 				    saddr);
17347 			}
17348 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17349 				sata_process_device_attached(sata_hba_inst,
17350 				    saddr);
17351 			}
17352 			if (event_flags &
17353 			    (SATA_EVNT_LINK_ESTABLISHED |
17354 			    SATA_EVNT_LINK_LOST)) {
17355 				sata_process_port_link_events(sata_hba_inst,
17356 				    saddr);
17357 			}
17358 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
17359 				sata_process_port_pwr_change(sata_hba_inst,
17360 				    saddr);
17361 			}
17362 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17363 				sata_process_target_node_cleanup(
17364 				    sata_hba_inst, saddr);
17365 			}
17366 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
17367 				sata_process_device_autoonline(
17368 				    sata_hba_inst, saddr);
17369 			}
17370 		}
17371 
17372 
17373 		/*
17374 		 * Scan port multiplier and all its sub-ports event flags.
17375 		 * The events are marked by
17376 		 * (1) sata_pmult_info.pmult_event_flags
17377 		 * (2) sata_pmport_info.pmport_event_flags
17378 		 */
17379 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17380 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
17381 			/*
17382 			 * There should be another extra check: this
17383 			 * port multiplier still exists?
17384 			 */
17385 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
17386 			    ncport);
17387 
17388 			if (pmultinfo != NULL) {
17389 				mutex_exit(&(SATA_CPORT_MUTEX(
17390 				    sata_hba_inst, ncport)));
17391 				sata_process_pmult_events(
17392 				    sata_hba_inst, ncport);
17393 				mutex_enter(&(SATA_CPORT_MUTEX(
17394 				    sata_hba_inst, ncport)));
17395 			} else {
17396 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17397 				    "Port-multiplier is gone. "
17398 				    "Ignore all sub-device events "
17399 				    "at port %d.", ncport);
17400 			}
17401 		}
17402 
17403 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
17404 		    SATA_DTYPE_NONE) &&
17405 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
17406 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
17407 			    satadrv_event_flags &
17408 			    (SATA_EVNT_DEVICE_RESET |
17409 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17410 				/* Have device event */
17411 				sata_process_device_reset(sata_hba_inst,
17412 				    saddr);
17413 			}
17414 		}
17415 		/* Release PORT_BUSY flag */
17416 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17417 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17418 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17419 
17420 	} /* End of loop through the controller SATA ports */
17421 }
17422 
17423 /*
17424  * Specific port multiplier instance event processing. At the moment, device
17425  * event processing is limited to link/attach event only.
17426  *
17427  * NOTE: power management event is not supported yet.
17428  */
17429 static void
17430 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
17431 {
17432 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17433 	sata_pmult_info_t *pmultinfo;
17434 	sata_pmport_info_t *pmportinfo;
17435 	sata_address_t *saddr;
17436 	sata_device_t sata_device;
17437 	uint32_t event_flags;
17438 	int npmport;
17439 	int rval;
17440 
17441 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17442 	    "Processing pmult event(s) on cport %d of controller %d",
17443 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17444 
17445 	/* First process events on port multiplier */
17446 	mutex_enter(&cportinfo->cport_mutex);
17447 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17448 	event_flags = pmultinfo->pmult_event_flags;
17449 
17450 	/*
17451 	 * Reset event (of port multiplier) has higher priority because the
17452 	 * port multiplier itself might be failed or removed after reset.
17453 	 */
17454 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
17455 		/*
17456 		 * The status of the sub-links are uncertain,
17457 		 * so mark all sub-ports as RESET
17458 		 */
17459 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
17460 		    sata_hba_inst, cport); npmport ++) {
17461 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17462 			    cport, npmport);
17463 			if (pmportinfo == NULL) {
17464 				/* That's weird. */
17465 				SATA_LOG_D((sata_hba_inst, CE_WARN,
17466 				    "sata_hba_event_notify: "
17467 				    "invalid/un-implemented "
17468 				    "port %d:%d (%d ports), ",
17469 				    cport, npmport, SATA_NUM_PMPORTS(
17470 				    sata_hba_inst, cport)));
17471 				continue;
17472 			}
17473 
17474 			mutex_enter(&pmportinfo->pmport_mutex);
17475 
17476 			/* Mark all pmport to unknow state. */
17477 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
17478 			/* Mark all pmports with link events. */
17479 			pmportinfo->pmport_event_flags =
17480 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
17481 			mutex_exit(&pmportinfo->pmport_mutex);
17482 		}
17483 
17484 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
17485 		/*
17486 		 * We need probe the port multiplier to know what has
17487 		 * happened.
17488 		 */
17489 		bzero(&sata_device, sizeof (sata_device_t));
17490 		sata_device.satadev_rev = SATA_DEVICE_REV;
17491 		sata_device.satadev_addr.cport = cport;
17492 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
17493 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
17494 
17495 		mutex_exit(&cportinfo->cport_mutex);
17496 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17497 		    (SATA_DIP(sata_hba_inst), &sata_device);
17498 		mutex_enter(&cportinfo->cport_mutex);
17499 		if (rval != SATA_SUCCESS) {
17500 			/* Something went wrong? Fail the port */
17501 			cportinfo->cport_state = SATA_PSTATE_FAILED;
17502 			mutex_exit(&cportinfo->cport_mutex);
17503 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17504 			    "SATA port %d probing failed", cport));
17505 
17506 			/* PMult structure must be released.  */
17507 			sata_free_pmult(sata_hba_inst, &sata_device);
17508 			return;
17509 		}
17510 
17511 		sata_update_port_info(sata_hba_inst, &sata_device);
17512 
17513 		/*
17514 		 * Sanity check - Port is active? Is the link active?
17515 		 * The device is still a port multiplier?
17516 		 */
17517 		if ((cportinfo->cport_state &
17518 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
17519 		    ((cportinfo->cport_scr.sstatus &
17520 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
17521 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
17522 			mutex_exit(&cportinfo->cport_mutex);
17523 
17524 			/* PMult structure must be released.  */
17525 			sata_free_pmult(sata_hba_inst, &sata_device);
17526 			return;
17527 		}
17528 
17529 		/* Probed succeed, set port ready. */
17530 		cportinfo->cport_state |=
17531 		    SATA_STATE_PROBED | SATA_STATE_READY;
17532 	}
17533 
17534 	/* Release port multiplier event flags. */
17535 	pmultinfo->pmult_event_flags &=
17536 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
17537 	mutex_exit(&cportinfo->cport_mutex);
17538 
17539 	/*
17540 	 * Check all sub-links.
17541 	 */
17542 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
17543 	    npmport ++) {
17544 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
17545 		mutex_enter(&pmportinfo->pmport_mutex);
17546 		event_flags = pmportinfo->pmport_event_flags;
17547 		mutex_exit(&pmportinfo->pmport_mutex);
17548 		saddr = &pmportinfo->pmport_addr;
17549 
17550 		if ((event_flags &
17551 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17552 			/*
17553 			 * Got port multiplier port event.
17554 			 * We need some hierarchy of event processing as they
17555 			 * are affecting each other:
17556 			 * 1. device detached/attached
17557 			 * 2. link events - link events may trigger device
17558 			 *    detached or device attached events in some
17559 			 *    circumstances.
17560 			 */
17561 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17562 				sata_process_pmdevice_detached(sata_hba_inst,
17563 				    saddr);
17564 			}
17565 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17566 				sata_process_pmdevice_attached(sata_hba_inst,
17567 				    saddr);
17568 			}
17569 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
17570 			    event_flags & SATA_EVNT_LINK_LOST) {
17571 				sata_process_pmport_link_events(sata_hba_inst,
17572 				    saddr);
17573 			}
17574 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17575 				sata_process_target_node_cleanup(
17576 				    sata_hba_inst, saddr);
17577 			}
17578 		}
17579 
17580 		/* Checking drive event(s). */
17581 		mutex_enter(&pmportinfo->pmport_mutex);
17582 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
17583 		    pmportinfo->pmport_sata_drive != NULL) {
17584 			event_flags = pmportinfo->pmport_sata_drive->
17585 			    satadrv_event_flags;
17586 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
17587 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17588 
17589 				/* Have device event */
17590 				sata_process_pmdevice_reset(sata_hba_inst,
17591 				    saddr);
17592 			}
17593 		}
17594 		mutex_exit(&pmportinfo->pmport_mutex);
17595 
17596 		/* Release PORT_BUSY flag */
17597 		mutex_enter(&cportinfo->cport_mutex);
17598 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17599 		mutex_exit(&cportinfo->cport_mutex);
17600 	}
17601 
17602 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17603 	    "[DONE] pmult event(s) on cport %d of controller %d",
17604 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17605 }
17606 
17607 /*
17608  * Process HBA power level change reported by HBA driver.
17609  * Not implemented at this time - event is ignored.
17610  */
17611 static void
17612 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
17613 {
17614 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17615 	    "Processing controller power level change", NULL);
17616 
17617 	/* Ignoring it for now */
17618 	mutex_enter(&sata_hba_inst->satahba_mutex);
17619 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17620 	mutex_exit(&sata_hba_inst->satahba_mutex);
17621 }
17622 
17623 /*
17624  * Process port power level change reported by HBA driver.
17625  * Not implemented at this time - event is ignored.
17626  */
17627 static void
17628 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
17629     sata_address_t *saddr)
17630 {
17631 	sata_cport_info_t *cportinfo;
17632 
17633 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17634 	    "Processing port power level change", NULL);
17635 
17636 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17637 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17638 	/* Reset event flag */
17639 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17640 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17641 }
17642 
17643 /*
17644  * Process port failure reported by HBA driver.
17645  * cports support only - no pmports.
17646  */
17647 static void
17648 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
17649     sata_address_t *saddr)
17650 {
17651 	sata_cport_info_t *cportinfo;
17652 
17653 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17654 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17655 	/* Reset event flag first */
17656 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
17657 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
17658 	if ((cportinfo->cport_state &
17659 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
17660 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17661 		    cport_mutex);
17662 		return;
17663 	}
17664 	/* Fail the port */
17665 	cportinfo->cport_state = SATA_PSTATE_FAILED;
17666 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17667 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
17668 }
17669 
17670 /*
17671  * Device Reset Event processing.
17672  * The seqeunce is managed by 3 stage flags:
17673  * - reset event reported,
17674  * - reset event being processed,
17675  * - request to clear device reset state.
17676  *
17677  * NOTE: This function has to be entered with cport mutex held. It exits with
17678  * mutex held as well, but can release mutex during the processing.
17679  */
17680 static void
17681 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
17682     sata_address_t *saddr)
17683 {
17684 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17685 	sata_drive_info_t *sdinfo;
17686 	sata_cport_info_t *cportinfo;
17687 	sata_device_t sata_device;
17688 	int rval_probe, rval_set;
17689 
17690 	/* We only care about host sata cport for now */
17691 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17692 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17693 	/*
17694 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17695 	 * state, ignore reset event.
17696 	 */
17697 	if (((cportinfo->cport_state &
17698 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17699 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17700 		sdinfo->satadrv_event_flags &=
17701 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17702 		return;
17703 	}
17704 
17705 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
17706 	    SATA_DTYPE_PMULT)) {
17707 		/*
17708 		 * Should not happened: this is already handled in
17709 		 * sata_hba_event_notify()
17710 		 */
17711 		mutex_exit(&cportinfo->cport_mutex);
17712 		goto done;
17713 	}
17714 
17715 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
17716 	    SATA_VALID_DEV_TYPE) == 0) {
17717 		/*
17718 		 * This should not happen - coding error.
17719 		 * But we can recover, so do not panic, just clean up
17720 		 * and if in debug mode, log the message.
17721 		 */
17722 #ifdef SATA_DEBUG
17723 		sata_log(sata_hba_inst, CE_WARN,
17724 		    "sata_process_device_reset: "
17725 		    "Invalid device type with sdinfo!", NULL);
17726 #endif
17727 		sdinfo->satadrv_event_flags = 0;
17728 		return;
17729 	}
17730 
17731 #ifdef SATA_DEBUG
17732 	if ((sdinfo->satadrv_event_flags &
17733 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17734 		/* Nothing to do */
17735 		/* Something is weird - why we are processing dev reset? */
17736 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17737 		    "No device reset event!!!!", NULL);
17738 
17739 		return;
17740 	}
17741 	if ((sdinfo->satadrv_event_flags &
17742 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17743 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17744 		/* Something is weird - new device reset event */
17745 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17746 		    "Overlapping device reset events!", NULL);
17747 	}
17748 #endif
17749 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17750 	    "Processing port %d device reset", saddr->cport);
17751 
17752 	/* Clear event flag */
17753 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17754 
17755 	/* It seems that we always need to check the port state first */
17756 	sata_device.satadev_rev = SATA_DEVICE_REV;
17757 	sata_device.satadev_addr = *saddr;
17758 	/*
17759 	 * We have to exit mutex, because the HBA probe port function may
17760 	 * block on its own mutex.
17761 	 */
17762 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17763 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17764 	    (SATA_DIP(sata_hba_inst), &sata_device);
17765 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17766 	sata_update_port_info(sata_hba_inst, &sata_device);
17767 	if (rval_probe != SATA_SUCCESS) {
17768 		/* Something went wrong? Fail the port */
17769 		cportinfo->cport_state = SATA_PSTATE_FAILED;
17770 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17771 		if (sdinfo != NULL)
17772 			sdinfo->satadrv_event_flags = 0;
17773 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17774 		    cport_mutex);
17775 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17776 		    "SATA port %d probing failed",
17777 		    saddr->cport));
17778 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
17779 		    saddr->cport)->cport_mutex);
17780 		return;
17781 	}
17782 	if ((sata_device.satadev_scr.sstatus  &
17783 	    SATA_PORT_DEVLINK_UP_MASK) !=
17784 	    SATA_PORT_DEVLINK_UP ||
17785 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
17786 		/*
17787 		 * No device to process, anymore. Some other event processing
17788 		 * would or have already performed port info cleanup.
17789 		 * To be safe (HBA may need it), request clearing device
17790 		 * reset condition.
17791 		 */
17792 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17793 		if (sdinfo != NULL) {
17794 			sdinfo->satadrv_event_flags &=
17795 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17796 			sdinfo->satadrv_event_flags |=
17797 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17798 		}
17799 		return;
17800 	}
17801 
17802 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17803 	if (sdinfo == NULL) {
17804 		return;
17805 	}
17806 	if ((sdinfo->satadrv_event_flags &
17807 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
17808 		/*
17809 		 * Start tracking time for device feature restoration and
17810 		 * identification. Save current time (lbolt value).
17811 		 */
17812 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
17813 	}
17814 	/* Mark device reset processing as active */
17815 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
17816 
17817 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
17818 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17819 
17820 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
17821 
17822 	if (rval_set  != SATA_SUCCESS) {
17823 		/*
17824 		 * Restoring drive setting failed.
17825 		 * Probe the port first, to check if the port state has changed
17826 		 */
17827 		sata_device.satadev_rev = SATA_DEVICE_REV;
17828 		sata_device.satadev_addr = *saddr;
17829 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
17830 		/* probe port */
17831 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17832 		    (SATA_DIP(sata_hba_inst), &sata_device);
17833 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17834 		    cport_mutex);
17835 		if (rval_probe == SATA_SUCCESS &&
17836 		    (sata_device.satadev_state &
17837 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
17838 		    (sata_device.satadev_scr.sstatus  &
17839 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
17840 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
17841 			/*
17842 			 * We may retry this a bit later - in-process reset
17843 			 * condition should be already set.
17844 			 * Track retry time for device identification.
17845 			 */
17846 			if ((cportinfo->cport_dev_type &
17847 			    SATA_VALID_DEV_TYPE) != 0 &&
17848 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
17849 			    sdinfo->satadrv_reset_time != 0) {
17850 				clock_t cur_time = ddi_get_lbolt();
17851 				/*
17852 				 * If the retry time limit was not
17853 				 * exceeded, retry.
17854 				 */
17855 				if ((cur_time - sdinfo->satadrv_reset_time) <
17856 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
17857 					mutex_enter(
17858 					    &sata_hba_inst->satahba_mutex);
17859 					sata_hba_inst->satahba_event_flags |=
17860 					    SATA_EVNT_MAIN;
17861 					mutex_exit(
17862 					    &sata_hba_inst->satahba_mutex);
17863 					mutex_enter(&sata_mutex);
17864 					sata_event_pending |= SATA_EVNT_MAIN;
17865 					mutex_exit(&sata_mutex);
17866 					return;
17867 				}
17868 				if (rval_set == SATA_RETRY) {
17869 					/*
17870 					 * Setting drive features failed, but
17871 					 * the drive is still accessible,
17872 					 * so emit a warning message before
17873 					 * return.
17874 					 */
17875 					mutex_exit(&SATA_CPORT_INFO(
17876 					    sata_hba_inst,
17877 					    saddr->cport)->cport_mutex);
17878 					goto done;
17879 				}
17880 			}
17881 			/* Fail the drive */
17882 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
17883 
17884 			sata_log(sata_hba_inst, CE_WARN,
17885 			    "SATA device at port %d - device failed",
17886 			    saddr->cport);
17887 		}
17888 		/*
17889 		 * No point of retrying - device failed or some other event
17890 		 * processing or already did or will do port info cleanup.
17891 		 * To be safe (HBA may need it),
17892 		 * request clearing device reset condition.
17893 		 */
17894 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
17895 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
17896 		sdinfo->satadrv_reset_time = 0;
17897 		return;
17898 	}
17899 done:
17900 	/*
17901 	 * If setting of drive features failed, but the drive is still
17902 	 * accessible, emit a warning message.
17903 	 */
17904 	if (rval_set == SATA_RETRY) {
17905 		sata_log(sata_hba_inst, CE_WARN,
17906 		    "SATA device at port %d - desired setting could not be "
17907 		    "restored after reset. Device may not operate as expected.",
17908 		    saddr->cport);
17909 	}
17910 	/*
17911 	 * Raise the flag indicating that the next sata command could
17912 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
17913 	 * reset is reported.
17914 	 */
17915 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17916 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
17917 		sdinfo->satadrv_reset_time = 0;
17918 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
17919 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
17920 			sdinfo->satadrv_event_flags &=
17921 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17922 			sdinfo->satadrv_event_flags |=
17923 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17924 		}
17925 	}
17926 }
17927 
17928 
17929 /*
17930  * Port Multiplier Port Device Reset Event processing.
17931  *
17932  * NOTE: This function has to be entered with pmport mutex held. It exits with
17933  * mutex held as well, but can release mutex during the processing.
17934  */
17935 static void
17936 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
17937     sata_address_t *saddr)
17938 {
17939 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17940 	sata_drive_info_t *sdinfo = NULL;
17941 	sata_cport_info_t *cportinfo = NULL;
17942 	sata_pmport_info_t *pmportinfo = NULL;
17943 	sata_pmult_info_t *pminfo = NULL;
17944 	sata_device_t sata_device;
17945 	uint8_t cport = saddr->cport;
17946 	uint8_t pmport = saddr->pmport;
17947 	int rval;
17948 
17949 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17950 	    "Processing drive reset at port %d:%d", cport, pmport);
17951 
17952 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17953 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
17954 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
17955 
17956 	/*
17957 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17958 	 * state, ignore reset event.
17959 	 */
17960 	if (((cportinfo->cport_state &
17961 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17962 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17963 		sdinfo->satadrv_event_flags &=
17964 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17965 		return;
17966 	}
17967 
17968 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
17969 		/*
17970 		 * This should not happen - coding error.
17971 		 * But we can recover, so do not panic, just clean up
17972 		 * and if in debug mode, log the message.
17973 		 */
17974 #ifdef SATA_DEBUG
17975 		sata_log(sata_hba_inst, CE_WARN,
17976 		    "sata_process_pmdevice_reset: "
17977 		    "Invalid device type with sdinfo!", NULL);
17978 #endif
17979 		sdinfo->satadrv_event_flags = 0;
17980 		return;
17981 	}
17982 
17983 #ifdef SATA_DEBUG
17984 	if ((sdinfo->satadrv_event_flags &
17985 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17986 		/* Nothing to do */
17987 		/* Something is weird - why we are processing dev reset? */
17988 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17989 		    "No device reset event!!!!", NULL);
17990 
17991 		return;
17992 	}
17993 	if ((sdinfo->satadrv_event_flags &
17994 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17995 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17996 		/* Something is weird - new device reset event */
17997 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17998 		    "Overlapping device reset events!", NULL);
17999 	}
18000 #endif
18001 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18002 	    "Processing port %d:%d device reset", cport, pmport);
18003 
18004 	/* Clear event flag */
18005 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18006 
18007 	/* It seems that we always need to check the port state first */
18008 	sata_device.satadev_rev = SATA_DEVICE_REV;
18009 	sata_device.satadev_addr = *saddr;
18010 	/*
18011 	 * We have to exit mutex, because the HBA probe port function may
18012 	 * block on its own mutex.
18013 	 */
18014 	mutex_exit(&pmportinfo->pmport_mutex);
18015 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18016 	    (SATA_DIP(sata_hba_inst), &sata_device);
18017 	mutex_enter(&pmportinfo->pmport_mutex);
18018 
18019 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18020 	if (rval != SATA_SUCCESS) {
18021 		/* Something went wrong? Fail the port */
18022 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18023 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18024 		    saddr->pmport);
18025 		if (sdinfo != NULL)
18026 			sdinfo->satadrv_event_flags = 0;
18027 		mutex_exit(&pmportinfo->pmport_mutex);
18028 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18029 		    "SATA port %d:%d probing failed",
18030 		    saddr->cport, saddr->pmport));
18031 		mutex_enter(&pmportinfo->pmport_mutex);
18032 		return;
18033 	}
18034 	if ((sata_device.satadev_scr.sstatus  &
18035 	    SATA_PORT_DEVLINK_UP_MASK) !=
18036 	    SATA_PORT_DEVLINK_UP ||
18037 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18038 		/*
18039 		 * No device to process, anymore. Some other event processing
18040 		 * would or have already performed port info cleanup.
18041 		 * To be safe (HBA may need it), request clearing device
18042 		 * reset condition.
18043 		 */
18044 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18045 		    saddr->pmport);
18046 		if (sdinfo != NULL) {
18047 			sdinfo->satadrv_event_flags &=
18048 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18049 			/* must clear flags on cport */
18050 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18051 			    saddr->cport);
18052 			pminfo->pmult_event_flags |=
18053 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18054 		}
18055 		return;
18056 	}
18057 
18058 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18059 	    saddr->pmport);
18060 	if (sdinfo == NULL) {
18061 		return;
18062 	}
18063 	if ((sdinfo->satadrv_event_flags &
18064 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18065 		/*
18066 		 * Start tracking time for device feature restoration and
18067 		 * identification. Save current time (lbolt value).
18068 		 */
18069 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18070 	}
18071 	/* Mark device reset processing as active */
18072 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18073 
18074 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18075 	mutex_exit(&pmportinfo->pmport_mutex);
18076 
18077 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18078 	    SATA_FAILURE) {
18079 		/*
18080 		 * Restoring drive setting failed.
18081 		 * Probe the port first, to check if the port state has changed
18082 		 */
18083 		sata_device.satadev_rev = SATA_DEVICE_REV;
18084 		sata_device.satadev_addr = *saddr;
18085 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18086 
18087 		/* probe port */
18088 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18089 		    (SATA_DIP(sata_hba_inst), &sata_device);
18090 		mutex_enter(&pmportinfo->pmport_mutex);
18091 		if (rval == SATA_SUCCESS &&
18092 		    (sata_device.satadev_state &
18093 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18094 		    (sata_device.satadev_scr.sstatus  &
18095 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18096 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18097 			/*
18098 			 * We may retry this a bit later - in-process reset
18099 			 * condition should be already set.
18100 			 * Track retry time for device identification.
18101 			 */
18102 			if ((pmportinfo->pmport_dev_type &
18103 			    SATA_VALID_DEV_TYPE) != 0 &&
18104 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18105 			    sdinfo->satadrv_reset_time != 0) {
18106 				clock_t cur_time = ddi_get_lbolt();
18107 				/*
18108 				 * If the retry time limit was not
18109 				 * exceeded, retry.
18110 				 */
18111 				if ((cur_time - sdinfo->satadrv_reset_time) <
18112 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18113 					mutex_enter(
18114 					    &sata_hba_inst->satahba_mutex);
18115 					sata_hba_inst->satahba_event_flags |=
18116 					    SATA_EVNT_MAIN;
18117 					mutex_exit(
18118 					    &sata_hba_inst->satahba_mutex);
18119 					mutex_enter(&sata_mutex);
18120 					sata_event_pending |= SATA_EVNT_MAIN;
18121 					mutex_exit(&sata_mutex);
18122 					return;
18123 				}
18124 			}
18125 			/* Fail the drive */
18126 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18127 
18128 			sata_log(sata_hba_inst, CE_WARN,
18129 			    "SATA device at port %d:%d - device failed",
18130 			    saddr->cport, saddr->pmport);
18131 		} else {
18132 			/*
18133 			 * No point of retrying - some other event processing
18134 			 * would or already did port info cleanup.
18135 			 * To be safe (HBA may need it),
18136 			 * request clearing device reset condition.
18137 			 */
18138 			sdinfo->satadrv_event_flags |=
18139 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18140 		}
18141 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18142 		sdinfo->satadrv_reset_time = 0;
18143 		return;
18144 	}
18145 	/*
18146 	 * Raise the flag indicating that the next sata command could
18147 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18148 	 * reset is reported.
18149 	 */
18150 	mutex_enter(&pmportinfo->pmport_mutex);
18151 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18152 		sdinfo->satadrv_reset_time = 0;
18153 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
18154 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18155 			sdinfo->satadrv_event_flags &=
18156 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18157 			/* must clear flags on cport */
18158 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18159 			    saddr->cport);
18160 			pminfo->pmult_event_flags |=
18161 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18162 		}
18163 	}
18164 }
18165 
18166 /*
18167  * Port Link Events processing.
18168  * Every link established event may involve device reset (due to
18169  * COMRESET signal, equivalent of the hard reset) so arbitrarily
18170  * set device reset event for an attached device (if any).
18171  * If the port is in SHUTDOWN or FAILED state, ignore link events.
18172  *
18173  * The link established event processing varies, depending on the state
18174  * of the target node, HBA hotplugging capabilities, state of the port.
18175  * If the link is not active, the link established event is ignored.
18176  * If HBA cannot detect device attachment and there is no target node,
18177  * the link established event triggers device attach event processing.
18178  * Else, link established event triggers device reset event processing.
18179  *
18180  * The link lost event processing varies, depending on a HBA hotplugging
18181  * capability and the state of the port (link active or not active).
18182  * If the link is active, the lost link event is ignored.
18183  * If HBA cannot detect device removal, the lost link event triggers
18184  * device detached event processing after link lost timeout.
18185  * Else, the event is ignored.
18186  *
18187  * NOTE: Port multiplier ports events are handled by
18188  * sata_process_pmport_link_events();
18189  */
18190 static void
18191 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
18192     sata_address_t *saddr)
18193 {
18194 	sata_device_t sata_device;
18195 	sata_cport_info_t *cportinfo;
18196 	sata_drive_info_t *sdinfo;
18197 	uint32_t event_flags;
18198 	int rval;
18199 
18200 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18201 	    "Processing port %d link event(s)", saddr->cport);
18202 
18203 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18204 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18205 	event_flags = cportinfo->cport_event_flags;
18206 
18207 	/* Reset event flags first */
18208 	cportinfo->cport_event_flags &=
18209 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18210 
18211 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18212 	if ((cportinfo->cport_state &
18213 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18214 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18215 		    cport_mutex);
18216 		return;
18217 	}
18218 
18219 	/*
18220 	 * For the sanity sake get current port state.
18221 	 * Set device address only. Other sata_device fields should be
18222 	 * set by HBA driver.
18223 	 */
18224 	sata_device.satadev_rev = SATA_DEVICE_REV;
18225 	sata_device.satadev_addr = *saddr;
18226 	/*
18227 	 * We have to exit mutex, because the HBA probe port function may
18228 	 * block on its own mutex.
18229 	 */
18230 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18231 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18232 	    (SATA_DIP(sata_hba_inst), &sata_device);
18233 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18234 	sata_update_port_info(sata_hba_inst, &sata_device);
18235 	if (rval != SATA_SUCCESS) {
18236 		/* Something went wrong? Fail the port */
18237 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18238 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18239 		    cport_mutex);
18240 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18241 		    "SATA port %d probing failed",
18242 		    saddr->cport));
18243 		/*
18244 		 * We may want to release device info structure, but
18245 		 * it is not necessary.
18246 		 */
18247 		return;
18248 	} else {
18249 		/* port probed successfully */
18250 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18251 	}
18252 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18253 
18254 		if ((sata_device.satadev_scr.sstatus &
18255 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18256 			/* Ignore event */
18257 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18258 			    "Ignoring port %d link established event - "
18259 			    "link down",
18260 			    saddr->cport);
18261 			goto linklost;
18262 		}
18263 
18264 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18265 		    "Processing port %d link established event",
18266 		    saddr->cport);
18267 
18268 		/*
18269 		 * For the sanity sake check if a device is attached - check
18270 		 * return state of a port probing.
18271 		 */
18272 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
18273 			/*
18274 			 * HBA port probe indicated that there is a device
18275 			 * attached. Check if the framework had device info
18276 			 * structure attached for this device.
18277 			 */
18278 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
18279 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
18280 				    NULL);
18281 
18282 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18283 				if ((sdinfo->satadrv_type &
18284 				    SATA_VALID_DEV_TYPE) != 0) {
18285 					/*
18286 					 * Dev info structure is present.
18287 					 * If dev_type is set to known type in
18288 					 * the framework's drive info struct
18289 					 * then the device existed before and
18290 					 * the link was probably lost
18291 					 * momentarily - in such case
18292 					 * we may want to check device
18293 					 * identity.
18294 					 * Identity check is not supported now.
18295 					 *
18296 					 * Link established event
18297 					 * triggers device reset event.
18298 					 */
18299 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
18300 					    satadrv_event_flags |=
18301 					    SATA_EVNT_DEVICE_RESET;
18302 				}
18303 			} else if (cportinfo->cport_dev_type ==
18304 			    SATA_DTYPE_NONE) {
18305 				/*
18306 				 * We got new device attached! If HBA does not
18307 				 * generate device attached events, trigger it
18308 				 * here.
18309 				 */
18310 				if (!(SATA_FEATURES(sata_hba_inst) &
18311 				    SATA_CTLF_HOTPLUG)) {
18312 					cportinfo->cport_event_flags |=
18313 					    SATA_EVNT_DEVICE_ATTACHED;
18314 				}
18315 			}
18316 			/* Reset link lost timeout */
18317 			cportinfo->cport_link_lost_time = 0;
18318 		}
18319 	}
18320 linklost:
18321 	if (event_flags & SATA_EVNT_LINK_LOST) {
18322 		if ((sata_device.satadev_scr.sstatus &
18323 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18324 			/* Ignore event */
18325 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18326 			    "Ignoring port %d link lost event - link is up",
18327 			    saddr->cport);
18328 			goto done;
18329 		}
18330 #ifdef SATA_DEBUG
18331 		if (cportinfo->cport_link_lost_time == 0) {
18332 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18333 			    "Processing port %d link lost event",
18334 			    saddr->cport);
18335 		}
18336 #endif
18337 		/*
18338 		 * When HBA cannot generate device attached/detached events,
18339 		 * we need to track link lost time and eventually generate
18340 		 * device detach event.
18341 		 */
18342 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18343 			/* We are tracking link lost time */
18344 			if (cportinfo->cport_link_lost_time == 0) {
18345 				/* save current time (lbolt value) */
18346 				cportinfo->cport_link_lost_time =
18347 				    ddi_get_lbolt();
18348 				/* just keep link lost event */
18349 				cportinfo->cport_event_flags |=
18350 				    SATA_EVNT_LINK_LOST;
18351 			} else {
18352 				clock_t cur_time = ddi_get_lbolt();
18353 				if ((cur_time -
18354 				    cportinfo->cport_link_lost_time) >=
18355 				    drv_usectohz(
18356 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18357 					/* trigger device detach event */
18358 					cportinfo->cport_event_flags |=
18359 					    SATA_EVNT_DEVICE_DETACHED;
18360 					cportinfo->cport_link_lost_time = 0;
18361 					SATADBG1(SATA_DBG_EVENTS,
18362 					    sata_hba_inst,
18363 					    "Triggering port %d "
18364 					    "device detached event",
18365 					    saddr->cport);
18366 				} else {
18367 					/* keep link lost event */
18368 					cportinfo->cport_event_flags |=
18369 					    SATA_EVNT_LINK_LOST;
18370 				}
18371 			}
18372 		}
18373 		/*
18374 		 * We could change port state to disable/delay access to
18375 		 * the attached device until the link is recovered.
18376 		 */
18377 	}
18378 done:
18379 	event_flags = cportinfo->cport_event_flags;
18380 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18381 	if (event_flags != 0) {
18382 		mutex_enter(&sata_hba_inst->satahba_mutex);
18383 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18384 		mutex_exit(&sata_hba_inst->satahba_mutex);
18385 		mutex_enter(&sata_mutex);
18386 		sata_event_pending |= SATA_EVNT_MAIN;
18387 		mutex_exit(&sata_mutex);
18388 	}
18389 }
18390 
18391 /*
18392  * Port Multiplier Port Link Events processing.
18393  */
18394 static void
18395 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
18396     sata_address_t *saddr)
18397 {
18398 	sata_device_t sata_device;
18399 	sata_pmport_info_t *pmportinfo = NULL;
18400 	sata_drive_info_t *sdinfo = NULL;
18401 	uint32_t event_flags;
18402 	uint8_t cport = saddr->cport;
18403 	uint8_t pmport = saddr->pmport;
18404 	int rval;
18405 
18406 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18407 	    "Processing port %d:%d link event(s)",
18408 	    cport, pmport);
18409 
18410 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18411 	mutex_enter(&pmportinfo->pmport_mutex);
18412 	event_flags = pmportinfo->pmport_event_flags;
18413 
18414 	/* Reset event flags first */
18415 	pmportinfo->pmport_event_flags &=
18416 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18417 
18418 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18419 	if ((pmportinfo->pmport_state &
18420 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18421 		mutex_exit(&pmportinfo->pmport_mutex);
18422 		return;
18423 	}
18424 
18425 	/*
18426 	 * For the sanity sake get current port state.
18427 	 * Set device address only. Other sata_device fields should be
18428 	 * set by HBA driver.
18429 	 */
18430 	sata_device.satadev_rev = SATA_DEVICE_REV;
18431 	sata_device.satadev_addr = *saddr;
18432 	/*
18433 	 * We have to exit mutex, because the HBA probe port function may
18434 	 * block on its own mutex.
18435 	 */
18436 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18437 	    saddr->pmport));
18438 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18439 	    (SATA_DIP(sata_hba_inst), &sata_device);
18440 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18441 	    saddr->pmport));
18442 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18443 	if (rval != SATA_SUCCESS) {
18444 		/* Something went wrong? Fail the port */
18445 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18446 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18447 		    saddr->pmport));
18448 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18449 		    "SATA port %d:%d probing failed",
18450 		    saddr->cport, saddr->pmport));
18451 		/*
18452 		 * We may want to release device info structure, but
18453 		 * it is not necessary.
18454 		 */
18455 		return;
18456 	} else {
18457 		/* port probed successfully */
18458 		pmportinfo->pmport_state |=
18459 		    SATA_STATE_PROBED | SATA_STATE_READY;
18460 	}
18461 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
18462 	    saddr->cport, saddr->pmport));
18463 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
18464 	    saddr->cport, saddr->pmport));
18465 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18466 
18467 		if ((sata_device.satadev_scr.sstatus &
18468 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18469 			/* Ignore event */
18470 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18471 			    "Ignoring port %d:%d link established event - "
18472 			    "link down",
18473 			    saddr->cport, saddr->pmport);
18474 			goto linklost;
18475 		}
18476 
18477 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18478 		    "Processing port %d:%d link established event",
18479 		    cport, pmport);
18480 
18481 		/*
18482 		 * For the sanity sake check if a device is attached - check
18483 		 * return state of a port probing.
18484 		 */
18485 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
18486 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
18487 			/*
18488 			 * HBA port probe indicated that there is a device
18489 			 * attached. Check if the framework had device info
18490 			 * structure attached for this device.
18491 			 */
18492 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
18493 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
18494 				    NULL);
18495 
18496 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18497 				if ((sdinfo->satadrv_type &
18498 				    SATA_VALID_DEV_TYPE) != 0) {
18499 					/*
18500 					 * Dev info structure is present.
18501 					 * If dev_type is set to known type in
18502 					 * the framework's drive info struct
18503 					 * then the device existed before and
18504 					 * the link was probably lost
18505 					 * momentarily - in such case
18506 					 * we may want to check device
18507 					 * identity.
18508 					 * Identity check is not supported now.
18509 					 *
18510 					 * Link established event
18511 					 * triggers device reset event.
18512 					 */
18513 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
18514 					    satadrv_event_flags |=
18515 					    SATA_EVNT_DEVICE_RESET;
18516 				}
18517 			} else if (pmportinfo->pmport_dev_type ==
18518 			    SATA_DTYPE_NONE) {
18519 				/*
18520 				 * We got new device attached! If HBA does not
18521 				 * generate device attached events, trigger it
18522 				 * here.
18523 				 */
18524 				if (!(SATA_FEATURES(sata_hba_inst) &
18525 				    SATA_CTLF_HOTPLUG)) {
18526 					pmportinfo->pmport_event_flags |=
18527 					    SATA_EVNT_DEVICE_ATTACHED;
18528 				}
18529 			}
18530 			/* Reset link lost timeout */
18531 			pmportinfo->pmport_link_lost_time = 0;
18532 		}
18533 	}
18534 linklost:
18535 	if (event_flags & SATA_EVNT_LINK_LOST) {
18536 #ifdef SATA_DEBUG
18537 		if (pmportinfo->pmport_link_lost_time == 0) {
18538 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18539 			    "Processing port %d:%d link lost event",
18540 			    saddr->cport, saddr->pmport);
18541 		}
18542 #endif
18543 		if ((sata_device.satadev_scr.sstatus &
18544 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18545 			/* Ignore event */
18546 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18547 			    "Ignoring port %d:%d link lost event - link is up",
18548 			    saddr->cport, saddr->pmport);
18549 			goto done;
18550 		}
18551 		/*
18552 		 * When HBA cannot generate device attached/detached events,
18553 		 * we need to track link lost time and eventually generate
18554 		 * device detach event.
18555 		 */
18556 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18557 			/* We are tracking link lost time */
18558 			if (pmportinfo->pmport_link_lost_time == 0) {
18559 				/* save current time (lbolt value) */
18560 				pmportinfo->pmport_link_lost_time =
18561 				    ddi_get_lbolt();
18562 				/* just keep link lost event */
18563 				pmportinfo->pmport_event_flags |=
18564 				    SATA_EVNT_LINK_LOST;
18565 			} else {
18566 				clock_t cur_time = ddi_get_lbolt();
18567 				if ((cur_time -
18568 				    pmportinfo->pmport_link_lost_time) >=
18569 				    drv_usectohz(
18570 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18571 					/* trigger device detach event */
18572 					pmportinfo->pmport_event_flags |=
18573 					    SATA_EVNT_DEVICE_DETACHED;
18574 					pmportinfo->pmport_link_lost_time = 0;
18575 					SATADBG2(SATA_DBG_EVENTS,
18576 					    sata_hba_inst,
18577 					    "Triggering port %d:%d "
18578 					    "device detached event",
18579 					    saddr->cport, saddr->pmport);
18580 				} else {
18581 					/* keep link lost event */
18582 					pmportinfo->pmport_event_flags |=
18583 					    SATA_EVNT_LINK_LOST;
18584 				}
18585 			}
18586 		}
18587 		/*
18588 		 * We could change port state to disable/delay access to
18589 		 * the attached device until the link is recovered.
18590 		 */
18591 	}
18592 done:
18593 	event_flags = pmportinfo->pmport_event_flags;
18594 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18595 	    saddr->pmport));
18596 	if (event_flags != 0) {
18597 		mutex_enter(&sata_hba_inst->satahba_mutex);
18598 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18599 		mutex_exit(&sata_hba_inst->satahba_mutex);
18600 		mutex_enter(&sata_mutex);
18601 		sata_event_pending |= SATA_EVNT_MAIN;
18602 		mutex_exit(&sata_mutex);
18603 	}
18604 }
18605 
18606 /*
18607  * Device Detached Event processing.
18608  * Port is probed to find if a device is really gone. If so,
18609  * the device info structure is detached from the SATA port info structure
18610  * and released.
18611  * Port status is updated.
18612  *
18613  * NOTE: Port multiplier ports events are handled by
18614  * sata_process_pmdevice_detached()
18615  */
18616 static void
18617 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
18618     sata_address_t *saddr)
18619 {
18620 	sata_cport_info_t *cportinfo;
18621 	sata_pmport_info_t *pmportinfo;
18622 	sata_drive_info_t *sdevinfo;
18623 	sata_device_t sata_device;
18624 	sata_address_t pmport_addr;
18625 	char name[16];
18626 	uint8_t cport = saddr->cport;
18627 	int npmport;
18628 	int rval;
18629 
18630 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18631 	    "Processing port %d device detached", saddr->cport);
18632 
18633 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18634 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18635 	/* Clear event flag */
18636 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18637 
18638 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18639 	if ((cportinfo->cport_state &
18640 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18641 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18642 		    cport_mutex);
18643 		return;
18644 	}
18645 	/* For sanity, re-probe the port */
18646 	sata_device.satadev_rev = SATA_DEVICE_REV;
18647 	sata_device.satadev_addr = *saddr;
18648 
18649 	/*
18650 	 * We have to exit mutex, because the HBA probe port function may
18651 	 * block on its own mutex.
18652 	 */
18653 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18654 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18655 	    (SATA_DIP(sata_hba_inst), &sata_device);
18656 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18657 	sata_update_port_info(sata_hba_inst, &sata_device);
18658 	if (rval != SATA_SUCCESS) {
18659 		/* Something went wrong? Fail the port */
18660 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18661 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18662 		    cport_mutex);
18663 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18664 		    "SATA port %d probing failed",
18665 		    saddr->cport));
18666 		/*
18667 		 * We may want to release device info structure, but
18668 		 * it is not necessary.
18669 		 */
18670 		return;
18671 	} else {
18672 		/* port probed successfully */
18673 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18674 	}
18675 	/*
18676 	 * Check if a device is still attached. For sanity, check also
18677 	 * link status - if no link, there is no device.
18678 	 */
18679 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18680 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18681 	    SATA_DTYPE_NONE) {
18682 		/*
18683 		 * Device is still attached - ignore detach event.
18684 		 */
18685 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18686 		    cport_mutex);
18687 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18688 		    "Ignoring detach - device still attached to port %d",
18689 		    sata_device.satadev_addr.cport);
18690 		return;
18691 	}
18692 	/*
18693 	 * We need to detach and release device info structure here
18694 	 */
18695 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18696 		/*
18697 		 * A port-multiplier is removed.
18698 		 *
18699 		 * Calling sata_process_pmdevice_detached() does not work
18700 		 * here. The port multiplier is gone, so we cannot probe
18701 		 * sub-port any more and all pmult-related data structure must
18702 		 * be de-allocated immediately. Following structure of every
18703 		 * implemented sub-port behind the pmult are required to
18704 		 * released.
18705 		 *
18706 		 *   - attachment point
18707 		 *   - target node
18708 		 *   - sata_drive_info
18709 		 *   - sata_pmport_info
18710 		 */
18711 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
18712 		    cport); npmport ++) {
18713 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
18714 			    sata_hba_inst,
18715 			    "Detaching target node at port %d:%d",
18716 			    cport, npmport);
18717 
18718 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18719 
18720 			/* Remove attachment point. */
18721 			name[0] = '\0';
18722 			(void) sprintf(name, "%d.%d", cport, npmport);
18723 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
18724 			sata_log(sata_hba_inst, CE_NOTE,
18725 			    "Remove attachment point of port %d:%d",
18726 			    cport, npmport);
18727 
18728 			/* Remove target node */
18729 			pmport_addr.cport = cport;
18730 			pmport_addr.pmport = (uint8_t)npmport;
18731 			pmport_addr.qual = SATA_ADDR_PMPORT;
18732 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
18733 
18734 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18735 
18736 			/* Release sata_pmport_info & sata_drive_info. */
18737 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18738 			    cport, npmport);
18739 			ASSERT(pmportinfo != NULL);
18740 
18741 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18742 			if (sdevinfo != NULL) {
18743 				(void) kmem_free((void *) sdevinfo,
18744 				    sizeof (sata_drive_info_t));
18745 			}
18746 
18747 			/* Release sata_pmport_info at last */
18748 			(void) kmem_free((void *) pmportinfo,
18749 			    sizeof (sata_pmport_info_t));
18750 		}
18751 
18752 		/* Finally, release sata_pmult_info */
18753 		(void) kmem_free((void *)
18754 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
18755 		    sizeof (sata_pmult_info_t));
18756 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
18757 
18758 		sata_log(sata_hba_inst, CE_WARN,
18759 		    "SATA port-multiplier detached at port %d", cport);
18760 
18761 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18762 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18763 		    saddr->cport)->cport_mutex);
18764 	} else {
18765 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18766 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18767 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18768 			(void) kmem_free((void *)sdevinfo,
18769 			    sizeof (sata_drive_info_t));
18770 		}
18771 		sata_log(sata_hba_inst, CE_WARN,
18772 		    "SATA device detached at port %d", cport);
18773 
18774 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18775 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18776 		    saddr->cport)->cport_mutex);
18777 
18778 		/*
18779 		 * Try to offline a device and remove target node
18780 		 * if it still exists
18781 		 */
18782 		sata_remove_target_node(sata_hba_inst, saddr);
18783 	}
18784 
18785 
18786 	/*
18787 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18788 	 * with the hint: SE_HINT_REMOVE
18789 	 */
18790 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18791 }
18792 
18793 /*
18794  * Port Multiplier Port Device Deattached Event processing.
18795  *
18796  * NOTE: No Mutex should be hold.
18797  */
18798 static void
18799 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
18800     sata_address_t *saddr)
18801 {
18802 	sata_pmport_info_t *pmportinfo;
18803 	sata_drive_info_t *sdevinfo;
18804 	sata_device_t sata_device;
18805 	int rval;
18806 	uint8_t cport, pmport;
18807 
18808 	cport = saddr->cport;
18809 	pmport = saddr->pmport;
18810 
18811 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18812 	    "Processing port %d:%d device detached",
18813 	    cport, pmport);
18814 
18815 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18816 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18817 
18818 	/* Clear event flag */
18819 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18820 
18821 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18822 	if ((pmportinfo->pmport_state &
18823 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18824 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18825 		return;
18826 	}
18827 	/* For sanity, re-probe the port */
18828 	sata_device.satadev_rev = SATA_DEVICE_REV;
18829 	sata_device.satadev_addr = *saddr;
18830 
18831 	/*
18832 	 * We have to exit mutex, because the HBA probe port function may
18833 	 * block on its own mutex.
18834 	 */
18835 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18836 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18837 	    (SATA_DIP(sata_hba_inst), &sata_device);
18838 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18839 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18840 	if (rval != SATA_SUCCESS) {
18841 		/* Something went wrong? Fail the port */
18842 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18843 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18844 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18845 		    "SATA port %d:%d probing failed",
18846 		    saddr->pmport));
18847 		/*
18848 		 * We may want to release device info structure, but
18849 		 * it is not necessary.
18850 		 */
18851 		return;
18852 	} else {
18853 		/* port probed successfully */
18854 		pmportinfo->pmport_state |=
18855 		    SATA_STATE_PROBED | SATA_STATE_READY;
18856 	}
18857 	/*
18858 	 * Check if a device is still attached. For sanity, check also
18859 	 * link status - if no link, there is no device.
18860 	 */
18861 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18862 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18863 	    SATA_DTYPE_NONE) {
18864 		/*
18865 		 * Device is still attached - ignore detach event.
18866 		 */
18867 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18868 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18869 		    "Ignoring detach - device still attached to port %d",
18870 		    sata_device.satadev_addr.pmport);
18871 		return;
18872 	}
18873 	/*
18874 	 * We need to detach and release device info structure here
18875 	 */
18876 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18877 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18878 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
18879 		(void) kmem_free((void *)sdevinfo,
18880 		    sizeof (sata_drive_info_t));
18881 	}
18882 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
18883 	/*
18884 	 * Device cannot be reached anymore, even if the target node may be
18885 	 * still present.
18886 	 */
18887 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18888 
18889 	/*
18890 	 * Try to offline a device and remove target node if it still exists
18891 	 */
18892 	sata_remove_target_node(sata_hba_inst, saddr);
18893 
18894 	/*
18895 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18896 	 * with the hint: SE_HINT_REMOVE
18897 	 */
18898 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18899 }
18900 
18901 
18902 /*
18903  * Device Attached Event processing.
18904  * Port state is checked to verify that a device is really attached. If so,
18905  * the device info structure is created and attached to the SATA port info
18906  * structure.
18907  *
18908  * If attached device cannot be identified or set-up, the retry for the
18909  * attach processing is set-up. Subsequent daemon run would try again to
18910  * identify the device, until the time limit is reached
18911  * (SATA_DEV_IDENTIFY_TIMEOUT).
18912  *
18913  * This function cannot be called in interrupt context (it may sleep).
18914  *
18915  * NOTE: Port multiplier ports events are handled by
18916  * sata_process_pmdevice_attached()
18917  */
18918 static void
18919 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
18920     sata_address_t *saddr)
18921 {
18922 	sata_cport_info_t *cportinfo = NULL;
18923 	sata_drive_info_t *sdevinfo = NULL;
18924 	sata_pmult_info_t *pmultinfo = NULL;
18925 	sata_pmport_info_t *pmportinfo = NULL;
18926 	sata_device_t sata_device;
18927 	dev_info_t *tdip;
18928 	uint32_t event_flags = 0, pmult_event_flags = 0;
18929 	int rval;
18930 	int npmport;
18931 
18932 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18933 	    "Processing port %d device attached", saddr->cport);
18934 
18935 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18936 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18937 
18938 	/* Clear attach event flag first */
18939 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
18940 
18941 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
18942 	if ((cportinfo->cport_state &
18943 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18944 		cportinfo->cport_dev_attach_time = 0;
18945 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18946 		    cport_mutex);
18947 		return;
18948 	}
18949 
18950 	/*
18951 	 * If the sata_drive_info structure is found attached to the port info,
18952 	 * despite the fact the device was removed and now it is re-attached,
18953 	 * the old drive info structure was not removed.
18954 	 * Arbitrarily release device info structure.
18955 	 */
18956 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18957 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18958 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18959 		(void) kmem_free((void *)sdevinfo,
18960 		    sizeof (sata_drive_info_t));
18961 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18962 		    "Arbitrarily detaching old device info.", NULL);
18963 	}
18964 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18965 
18966 	/* For sanity, re-probe the port */
18967 	sata_device.satadev_rev = SATA_DEVICE_REV;
18968 	sata_device.satadev_addr = *saddr;
18969 
18970 	/*
18971 	 * We have to exit mutex, because the HBA probe port function may
18972 	 * block on its own mutex.
18973 	 */
18974 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18975 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18976 	    (SATA_DIP(sata_hba_inst), &sata_device);
18977 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18978 	sata_update_port_info(sata_hba_inst, &sata_device);
18979 	if (rval != SATA_SUCCESS) {
18980 		/* Something went wrong? Fail the port */
18981 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18982 		cportinfo->cport_dev_attach_time = 0;
18983 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18984 		    cport_mutex);
18985 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18986 		    "SATA port %d probing failed",
18987 		    saddr->cport));
18988 		return;
18989 	} else {
18990 		/* port probed successfully */
18991 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18992 	}
18993 	/*
18994 	 * Check if a device is still attached. For sanity, check also
18995 	 * link status - if no link, there is no device.
18996 	 */
18997 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
18998 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
18999 	    SATA_DTYPE_NONE) {
19000 		/*
19001 		 * No device - ignore attach event.
19002 		 */
19003 		cportinfo->cport_dev_attach_time = 0;
19004 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19005 		    cport_mutex);
19006 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19007 		    "Ignoring attach - no device connected to port %d",
19008 		    sata_device.satadev_addr.cport);
19009 		return;
19010 	}
19011 
19012 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19013 	/*
19014 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19015 	 * with the hint: SE_HINT_INSERT
19016 	 */
19017 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19018 
19019 	/*
19020 	 * Port reprobing will take care of the creation of the device
19021 	 * info structure and determination of the device type.
19022 	 */
19023 	sata_device.satadev_addr = *saddr;
19024 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19025 	    SATA_DEV_IDENTIFY_NORETRY);
19026 
19027 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19028 	    cport_mutex);
19029 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19030 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19031 		/* Some device is attached to the port */
19032 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19033 			/*
19034 			 * A device was not successfully attached.
19035 			 * Track retry time for device identification.
19036 			 */
19037 			if (cportinfo->cport_dev_attach_time != 0) {
19038 				clock_t cur_time = ddi_get_lbolt();
19039 				/*
19040 				 * If the retry time limit was not exceeded,
19041 				 * reinstate attach event.
19042 				 */
19043 				if ((cur_time -
19044 				    cportinfo->cport_dev_attach_time) <
19045 				    drv_usectohz(
19046 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19047 					/* OK, restore attach event */
19048 					cportinfo->cport_event_flags |=
19049 					    SATA_EVNT_DEVICE_ATTACHED;
19050 				} else {
19051 					/* Timeout - cannot identify device */
19052 					cportinfo->cport_dev_attach_time = 0;
19053 					sata_log(sata_hba_inst,
19054 					    CE_WARN,
19055 					    "Could not identify SATA device "
19056 					    "at port %d",
19057 					    saddr->cport);
19058 				}
19059 			} else {
19060 				/*
19061 				 * Start tracking time for device
19062 				 * identification.
19063 				 * Save current time (lbolt value).
19064 				 */
19065 				cportinfo->cport_dev_attach_time =
19066 				    ddi_get_lbolt();
19067 				/* Restore attach event */
19068 				cportinfo->cport_event_flags |=
19069 				    SATA_EVNT_DEVICE_ATTACHED;
19070 			}
19071 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19072 			cportinfo->cport_dev_attach_time = 0;
19073 			sata_log(sata_hba_inst, CE_NOTE,
19074 			    "SATA port-multiplier detected at port %d",
19075 			    saddr->cport);
19076 
19077 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19078 				/* Log the info of new port multiplier */
19079 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19080 				    saddr->cport)->cport_mutex);
19081 				sata_show_pmult_info(sata_hba_inst,
19082 				    &sata_device);
19083 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19084 				    saddr->cport)->cport_mutex);
19085 			}
19086 
19087 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19088 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19089 			for (npmport = 0; npmport <
19090 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19091 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19092 				    saddr->cport, npmport);
19093 				ASSERT(pmportinfo != NULL);
19094 
19095 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19096 				    saddr->cport)->cport_mutex);
19097 				mutex_enter(&pmportinfo->pmport_mutex);
19098 				/* Marked all pmports with link events. */
19099 				pmportinfo->pmport_event_flags =
19100 				    SATA_EVNT_LINK_ESTABLISHED;
19101 				pmult_event_flags |=
19102 				    pmportinfo->pmport_event_flags;
19103 				mutex_exit(&pmportinfo->pmport_mutex);
19104 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19105 				    saddr->cport)->cport_mutex);
19106 			}
19107 			/* Auto-online is not available for PMult now. */
19108 
19109 		} else {
19110 			/*
19111 			 * If device was successfully attached, the subsequent
19112 			 * action depends on a state of the
19113 			 * sata_auto_online variable. If it is set to zero.
19114 			 * an explicit 'configure' command will be needed to
19115 			 * configure it. If its value is non-zero, we will
19116 			 * attempt to online (configure) the device.
19117 			 * First, log the message indicating that a device
19118 			 * was attached.
19119 			 */
19120 			cportinfo->cport_dev_attach_time = 0;
19121 			sata_log(sata_hba_inst, CE_WARN,
19122 			    "SATA device detected at port %d", saddr->cport);
19123 
19124 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19125 				sata_drive_info_t new_sdinfo;
19126 
19127 				/* Log device info data */
19128 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
19129 				    cportinfo));
19130 				sata_show_drive_info(sata_hba_inst,
19131 				    &new_sdinfo);
19132 			}
19133 
19134 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19135 			    saddr->cport)->cport_mutex);
19136 
19137 			/*
19138 			 * Make sure that there is no target node for that
19139 			 * device. If so, release it. It should not happen,
19140 			 * unless we had problem removing the node when
19141 			 * device was detached.
19142 			 */
19143 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19144 			    saddr->cport, saddr->pmport);
19145 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19146 			    saddr->cport)->cport_mutex);
19147 			if (tdip != NULL) {
19148 
19149 #ifdef SATA_DEBUG
19150 				if ((cportinfo->cport_event_flags &
19151 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19152 					sata_log(sata_hba_inst, CE_WARN,
19153 					    "sata_process_device_attached: "
19154 					    "old device target node exists!");
19155 #endif
19156 				/*
19157 				 * target node exists - try to unconfigure
19158 				 * device and remove the node.
19159 				 */
19160 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19161 				    saddr->cport)->cport_mutex);
19162 				rval = ndi_devi_offline(tdip,
19163 				    NDI_DEVI_REMOVE);
19164 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19165 				    saddr->cport)->cport_mutex);
19166 
19167 				if (rval == NDI_SUCCESS) {
19168 					cportinfo->cport_event_flags &=
19169 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19170 					cportinfo->cport_tgtnode_clean = B_TRUE;
19171 				} else {
19172 					/*
19173 					 * PROBLEM - the target node remained
19174 					 * and it belongs to a previously
19175 					 * attached device.
19176 					 * This happens when the file was open
19177 					 * or the node was waiting for
19178 					 * resources at the time the
19179 					 * associated device was removed.
19180 					 * Instruct event daemon to retry the
19181 					 * cleanup later.
19182 					 */
19183 					sata_log(sata_hba_inst,
19184 					    CE_WARN,
19185 					    "Application(s) accessing "
19186 					    "previously attached SATA "
19187 					    "device have to release "
19188 					    "it before newly inserted "
19189 					    "device can be made accessible.",
19190 					    saddr->cport);
19191 					cportinfo->cport_event_flags |=
19192 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19193 					cportinfo->cport_tgtnode_clean =
19194 					    B_FALSE;
19195 				}
19196 			}
19197 			if (sata_auto_online != 0) {
19198 				cportinfo->cport_event_flags |=
19199 				    SATA_EVNT_AUTOONLINE_DEVICE;
19200 			}
19201 
19202 		}
19203 	} else {
19204 		cportinfo->cport_dev_attach_time = 0;
19205 	}
19206 
19207 	event_flags = cportinfo->cport_event_flags;
19208 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19209 	if (event_flags != 0 || pmult_event_flags != 0) {
19210 		mutex_enter(&sata_hba_inst->satahba_mutex);
19211 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19212 		mutex_exit(&sata_hba_inst->satahba_mutex);
19213 		mutex_enter(&sata_mutex);
19214 		sata_event_pending |= SATA_EVNT_MAIN;
19215 		mutex_exit(&sata_mutex);
19216 	}
19217 }
19218 
19219 /*
19220  * Port Multiplier Port Device Attached Event processing.
19221  *
19222  * NOTE: No Mutex should be hold.
19223  */
19224 static void
19225 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
19226     sata_address_t *saddr)
19227 {
19228 	sata_pmport_info_t *pmportinfo;
19229 	sata_drive_info_t *sdinfo;
19230 	sata_device_t sata_device;
19231 	dev_info_t *tdip;
19232 	uint32_t event_flags;
19233 	uint8_t cport = saddr->cport;
19234 	uint8_t pmport = saddr->pmport;
19235 	int rval;
19236 
19237 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19238 	    "Processing port %d:%d device attached", cport, pmport);
19239 
19240 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19241 
19242 	mutex_enter(&pmportinfo->pmport_mutex);
19243 
19244 	/* Clear attach event flag first */
19245 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19246 
19247 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19248 	if ((pmportinfo->pmport_state &
19249 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19250 		pmportinfo->pmport_dev_attach_time = 0;
19251 		mutex_exit(&pmportinfo->pmport_mutex);
19252 		return;
19253 	}
19254 
19255 	/*
19256 	 * If the sata_drive_info structure is found attached to the port info,
19257 	 * despite the fact the device was removed and now it is re-attached,
19258 	 * the old drive info structure was not removed.
19259 	 * Arbitrarily release device info structure.
19260 	 */
19261 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19262 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19263 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19264 		(void) kmem_free((void *)sdinfo,
19265 		    sizeof (sata_drive_info_t));
19266 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19267 		    "Arbitrarily detaching old device info.", NULL);
19268 	}
19269 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19270 
19271 	/* For sanity, re-probe the port */
19272 	sata_device.satadev_rev = SATA_DEVICE_REV;
19273 	sata_device.satadev_addr = *saddr;
19274 
19275 	/*
19276 	 * We have to exit mutex, because the HBA probe port function may
19277 	 * block on its own mutex.
19278 	 */
19279 	mutex_exit(&pmportinfo->pmport_mutex);
19280 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19281 	    (SATA_DIP(sata_hba_inst), &sata_device);
19282 	mutex_enter(&pmportinfo->pmport_mutex);
19283 
19284 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19285 	if (rval != SATA_SUCCESS) {
19286 		/* Something went wrong? Fail the port */
19287 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19288 		pmportinfo->pmport_dev_attach_time = 0;
19289 		mutex_exit(&pmportinfo->pmport_mutex);
19290 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19291 		    "SATA port %d:%d probing failed", cport, pmport));
19292 		return;
19293 	} else {
19294 		/* pmport probed successfully */
19295 		pmportinfo->pmport_state |=
19296 		    SATA_STATE_PROBED | SATA_STATE_READY;
19297 	}
19298 	/*
19299 	 * Check if a device is still attached. For sanity, check also
19300 	 * link status - if no link, there is no device.
19301 	 */
19302 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19303 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19304 	    SATA_DTYPE_NONE) {
19305 		/*
19306 		 * No device - ignore attach event.
19307 		 */
19308 		pmportinfo->pmport_dev_attach_time = 0;
19309 		mutex_exit(&pmportinfo->pmport_mutex);
19310 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19311 		    "Ignoring attach - no device connected to port %d:%d",
19312 		    cport, pmport);
19313 		return;
19314 	}
19315 
19316 	mutex_exit(&pmportinfo->pmport_mutex);
19317 	/*
19318 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19319 	 * with the hint: SE_HINT_INSERT
19320 	 */
19321 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19322 
19323 	/*
19324 	 * Port reprobing will take care of the creation of the device
19325 	 * info structure and determination of the device type.
19326 	 */
19327 	sata_device.satadev_addr = *saddr;
19328 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19329 	    SATA_DEV_IDENTIFY_NORETRY);
19330 
19331 	mutex_enter(&pmportinfo->pmport_mutex);
19332 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
19333 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
19334 		/* Some device is attached to the port */
19335 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
19336 			/*
19337 			 * A device was not successfully attached.
19338 			 * Track retry time for device identification.
19339 			 */
19340 			if (pmportinfo->pmport_dev_attach_time != 0) {
19341 				clock_t cur_time = ddi_get_lbolt();
19342 				/*
19343 				 * If the retry time limit was not exceeded,
19344 				 * reinstate attach event.
19345 				 */
19346 				if ((cur_time -
19347 				    pmportinfo->pmport_dev_attach_time) <
19348 				    drv_usectohz(
19349 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19350 					/* OK, restore attach event */
19351 					pmportinfo->pmport_event_flags |=
19352 					    SATA_EVNT_DEVICE_ATTACHED;
19353 				} else {
19354 					/* Timeout - cannot identify device */
19355 					pmportinfo->pmport_dev_attach_time = 0;
19356 					sata_log(sata_hba_inst, CE_WARN,
19357 					    "Could not identify SATA device "
19358 					    "at port %d:%d",
19359 					    cport, pmport);
19360 				}
19361 			} else {
19362 				/*
19363 				 * Start tracking time for device
19364 				 * identification.
19365 				 * Save current time (lbolt value).
19366 				 */
19367 				pmportinfo->pmport_dev_attach_time =
19368 				    ddi_get_lbolt();
19369 				/* Restore attach event */
19370 				pmportinfo->pmport_event_flags |=
19371 				    SATA_EVNT_DEVICE_ATTACHED;
19372 			}
19373 		} else {
19374 			/*
19375 			 * If device was successfully attached, the subsequent
19376 			 * action depends on a state of the
19377 			 * sata_auto_online variable. If it is set to zero.
19378 			 * an explicit 'configure' command will be needed to
19379 			 * configure it. If its value is non-zero, we will
19380 			 * attempt to online (configure) the device.
19381 			 * First, log the message indicating that a device
19382 			 * was attached.
19383 			 */
19384 			pmportinfo->pmport_dev_attach_time = 0;
19385 			sata_log(sata_hba_inst, CE_WARN,
19386 			    "SATA device detected at port %d:%d",
19387 			    cport, pmport);
19388 
19389 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19390 				sata_drive_info_t new_sdinfo;
19391 
19392 				/* Log device info data */
19393 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
19394 				    pmportinfo));
19395 				sata_show_drive_info(sata_hba_inst,
19396 				    &new_sdinfo);
19397 			}
19398 
19399 			mutex_exit(&pmportinfo->pmport_mutex);
19400 
19401 			/*
19402 			 * Make sure that there is no target node for that
19403 			 * device. If so, release it. It should not happen,
19404 			 * unless we had problem removing the node when
19405 			 * device was detached.
19406 			 */
19407 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19408 			    saddr->cport, saddr->pmport);
19409 			mutex_enter(&pmportinfo->pmport_mutex);
19410 			if (tdip != NULL) {
19411 
19412 #ifdef SATA_DEBUG
19413 				if ((pmportinfo->pmport_event_flags &
19414 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19415 					sata_log(sata_hba_inst, CE_WARN,
19416 					    "sata_process_device_attached: "
19417 					    "old device target node exists!");
19418 #endif
19419 				/*
19420 				 * target node exists - try to unconfigure
19421 				 * device and remove the node.
19422 				 */
19423 				mutex_exit(&pmportinfo->pmport_mutex);
19424 				rval = ndi_devi_offline(tdip,
19425 				    NDI_DEVI_REMOVE);
19426 				mutex_enter(&pmportinfo->pmport_mutex);
19427 
19428 				if (rval == NDI_SUCCESS) {
19429 					pmportinfo->pmport_event_flags &=
19430 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19431 					pmportinfo->pmport_tgtnode_clean =
19432 					    B_TRUE;
19433 				} else {
19434 					/*
19435 					 * PROBLEM - the target node remained
19436 					 * and it belongs to a previously
19437 					 * attached device.
19438 					 * This happens when the file was open
19439 					 * or the node was waiting for
19440 					 * resources at the time the
19441 					 * associated device was removed.
19442 					 * Instruct event daemon to retry the
19443 					 * cleanup later.
19444 					 */
19445 					sata_log(sata_hba_inst,
19446 					    CE_WARN,
19447 					    "Application(s) accessing "
19448 					    "previously attached SATA "
19449 					    "device have to release "
19450 					    "it before newly inserted "
19451 					    "device can be made accessible."
19452 					    "at port %d:%d",
19453 					    cport, pmport);
19454 					pmportinfo->pmport_event_flags |=
19455 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19456 					pmportinfo->pmport_tgtnode_clean =
19457 					    B_FALSE;
19458 				}
19459 			}
19460 			if (sata_auto_online != 0) {
19461 				pmportinfo->pmport_event_flags |=
19462 				    SATA_EVNT_AUTOONLINE_DEVICE;
19463 			}
19464 
19465 		}
19466 	} else {
19467 		pmportinfo->pmport_dev_attach_time = 0;
19468 	}
19469 
19470 	event_flags = pmportinfo->pmport_event_flags;
19471 	mutex_exit(&pmportinfo->pmport_mutex);
19472 	if (event_flags != 0) {
19473 		mutex_enter(&sata_hba_inst->satahba_mutex);
19474 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19475 		mutex_exit(&sata_hba_inst->satahba_mutex);
19476 		mutex_enter(&sata_mutex);
19477 		sata_event_pending |= SATA_EVNT_MAIN;
19478 		mutex_exit(&sata_mutex);
19479 	}
19480 
19481 	/* clear the reset_in_progress events */
19482 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19483 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19484 			/* must clear flags on cport */
19485 			sata_pmult_info_t *pminfo =
19486 			    SATA_PMULT_INFO(sata_hba_inst,
19487 			    saddr->cport);
19488 			pminfo->pmult_event_flags |=
19489 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19490 		}
19491 	}
19492 }
19493 
19494 /*
19495  * Device Target Node Cleanup Event processing.
19496  * If the target node associated with a sata port device is in
19497  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
19498  * If the target node cannot be removed, the event flag is left intact,
19499  * so that event daemon may re-run this function later.
19500  *
19501  * This function cannot be called in interrupt context (it may sleep).
19502  *
19503  * NOTE: Processes cport events only, not port multiplier ports.
19504  */
19505 static void
19506 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19507     sata_address_t *saddr)
19508 {
19509 	sata_cport_info_t *cportinfo;
19510 	dev_info_t *tdip;
19511 
19512 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19513 	    "Processing port %d device target node cleanup", saddr->cport);
19514 
19515 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19516 
19517 	/*
19518 	 * Check if there is target node for that device and it is in the
19519 	 * DEVI_DEVICE_REMOVED state. If so, release it.
19520 	 */
19521 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19522 	    saddr->pmport);
19523 	if (tdip != NULL) {
19524 		/*
19525 		 * target node exists - check if it is target node of
19526 		 * a removed device.
19527 		 */
19528 		if (sata_check_device_removed(tdip) == B_TRUE) {
19529 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19530 			    "sata_process_target_node_cleanup: "
19531 			    "old device target node exists!", NULL);
19532 			/*
19533 			 * Unconfigure and remove the target node
19534 			 */
19535 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
19536 			    NDI_SUCCESS) {
19537 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19538 				    saddr->cport)->cport_mutex);
19539 				cportinfo->cport_event_flags &=
19540 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19541 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19542 				    saddr->cport)->cport_mutex);
19543 				return;
19544 			}
19545 			/*
19546 			 * Event daemon will retry the cleanup later.
19547 			 */
19548 			mutex_enter(&sata_hba_inst->satahba_mutex);
19549 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19550 			mutex_exit(&sata_hba_inst->satahba_mutex);
19551 			mutex_enter(&sata_mutex);
19552 			sata_event_pending |= SATA_EVNT_MAIN;
19553 			mutex_exit(&sata_mutex);
19554 		}
19555 	} else {
19556 		if (saddr->qual == SATA_ADDR_CPORT ||
19557 		    saddr->qual == SATA_ADDR_DCPORT) {
19558 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19559 			    saddr->cport)->cport_mutex);
19560 			cportinfo->cport_event_flags &=
19561 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19562 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19563 			    saddr->cport)->cport_mutex);
19564 		} else {
19565 			/* sanity check */
19566 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
19567 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
19568 			    saddr->cport) == NULL)
19569 				return;
19570 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19571 			    saddr->pmport) == NULL)
19572 				return;
19573 
19574 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19575 			    saddr->cport, saddr->pmport)->pmport_mutex);
19576 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19577 			    saddr->pmport)->pmport_event_flags &=
19578 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19579 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19580 			    saddr->cport, saddr->pmport)->pmport_mutex);
19581 		}
19582 	}
19583 }
19584 
19585 /*
19586  * Device AutoOnline Event processing.
19587  * If attached device is to be onlined, an attempt is made to online this
19588  * device, but only if there is no lingering (old) target node present.
19589  * If the device cannot be onlined, the event flag is left intact,
19590  * so that event daemon may re-run this function later.
19591  *
19592  * This function cannot be called in interrupt context (it may sleep).
19593  *
19594  * NOTE: Processes cport events only, not port multiplier ports.
19595  */
19596 static void
19597 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
19598     sata_address_t *saddr)
19599 {
19600 	sata_cport_info_t *cportinfo;
19601 	sata_drive_info_t *sdinfo;
19602 	sata_device_t sata_device;
19603 	dev_info_t *tdip;
19604 
19605 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19606 	    "Processing port %d attached device auto-onlining", saddr->cport);
19607 
19608 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19609 
19610 	/*
19611 	 * Check if device is present and recognized. If not, reset event.
19612 	 */
19613 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19614 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
19615 		/* Nothing to online */
19616 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19617 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19618 		    saddr->cport)->cport_mutex);
19619 		return;
19620 	}
19621 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19622 
19623 	/*
19624 	 * Check if there is target node for this device and if it is in the
19625 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
19626 	 * the event for later processing.
19627 	 */
19628 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19629 	    saddr->pmport);
19630 	if (tdip != NULL) {
19631 		/*
19632 		 * target node exists - check if it is target node of
19633 		 * a removed device.
19634 		 */
19635 		if (sata_check_device_removed(tdip) == B_TRUE) {
19636 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19637 			    "sata_process_device_autoonline: "
19638 			    "old device target node exists!", NULL);
19639 			/*
19640 			 * Event daemon will retry device onlining later.
19641 			 */
19642 			mutex_enter(&sata_hba_inst->satahba_mutex);
19643 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19644 			mutex_exit(&sata_hba_inst->satahba_mutex);
19645 			mutex_enter(&sata_mutex);
19646 			sata_event_pending |= SATA_EVNT_MAIN;
19647 			mutex_exit(&sata_mutex);
19648 			return;
19649 		}
19650 		/*
19651 		 * If the target node is not in the 'removed" state, assume
19652 		 * that it belongs to this device. There is nothing more to do,
19653 		 * but reset the event.
19654 		 */
19655 	} else {
19656 
19657 		/*
19658 		 * Try to online the device
19659 		 * If there is any reset-related event, remove it. We are
19660 		 * configuring the device and no state restoring is needed.
19661 		 */
19662 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19663 		    saddr->cport)->cport_mutex);
19664 		sata_device.satadev_addr = *saddr;
19665 		if (saddr->qual == SATA_ADDR_CPORT)
19666 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
19667 		else
19668 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
19669 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
19670 		if (sdinfo != NULL) {
19671 			if (sdinfo->satadrv_event_flags &
19672 			    (SATA_EVNT_DEVICE_RESET |
19673 			    SATA_EVNT_INPROC_DEVICE_RESET))
19674 				sdinfo->satadrv_event_flags = 0;
19675 			sdinfo->satadrv_event_flags |=
19676 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19677 
19678 			/* Need to create a new target node. */
19679 			cportinfo->cport_tgtnode_clean = B_TRUE;
19680 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19681 			    saddr->cport)->cport_mutex);
19682 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
19683 			    sata_hba_inst, &sata_device.satadev_addr);
19684 			if (tdip == NULL) {
19685 				/*
19686 				 * Configure (onlining) failed.
19687 				 * We will NOT retry
19688 				 */
19689 				SATA_LOG_D((sata_hba_inst, CE_WARN,
19690 				    "sata_process_device_autoonline: "
19691 				    "configuring SATA device at port %d failed",
19692 				    saddr->cport));
19693 			}
19694 		} else {
19695 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19696 			    saddr->cport)->cport_mutex);
19697 		}
19698 
19699 	}
19700 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19701 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19702 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19703 	    saddr->cport)->cport_mutex);
19704 }
19705 
19706 
19707 static void
19708 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
19709     int hint)
19710 {
19711 	char ap[MAXPATHLEN];
19712 	nvlist_t *ev_attr_list = NULL;
19713 	int err;
19714 
19715 	/* Allocate and build sysevent attribute list */
19716 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
19717 	if (err != 0) {
19718 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19719 		    "sata_gen_sysevent: "
19720 		    "cannot allocate memory for sysevent attributes\n"));
19721 		return;
19722 	}
19723 	/* Add hint attribute */
19724 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
19725 	if (err != 0) {
19726 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19727 		    "sata_gen_sysevent: "
19728 		    "failed to add DR_HINT attr for sysevent"));
19729 		nvlist_free(ev_attr_list);
19730 		return;
19731 	}
19732 	/*
19733 	 * Add AP attribute.
19734 	 * Get controller pathname and convert it into AP pathname by adding
19735 	 * a target number.
19736 	 */
19737 	(void) snprintf(ap, MAXPATHLEN, "/devices");
19738 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
19739 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
19740 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
19741 
19742 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
19743 	if (err != 0) {
19744 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19745 		    "sata_gen_sysevent: "
19746 		    "failed to add DR_AP_ID attr for sysevent"));
19747 		nvlist_free(ev_attr_list);
19748 		return;
19749 	}
19750 
19751 	/* Generate/log sysevent */
19752 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
19753 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
19754 	if (err != DDI_SUCCESS) {
19755 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19756 		    "sata_gen_sysevent: "
19757 		    "cannot log sysevent, err code %x\n", err));
19758 	}
19759 
19760 	nvlist_free(ev_attr_list);
19761 }
19762 
19763 
19764 
19765 
19766 /*
19767  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
19768  */
19769 static void
19770 sata_set_device_removed(dev_info_t *tdip)
19771 {
19772 	int circ;
19773 
19774 	ASSERT(tdip != NULL);
19775 
19776 	ndi_devi_enter(tdip, &circ);
19777 	mutex_enter(&DEVI(tdip)->devi_lock);
19778 	DEVI_SET_DEVICE_REMOVED(tdip);
19779 	mutex_exit(&DEVI(tdip)->devi_lock);
19780 	ndi_devi_exit(tdip, circ);
19781 }
19782 
19783 
19784 /*
19785  * Set internal event instructing event daemon to try
19786  * to perform the target node cleanup.
19787  */
19788 static void
19789 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19790     sata_address_t *saddr)
19791 {
19792 	if (saddr->qual == SATA_ADDR_CPORT ||
19793 	    saddr->qual == SATA_ADDR_DCPORT) {
19794 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19795 		    saddr->cport)->cport_mutex);
19796 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
19797 		    SATA_EVNT_TARGET_NODE_CLEANUP;
19798 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19799 		    cport_tgtnode_clean = B_FALSE;
19800 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19801 		    saddr->cport)->cport_mutex);
19802 	} else {
19803 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19804 		    saddr->cport, saddr->pmport)->pmport_mutex);
19805 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
19806 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
19807 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
19808 		    pmport_tgtnode_clean = B_FALSE;
19809 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19810 		    saddr->cport, saddr->pmport)->pmport_mutex);
19811 	}
19812 	mutex_enter(&sata_hba_inst->satahba_mutex);
19813 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19814 	mutex_exit(&sata_hba_inst->satahba_mutex);
19815 	mutex_enter(&sata_mutex);
19816 	sata_event_pending |= SATA_EVNT_MAIN;
19817 	mutex_exit(&sata_mutex);
19818 }
19819 
19820 
19821 /*
19822  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
19823  * i.e. check if the target node state indicates that it belongs to a removed
19824  * device.
19825  *
19826  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
19827  * B_FALSE otherwise.
19828  */
19829 static boolean_t
19830 sata_check_device_removed(dev_info_t *tdip)
19831 {
19832 	ASSERT(tdip != NULL);
19833 
19834 	if (DEVI_IS_DEVICE_REMOVED(tdip))
19835 		return (B_TRUE);
19836 	else
19837 		return (B_FALSE);
19838 }
19839 
19840 /* ************************ FAULT INJECTTION **************************** */
19841 
19842 #ifdef SATA_INJECT_FAULTS
19843 
19844 static	uint32_t sata_fault_count = 0;
19845 static	uint32_t sata_fault_suspend_count = 0;
19846 
19847 /*
19848  * Inject sata pkt fault
19849  * It modifies returned values of the sata packet.
19850  * It returns immediately if:
19851  * pkt fault injection is not enabled (via sata_inject_fault,
19852  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
19853  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
19854  * pkt is not directed to specified fault controller/device
19855  * (sata_fault_ctrl_dev and sata_fault_device).
19856  * If fault controller is not specified, fault injection applies to all
19857  * controllers and devices.
19858  *
19859  * First argument is the pointer to the executed sata packet.
19860  * Second argument is a pointer to a value returned by the HBA tran_start
19861  * function.
19862  * Third argument specifies injected error. Injected sata packet faults
19863  * are the satapkt_reason values.
19864  * SATA_PKT_BUSY		-1	Not completed, busy
19865  * SATA_PKT_DEV_ERROR		1	Device reported error
19866  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
19867  * SATA_PKT_PORT_ERROR		3	Not completed, port error
19868  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
19869  * SATA_PKT_ABORTED		5	Aborted by request
19870  * SATA_PKT_TIMEOUT		6	Operation timeut
19871  * SATA_PKT_RESET		7	Aborted by reset request
19872  *
19873  * Additional global variables affecting the execution:
19874  *
19875  * sata_inject_fault_count variable specifies number of times in row the
19876  * error is injected. Value of -1 specifies permanent fault, ie. every time
19877  * the fault injection point is reached, the fault is injected and a pause
19878  * between fault injection specified by sata_inject_fault_pause_count is
19879  * ignored). Fault injection routine decrements sata_inject_fault_count
19880  * (if greater than zero) until it reaches 0. No fault is injected when
19881  * sata_inject_fault_count is 0 (zero).
19882  *
19883  * sata_inject_fault_pause_count variable specifies number of times a fault
19884  * injection is bypassed (pause between fault injections).
19885  * If set to 0, a fault is injected only a number of times specified by
19886  * sata_inject_fault_count.
19887  *
19888  * The fault counts are static, so for periodic errors they have to be manually
19889  * reset to start repetition sequence from scratch.
19890  * If the original value returned by the HBA tran_start function is not
19891  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
19892  * is injected (to avoid masking real problems);
19893  *
19894  * NOTE: In its current incarnation, this function should be invoked only for
19895  * commands executed in SYNCHRONOUS mode.
19896  */
19897 
19898 
19899 static void
19900 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
19901 {
19902 
19903 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
19904 		return;
19905 
19906 	if (sata_inject_fault_count == 0)
19907 		return;
19908 
19909 	if (fault == 0)
19910 		return;
19911 
19912 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
19913 		return;
19914 
19915 	if (sata_fault_ctrl != NULL) {
19916 		sata_pkt_txlate_t *spx =
19917 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
19918 
19919 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
19920 		    spx->txlt_sata_hba_inst->satahba_dip)
19921 			return;
19922 
19923 		if (sata_fault_device.satadev_addr.cport !=
19924 		    spkt->satapkt_device.satadev_addr.cport ||
19925 		    sata_fault_device.satadev_addr.pmport !=
19926 		    spkt->satapkt_device.satadev_addr.pmport ||
19927 		    sata_fault_device.satadev_addr.qual !=
19928 		    spkt->satapkt_device.satadev_addr.qual)
19929 			return;
19930 	}
19931 
19932 	/* Modify pkt return parameters */
19933 	if (*rval != SATA_TRAN_ACCEPTED ||
19934 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
19935 		sata_fault_count = 0;
19936 		sata_fault_suspend_count = 0;
19937 		return;
19938 	}
19939 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
19940 		/* Pause in the injection */
19941 		sata_fault_suspend_count -= 1;
19942 		return;
19943 	}
19944 
19945 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
19946 		/*
19947 		 * Init inject fault cycle. If fault count is set to -1,
19948 		 * it is a permanent fault.
19949 		 */
19950 		if (sata_inject_fault_count != -1) {
19951 			sata_fault_count = sata_inject_fault_count;
19952 			sata_fault_suspend_count =
19953 			    sata_inject_fault_pause_count;
19954 			if (sata_fault_suspend_count == 0)
19955 				sata_inject_fault_count = 0;
19956 		}
19957 	}
19958 
19959 	if (sata_fault_count != 0)
19960 		sata_fault_count -= 1;
19961 
19962 	switch (fault) {
19963 	case SATA_PKT_BUSY:
19964 		*rval = SATA_TRAN_BUSY;
19965 		spkt->satapkt_reason = SATA_PKT_BUSY;
19966 		break;
19967 
19968 	case SATA_PKT_QUEUE_FULL:
19969 		*rval = SATA_TRAN_QUEUE_FULL;
19970 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
19971 		break;
19972 
19973 	case SATA_PKT_CMD_UNSUPPORTED:
19974 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
19975 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
19976 		break;
19977 
19978 	case SATA_PKT_PORT_ERROR:
19979 		/* This is "rejected" command */
19980 		*rval = SATA_TRAN_PORT_ERROR;
19981 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
19982 		/* Additional error setup could be done here - port state */
19983 		break;
19984 
19985 	case SATA_PKT_DEV_ERROR:
19986 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
19987 		/*
19988 		 * Additional error setup could be done here
19989 		 */
19990 		break;
19991 
19992 	case SATA_PKT_ABORTED:
19993 		spkt->satapkt_reason = SATA_PKT_ABORTED;
19994 		break;
19995 
19996 	case SATA_PKT_TIMEOUT:
19997 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
19998 		/* Additional error setup could be done here */
19999 		break;
20000 
20001 	case SATA_PKT_RESET:
20002 		spkt->satapkt_reason = SATA_PKT_RESET;
20003 		/*
20004 		 * Additional error setup could be done here - device reset
20005 		 */
20006 		break;
20007 
20008 	default:
20009 		break;
20010 	}
20011 }
20012 
20013 #endif
20014 
20015 /*
20016  * SATA Trace Ring Buffer
20017  * ----------------------
20018  *
20019  * Overview
20020  *
20021  * The SATA trace ring buffer is a ring buffer created and managed by
20022  * the SATA framework module that can be used by any module or driver
20023  * within the SATA framework to store debug messages.
20024  *
20025  * Ring Buffer Interfaces:
20026  *
20027  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20028  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20029  *
20030  *	Note that the sata_trace_debug() interface was created to give
20031  *	consumers the flexibilty of sending debug messages to ring buffer
20032  *	as variable arguments.  Consumers can send type va_list debug
20033  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20034  *	and sata_vtrace_debug() relationship is similar to that of
20035  *	cmn_err(9F) and vcmn_err(9F).
20036  *
20037  * Below is a diagram of the SATA trace ring buffer interfaces and
20038  * sample consumers:
20039  *
20040  * +---------------------------------+
20041  * |    o  o  SATA Framework Module  |
20042  * | o  SATA  o     +------------------+      +------------------+
20043  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20044  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20045  * | o        o     +------------------+   |  +------------------+
20046  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20047  * |                        |        |        +------------------+
20048  * |           +------------------+  |
20049  * |           |SATA Debug Message|  |
20050  * |           +------------------+  |
20051  * +---------------------------------+
20052  *
20053  * Supporting Routines:
20054  *
20055  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20056  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20057  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20058  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20059  *
20060  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20061  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20062  * /etc/system to desired size in unit of bytes.
20063  *
20064  * The individual debug message size in the ring buffer is restricted
20065  * to DMSG_BUF_SIZE.
20066  */
20067 void
20068 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20069 {
20070 	sata_trace_dmsg_t *dmsg;
20071 
20072 	if (sata_debug_rbuf == NULL) {
20073 		return;
20074 	}
20075 
20076 	/*
20077 	 * If max size of ring buffer is smaller than size
20078 	 * required for one debug message then just return
20079 	 * since we have no room for the debug message.
20080 	 */
20081 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20082 		return;
20083 	}
20084 
20085 	mutex_enter(&sata_debug_rbuf->lock);
20086 
20087 	/* alloc or reuse on ring buffer */
20088 	dmsg = sata_trace_dmsg_alloc();
20089 
20090 	if (dmsg == NULL) {
20091 		/* resource allocation failed */
20092 		mutex_exit(&sata_debug_rbuf->lock);
20093 		return;
20094 	}
20095 
20096 	dmsg->dip = dip;
20097 	gethrestime(&dmsg->timestamp);
20098 
20099 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
20100 
20101 	mutex_exit(&sata_debug_rbuf->lock);
20102 }
20103 
20104 void
20105 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
20106 {
20107 	va_list ap;
20108 
20109 	va_start(ap, fmt);
20110 	sata_vtrace_debug(dip, fmt, ap);
20111 	va_end(ap);
20112 }
20113 
20114 /*
20115  * This routine is used to manage debug messages
20116  * on ring buffer.
20117  */
20118 static sata_trace_dmsg_t *
20119 sata_trace_dmsg_alloc(void)
20120 {
20121 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
20122 
20123 	if (sata_debug_rbuf->looped == TRUE) {
20124 		sata_debug_rbuf->dmsgp = dmsg->next;
20125 		return (sata_debug_rbuf->dmsgp);
20126 	}
20127 
20128 	/*
20129 	 * If we're looping for the first time,
20130 	 * connect the ring.
20131 	 */
20132 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
20133 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
20134 		dmsg->next = sata_debug_rbuf->dmsgh;
20135 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
20136 		sata_debug_rbuf->looped = TRUE;
20137 		return (sata_debug_rbuf->dmsgp);
20138 	}
20139 
20140 	/* If we've gotten this far then memory allocation is needed */
20141 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
20142 	if (dmsg_alloc == NULL) {
20143 		sata_debug_rbuf->allocfailed++;
20144 		return (dmsg_alloc);
20145 	} else {
20146 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
20147 	}
20148 
20149 	if (sata_debug_rbuf->dmsgp != NULL) {
20150 		dmsg->next = dmsg_alloc;
20151 		sata_debug_rbuf->dmsgp = dmsg->next;
20152 		return (sata_debug_rbuf->dmsgp);
20153 	} else {
20154 		/*
20155 		 * We should only be here if we're initializing
20156 		 * the ring buffer.
20157 		 */
20158 		if (sata_debug_rbuf->dmsgh == NULL) {
20159 			sata_debug_rbuf->dmsgh = dmsg_alloc;
20160 		} else {
20161 			/* Something is wrong */
20162 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
20163 			return (NULL);
20164 		}
20165 
20166 		sata_debug_rbuf->dmsgp = dmsg_alloc;
20167 		return (sata_debug_rbuf->dmsgp);
20168 	}
20169 }
20170 
20171 
20172 /*
20173  * Free all messages on debug ring buffer.
20174  */
20175 static void
20176 sata_trace_dmsg_free(void)
20177 {
20178 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
20179 
20180 	while (dmsg != NULL) {
20181 		dmsg_next = dmsg->next;
20182 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
20183 
20184 		/*
20185 		 * If we've looped around the ring than we're done.
20186 		 */
20187 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
20188 			break;
20189 		} else {
20190 			dmsg = dmsg_next;
20191 		}
20192 	}
20193 }
20194 
20195 
20196 /*
20197  * This function can block
20198  */
20199 static void
20200 sata_trace_rbuf_alloc(void)
20201 {
20202 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
20203 
20204 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
20205 
20206 	if (dmsg_ring_size > 0) {
20207 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
20208 	}
20209 }
20210 
20211 
20212 static void
20213 sata_trace_rbuf_free(void)
20214 {
20215 	sata_trace_dmsg_free();
20216 	mutex_destroy(&sata_debug_rbuf->lock);
20217 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
20218 }
20219 
20220 /*
20221  * If SATA_DEBUG is not defined then this routine is called instead
20222  * of sata_log() via the SATA_LOG_D macro.
20223  */
20224 static void
20225 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
20226     const char *fmt, ...)
20227 {
20228 #ifndef __lock_lint
20229 	_NOTE(ARGUNUSED(level))
20230 #endif
20231 
20232 	dev_info_t *dip = NULL;
20233 	va_list ap;
20234 
20235 	if (sata_hba_inst != NULL) {
20236 		dip = SATA_DIP(sata_hba_inst);
20237 	}
20238 
20239 	va_start(ap, fmt);
20240 	sata_vtrace_debug(dip, fmt, ap);
20241 	va_end(ap);
20242 }
20243