xref: /titanic_44/usr/src/uts/common/io/sata/impl/sata.c (revision 7b0bedd42192a2f6bcd6fc4b637d23892303a962)
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  * Flag argument indicates that a non-read/write ATA command may be sent
3076  * to HBA in arbitrary SYNC mode to execute this packet.
3077  *
3078  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
3079  * sata_pkt was set-up.
3080  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
3081  * exist and pkt_comp callback was scheduled.
3082  * Returns other TRAN_XXXXX values when error occured and command should be
3083  * rejected with the returned TRAN_XXXXX value.
3084  *
3085  * This function should be called with port mutex held.
3086  */
3087 static int
3088 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason, int flag)
3089 {
3090 	sata_drive_info_t *sdinfo;
3091 	sata_device_t sata_device;
3092 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3093 		SATA_DIR_NODATA_XFER,
3094 		/* all other values to 0/FALSE */
3095 	};
3096 	/*
3097 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
3098 	 * and that implies TRAN_ACCEPT return value. Any other returned value
3099 	 * indicates that the scsi packet was not accepted (the reason will not
3100 	 * be checked by the scsi target driver).
3101 	 * To make debugging easier, we set pkt_reason to know value here.
3102 	 * It may be changed later when different completion reason is
3103 	 * determined.
3104 	 */
3105 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
3106 	*reason = CMD_TRAN_ERR;
3107 
3108 	/* Validate address */
3109 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3110 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3111 
3112 	case -1:
3113 		/* Invalid address or invalid device type */
3114 		return (TRAN_BADPKT);
3115 	case 2:
3116 		/*
3117 		 * Valid address but device type is unknown - Chack if it is
3118 		 * in the reset state and therefore in an indeterminate state.
3119 		 */
3120 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3121 		    &spx->txlt_sata_pkt->satapkt_device);
3122 		if (sdinfo != NULL && (sdinfo->satadrv_event_flags &
3123 		    (SATA_EVNT_DEVICE_RESET |
3124 		    SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3125 			if (!ddi_in_panic()) {
3126 				spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3127 				*reason = CMD_INCOMPLETE;
3128 				SATADBG1(SATA_DBG_SCSI_IF,
3129 				    spx->txlt_sata_hba_inst,
3130 				    "sata_scsi_start: rejecting command "
3131 				    "because of device reset state\n", NULL);
3132 				return (TRAN_BUSY);
3133 			}
3134 		}
3135 		/* FALLTHROUGH */
3136 	case 1:
3137 		/* valid address but no valid device - it has disappeared */
3138 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3139 		*reason = CMD_DEV_GONE;
3140 		/*
3141 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
3142 		 * only in callback function (for normal requests) and
3143 		 * in the dump code path.
3144 		 * So, if the callback is available, we need to do
3145 		 * the callback rather than returning TRAN_FATAL_ERROR here.
3146 		 */
3147 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
3148 			/* scsi callback required */
3149 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3150 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3151 			    (void *)spx->txlt_scsi_pkt,
3152 			    TQ_SLEEP) == NULL)
3153 				/* Scheduling the callback failed */
3154 				return (TRAN_BUSY);
3155 
3156 			return (TRAN_ACCEPT);
3157 		}
3158 		return (TRAN_FATAL_ERROR);
3159 	default:
3160 		/* all OK; pkt reason will be overwritten later */
3161 		break;
3162 	}
3163 	/*
3164 	 * If pkt is to be executed in polling mode and a command will not be
3165 	 * emulated in SATA module (requires sending a non-read/write ATA
3166 	 * command to HBA driver in arbitrary SYNC mode) and we are in the
3167 	 * interrupt context and not in the panic dump, then reject the packet
3168 	 * to avoid a possible interrupt stack overrun or hang caused by
3169 	 * a potentially blocked interrupt.
3170 	 */
3171 	if (((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0 || flag != 0) &&
3172 	    servicing_interrupt() && !ddi_in_panic()) {
3173 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3174 		    "sata_scsi_start: rejecting synchronous command because "
3175 		    "of interrupt context\n", NULL);
3176 		return (TRAN_BUSY);
3177 	}
3178 
3179 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3180 	    &spx->txlt_sata_pkt->satapkt_device);
3181 
3182 	/*
3183 	 * If device is in reset condition, reject the packet with
3184 	 * TRAN_BUSY, unless:
3185 	 * 1. system is panicking (dumping)
3186 	 * In such case only one thread is running and there is no way to
3187 	 * process reset.
3188 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
3189 	 * Some cfgadm operations involve drive commands, so reset condition
3190 	 * needs to be ignored for IOCTL operations.
3191 	 */
3192 	if ((sdinfo->satadrv_event_flags &
3193 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3194 
3195 		if (!ddi_in_panic() &&
3196 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
3197 		    sata_device.satadev_addr.cport) &
3198 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
3199 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3200 			*reason = CMD_INCOMPLETE;
3201 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3202 			    "sata_scsi_start: rejecting command because "
3203 			    "of device reset state\n", NULL);
3204 			return (TRAN_BUSY);
3205 		}
3206 	}
3207 
3208 	/*
3209 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3210 	 * sata_scsi_pkt_init() because pkt init had to work also with
3211 	 * non-existing devices.
3212 	 * Now we know that the packet was set-up for a real device, so its
3213 	 * type is known.
3214 	 */
3215 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3216 
3217 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3218 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
3219 	    sata_device.satadev_addr.cport)->cport_event_flags &
3220 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
3221 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3222 		    sata_ignore_dev_reset = B_TRUE;
3223 	}
3224 	/*
3225 	 * At this point the generic translation routine determined that the
3226 	 * scsi packet should be accepted. Packet completion reason may be
3227 	 * changed later when a different completion reason is determined.
3228 	 */
3229 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3230 	*reason = CMD_CMPLT;
3231 
3232 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3233 		/* Synchronous execution */
3234 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3235 		    SATA_OPMODE_POLLING;
3236 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3237 		    sata_ignore_dev_reset = ddi_in_panic();
3238 	} else {
3239 		/* Asynchronous execution */
3240 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3241 		    SATA_OPMODE_INTERRUPTS;
3242 	}
3243 	/* Convert queuing information */
3244 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3245 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3246 		    B_TRUE;
3247 	else if (spx->txlt_scsi_pkt->pkt_flags &
3248 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3249 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3250 		    B_TRUE;
3251 
3252 	/* Always limit pkt time */
3253 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3254 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3255 	else
3256 		/* Pass on scsi_pkt time */
3257 		spx->txlt_sata_pkt->satapkt_time =
3258 		    spx->txlt_scsi_pkt->pkt_time;
3259 
3260 	return (TRAN_ACCEPT);
3261 }
3262 
3263 
3264 /*
3265  * Translate ATA Identify Device data to SCSI Inquiry data.
3266  * This function may be called only for ATA devices.
3267  * This function should not be called for ATAPI devices - they
3268  * respond directly to SCSI Inquiry command.
3269  *
3270  * SATA Identify Device data has to be valid in sata_drive_info.
3271  * Buffer has to accomodate the inquiry length (36 bytes).
3272  *
3273  * This function should be called with a port mutex held.
3274  */
3275 static	void
3276 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3277     sata_drive_info_t *sdinfo, uint8_t *buf)
3278 {
3279 
3280 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3281 	struct sata_id *sid = &sdinfo->satadrv_id;
3282 
3283 	/* Start with a nice clean slate */
3284 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3285 
3286 	/*
3287 	 * Rely on the dev_type for setting paripheral qualifier.
3288 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
3289 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
3290 	 * ATAPI Inquiry may provide more data to the target driver.
3291 	 */
3292 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3293 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
3294 
3295 	/* CFA type device is not a removable media device */
3296 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
3297 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
3298 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3299 	inq->inq_iso = 0;	/* ISO version */
3300 	inq->inq_ecma = 0;	/* ECMA version */
3301 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3302 	inq->inq_aenc = 0;	/* Async event notification cap. */
3303 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
3304 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3305 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3306 	inq->inq_len = 31;	/* Additional length */
3307 	inq->inq_dualp = 0;	/* dual port device - NO */
3308 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3309 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3310 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3311 				/*
3312 				 * Queuing support - controller has to
3313 				 * support some sort of command queuing.
3314 				 */
3315 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3316 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3317 	else
3318 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3319 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3320 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3321 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3322 
3323 #ifdef	_LITTLE_ENDIAN
3324 	/* Swap text fields to match SCSI format */
3325 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3326 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3327 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3328 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3329 	else
3330 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3331 #else	/* _LITTLE_ENDIAN */
3332 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3333 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3334 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3335 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3336 	else
3337 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3338 #endif	/* _LITTLE_ENDIAN */
3339 }
3340 
3341 
3342 /*
3343  * Scsi response set up for invalid command (command not supported)
3344  *
3345  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3346  */
3347 static int
3348 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3349 {
3350 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3351 	struct scsi_extended_sense *sense;
3352 
3353 	scsipkt->pkt_reason = CMD_CMPLT;
3354 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3355 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3356 
3357 	*scsipkt->pkt_scbp = STATUS_CHECK;
3358 
3359 	sense = sata_arq_sense(spx);
3360 	sense->es_key = KEY_ILLEGAL_REQUEST;
3361 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
3362 
3363 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3364 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3365 
3366 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3367 	    scsipkt->pkt_comp != NULL)
3368 		/* scsi callback required */
3369 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3370 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3371 		    (void *)spx->txlt_scsi_pkt,
3372 		    TQ_SLEEP) == NULL)
3373 			/* Scheduling the callback failed */
3374 			return (TRAN_BUSY);
3375 	return (TRAN_ACCEPT);
3376 }
3377 
3378 /*
3379  * Scsi response set up for check condition with special sense key
3380  * and additional sense code.
3381  *
3382  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3383  */
3384 static int
3385 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3386 {
3387 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3388 	int cport = SATA_TXLT_CPORT(spx);
3389 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3390 	struct scsi_extended_sense *sense;
3391 
3392 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3393 	scsipkt->pkt_reason = CMD_CMPLT;
3394 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3395 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3396 
3397 	*scsipkt->pkt_scbp = STATUS_CHECK;
3398 
3399 	sense = sata_arq_sense(spx);
3400 	sense->es_key = key;
3401 	sense->es_add_code = code;
3402 
3403 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3404 
3405 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3406 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3407 
3408 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3409 		/* scsi callback required */
3410 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3411 		    (task_func_t *)scsi_hba_pkt_comp,
3412 		    (void *)spx->txlt_scsi_pkt,
3413 		    TQ_SLEEP) == NULL)
3414 			/* Scheduling the callback failed */
3415 			return (TRAN_BUSY);
3416 	return (TRAN_ACCEPT);
3417 }
3418 
3419 /*
3420  * Scsi response setup for
3421  * emulated non-data command that requires no action/return data
3422  *
3423  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3424  */
3425 static	int
3426 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3427 {
3428 	int rval;
3429 	int reason;
3430 
3431 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3432 
3433 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3434 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3435 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3436 		return (rval);
3437 	}
3438 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3439 
3440 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3441 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3442 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3443 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3444 
3445 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3446 	    "Scsi_pkt completion reason %x\n",
3447 	    spx->txlt_scsi_pkt->pkt_reason);
3448 
3449 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3450 	    spx->txlt_scsi_pkt->pkt_comp != NULL)
3451 		/* scsi callback required */
3452 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3453 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3454 		    (void *)spx->txlt_scsi_pkt,
3455 		    TQ_SLEEP) == NULL)
3456 			/* Scheduling the callback failed */
3457 			return (TRAN_BUSY);
3458 	return (TRAN_ACCEPT);
3459 }
3460 
3461 
3462 /*
3463  * SATA translate command: Inquiry / Identify Device
3464  * Use cached Identify Device data for now, rather than issuing actual
3465  * Device Identify cmd request. If device is detached and re-attached,
3466  * asynchronous event processing should fetch and refresh Identify Device
3467  * data.
3468  * Two VPD pages are supported now:
3469  * Vital Product Data page
3470  * Unit Serial Number page
3471  *
3472  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3473  */
3474 
3475 #define	EVPD			1	/* Extended Vital Product Data flag */
3476 #define	CMDDT			2	/* Command Support Data - Obsolete */
3477 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3478 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3479 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3480 
3481 static int
3482 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3483 {
3484 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3485 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3486 	sata_drive_info_t *sdinfo;
3487 	struct scsi_extended_sense *sense;
3488 	int count;
3489 	uint8_t *p;
3490 	int i, j;
3491 	uint8_t page_buf[0xff]; /* Max length */
3492 	int rval, reason;
3493 
3494 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3495 
3496 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3497 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3498 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3499 		return (rval);
3500 	}
3501 
3502 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3503 	    &spx->txlt_sata_pkt->satapkt_device);
3504 
3505 	ASSERT(sdinfo != NULL);
3506 
3507 	scsipkt->pkt_reason = CMD_CMPLT;
3508 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3509 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3510 
3511 	/* Reject not supported request */
3512 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3513 		*scsipkt->pkt_scbp = STATUS_CHECK;
3514 		sense = sata_arq_sense(spx);
3515 		sense->es_key = KEY_ILLEGAL_REQUEST;
3516 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3517 		goto done;
3518 	}
3519 
3520 	/* Valid Inquiry request */
3521 	*scsipkt->pkt_scbp = STATUS_GOOD;
3522 
3523 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3524 
3525 		/*
3526 		 * Because it is fully emulated command storing data
3527 		 * programatically in the specified buffer, release
3528 		 * preallocated DMA resources before storing data in the buffer,
3529 		 * so no unwanted DMA sync would take place.
3530 		 */
3531 		sata_scsi_dmafree(NULL, scsipkt);
3532 
3533 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3534 			/* Standard Inquiry Data request */
3535 			struct scsi_inquiry inq;
3536 			unsigned int bufsize;
3537 
3538 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3539 			    sdinfo, (uint8_t *)&inq);
3540 			/* Copy no more than requested */
3541 			count = MIN(bp->b_bcount,
3542 			    sizeof (struct scsi_inquiry));
3543 			bufsize = scsipkt->pkt_cdbp[4];
3544 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3545 			count = MIN(count, bufsize);
3546 			bcopy(&inq, bp->b_un.b_addr, count);
3547 
3548 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3549 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3550 			    bufsize - count : 0;
3551 		} else {
3552 			/*
3553 			 * peripheral_qualifier = 0;
3554 			 *
3555 			 * We are dealing only with HD and will be
3556 			 * dealing with CD/DVD devices soon
3557 			 */
3558 			uint8_t peripheral_device_type =
3559 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3560 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3561 
3562 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3563 			case INQUIRY_SUP_VPD_PAGE:
3564 				/*
3565 				 * Request for suported Vital Product Data
3566 				 * pages - assuming only 2 page codes
3567 				 * supported.
3568 				 */
3569 				page_buf[0] = peripheral_device_type;
3570 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3571 				page_buf[2] = 0;
3572 				page_buf[3] = 2; /* page length */
3573 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3574 				page_buf[5] = INQUIRY_USN_PAGE;
3575 				/* Copy no more than requested */
3576 				count = MIN(bp->b_bcount, 6);
3577 				bcopy(page_buf, bp->b_un.b_addr, count);
3578 				break;
3579 
3580 			case INQUIRY_USN_PAGE:
3581 				/*
3582 				 * Request for Unit Serial Number page.
3583 				 * Set-up the page.
3584 				 */
3585 				page_buf[0] = peripheral_device_type;
3586 				page_buf[1] = INQUIRY_USN_PAGE;
3587 				page_buf[2] = 0;
3588 				/* remaining page length */
3589 				page_buf[3] = SATA_ID_SERIAL_LEN;
3590 
3591 				/*
3592 				 * Copy serial number from Identify Device data
3593 				 * words into the inquiry page and swap bytes
3594 				 * when necessary.
3595 				 */
3596 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3597 #ifdef	_LITTLE_ENDIAN
3598 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3599 #else
3600 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3601 #endif
3602 				/*
3603 				 * Least significant character of the serial
3604 				 * number shall appear as the last byte,
3605 				 * according to SBC-3 spec.
3606 				 * Count trailing spaces to determine the
3607 				 * necessary shift length.
3608 				 */
3609 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3610 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3611 					if (*(p - j) != '\0' &&
3612 					    *(p - j) != '\040')
3613 						break;
3614 				}
3615 
3616 				/*
3617 				 * Shift SN string right, so that the last
3618 				 * non-blank character would appear in last
3619 				 * byte of SN field in the page.
3620 				 * 'j' is the shift length.
3621 				 */
3622 				for (i = 0;
3623 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3624 				    i++, p--)
3625 					*p = *(p - j);
3626 
3627 				/*
3628 				 * Add leading spaces - same number as the
3629 				 * shift size
3630 				 */
3631 				for (; j > 0; j--)
3632 					page_buf[4 + j - 1] = '\040';
3633 
3634 				count = MIN(bp->b_bcount,
3635 				    SATA_ID_SERIAL_LEN + 4);
3636 				bcopy(page_buf, bp->b_un.b_addr, count);
3637 				break;
3638 
3639 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3640 				/*
3641 				 * We may want to implement this page, when
3642 				 * identifiers are common for SATA devices
3643 				 * But not now.
3644 				 */
3645 				/*FALLTHROUGH*/
3646 
3647 			default:
3648 				/* Request for unsupported VPD page */
3649 				*scsipkt->pkt_scbp = STATUS_CHECK;
3650 				sense = sata_arq_sense(spx);
3651 				sense->es_key = KEY_ILLEGAL_REQUEST;
3652 				sense->es_add_code =
3653 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3654 				goto done;
3655 			}
3656 		}
3657 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3658 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3659 		    scsipkt->pkt_cdbp[4] - count : 0;
3660 	}
3661 done:
3662 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3663 
3664 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3665 	    "Scsi_pkt completion reason %x\n",
3666 	    scsipkt->pkt_reason);
3667 
3668 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3669 	    scsipkt->pkt_comp != NULL) {
3670 		/* scsi callback required */
3671 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3672 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3673 		    TQ_SLEEP) == NULL)
3674 			/* Scheduling the callback failed */
3675 			return (TRAN_BUSY);
3676 	}
3677 	return (TRAN_ACCEPT);
3678 }
3679 
3680 /*
3681  * SATA translate command: Request Sense.
3682  *
3683  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3684  * At the moment this is an emulated command (ATA version for SATA hard disks).
3685  * May be translated into Check Power Mode command in the future.
3686  *
3687  * Note: There is a mismatch between already implemented Informational
3688  * Exception Mode Select page 0x1C and this function.
3689  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3690  * NO SENSE and set additional sense code to the exception code - this is not
3691  * implemented here.
3692  */
3693 static int
3694 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3695 {
3696 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3697 	struct scsi_extended_sense sense;
3698 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3699 	sata_drive_info_t *sdinfo;
3700 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3701 	int rval, reason, power_state = 0;
3702 
3703 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3704 
3705 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3706 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3707 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3708 		return (rval);
3709 	}
3710 
3711 	scsipkt->pkt_reason = CMD_CMPLT;
3712 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3713 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3714 	*scsipkt->pkt_scbp = STATUS_GOOD;
3715 
3716 	/*
3717 	 * when CONTROL field's NACA bit == 1
3718 	 * return ILLEGAL_REQUEST
3719 	 */
3720 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3721 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3722 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3723 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3724 	}
3725 
3726 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3727 	    &spx->txlt_sata_pkt->satapkt_device);
3728 	ASSERT(sdinfo != NULL);
3729 
3730 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3731 
3732 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3733 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3734 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3735 	if (sata_hba_start(spx, &rval) != 0) {
3736 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3737 		return (rval);
3738 	} else {
3739 		if (scmd->satacmd_error_reg != 0) {
3740 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3741 			return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3742 			    SD_SCSI_ASC_NO_ADD_SENSE));
3743 		}
3744 	}
3745 
3746 	switch (scmd->satacmd_sec_count_lsb) {
3747 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3748 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3749 			power_state = SATA_POWER_STOPPED;
3750 		else {
3751 			power_state = SATA_POWER_STANDBY;
3752 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
3753 		}
3754 		break;
3755 	case SATA_PWRMODE_IDLE: /* device in idle mode */
3756 		power_state = SATA_POWER_IDLE;
3757 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3758 		break;
3759 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
3760 	default:		  /* 0x40, 0x41 active mode */
3761 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
3762 			power_state = SATA_POWER_IDLE;
3763 		else {
3764 			power_state = SATA_POWER_ACTIVE;
3765 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3766 		}
3767 		break;
3768 	}
3769 
3770 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3771 
3772 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3773 		/*
3774 		 * Because it is fully emulated command storing data
3775 		 * programatically in the specified buffer, release
3776 		 * preallocated DMA resources before storing data in the buffer,
3777 		 * so no unwanted DMA sync would take place.
3778 		 */
3779 		int count = MIN(bp->b_bcount,
3780 		    sizeof (struct scsi_extended_sense));
3781 		sata_scsi_dmafree(NULL, scsipkt);
3782 		bzero(&sense, sizeof (struct scsi_extended_sense));
3783 		sense.es_valid = 0;	/* Valid LBA */
3784 		sense.es_class = 7;	/* Response code 0x70 - current err */
3785 		sense.es_key = KEY_NO_SENSE;
3786 		sense.es_add_len = 6;	/* Additional length */
3787 		/* Copy no more than requested */
3788 		bcopy(&sense, bp->b_un.b_addr, count);
3789 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3790 		scsipkt->pkt_resid = 0;
3791 		switch (power_state) {
3792 		case SATA_POWER_IDLE:
3793 		case SATA_POWER_STANDBY:
3794 			sense.es_add_code =
3795 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
3796 			break;
3797 		case SATA_POWER_STOPPED:
3798 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
3799 			break;
3800 		case SATA_POWER_ACTIVE:
3801 		default:
3802 			break;
3803 		}
3804 	}
3805 
3806 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3807 	    "Scsi_pkt completion reason %x\n",
3808 	    scsipkt->pkt_reason);
3809 
3810 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3811 		/* scsi callback required */
3812 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3813 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
3814 		    TQ_SLEEP) == NULL)
3815 			/* Scheduling the callback failed */
3816 			return (TRAN_BUSY);
3817 	return (TRAN_ACCEPT);
3818 }
3819 
3820 /*
3821  * SATA translate command: Test Unit Ready
3822  * (ATA version for SATA hard disks).
3823  * It is translated into the Check Power Mode command.
3824  *
3825  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3826  */
3827 static int
3828 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3829 {
3830 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3831 	struct scsi_extended_sense *sense;
3832 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3833 	sata_drive_info_t *sdinfo;
3834 	int power_state;
3835 	int rval, reason;
3836 
3837 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3838 
3839 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3840 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3841 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3842 		return (rval);
3843 	}
3844 
3845 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3846 	    &spx->txlt_sata_pkt->satapkt_device);
3847 	ASSERT(sdinfo != NULL);
3848 
3849 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3850 
3851 	/* send CHECK POWER MODE command */
3852 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3853 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3854 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3855 	if (sata_hba_start(spx, &rval) != 0) {
3856 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3857 		return (rval);
3858 	} else {
3859 		if (scmd->satacmd_error_reg != 0) {
3860 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3861 			return (sata_txlt_check_condition(spx, KEY_NOT_READY,
3862 			    SD_SCSI_ASC_LU_NOT_RESPONSE));
3863 		}
3864 	}
3865 
3866 	power_state = scmd->satacmd_sec_count_lsb;
3867 
3868 	/*
3869 	 * return NOT READY when device in STOPPED mode
3870 	 */
3871 	if (power_state == SATA_PWRMODE_STANDBY &&
3872 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
3873 		*scsipkt->pkt_scbp = STATUS_CHECK;
3874 		sense = sata_arq_sense(spx);
3875 		sense->es_key = KEY_NOT_READY;
3876 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3877 	} else {
3878 		/*
3879 		 * For other power mode, return GOOD status
3880 		 */
3881 		*scsipkt->pkt_scbp = STATUS_GOOD;
3882 	}
3883 
3884 	scsipkt->pkt_reason = CMD_CMPLT;
3885 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3886 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3887 
3888 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3889 
3890 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3891 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3892 
3893 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3894 		/* scsi callback required */
3895 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3896 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
3897 		    TQ_SLEEP) == NULL)
3898 			/* Scheduling the callback failed */
3899 			return (TRAN_BUSY);
3900 
3901 	return (TRAN_ACCEPT);
3902 }
3903 
3904 /*
3905  * SATA translate command: Start Stop Unit
3906  * Translation depends on a command:
3907  *
3908  * Power condition bits will be supported
3909  * and the power level should be maintained by SATL,
3910  * When SATL received a command, it will check the
3911  * power level firstly, and return the status according
3912  * to SAT2 v2.6 and SAT-2 Standby Modifications
3913  *
3914  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
3915  * -----------------------------------------------------------------------
3916  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
3917  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
3918  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
3919  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
3920  *
3921  *	Unload Media / NOT SUPPORTED YET
3922  *	Load Media / NOT SUPPROTED YET
3923  *	Immediate bit / NOT SUPPORTED YET (deferred error)
3924  *
3925  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3926  * appropriate values in scsi_pkt fields.
3927  */
3928 static int
3929 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3930 {
3931 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3932 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3933 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3934 	int cport = SATA_TXLT_CPORT(spx);
3935 	int rval, reason;
3936 	sata_drive_info_t *sdinfo;
3937 	sata_id_t *sata_id;
3938 
3939 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3940 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
3941 
3942 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3943 
3944 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3945 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3946 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3947 		return (rval);
3948 	}
3949 
3950 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
3951 		/* IMMED bit - not supported */
3952 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3953 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3954 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
3955 	}
3956 
3957 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3958 	spx->txlt_sata_pkt->satapkt_comp = NULL;
3959 
3960 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3961 	    &spx->txlt_sata_pkt->satapkt_device);
3962 	ASSERT(sdinfo != NULL);
3963 	sata_id = &sdinfo->satadrv_id;
3964 
3965 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
3966 	case 0:
3967 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
3968 			/* Load/Unload Media - invalid request */
3969 			goto err_out;
3970 		}
3971 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
3972 			/* Start Unit */
3973 			sata_build_read_verify_cmd(scmd, 1, 5);
3974 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3975 			/* Transfer command to HBA */
3976 			if (sata_hba_start(spx, &rval) != 0) {
3977 				/* Pkt not accepted for execution */
3978 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3979 				return (rval);
3980 			} else {
3981 				if (scmd->satacmd_error_reg != 0) {
3982 					goto err_out;
3983 				}
3984 			}
3985 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3986 		} else {
3987 			/* Stop Unit */
3988 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
3989 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3990 			if (sata_hba_start(spx, &rval) != 0) {
3991 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3992 				return (rval);
3993 			} else {
3994 				if (scmd->satacmd_error_reg != 0) {
3995 					goto err_out;
3996 				}
3997 			}
3998 			/* ata standby immediate command */
3999 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4000 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4001 			if (sata_hba_start(spx, &rval) != 0) {
4002 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4003 				return (rval);
4004 			} else {
4005 				if (scmd->satacmd_error_reg != 0) {
4006 					goto err_out;
4007 				}
4008 			}
4009 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4010 		}
4011 		break;
4012 	case 0x1:
4013 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4014 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4015 		if (sata_hba_start(spx, &rval) != 0) {
4016 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4017 			return (rval);
4018 		} else {
4019 			if (scmd->satacmd_error_reg != 0) {
4020 				goto err_out;
4021 			}
4022 		}
4023 		sata_build_read_verify_cmd(scmd, 1, 5);
4024 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4025 		/* Transfer command to HBA */
4026 		if (sata_hba_start(spx, &rval) != 0) {
4027 			/* Pkt not accepted for execution */
4028 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4029 			return (rval);
4030 		} else {
4031 			if (scmd->satacmd_error_reg != 0) {
4032 				goto err_out;
4033 			}
4034 		}
4035 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4036 		break;
4037 	case 0x2:
4038 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4039 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4040 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4041 			if (sata_hba_start(spx, &rval) != 0) {
4042 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4043 				return (rval);
4044 			} else {
4045 				if (scmd->satacmd_error_reg != 0) {
4046 					goto err_out;
4047 				}
4048 			}
4049 		}
4050 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4051 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4052 		if (sata_hba_start(spx, &rval) != 0) {
4053 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4054 			return (rval);
4055 		} else {
4056 			if (scmd->satacmd_error_reg != 0) {
4057 				goto err_out;
4058 			}
4059 		}
4060 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4061 			/*
4062 			 *  POWER CONDITION MODIFIER bit set
4063 			 *  to 0x1 or larger it will be handled
4064 			 *  on the same way as bit = 0x1
4065 			 */
4066 			if (!(sata_id->ai_cmdset84 &
4067 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4068 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4069 				break;
4070 			}
4071 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4072 			scmd->satacmd_features_reg = 0x44;
4073 			scmd->satacmd_lba_low_lsb = 0x4c;
4074 			scmd->satacmd_lba_mid_lsb = 0x4e;
4075 			scmd->satacmd_lba_high_lsb = 0x55;
4076 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4077 			if (sata_hba_start(spx, &rval) != 0) {
4078 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4079 				return (rval);
4080 			} else {
4081 				if (scmd->satacmd_error_reg != 0) {
4082 					goto err_out;
4083 				}
4084 			}
4085 		}
4086 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4087 		break;
4088 	case 0x3:
4089 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4090 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4091 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4092 			if (sata_hba_start(spx, &rval) != 0) {
4093 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4094 				return (rval);
4095 			} else {
4096 				if (scmd->satacmd_error_reg != 0) {
4097 					goto err_out;
4098 				}
4099 			}
4100 		}
4101 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4102 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4103 		if (sata_hba_start(spx, &rval) != 0) {
4104 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4105 			return (rval);
4106 		} else {
4107 			if (scmd->satacmd_error_reg != 0) {
4108 				goto err_out;
4109 			}
4110 		}
4111 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4112 		break;
4113 	case 0x7:
4114 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4115 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4116 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4117 		if (sata_hba_start(spx, &rval) != 0) {
4118 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4119 			return (rval);
4120 		} else {
4121 			if (scmd->satacmd_error_reg != 0) {
4122 				goto err_out;
4123 			}
4124 		}
4125 		switch (scmd->satacmd_sec_count_lsb) {
4126 		case SATA_PWRMODE_STANDBY:
4127 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4128 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4129 			    sdinfo->satadrv_standby_timer);
4130 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4131 			if (sata_hba_start(spx, &rval) != 0) {
4132 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4133 				return (rval);
4134 			} else {
4135 				if (scmd->satacmd_error_reg != 0) {
4136 					goto err_out;
4137 				}
4138 			}
4139 			break;
4140 		case SATA_PWRMODE_IDLE:
4141 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4142 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4143 			    sdinfo->satadrv_standby_timer);
4144 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4145 			if (sata_hba_start(spx, &rval) != 0) {
4146 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4147 				return (rval);
4148 			} else {
4149 				if (scmd->satacmd_error_reg != 0) {
4150 					goto err_out;
4151 				}
4152 			}
4153 			break;
4154 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4155 		case SATA_PWRMODE_ACTIVE_SPINUP:
4156 		case SATA_PWRMODE_ACTIVE:
4157 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4158 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4159 			    sdinfo->satadrv_standby_timer);
4160 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4161 			if (sata_hba_start(spx, &rval) != 0) {
4162 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4163 				return (rval);
4164 			} else {
4165 				if (scmd->satacmd_error_reg != 0) {
4166 					goto err_out;
4167 				}
4168 			}
4169 			sata_build_read_verify_cmd(scmd, 1, 5);
4170 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4171 			if (sata_hba_start(spx, &rval) != 0) {
4172 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4173 				return (rval);
4174 			} else {
4175 				if (scmd->satacmd_error_reg != 0) {
4176 					goto err_out;
4177 				}
4178 			}
4179 			break;
4180 		default:
4181 			goto err_out;
4182 		}
4183 		break;
4184 	case 0xb:
4185 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4186 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4187 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4188 			return (sata_txlt_check_condition(spx,
4189 			    KEY_ILLEGAL_REQUEST,
4190 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4191 		}
4192 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4193 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4194 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4195 			if (sata_hba_start(spx, &rval) != 0) {
4196 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4197 				return (rval);
4198 			} else {
4199 				if (scmd->satacmd_error_reg != 0) {
4200 					goto err_out;
4201 				}
4202 			}
4203 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4204 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4205 			if (sata_hba_start(spx, &rval) != 0) {
4206 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4207 				return (rval);
4208 			} else {
4209 				if (scmd->satacmd_error_reg != 0) {
4210 					goto err_out;
4211 				}
4212 			}
4213 		}
4214 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4215 		break;
4216 	default:
4217 err_out:
4218 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4219 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4220 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4221 	}
4222 
4223 	/*
4224 	 * Since it was a synchronous command,
4225 	 * a callback function will be called directly.
4226 	 */
4227 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4228 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4229 	    "synchronous execution status %x\n",
4230 	    spx->txlt_sata_pkt->satapkt_reason);
4231 
4232 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0) {
4233 		sata_set_arq_data(spx->txlt_sata_pkt);
4234 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4235 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
4236 		    TQ_SLEEP) == 0) {
4237 			return (TRAN_BUSY);
4238 		}
4239 	}
4240 	else
4241 
4242 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4243 
4244 	return (TRAN_ACCEPT);
4245 
4246 }
4247 
4248 /*
4249  * SATA translate command:  Read Capacity.
4250  * Emulated command for SATA disks.
4251  * Capacity is retrieved from cached Idenifty Device data.
4252  * Identify Device data shows effective disk capacity, not the native
4253  * capacity, which may be limitted by Set Max Address command.
4254  * This is ATA version for SATA hard disks.
4255  *
4256  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4257  */
4258 static int
4259 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4260 {
4261 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4262 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4263 	sata_drive_info_t *sdinfo;
4264 	uint64_t val;
4265 	uchar_t *rbuf;
4266 	int rval, reason;
4267 
4268 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4269 	    "sata_txlt_read_capacity: ", NULL);
4270 
4271 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4272 
4273 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4274 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4275 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4276 		return (rval);
4277 	}
4278 
4279 	scsipkt->pkt_reason = CMD_CMPLT;
4280 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4281 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4282 	*scsipkt->pkt_scbp = STATUS_GOOD;
4283 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4284 		/*
4285 		 * Because it is fully emulated command storing data
4286 		 * programatically in the specified buffer, release
4287 		 * preallocated DMA resources before storing data in the buffer,
4288 		 * so no unwanted DMA sync would take place.
4289 		 */
4290 		sata_scsi_dmafree(NULL, scsipkt);
4291 
4292 		sdinfo = sata_get_device_info(
4293 		    spx->txlt_sata_hba_inst,
4294 		    &spx->txlt_sata_pkt->satapkt_device);
4295 		/* Last logical block address */
4296 		val = sdinfo->satadrv_capacity - 1;
4297 		rbuf = (uchar_t *)bp->b_un.b_addr;
4298 		/* Need to swap endians to match scsi format */
4299 		rbuf[0] = (val >> 24) & 0xff;
4300 		rbuf[1] = (val >> 16) & 0xff;
4301 		rbuf[2] = (val >> 8) & 0xff;
4302 		rbuf[3] = val & 0xff;
4303 		/* block size - always 512 bytes, for now */
4304 		rbuf[4] = 0;
4305 		rbuf[5] = 0;
4306 		rbuf[6] = 0x02;
4307 		rbuf[7] = 0;
4308 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4309 		scsipkt->pkt_resid = 0;
4310 
4311 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4312 		    sdinfo->satadrv_capacity -1);
4313 	}
4314 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4315 	/*
4316 	 * If a callback was requested, do it now.
4317 	 */
4318 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4319 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4320 
4321 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4322 	    scsipkt->pkt_comp != NULL)
4323 		/* scsi callback required */
4324 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4325 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4326 		    TQ_SLEEP) == NULL)
4327 			/* Scheduling the callback failed */
4328 			return (TRAN_BUSY);
4329 
4330 	return (TRAN_ACCEPT);
4331 }
4332 
4333 /*
4334  * SATA translate command: Mode Sense.
4335  * Translated into appropriate SATA command or emulated.
4336  * Saved Values Page Control (03) are not supported.
4337  *
4338  * NOTE: only caching mode sense page is currently implemented.
4339  *
4340  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4341  */
4342 
4343 #define	LLBAA	0x10	/* Long LBA Accepted */
4344 
4345 static int
4346 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4347 {
4348 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4349 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4350 	sata_drive_info_t *sdinfo;
4351 	sata_id_t *sata_id;
4352 	struct scsi_extended_sense *sense;
4353 	int 		len, bdlen, count, alc_len;
4354 	int		pc;	/* Page Control code */
4355 	uint8_t		*buf;	/* mode sense buffer */
4356 	int		rval, reason;
4357 
4358 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4359 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4360 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4361 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4362 
4363 	buf = kmem_zalloc(1024, KM_SLEEP);
4364 
4365 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4366 
4367 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4368 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4369 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4370 		kmem_free(buf, 1024);
4371 		return (rval);
4372 	}
4373 
4374 	scsipkt->pkt_reason = CMD_CMPLT;
4375 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4376 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4377 
4378 	pc = scsipkt->pkt_cdbp[2] >> 6;
4379 
4380 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4381 		/*
4382 		 * Because it is fully emulated command storing data
4383 		 * programatically in the specified buffer, release
4384 		 * preallocated DMA resources before storing data in the buffer,
4385 		 * so no unwanted DMA sync would take place.
4386 		 */
4387 		sata_scsi_dmafree(NULL, scsipkt);
4388 
4389 		len = 0;
4390 		bdlen = 0;
4391 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4392 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4393 			    (scsipkt->pkt_cdbp[1] & LLBAA))
4394 				bdlen = 16;
4395 			else
4396 				bdlen = 8;
4397 		}
4398 		/* Build mode parameter header */
4399 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4400 			/* 4-byte mode parameter header */
4401 			buf[len++] = 0;		/* mode data length */
4402 			buf[len++] = 0;		/* medium type */
4403 			buf[len++] = 0;		/* dev-specific param */
4404 			buf[len++] = bdlen;	/* Block Descriptor length */
4405 		} else {
4406 			/* 8-byte mode parameter header */
4407 			buf[len++] = 0;		/* mode data length */
4408 			buf[len++] = 0;
4409 			buf[len++] = 0;		/* medium type */
4410 			buf[len++] = 0;		/* dev-specific param */
4411 			if (bdlen == 16)
4412 				buf[len++] = 1;	/* long lba descriptor */
4413 			else
4414 				buf[len++] = 0;
4415 			buf[len++] = 0;
4416 			buf[len++] = 0;		/* Block Descriptor length */
4417 			buf[len++] = bdlen;
4418 		}
4419 
4420 		sdinfo = sata_get_device_info(
4421 		    spx->txlt_sata_hba_inst,
4422 		    &spx->txlt_sata_pkt->satapkt_device);
4423 
4424 		/* Build block descriptor only if not disabled (DBD) */
4425 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4426 			/* Block descriptor - direct-access device format */
4427 			if (bdlen == 8) {
4428 				/* build regular block descriptor */
4429 				buf[len++] =
4430 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4431 				buf[len++] =
4432 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4433 				buf[len++] =
4434 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4435 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4436 				buf[len++] = 0; /* density code */
4437 				buf[len++] = 0;
4438 				if (sdinfo->satadrv_type ==
4439 				    SATA_DTYPE_ATADISK)
4440 					buf[len++] = 2;
4441 				else
4442 					/* ATAPI */
4443 					buf[len++] = 8;
4444 				buf[len++] = 0;
4445 			} else if (bdlen == 16) {
4446 				/* Long LBA Accepted */
4447 				/* build long lba block descriptor */
4448 #ifndef __lock_lint
4449 				buf[len++] =
4450 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4451 				buf[len++] =
4452 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4453 				buf[len++] =
4454 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4455 				buf[len++] =
4456 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4457 #endif
4458 				buf[len++] =
4459 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4460 				buf[len++] =
4461 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4462 				buf[len++] =
4463 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4464 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4465 				buf[len++] = 0;
4466 				buf[len++] = 0; /* density code */
4467 				buf[len++] = 0;
4468 				buf[len++] = 0;
4469 				if (sdinfo->satadrv_type ==
4470 				    SATA_DTYPE_ATADISK)
4471 					buf[len++] = 2;
4472 				else
4473 					/* ATAPI */
4474 					buf[len++] = 8;
4475 				buf[len++] = 0;
4476 			}
4477 		}
4478 
4479 		sata_id = &sdinfo->satadrv_id;
4480 
4481 		/*
4482 		 * Add requested pages.
4483 		 * Page 3 and 4 are obsolete and we are not supporting them.
4484 		 * We deal now with:
4485 		 * caching (read/write cache control).
4486 		 * We should eventually deal with following mode pages:
4487 		 * error recovery  (0x01),
4488 		 * power condition (0x1a),
4489 		 * exception control page (enables SMART) (0x1c),
4490 		 * enclosure management (ses),
4491 		 * protocol-specific port mode (port control).
4492 		 */
4493 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4494 		case MODEPAGE_RW_ERRRECOV:
4495 			/* DAD_MODE_ERR_RECOV */
4496 			/* R/W recovery */
4497 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4498 			break;
4499 		case MODEPAGE_CACHING:
4500 			/* DAD_MODE_CACHE */
4501 			/* Reject not supported request for saved parameters */
4502 			if (pc == 3) {
4503 				*scsipkt->pkt_scbp = STATUS_CHECK;
4504 				sense = sata_arq_sense(spx);
4505 				sense->es_key = KEY_ILLEGAL_REQUEST;
4506 				sense->es_add_code =
4507 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
4508 				goto done;
4509 			}
4510 
4511 			/* caching */
4512 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4513 			break;
4514 		case MODEPAGE_INFO_EXCPT:
4515 			/* exception cntrl */
4516 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4517 				len += sata_build_msense_page_1c(sdinfo, pc,
4518 				    buf+len);
4519 			}
4520 			else
4521 				goto err;
4522 			break;
4523 		case MODEPAGE_POWER_COND:
4524 			/* DAD_MODE_POWER_COND */
4525 			/* power condition */
4526 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4527 			break;
4528 
4529 		case MODEPAGE_ACOUSTIC_MANAG:
4530 			/* acoustic management */
4531 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4532 			break;
4533 		case MODEPAGE_ALLPAGES:
4534 			/* all pages */
4535 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4536 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4537 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4538 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4539 				len += sata_build_msense_page_1c(sdinfo, pc,
4540 				    buf+len);
4541 			}
4542 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4543 			break;
4544 		default:
4545 		err:
4546 			/* Invalid request */
4547 			*scsipkt->pkt_scbp = STATUS_CHECK;
4548 			sense = sata_arq_sense(spx);
4549 			sense->es_key = KEY_ILLEGAL_REQUEST;
4550 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4551 			goto done;
4552 		}
4553 
4554 		/* fix total mode data length */
4555 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4556 			/* 4-byte mode parameter header */
4557 			buf[0] = len - 1;	/* mode data length */
4558 		} else {
4559 			buf[0] = (len -2) >> 8;
4560 			buf[1] = (len -2) & 0xff;
4561 		}
4562 
4563 
4564 		/* Check allocation length */
4565 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4566 			alc_len = scsipkt->pkt_cdbp[4];
4567 		} else {
4568 			alc_len = scsipkt->pkt_cdbp[7];
4569 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4570 		}
4571 		/*
4572 		 * We do not check for possible parameters truncation
4573 		 * (alc_len < len) assuming that the target driver works
4574 		 * correctly. Just avoiding overrun.
4575 		 * Copy no more than requested and possible, buffer-wise.
4576 		 */
4577 		count = MIN(alc_len, len);
4578 		count = MIN(bp->b_bcount, count);
4579 		bcopy(buf, bp->b_un.b_addr, count);
4580 
4581 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4582 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4583 	}
4584 	*scsipkt->pkt_scbp = STATUS_GOOD;
4585 done:
4586 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4587 	(void) kmem_free(buf, 1024);
4588 
4589 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4590 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4591 
4592 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4593 	    scsipkt->pkt_comp != NULL)
4594 		/* scsi callback required */
4595 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4596 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4597 		    TQ_SLEEP) == NULL)
4598 			/* Scheduling the callback failed */
4599 			return (TRAN_BUSY);
4600 
4601 	return (TRAN_ACCEPT);
4602 }
4603 
4604 
4605 /*
4606  * SATA translate command: Mode Select.
4607  * Translated into appropriate SATA command or emulated.
4608  * Saving parameters is not supported.
4609  * Changing device capacity is not supported (although theoretically
4610  * possible by executing SET FEATURES/SET MAX ADDRESS)
4611  *
4612  * Assumption is that the target driver is working correctly.
4613  *
4614  * More than one SATA command may be executed to perform operations specified
4615  * by mode select pages. The first error terminates further execution.
4616  * Operations performed successully are not backed-up in such case.
4617  *
4618  * NOTE: Implemented pages:
4619  * - caching page
4620  * - informational exception page
4621  * - acoustic management page
4622  * - power condition page
4623  * Caching setup is remembered so it could be re-stored in case of
4624  * an unexpected device reset.
4625  *
4626  * Returns TRAN_XXXX.
4627  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
4628  */
4629 
4630 static int
4631 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4632 {
4633 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4634 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4635 	struct scsi_extended_sense *sense;
4636 	int len, pagelen, count, pllen;
4637 	uint8_t *buf;	/* mode select buffer */
4638 	int rval, stat, reason;
4639 	uint_t nointr_flag;
4640 	int dmod = 0;
4641 
4642 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4643 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4644 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4645 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4646 
4647 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4648 
4649 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4650 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4651 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4652 		return (rval);
4653 	}
4654 
4655 	rval = TRAN_ACCEPT;
4656 
4657 	scsipkt->pkt_reason = CMD_CMPLT;
4658 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4659 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4660 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4661 
4662 	/* Reject not supported request */
4663 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4664 		*scsipkt->pkt_scbp = STATUS_CHECK;
4665 		sense = sata_arq_sense(spx);
4666 		sense->es_key = KEY_ILLEGAL_REQUEST;
4667 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4668 		goto done;
4669 	}
4670 
4671 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4672 		pllen = scsipkt->pkt_cdbp[4];
4673 	} else {
4674 		pllen = scsipkt->pkt_cdbp[7];
4675 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4676 	}
4677 
4678 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4679 
4680 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4681 		buf = (uint8_t *)bp->b_un.b_addr;
4682 		count = MIN(bp->b_bcount, pllen);
4683 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4684 		scsipkt->pkt_resid = 0;
4685 		pllen = count;
4686 
4687 		/*
4688 		 * Check the header to skip the block descriptor(s) - we
4689 		 * do not support setting device capacity.
4690 		 * Existing macros do not recognize long LBA dscriptor,
4691 		 * hence manual calculation.
4692 		 */
4693 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4694 			/* 6-bytes CMD, 4 bytes header */
4695 			if (count <= 4)
4696 				goto done;		/* header only */
4697 			len = buf[3] + 4;
4698 		} else {
4699 			/* 10-bytes CMD, 8 bytes header */
4700 			if (count <= 8)
4701 				goto done;		/* header only */
4702 			len = buf[6];
4703 			len = (len << 8) + buf[7] + 8;
4704 		}
4705 		if (len >= count)
4706 			goto done;	/* header + descriptor(s) only */
4707 
4708 		pllen -= len;		/* remaining data length */
4709 
4710 		/*
4711 		 * We may be executing SATA command and want to execute it
4712 		 * in SYNCH mode, regardless of scsi_pkt setting.
4713 		 * Save scsi_pkt setting and indicate SYNCH mode
4714 		 */
4715 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4716 		    scsipkt->pkt_comp != NULL) {
4717 			scsipkt->pkt_flags |= FLAG_NOINTR;
4718 		}
4719 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
4720 
4721 		/*
4722 		 * len is now the offset to a first mode select page
4723 		 * Process all pages
4724 		 */
4725 		while (pllen > 0) {
4726 			switch ((int)buf[len]) {
4727 			case MODEPAGE_CACHING:
4728 				/* No support for SP (saving) */
4729 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4730 					*scsipkt->pkt_scbp = STATUS_CHECK;
4731 					sense = sata_arq_sense(spx);
4732 					sense->es_key = KEY_ILLEGAL_REQUEST;
4733 					sense->es_add_code =
4734 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4735 					goto done;
4736 				}
4737 				stat = sata_mode_select_page_8(spx,
4738 				    (struct mode_cache_scsi3 *)&buf[len],
4739 				    pllen, &pagelen, &rval, &dmod);
4740 				/*
4741 				 * The pagelen value indicates the number of
4742 				 * parameter bytes already processed.
4743 				 * The rval is the return value from
4744 				 * sata_tran_start().
4745 				 * The stat indicates the overall status of
4746 				 * the operation(s).
4747 				 */
4748 				if (stat != SATA_SUCCESS)
4749 					/*
4750 					 * Page processing did not succeed -
4751 					 * all error info is already set-up,
4752 					 * just return
4753 					 */
4754 					pllen = 0; /* this breaks the loop */
4755 				else {
4756 					len += pagelen;
4757 					pllen -= pagelen;
4758 				}
4759 				break;
4760 
4761 			case MODEPAGE_INFO_EXCPT:
4762 				stat = sata_mode_select_page_1c(spx,
4763 				    (struct mode_info_excpt_page *)&buf[len],
4764 				    pllen, &pagelen, &rval, &dmod);
4765 				/*
4766 				 * The pagelen value indicates the number of
4767 				 * parameter bytes already processed.
4768 				 * The rval is the return value from
4769 				 * sata_tran_start().
4770 				 * The stat indicates the overall status of
4771 				 * the operation(s).
4772 				 */
4773 				if (stat != SATA_SUCCESS)
4774 					/*
4775 					 * Page processing did not succeed -
4776 					 * all error info is already set-up,
4777 					 * just return
4778 					 */
4779 					pllen = 0; /* this breaks the loop */
4780 				else {
4781 					len += pagelen;
4782 					pllen -= pagelen;
4783 				}
4784 				break;
4785 
4786 			case MODEPAGE_ACOUSTIC_MANAG:
4787 				stat = sata_mode_select_page_30(spx,
4788 				    (struct mode_acoustic_management *)
4789 				    &buf[len], pllen, &pagelen, &rval, &dmod);
4790 				/*
4791 				 * The pagelen value indicates the number of
4792 				 * parameter bytes already processed.
4793 				 * The rval is the return value from
4794 				 * sata_tran_start().
4795 				 * The stat indicates the overall status of
4796 				 * the operation(s).
4797 				 */
4798 				if (stat != SATA_SUCCESS)
4799 					/*
4800 					 * Page processing did not succeed -
4801 					 * all error info is already set-up,
4802 					 * just return
4803 					 */
4804 					pllen = 0; /* this breaks the loop */
4805 				else {
4806 					len += pagelen;
4807 					pllen -= pagelen;
4808 				}
4809 
4810 				break;
4811 			case MODEPAGE_POWER_COND:
4812 				stat = sata_mode_select_page_1a(spx,
4813 				    (struct mode_info_power_cond *)&buf[len],
4814 				    pllen, &pagelen, &rval, &dmod);
4815 				/*
4816 				 * The pagelen value indicates the number of
4817 				 * parameter bytes already processed.
4818 				 * The rval is the return value from
4819 				 * sata_tran_start().
4820 				 * The stat indicates the overall status of
4821 				 * the operation(s).
4822 				 */
4823 				if (stat != SATA_SUCCESS)
4824 					/*
4825 					 * Page processing did not succeed -
4826 					 * all error info is already set-up,
4827 					 * just return
4828 					 */
4829 					pllen = 0; /* this breaks the loop */
4830 				else {
4831 					len += pagelen;
4832 					pllen -= pagelen;
4833 				}
4834 				break;
4835 			default:
4836 				*scsipkt->pkt_scbp = STATUS_CHECK;
4837 				sense = sata_arq_sense(spx);
4838 				sense->es_key = KEY_ILLEGAL_REQUEST;
4839 				sense->es_add_code =
4840 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
4841 				goto done;
4842 			}
4843 		}
4844 	}
4845 done:
4846 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4847 	/*
4848 	 * If device parameters were modified, fetch and store the new
4849 	 * Identify Device data. Since port mutex could have been released
4850 	 * for accessing HBA driver, we need to re-check device existence.
4851 	 */
4852 	if (dmod != 0) {
4853 		sata_drive_info_t new_sdinfo, *sdinfo;
4854 		int rv = 0;
4855 
4856 		/*
4857 		 * Following statement has to be changed if this function is
4858 		 * used for devices other than SATA hard disks.
4859 		 */
4860 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4861 
4862 		new_sdinfo.satadrv_addr =
4863 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4864 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4865 		    &new_sdinfo);
4866 
4867 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4868 		/*
4869 		 * Since port mutex could have been released when
4870 		 * accessing HBA driver, we need to re-check that the
4871 		 * framework still holds the device info structure.
4872 		 */
4873 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4874 		    &spx->txlt_sata_pkt->satapkt_device);
4875 		if (sdinfo != NULL) {
4876 			/*
4877 			 * Device still has info structure in the
4878 			 * sata framework. Copy newly fetched info
4879 			 */
4880 			if (rv == 0) {
4881 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4882 				sata_save_drive_settings(sdinfo);
4883 			} else {
4884 				/*
4885 				 * Could not fetch new data - invalidate
4886 				 * sata_drive_info. That makes device
4887 				 * unusable.
4888 				 */
4889 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4890 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4891 			}
4892 		}
4893 		if (rv != 0 || sdinfo == NULL) {
4894 			/*
4895 			 * This changes the overall mode select completion
4896 			 * reason to a failed one !!!!!
4897 			 */
4898 			*scsipkt->pkt_scbp = STATUS_CHECK;
4899 			sense = sata_arq_sense(spx);
4900 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4901 			rval = TRAN_ACCEPT;
4902 		}
4903 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4904 	}
4905 	/* Restore the scsi pkt flags */
4906 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
4907 	scsipkt->pkt_flags |= nointr_flag;
4908 
4909 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4910 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4911 
4912 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4913 	    scsipkt->pkt_comp != NULL)
4914 		/* scsi callback required */
4915 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4916 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4917 		    TQ_SLEEP) == NULL)
4918 			/* Scheduling the callback failed */
4919 			return (TRAN_BUSY);
4920 
4921 	return (rval);
4922 }
4923 
4924 /*
4925  * Translate command: ATA Pass Through
4926  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
4927  * PIO Data-Out protocols.  Also supports CK_COND bit.
4928  *
4929  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
4930  * described in Table 111 of SAT-2 (Draft 9).
4931  */
4932 static  int
4933 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
4934 {
4935 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4936 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4937 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4938 	int extend;
4939 	uint64_t lba;
4940 	uint16_t feature, sec_count;
4941 	int t_len, synch;
4942 	int rval, reason;
4943 
4944 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4945 
4946 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
4947 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4948 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4949 		return (rval);
4950 	}
4951 
4952 	/* T_DIR bit */
4953 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
4954 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
4955 	else
4956 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
4957 
4958 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
4959 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
4960 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4961 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4962 	}
4963 
4964 	/* OFFLINE field. If non-zero, invalid command (for now). */
4965 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
4966 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4967 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4968 	}
4969 
4970 	/* PROTOCOL field */
4971 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
4972 	case SATL_APT_P_HW_RESET:
4973 	case SATL_APT_P_SRST:
4974 	case SATL_APT_P_DMA:
4975 	case SATL_APT_P_DMA_QUEUED:
4976 	case SATL_APT_P_DEV_DIAG:
4977 	case SATL_APT_P_DEV_RESET:
4978 	case SATL_APT_P_UDMA_IN:
4979 	case SATL_APT_P_UDMA_OUT:
4980 	case SATL_APT_P_FPDMA:
4981 	case SATL_APT_P_RET_RESP:
4982 		/* Not yet implemented */
4983 	default:
4984 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4985 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4986 
4987 	case SATL_APT_P_NON_DATA:
4988 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
4989 		break;
4990 
4991 	case SATL_APT_P_PIO_DATA_IN:
4992 		/* If PROTOCOL disagrees with T_DIR, invalid command */
4993 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
4994 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4995 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4996 		}
4997 
4998 		/* if there is a buffer, release its DMA resources */
4999 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5000 			sata_scsi_dmafree(NULL, scsipkt);
5001 		} else {
5002 			/* if there is no buffer, how do you PIO in? */
5003 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5004 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5005 		}
5006 
5007 		break;
5008 
5009 	case SATL_APT_P_PIO_DATA_OUT:
5010 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5011 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5012 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5013 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5014 		}
5015 
5016 		/* if there is a buffer, release its DMA resources */
5017 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5018 			sata_scsi_dmafree(NULL, scsipkt);
5019 		} else {
5020 			/* if there is no buffer, how do you PIO out? */
5021 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5022 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5023 		}
5024 
5025 		break;
5026 	}
5027 
5028 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5029 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5030 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5031 		feature = scsipkt->pkt_cdbp[3];
5032 
5033 		sec_count = scsipkt->pkt_cdbp[4];
5034 
5035 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5036 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5037 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5038 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5039 
5040 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5041 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5042 
5043 		break;
5044 
5045 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5046 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5047 			extend = 1;
5048 
5049 			feature = scsipkt->pkt_cdbp[3];
5050 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5051 
5052 			sec_count = scsipkt->pkt_cdbp[5];
5053 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5054 
5055 			lba = scsipkt->pkt_cdbp[11];
5056 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5057 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5058 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5059 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5060 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5061 
5062 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5063 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5064 		} else {
5065 			feature = scsipkt->pkt_cdbp[3];
5066 
5067 			sec_count = scsipkt->pkt_cdbp[5];
5068 
5069 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5070 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5071 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5072 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5073 
5074 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5075 			    0xf0;
5076 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5077 		}
5078 
5079 		break;
5080 	}
5081 
5082 	/* CK_COND bit */
5083 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5084 		if (extend) {
5085 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5086 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5087 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5088 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5089 		}
5090 
5091 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5092 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5093 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5094 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5095 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5096 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5097 	}
5098 
5099 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5100 	if (extend) {
5101 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5102 
5103 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5104 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5105 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5106 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5107 		scmd->satacmd_lba_high_msb = lba >> 40;
5108 	} else {
5109 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5110 
5111 		scmd->satacmd_features_reg_ext = 0;
5112 		scmd->satacmd_sec_count_msb = 0;
5113 		scmd->satacmd_lba_low_msb = 0;
5114 		scmd->satacmd_lba_mid_msb = 0;
5115 		scmd->satacmd_lba_high_msb = 0;
5116 	}
5117 
5118 	scmd->satacmd_features_reg = feature & 0xff;
5119 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5120 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5121 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5122 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5123 
5124 	/* Determine transfer length */
5125 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5126 	case 1:
5127 		t_len = feature;
5128 		break;
5129 	case 2:
5130 		t_len = sec_count;
5131 		break;
5132 	default:
5133 		t_len = 0;
5134 		break;
5135 	}
5136 
5137 	/* Adjust transfer length for the Byte Block bit */
5138 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5139 		t_len *= SATA_DISK_SECTOR_SIZE;
5140 
5141 	/* Start processing command */
5142 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5143 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5144 		synch = FALSE;
5145 	} else {
5146 		synch = TRUE;
5147 	}
5148 
5149 	if (sata_hba_start(spx, &rval) != 0) {
5150 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5151 		return (rval);
5152 	}
5153 
5154 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5155 
5156 	if (synch) {
5157 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5158 	}
5159 
5160 	return (TRAN_ACCEPT);
5161 }
5162 
5163 /*
5164  * Translate command: Log Sense
5165  */
5166 static 	int
5167 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5168 {
5169 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5170 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5171 	sata_drive_info_t *sdinfo;
5172 	struct scsi_extended_sense *sense;
5173 	int 		len, count, alc_len;
5174 	int		pc;	/* Page Control code */
5175 	int		page_code;	/* Page code */
5176 	uint8_t		*buf;	/* log sense buffer */
5177 	int		rval, reason;
5178 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5179 
5180 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5181 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5182 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5183 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5184 
5185 	buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5186 
5187 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5188 
5189 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5190 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5191 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5192 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5193 		return (rval);
5194 	}
5195 
5196 	scsipkt->pkt_reason = CMD_CMPLT;
5197 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5198 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5199 
5200 	pc = scsipkt->pkt_cdbp[2] >> 6;
5201 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5202 
5203 	/* Reject not supported request for all but cumulative values */
5204 	switch (pc) {
5205 	case PC_CUMULATIVE_VALUES:
5206 		break;
5207 	default:
5208 		*scsipkt->pkt_scbp = STATUS_CHECK;
5209 		sense = sata_arq_sense(spx);
5210 		sense->es_key = KEY_ILLEGAL_REQUEST;
5211 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5212 		goto done;
5213 	}
5214 
5215 	switch (page_code) {
5216 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5217 	case PAGE_CODE_SELF_TEST_RESULTS:
5218 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5219 	case PAGE_CODE_SMART_READ_DATA:
5220 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5221 		break;
5222 	default:
5223 		*scsipkt->pkt_scbp = STATUS_CHECK;
5224 		sense = sata_arq_sense(spx);
5225 		sense->es_key = KEY_ILLEGAL_REQUEST;
5226 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5227 		goto done;
5228 	}
5229 
5230 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5231 		/*
5232 		 * Because log sense uses local buffers for data retrieval from
5233 		 * the devices and sets the data programatically in the
5234 		 * original specified buffer, release preallocated DMA
5235 		 * resources before storing data in the original buffer,
5236 		 * so no unwanted DMA sync would take place.
5237 		 */
5238 		sata_id_t *sata_id;
5239 
5240 		sata_scsi_dmafree(NULL, scsipkt);
5241 
5242 		len = 0;
5243 
5244 		/* Build log parameter header */
5245 		buf[len++] = page_code;	/* page code as in the CDB */
5246 		buf[len++] = 0;		/* reserved */
5247 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5248 		buf[len++] = 0;		/* (LSB) */
5249 
5250 		sdinfo = sata_get_device_info(
5251 		    spx->txlt_sata_hba_inst,
5252 		    &spx->txlt_sata_pkt->satapkt_device);
5253 
5254 		/*
5255 		 * Add requested pages.
5256 		 */
5257 		switch (page_code) {
5258 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5259 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5260 			break;
5261 		case PAGE_CODE_SELF_TEST_RESULTS:
5262 			sata_id = &sdinfo->satadrv_id;
5263 			if ((! (sata_id->ai_cmdset84 &
5264 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5265 			    (! (sata_id->ai_features87 &
5266 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5267 				*scsipkt->pkt_scbp = STATUS_CHECK;
5268 				sense = sata_arq_sense(spx);
5269 				sense->es_key = KEY_ILLEGAL_REQUEST;
5270 				sense->es_add_code =
5271 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5272 
5273 				goto done;
5274 			}
5275 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5276 			    spx->txlt_sata_hba_inst);
5277 			break;
5278 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5279 			sata_id = &sdinfo->satadrv_id;
5280 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5281 				*scsipkt->pkt_scbp = STATUS_CHECK;
5282 				sense = sata_arq_sense(spx);
5283 				sense->es_key = KEY_ILLEGAL_REQUEST;
5284 				sense->es_add_code =
5285 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5286 
5287 				goto done;
5288 			}
5289 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5290 				*scsipkt->pkt_scbp = STATUS_CHECK;
5291 				sense = sata_arq_sense(spx);
5292 				sense->es_key = KEY_ABORTED_COMMAND;
5293 				sense->es_add_code =
5294 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5295 				sense->es_qual_code =
5296 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5297 
5298 				goto done;
5299 			}
5300 
5301 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5302 			    spx->txlt_sata_hba_inst);
5303 			break;
5304 		case PAGE_CODE_SMART_READ_DATA:
5305 			sata_id = &sdinfo->satadrv_id;
5306 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5307 				*scsipkt->pkt_scbp = STATUS_CHECK;
5308 				sense = sata_arq_sense(spx);
5309 				sense->es_key = KEY_ILLEGAL_REQUEST;
5310 				sense->es_add_code =
5311 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5312 
5313 				goto done;
5314 			}
5315 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5316 				*scsipkt->pkt_scbp = STATUS_CHECK;
5317 				sense = sata_arq_sense(spx);
5318 				sense->es_key = KEY_ABORTED_COMMAND;
5319 				sense->es_add_code =
5320 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5321 				sense->es_qual_code =
5322 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5323 
5324 				goto done;
5325 			}
5326 
5327 			/* This page doesn't include a page header */
5328 			len = sata_build_lsense_page_30(sdinfo, buf,
5329 			    spx->txlt_sata_hba_inst);
5330 			goto no_header;
5331 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5332 			sata_id = &sdinfo->satadrv_id;
5333 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5334 				*scsipkt->pkt_scbp = STATUS_CHECK;
5335 				sense = sata_arq_sense(spx);
5336 				sense->es_key = KEY_ILLEGAL_REQUEST;
5337 				sense->es_add_code =
5338 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5339 
5340 				goto done;
5341 			}
5342 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5343 				*scsipkt->pkt_scbp = STATUS_CHECK;
5344 				sense = sata_arq_sense(spx);
5345 				sense->es_key = KEY_ABORTED_COMMAND;
5346 				sense->es_add_code =
5347 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5348 				sense->es_qual_code =
5349 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5350 
5351 				goto done;
5352 			}
5353 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
5354 			goto no_header;
5355 		default:
5356 			/* Invalid request */
5357 			*scsipkt->pkt_scbp = STATUS_CHECK;
5358 			sense = sata_arq_sense(spx);
5359 			sense->es_key = KEY_ILLEGAL_REQUEST;
5360 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5361 			goto done;
5362 		}
5363 
5364 		/* set parameter log sense data length */
5365 		buf[2] = len >> 8;	/* log sense length (MSB) */
5366 		buf[3] = len & 0xff;	/* log sense length (LSB) */
5367 
5368 		len += SCSI_LOG_PAGE_HDR_LEN;
5369 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
5370 
5371 no_header:
5372 		/* Check allocation length */
5373 		alc_len = scsipkt->pkt_cdbp[7];
5374 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5375 
5376 		/*
5377 		 * We do not check for possible parameters truncation
5378 		 * (alc_len < len) assuming that the target driver works
5379 		 * correctly. Just avoiding overrun.
5380 		 * Copy no more than requested and possible, buffer-wise.
5381 		 */
5382 		count = MIN(alc_len, len);
5383 		count = MIN(bp->b_bcount, count);
5384 		bcopy(buf, bp->b_un.b_addr, count);
5385 
5386 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5387 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5388 	}
5389 	*scsipkt->pkt_scbp = STATUS_GOOD;
5390 done:
5391 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5392 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5393 
5394 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5395 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5396 
5397 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5398 	    scsipkt->pkt_comp != NULL)
5399 		/* scsi callback required */
5400 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5401 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5402 		    TQ_SLEEP) == NULL)
5403 			/* Scheduling the callback failed */
5404 			return (TRAN_BUSY);
5405 
5406 	return (TRAN_ACCEPT);
5407 }
5408 
5409 /*
5410  * Translate command: Log Select
5411  * Not implemented at this time - returns invalid command response.
5412  */
5413 static	int
5414 sata_txlt_log_select(sata_pkt_txlate_t *spx)
5415 {
5416 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5417 	    "sata_txlt_log_select\n", NULL);
5418 
5419 	return (sata_txlt_invalid_command(spx));
5420 }
5421 
5422 
5423 /*
5424  * Translate command: Read (various types).
5425  * Translated into appropriate type of ATA READ command
5426  * for SATA hard disks.
5427  * Both the device capabilities and requested operation mode are
5428  * considered.
5429  *
5430  * Following scsi cdb fields are ignored:
5431  * rdprotect, dpo, fua, fua_nv, group_number.
5432  *
5433  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5434  * enable variable sata_func_enable), the capability of the controller and
5435  * capability of a device are checked and if both support queueing, read
5436  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
5437  * command rather than plain READ_XXX command.
5438  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5439  * both the controller and device suport such functionality, the read
5440  * request will be translated to READ_FPDMA_QUEUED command.
5441  * In both cases the maximum queue depth is derived as minimum of:
5442  * HBA capability,device capability and sata_max_queue_depth variable setting.
5443  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5444  * used to pass max queue depth value, and the maximum possible queue depth
5445  * is 32.
5446  *
5447  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5448  * appropriate values in scsi_pkt fields.
5449  */
5450 static int
5451 sata_txlt_read(sata_pkt_txlate_t *spx)
5452 {
5453 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5454 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5455 	sata_drive_info_t *sdinfo;
5456 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5457 	int cport = SATA_TXLT_CPORT(spx);
5458 	uint16_t sec_count;
5459 	uint64_t lba;
5460 	int rval, reason;
5461 	int synch;
5462 
5463 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5464 
5465 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5466 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5467 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5468 		return (rval);
5469 	}
5470 
5471 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5472 	    &spx->txlt_sata_pkt->satapkt_device);
5473 
5474 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5475 	/*
5476 	 * Extract LBA and sector count from scsi CDB.
5477 	 */
5478 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5479 	case SCMD_READ:
5480 		/* 6-byte scsi read cmd : 0x08 */
5481 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5482 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5483 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5484 		sec_count = scsipkt->pkt_cdbp[4];
5485 		/* sec_count 0 will be interpreted as 256 by a device */
5486 		break;
5487 	case SCMD_READ_G1:
5488 		/* 10-bytes scsi read command : 0x28 */
5489 		lba = scsipkt->pkt_cdbp[2];
5490 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5491 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5492 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5493 		sec_count = scsipkt->pkt_cdbp[7];
5494 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5495 		break;
5496 	case SCMD_READ_G5:
5497 		/* 12-bytes scsi read command : 0xA8 */
5498 		lba = scsipkt->pkt_cdbp[2];
5499 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5500 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5501 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5502 		sec_count = scsipkt->pkt_cdbp[6];
5503 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5504 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5505 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5506 		break;
5507 	case SCMD_READ_G4:
5508 		/* 16-bytes scsi read command : 0x88 */
5509 		lba = scsipkt->pkt_cdbp[2];
5510 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5511 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5512 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5513 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5514 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5515 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5516 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5517 		sec_count = scsipkt->pkt_cdbp[10];
5518 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5519 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5520 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5521 		break;
5522 	default:
5523 		/* Unsupported command */
5524 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5525 		return (sata_txlt_invalid_command(spx));
5526 	}
5527 
5528 	/*
5529 	 * Check if specified address exceeds device capacity
5530 	 */
5531 	if ((lba >= sdinfo->satadrv_capacity) ||
5532 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5533 		/* LBA out of range */
5534 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5535 		return (sata_txlt_lba_out_of_range(spx));
5536 	}
5537 
5538 	/*
5539 	 * For zero-length transfer, emulate good completion of the command
5540 	 * (reasons for rejecting the command were already checked).
5541 	 * No DMA resources were allocated.
5542 	 */
5543 	if (spx->txlt_dma_cookie_list == NULL) {
5544 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5545 		return (sata_emul_rw_completion(spx));
5546 	}
5547 
5548 	/*
5549 	 * Build cmd block depending on the device capability and
5550 	 * requested operation mode.
5551 	 * Do not bother with non-dma mode - we are working only with
5552 	 * devices supporting DMA.
5553 	 */
5554 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5555 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5556 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
5557 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5558 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5559 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
5560 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5561 #ifndef __lock_lint
5562 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5563 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5564 		scmd->satacmd_lba_high_msb = lba >> 40;
5565 #endif
5566 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5567 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5568 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5569 	}
5570 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5571 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5572 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5573 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5574 	scmd->satacmd_features_reg = 0;
5575 	scmd->satacmd_status_reg = 0;
5576 	scmd->satacmd_error_reg = 0;
5577 
5578 	/*
5579 	 * Check if queueing commands should be used and switch
5580 	 * to appropriate command if possible
5581 	 */
5582 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5583 		boolean_t using_queuing;
5584 
5585 		/* Queuing supported by controller and device? */
5586 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5587 		    (sdinfo->satadrv_features_support &
5588 		    SATA_DEV_F_NCQ) &&
5589 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5590 		    SATA_CTLF_NCQ)) {
5591 			using_queuing = B_TRUE;
5592 
5593 			/* NCQ supported - use FPDMA READ */
5594 			scmd->satacmd_cmd_reg =
5595 			    SATAC_READ_FPDMA_QUEUED;
5596 			scmd->satacmd_features_reg_ext =
5597 			    scmd->satacmd_sec_count_msb;
5598 			scmd->satacmd_sec_count_msb = 0;
5599 		} else if ((sdinfo->satadrv_features_support &
5600 		    SATA_DEV_F_TCQ) &&
5601 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5602 		    SATA_CTLF_QCMD)) {
5603 			using_queuing = B_TRUE;
5604 
5605 			/* Legacy queueing */
5606 			if (sdinfo->satadrv_features_support &
5607 			    SATA_DEV_F_LBA48) {
5608 				scmd->satacmd_cmd_reg =
5609 				    SATAC_READ_DMA_QUEUED_EXT;
5610 				scmd->satacmd_features_reg_ext =
5611 				    scmd->satacmd_sec_count_msb;
5612 				scmd->satacmd_sec_count_msb = 0;
5613 			} else {
5614 				scmd->satacmd_cmd_reg =
5615 				    SATAC_READ_DMA_QUEUED;
5616 			}
5617 		} else	/* NCQ nor legacy queuing not supported */
5618 			using_queuing = B_FALSE;
5619 
5620 		/*
5621 		 * If queuing, the sector count goes in the features register
5622 		 * and the secount count will contain the tag.
5623 		 */
5624 		if (using_queuing) {
5625 			scmd->satacmd_features_reg =
5626 			    scmd->satacmd_sec_count_lsb;
5627 			scmd->satacmd_sec_count_lsb = 0;
5628 			scmd->satacmd_flags.sata_queued = B_TRUE;
5629 
5630 			/* Set-up maximum queue depth */
5631 			scmd->satacmd_flags.sata_max_queue_depth =
5632 			    sdinfo->satadrv_max_queue_depth - 1;
5633 		} else if (sdinfo->satadrv_features_enabled &
5634 		    SATA_DEV_F_E_UNTAGGED_QING) {
5635 			/*
5636 			 * Although NCQ/TCQ is not enabled, untagged queuing
5637 			 * may be still used.
5638 			 * Set-up the maximum untagged queue depth.
5639 			 * Use controller's queue depth from sata_hba_tran.
5640 			 * SATA HBA drivers may ignore this value and rely on
5641 			 * the internal limits.For drivers that do not
5642 			 * ignore untaged queue depth, limit the value to
5643 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5644 			 * largest value that can be passed via
5645 			 * satacmd_flags.sata_max_queue_depth.
5646 			 */
5647 			scmd->satacmd_flags.sata_max_queue_depth =
5648 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5649 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5650 
5651 		} else {
5652 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5653 		}
5654 	} else
5655 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5656 
5657 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
5658 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
5659 	    scmd->satacmd_cmd_reg, lba, sec_count);
5660 
5661 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5662 		/* Need callback function */
5663 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5664 		synch = FALSE;
5665 	} else
5666 		synch = TRUE;
5667 
5668 	/* Transfer command to HBA */
5669 	if (sata_hba_start(spx, &rval) != 0) {
5670 		/* Pkt not accepted for execution */
5671 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5672 		return (rval);
5673 	}
5674 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5675 	/*
5676 	 * If execution is non-synchronous,
5677 	 * a callback function will handle potential errors, translate
5678 	 * the response and will do a callback to a target driver.
5679 	 * If it was synchronous, check execution status using the same
5680 	 * framework callback.
5681 	 */
5682 	if (synch) {
5683 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5684 		    "synchronous execution status %x\n",
5685 		    spx->txlt_sata_pkt->satapkt_reason);
5686 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5687 	}
5688 	return (TRAN_ACCEPT);
5689 }
5690 
5691 
5692 /*
5693  * SATA translate command: Write (various types)
5694  * Translated into appropriate type of ATA WRITE command
5695  * for SATA hard disks.
5696  * Both the device capabilities and requested operation mode are
5697  * considered.
5698  *
5699  * Following scsi cdb fields are ignored:
5700  * rwprotect, dpo, fua, fua_nv, group_number.
5701  *
5702  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5703  * enable variable sata_func_enable), the capability of the controller and
5704  * capability of a device are checked and if both support queueing, write
5705  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
5706  * command rather than plain WRITE_XXX command.
5707  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5708  * both the controller and device suport such functionality, the write
5709  * request will be translated to WRITE_FPDMA_QUEUED command.
5710  * In both cases the maximum queue depth is derived as minimum of:
5711  * HBA capability,device capability and sata_max_queue_depth variable setting.
5712  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5713  * used to pass max queue depth value, and the maximum possible queue depth
5714  * is 32.
5715  *
5716  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5717  * appropriate values in scsi_pkt fields.
5718  */
5719 static int
5720 sata_txlt_write(sata_pkt_txlate_t *spx)
5721 {
5722 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5723 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5724 	sata_drive_info_t *sdinfo;
5725 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5726 	int cport = SATA_TXLT_CPORT(spx);
5727 	uint16_t sec_count;
5728 	uint64_t lba;
5729 	int rval, reason;
5730 	int synch;
5731 
5732 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5733 
5734 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5735 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5736 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5737 		return (rval);
5738 	}
5739 
5740 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5741 	    &spx->txlt_sata_pkt->satapkt_device);
5742 
5743 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5744 	/*
5745 	 * Extract LBA and sector count from scsi CDB
5746 	 */
5747 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5748 	case SCMD_WRITE:
5749 		/* 6-byte scsi read cmd : 0x0A */
5750 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5751 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5752 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5753 		sec_count = scsipkt->pkt_cdbp[4];
5754 		/* sec_count 0 will be interpreted as 256 by a device */
5755 		break;
5756 	case SCMD_WRITE_G1:
5757 		/* 10-bytes scsi write command : 0x2A */
5758 		lba = scsipkt->pkt_cdbp[2];
5759 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5760 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5761 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5762 		sec_count = scsipkt->pkt_cdbp[7];
5763 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5764 		break;
5765 	case SCMD_WRITE_G5:
5766 		/* 12-bytes scsi read command : 0xAA */
5767 		lba = scsipkt->pkt_cdbp[2];
5768 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5769 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5770 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5771 		sec_count = scsipkt->pkt_cdbp[6];
5772 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5773 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5774 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5775 		break;
5776 	case SCMD_WRITE_G4:
5777 		/* 16-bytes scsi write command : 0x8A */
5778 		lba = scsipkt->pkt_cdbp[2];
5779 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5780 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5781 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5782 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5783 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5784 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5785 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5786 		sec_count = scsipkt->pkt_cdbp[10];
5787 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5788 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5789 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5790 		break;
5791 	default:
5792 		/* Unsupported command */
5793 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5794 		return (sata_txlt_invalid_command(spx));
5795 	}
5796 
5797 	/*
5798 	 * Check if specified address and length exceeds device capacity
5799 	 */
5800 	if ((lba >= sdinfo->satadrv_capacity) ||
5801 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5802 		/* LBA out of range */
5803 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5804 		return (sata_txlt_lba_out_of_range(spx));
5805 	}
5806 
5807 	/*
5808 	 * For zero-length transfer, emulate good completion of the command
5809 	 * (reasons for rejecting the command were already checked).
5810 	 * No DMA resources were allocated.
5811 	 */
5812 	if (spx->txlt_dma_cookie_list == NULL) {
5813 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5814 		return (sata_emul_rw_completion(spx));
5815 	}
5816 
5817 	/*
5818 	 * Build cmd block depending on the device capability and
5819 	 * requested operation mode.
5820 	 * Do not bother with non-dma mode- we are working only with
5821 	 * devices supporting DMA.
5822 	 */
5823 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5824 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5825 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
5826 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5827 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5828 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
5829 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5830 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5831 #ifndef __lock_lint
5832 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5833 		scmd->satacmd_lba_high_msb = lba >> 40;
5834 #endif
5835 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5836 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5837 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5838 	}
5839 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5840 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5841 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5842 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5843 	scmd->satacmd_features_reg = 0;
5844 	scmd->satacmd_status_reg = 0;
5845 	scmd->satacmd_error_reg = 0;
5846 
5847 	/*
5848 	 * Check if queueing commands should be used and switch
5849 	 * to appropriate command if possible
5850 	 */
5851 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5852 		boolean_t using_queuing;
5853 
5854 		/* Queuing supported by controller and device? */
5855 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5856 		    (sdinfo->satadrv_features_support &
5857 		    SATA_DEV_F_NCQ) &&
5858 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5859 		    SATA_CTLF_NCQ)) {
5860 			using_queuing = B_TRUE;
5861 
5862 			/* NCQ supported - use FPDMA WRITE */
5863 			scmd->satacmd_cmd_reg =
5864 			    SATAC_WRITE_FPDMA_QUEUED;
5865 			scmd->satacmd_features_reg_ext =
5866 			    scmd->satacmd_sec_count_msb;
5867 			scmd->satacmd_sec_count_msb = 0;
5868 		} else if ((sdinfo->satadrv_features_support &
5869 		    SATA_DEV_F_TCQ) &&
5870 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5871 		    SATA_CTLF_QCMD)) {
5872 			using_queuing = B_TRUE;
5873 
5874 			/* Legacy queueing */
5875 			if (sdinfo->satadrv_features_support &
5876 			    SATA_DEV_F_LBA48) {
5877 				scmd->satacmd_cmd_reg =
5878 				    SATAC_WRITE_DMA_QUEUED_EXT;
5879 				scmd->satacmd_features_reg_ext =
5880 				    scmd->satacmd_sec_count_msb;
5881 				scmd->satacmd_sec_count_msb = 0;
5882 			} else {
5883 				scmd->satacmd_cmd_reg =
5884 				    SATAC_WRITE_DMA_QUEUED;
5885 			}
5886 		} else	/*  NCQ nor legacy queuing not supported */
5887 			using_queuing = B_FALSE;
5888 
5889 		if (using_queuing) {
5890 			scmd->satacmd_features_reg =
5891 			    scmd->satacmd_sec_count_lsb;
5892 			scmd->satacmd_sec_count_lsb = 0;
5893 			scmd->satacmd_flags.sata_queued = B_TRUE;
5894 			/* Set-up maximum queue depth */
5895 			scmd->satacmd_flags.sata_max_queue_depth =
5896 			    sdinfo->satadrv_max_queue_depth - 1;
5897 		} else if (sdinfo->satadrv_features_enabled &
5898 		    SATA_DEV_F_E_UNTAGGED_QING) {
5899 			/*
5900 			 * Although NCQ/TCQ is not enabled, untagged queuing
5901 			 * may be still used.
5902 			 * Set-up the maximum untagged queue depth.
5903 			 * Use controller's queue depth from sata_hba_tran.
5904 			 * SATA HBA drivers may ignore this value and rely on
5905 			 * the internal limits. For drivera that do not
5906 			 * ignore untaged queue depth, limit the value to
5907 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5908 			 * largest value that can be passed via
5909 			 * satacmd_flags.sata_max_queue_depth.
5910 			 */
5911 			scmd->satacmd_flags.sata_max_queue_depth =
5912 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5913 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5914 
5915 		} else {
5916 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5917 		}
5918 	} else
5919 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5920 
5921 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5922 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
5923 	    scmd->satacmd_cmd_reg, lba, sec_count);
5924 
5925 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5926 		/* Need callback function */
5927 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5928 		synch = FALSE;
5929 	} else
5930 		synch = TRUE;
5931 
5932 	/* Transfer command to HBA */
5933 	if (sata_hba_start(spx, &rval) != 0) {
5934 		/* Pkt not accepted for execution */
5935 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5936 		return (rval);
5937 	}
5938 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5939 
5940 	/*
5941 	 * If execution is non-synchronous,
5942 	 * a callback function will handle potential errors, translate
5943 	 * the response and will do a callback to a target driver.
5944 	 * If it was synchronous, check execution status using the same
5945 	 * framework callback.
5946 	 */
5947 	if (synch) {
5948 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5949 		    "synchronous execution status %x\n",
5950 		    spx->txlt_sata_pkt->satapkt_reason);
5951 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5952 	}
5953 	return (TRAN_ACCEPT);
5954 }
5955 
5956 
5957 /*
5958  * Implements SCSI SBC WRITE BUFFER command download microcode option
5959  */
5960 static int
5961 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
5962 {
5963 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
5964 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
5965 
5966 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
5967 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5968 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
5969 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5970 
5971 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5972 	struct scsi_extended_sense *sense;
5973 	int rval, mode, sector_count, reason;
5974 	int cport = SATA_TXLT_CPORT(spx);
5975 
5976 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
5977 
5978 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5979 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
5980 
5981 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5982 
5983 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5984 	    TRAN_ACCEPT) {
5985 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5986 		return (rval);
5987 	}
5988 
5989 	/* Use synchronous mode */
5990 	spx->txlt_sata_pkt->satapkt_op_mode
5991 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
5992 
5993 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5994 
5995 	scsipkt->pkt_reason = CMD_CMPLT;
5996 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5997 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5998 
5999 	/*
6000 	 * The SCSI to ATA translation specification only calls
6001 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6002 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6003 	 * ATA 8 (draft) got rid of download microcode for temp
6004 	 * and it is even optional for ATA 7, so it may be aborted.
6005 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6006 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6007 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6008 	 * sectors.  Thus the offset really doesn't buy us anything.
6009 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6010 	 * is revised, this can be revisisted.
6011 	 */
6012 	/* Reject not supported request */
6013 	switch (mode) {
6014 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6015 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6016 		break;
6017 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6018 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6019 		break;
6020 	default:
6021 		goto bad_param;
6022 	}
6023 
6024 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6025 
6026 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6027 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6028 		goto bad_param;
6029 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6030 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6031 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6032 	scmd->satacmd_lba_mid_lsb = 0;
6033 	scmd->satacmd_lba_high_lsb = 0;
6034 	scmd->satacmd_device_reg = 0;
6035 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6036 	scmd->satacmd_addr_type = 0;
6037 
6038 	/* Transfer command to HBA */
6039 	if (sata_hba_start(spx, &rval) != 0) {
6040 		/* Pkt not accepted for execution */
6041 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6042 		return (rval);
6043 	}
6044 
6045 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6046 
6047 	/* Then we need synchronous check the status of the disk */
6048 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6049 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6050 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6051 		scsipkt->pkt_reason = CMD_CMPLT;
6052 
6053 		/* Download commmand succeed, so probe and identify device */
6054 		sata_reidentify_device(spx);
6055 	} else {
6056 		/* Something went wrong, microcode download command failed */
6057 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6058 		*scsipkt->pkt_scbp = STATUS_CHECK;
6059 		sense = sata_arq_sense(spx);
6060 		switch (sata_pkt->satapkt_reason) {
6061 		case SATA_PKT_PORT_ERROR:
6062 			/*
6063 			 * We have no device data. Assume no data transfered.
6064 			 */
6065 			sense->es_key = KEY_HARDWARE_ERROR;
6066 			break;
6067 
6068 		case SATA_PKT_DEV_ERROR:
6069 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6070 			    SATA_STATUS_ERR) {
6071 				/*
6072 				 * determine dev error reason from error
6073 				 * reg content
6074 				 */
6075 				sata_decode_device_error(spx, sense);
6076 				break;
6077 			}
6078 			/* No extended sense key - no info available */
6079 			break;
6080 
6081 		case SATA_PKT_TIMEOUT:
6082 			scsipkt->pkt_reason = CMD_TIMEOUT;
6083 			scsipkt->pkt_statistics |=
6084 			    STAT_TIMEOUT | STAT_DEV_RESET;
6085 			/* No extended sense key ? */
6086 			break;
6087 
6088 		case SATA_PKT_ABORTED:
6089 			scsipkt->pkt_reason = CMD_ABORTED;
6090 			scsipkt->pkt_statistics |= STAT_ABORTED;
6091 			/* No extended sense key ? */
6092 			break;
6093 
6094 		case SATA_PKT_RESET:
6095 			/* pkt aborted by an explicit reset from a host */
6096 			scsipkt->pkt_reason = CMD_RESET;
6097 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6098 			break;
6099 
6100 		default:
6101 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6102 			    "sata_txlt_nodata_cmd_completion: "
6103 			    "invalid packet completion reason %d",
6104 			    sata_pkt->satapkt_reason));
6105 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6106 			break;
6107 		}
6108 
6109 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6110 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6111 
6112 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6113 			/* scsi callback required */
6114 			scsi_hba_pkt_comp(scsipkt);
6115 	}
6116 	return (TRAN_ACCEPT);
6117 
6118 bad_param:
6119 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6120 	*scsipkt->pkt_scbp = STATUS_CHECK;
6121 	sense = sata_arq_sense(spx);
6122 	sense->es_key = KEY_ILLEGAL_REQUEST;
6123 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6124 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6125 	    scsipkt->pkt_comp != NULL) {
6126 		/* scsi callback required */
6127 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6128 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6129 		    TQ_SLEEP) == 0) {
6130 			/* Scheduling the callback failed */
6131 			rval = TRAN_BUSY;
6132 		}
6133 	}
6134 	return (rval);
6135 }
6136 
6137 /*
6138  * Re-identify device after doing a firmware download.
6139  */
6140 static void
6141 sata_reidentify_device(sata_pkt_txlate_t *spx)
6142 {
6143 #define	DOWNLOAD_WAIT_TIME_SECS	60
6144 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6145 	int rval;
6146 	int retry_cnt;
6147 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6148 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6149 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6150 	sata_drive_info_t *sdinfo;
6151 
6152 	/*
6153 	 * Before returning good status, probe device.
6154 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6155 	 * The assumption is that the new microcode is applied by the
6156 	 * device. It is a caller responsibility to verify this.
6157 	 */
6158 	for (retry_cnt = 0;
6159 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6160 	    retry_cnt++) {
6161 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6162 
6163 		if (rval == SATA_SUCCESS) { /* Set default features */
6164 			sdinfo = sata_get_device_info(sata_hba_inst,
6165 			    &sata_device);
6166 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6167 			    SATA_SUCCESS) {
6168 				/* retry */
6169 				rval = sata_initialize_device(sata_hba_inst,
6170 				    sdinfo);
6171 				if (rval == SATA_RETRY)
6172 					sata_log(sata_hba_inst, CE_WARN,
6173 					    "SATA device at port %d pmport %d -"
6174 					    " default device features could not"
6175 					    " be set. Device may not operate "
6176 					    "as expected.",
6177 					    sata_device.satadev_addr.cport,
6178 					    sata_device.satadev_addr.pmport);
6179 			}
6180 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6181 				scsi_hba_pkt_comp(scsipkt);
6182 			return;
6183 		} else if (rval == SATA_RETRY) {
6184 			delay(drv_usectohz(1000000 *
6185 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6186 			continue;
6187 		} else	/* failed - no reason to retry */
6188 			break;
6189 	}
6190 
6191 	/*
6192 	 * Something went wrong, device probing failed.
6193 	 */
6194 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6195 	    "Cannot probe device after downloading microcode\n"));
6196 
6197 	/* Reset device to force retrying the probe. */
6198 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6199 	    (SATA_DIP(sata_hba_inst), &sata_device);
6200 
6201 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6202 		scsi_hba_pkt_comp(scsipkt);
6203 }
6204 
6205 
6206 /*
6207  * Translate command: Synchronize Cache.
6208  * Translates into Flush Cache command for SATA hard disks.
6209  *
6210  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6211  * appropriate values in scsi_pkt fields.
6212  */
6213 static 	int
6214 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6215 {
6216 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6217 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6218 	int cport = SATA_TXLT_CPORT(spx);
6219 	int rval, reason;
6220 	int synch;
6221 
6222 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6223 
6224 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6225 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6226 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6227 		return (rval);
6228 	}
6229 
6230 	scmd->satacmd_addr_type = 0;
6231 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6232 	scmd->satacmd_device_reg = 0;
6233 	scmd->satacmd_sec_count_lsb = 0;
6234 	scmd->satacmd_lba_low_lsb = 0;
6235 	scmd->satacmd_lba_mid_lsb = 0;
6236 	scmd->satacmd_lba_high_lsb = 0;
6237 	scmd->satacmd_features_reg = 0;
6238 	scmd->satacmd_status_reg = 0;
6239 	scmd->satacmd_error_reg = 0;
6240 
6241 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6242 	    "sata_txlt_synchronize_cache\n", NULL);
6243 
6244 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6245 		/* Need to set-up a callback function */
6246 		spx->txlt_sata_pkt->satapkt_comp =
6247 		    sata_txlt_nodata_cmd_completion;
6248 		synch = FALSE;
6249 	} else
6250 		synch = TRUE;
6251 
6252 	/* Transfer command to HBA */
6253 	if (sata_hba_start(spx, &rval) != 0) {
6254 		/* Pkt not accepted for execution */
6255 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6256 		return (rval);
6257 	}
6258 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6259 
6260 	/*
6261 	 * If execution non-synchronous, it had to be completed
6262 	 * a callback function will handle potential errors, translate
6263 	 * the response and will do a callback to a target driver.
6264 	 * If it was synchronous, check status, using the same
6265 	 * framework callback.
6266 	 */
6267 	if (synch) {
6268 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6269 		    "synchronous execution status %x\n",
6270 		    spx->txlt_sata_pkt->satapkt_reason);
6271 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6272 	}
6273 	return (TRAN_ACCEPT);
6274 }
6275 
6276 
6277 /*
6278  * Send pkt to SATA HBA driver
6279  *
6280  * This function may be called only if the operation is requested by scsi_pkt,
6281  * i.e. scsi_pkt is not NULL.
6282  *
6283  * This function has to be called with cport mutex held. It does release
6284  * the mutex when it calls HBA driver sata_tran_start function and
6285  * re-acquires it afterwards.
6286  *
6287  * If return value is 0, pkt was accepted, -1 otherwise
6288  * rval is set to appropriate sata_scsi_start return value.
6289  *
6290  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6291  * have called the sata_pkt callback function for this packet.
6292  *
6293  * The scsi callback has to be performed by the caller of this routine.
6294  */
6295 static int
6296 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6297 {
6298 	int stat;
6299 	uint8_t cport = SATA_TXLT_CPORT(spx);
6300 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6301 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6302 	sata_drive_info_t *sdinfo;
6303 	sata_pmult_info_t *pminfo;
6304 	sata_pmport_info_t *pmportinfo = NULL;
6305 	sata_device_t *sata_device = NULL;
6306 	uint8_t cmd;
6307 	struct sata_cmd_flags cmd_flags;
6308 
6309 	ASSERT(spx->txlt_sata_pkt != NULL);
6310 
6311 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6312 
6313 	sdinfo = sata_get_device_info(sata_hba_inst,
6314 	    &spx->txlt_sata_pkt->satapkt_device);
6315 	ASSERT(sdinfo != NULL);
6316 
6317 	/* Clear device reset state? */
6318 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6319 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6320 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6321 
6322 		/*
6323 		 * Get the pmult_info of the its parent port multiplier, all
6324 		 * sub-devices share a common device reset flags on in
6325 		 * pmult_info.
6326 		 */
6327 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
6328 		pmportinfo = pminfo->pmult_dev_port[pmport];
6329 		ASSERT(pminfo != NULL);
6330 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
6331 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6332 			    sata_clear_dev_reset = B_TRUE;
6333 			pminfo->pmult_event_flags &=
6334 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6335 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6336 			    "sata_hba_start: clearing device reset state"
6337 			    "on pmult.\n", NULL);
6338 		}
6339 	} else {
6340 		if (sdinfo->satadrv_event_flags &
6341 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
6342 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6343 			    sata_clear_dev_reset = B_TRUE;
6344 			sdinfo->satadrv_event_flags &=
6345 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6346 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6347 			    "sata_hba_start: clearing device reset state\n",
6348 			    NULL);
6349 		}
6350 	}
6351 
6352 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
6353 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
6354 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
6355 
6356 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6357 
6358 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6359 	    "Sata cmd 0x%2x\n", cmd);
6360 
6361 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
6362 	    spx->txlt_sata_pkt);
6363 
6364 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6365 	/*
6366 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
6367 	 * with the sata callback, the sata_pkt could be already destroyed
6368 	 * by the time we check ther return status from the hba_start()
6369 	 * function, because sata_scsi_destroy_pkt() could have been already
6370 	 * called (perhaps in the interrupt context). So, in such case, there
6371 	 * should be no references to it. In other cases, sata_pkt still
6372 	 * exists.
6373 	 */
6374 	if (stat == SATA_TRAN_ACCEPTED) {
6375 		/*
6376 		 * pkt accepted for execution.
6377 		 * If it was executed synchronously, it is already completed
6378 		 * and pkt completion_reason indicates completion status.
6379 		 */
6380 		*rval = TRAN_ACCEPT;
6381 		return (0);
6382 	}
6383 
6384 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6385 	switch (stat) {
6386 	case SATA_TRAN_QUEUE_FULL:
6387 		/*
6388 		 * Controller detected queue full condition.
6389 		 */
6390 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
6391 		    "sata_hba_start: queue full\n", NULL);
6392 
6393 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6394 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
6395 
6396 		*rval = TRAN_BUSY;
6397 		break;
6398 
6399 	case SATA_TRAN_PORT_ERROR:
6400 		/*
6401 		 * Communication/link with device or general port error
6402 		 * detected before pkt execution begun.
6403 		 */
6404 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6405 		    SATA_ADDR_CPORT ||
6406 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6407 		    SATA_ADDR_DCPORT)
6408 			sata_log(sata_hba_inst, CE_CONT,
6409 			    "SATA port %d error",
6410 			    sata_device->satadev_addr.cport);
6411 		else
6412 			sata_log(sata_hba_inst, CE_CONT,
6413 			    "SATA port %d:%d error\n",
6414 			    sata_device->satadev_addr.cport,
6415 			    sata_device->satadev_addr.pmport);
6416 
6417 		/*
6418 		 * Update the port/device structure.
6419 		 * sata_pkt should be still valid. Since port error is
6420 		 * returned, sata_device content should reflect port
6421 		 * state - it means, that sata address have been changed,
6422 		 * because original packet's sata address refered to a device
6423 		 * attached to some port.
6424 		 */
6425 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
6426 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
6427 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6428 			mutex_enter(&pmportinfo->pmport_mutex);
6429 			sata_update_pmport_info(sata_hba_inst, sata_device);
6430 			mutex_exit(&pmportinfo->pmport_mutex);
6431 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6432 		} else {
6433 			sata_update_port_info(sata_hba_inst, sata_device);
6434 		}
6435 
6436 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6437 		*rval = TRAN_FATAL_ERROR;
6438 		break;
6439 
6440 	case SATA_TRAN_CMD_UNSUPPORTED:
6441 		/*
6442 		 * Command rejected by HBA as unsupported. It was HBA driver
6443 		 * that rejected the command, command was not sent to
6444 		 * an attached device.
6445 		 */
6446 		if ((sdinfo != NULL) &&
6447 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
6448 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6449 			    "sat_hba_start: cmd 0x%2x rejected "
6450 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
6451 
6452 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6453 		(void) sata_txlt_invalid_command(spx);
6454 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6455 
6456 		*rval = TRAN_ACCEPT;
6457 		break;
6458 
6459 	case SATA_TRAN_BUSY:
6460 		/*
6461 		 * Command rejected by HBA because other operation prevents
6462 		 * accepting the packet, or device is in RESET condition.
6463 		 */
6464 		if (sdinfo != NULL) {
6465 			sdinfo->satadrv_state =
6466 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
6467 
6468 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
6469 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6470 				    "sata_hba_start: cmd 0x%2x rejected "
6471 				    "because of device reset condition\n",
6472 				    cmd);
6473 			} else {
6474 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6475 				    "sata_hba_start: cmd 0x%2x rejected "
6476 				    "with SATA_TRAN_BUSY status\n",
6477 				    cmd);
6478 			}
6479 		}
6480 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6481 		*rval = TRAN_BUSY;
6482 		break;
6483 
6484 	default:
6485 		/* Unrecognized HBA response */
6486 		SATA_LOG_D((sata_hba_inst, CE_WARN,
6487 		    "sata_hba_start: unrecognized HBA response "
6488 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
6489 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6490 		*rval = TRAN_FATAL_ERROR;
6491 		break;
6492 	}
6493 
6494 	/*
6495 	 * If we got here, the packet was rejected.
6496 	 * Check if we need to remember reset state clearing request
6497 	 */
6498 	if (cmd_flags.sata_clear_dev_reset) {
6499 		/*
6500 		 * Check if device is still configured - it may have
6501 		 * disapeared from the configuration
6502 		 */
6503 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6504 		if (sdinfo != NULL) {
6505 			/*
6506 			 * Restore the flag that requests clearing of
6507 			 * the device reset state,
6508 			 * so the next sata packet may carry it to HBA.
6509 			 */
6510 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
6511 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
6512 				pminfo->pmult_event_flags |=
6513 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6514 			} else {
6515 				sdinfo->satadrv_event_flags |=
6516 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6517 			}
6518 		}
6519 	}
6520 	return (-1);
6521 }
6522 
6523 /*
6524  * Scsi response setup for invalid LBA
6525  *
6526  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
6527  */
6528 static int
6529 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
6530 {
6531 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6532 	struct scsi_extended_sense *sense;
6533 
6534 	scsipkt->pkt_reason = CMD_CMPLT;
6535 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6536 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6537 	*scsipkt->pkt_scbp = STATUS_CHECK;
6538 
6539 	*scsipkt->pkt_scbp = STATUS_CHECK;
6540 	sense = sata_arq_sense(spx);
6541 	sense->es_key = KEY_ILLEGAL_REQUEST;
6542 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6543 
6544 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6545 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6546 
6547 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6548 	    scsipkt->pkt_comp != NULL)
6549 		/* scsi callback required */
6550 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6551 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6552 		    TQ_SLEEP) == NULL)
6553 			/* Scheduling the callback failed */
6554 			return (TRAN_BUSY);
6555 	return (TRAN_ACCEPT);
6556 }
6557 
6558 
6559 /*
6560  * Analyze device status and error registers and translate them into
6561  * appropriate scsi sense codes.
6562  * NOTE: non-packet commands only for now
6563  */
6564 static void
6565 sata_decode_device_error(sata_pkt_txlate_t *spx,
6566     struct scsi_extended_sense *sense)
6567 {
6568 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
6569 
6570 	ASSERT(sense != NULL);
6571 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
6572 	    SATA_STATUS_ERR);
6573 
6574 
6575 	if (err_reg & SATA_ERROR_ICRC) {
6576 		sense->es_key = KEY_ABORTED_COMMAND;
6577 		sense->es_add_code = 0x08; /* Communication failure */
6578 		return;
6579 	}
6580 
6581 	if (err_reg & SATA_ERROR_UNC) {
6582 		sense->es_key = KEY_MEDIUM_ERROR;
6583 		/* Information bytes (LBA) need to be set by a caller */
6584 		return;
6585 	}
6586 
6587 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
6588 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
6589 		sense->es_key = KEY_UNIT_ATTENTION;
6590 		sense->es_add_code = 0x3a; /* No media present */
6591 		return;
6592 	}
6593 
6594 	if (err_reg & SATA_ERROR_IDNF) {
6595 		if (err_reg & SATA_ERROR_ABORT) {
6596 			sense->es_key = KEY_ABORTED_COMMAND;
6597 		} else {
6598 			sense->es_key = KEY_ILLEGAL_REQUEST;
6599 			sense->es_add_code = 0x21; /* LBA out of range */
6600 		}
6601 		return;
6602 	}
6603 
6604 	if (err_reg & SATA_ERROR_ABORT) {
6605 		ASSERT(spx->txlt_sata_pkt != NULL);
6606 		sense->es_key = KEY_ABORTED_COMMAND;
6607 		return;
6608 	}
6609 }
6610 
6611 /*
6612  * Extract error LBA from sata_pkt.satapkt_cmd register fields
6613  */
6614 static void
6615 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
6616 {
6617 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
6618 
6619 	*lba = 0;
6620 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
6621 		*lba = sata_cmd->satacmd_lba_high_msb;
6622 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
6623 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
6624 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
6625 		*lba = sata_cmd->satacmd_device_reg & 0xf;
6626 	}
6627 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
6628 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
6629 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
6630 }
6631 
6632 /*
6633  * This is fixed sense format - if LBA exceeds the info field size,
6634  * no valid info will be returned (valid bit in extended sense will
6635  * be set to 0).
6636  */
6637 static struct scsi_extended_sense *
6638 sata_arq_sense(sata_pkt_txlate_t *spx)
6639 {
6640 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6641 	struct scsi_arq_status *arqs;
6642 	struct scsi_extended_sense *sense;
6643 
6644 	/* Fill ARQ sense data */
6645 	scsipkt->pkt_state |= STATE_ARQ_DONE;
6646 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
6647 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
6648 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
6649 	arqs->sts_rqpkt_reason = CMD_CMPLT;
6650 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6651 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
6652 	arqs->sts_rqpkt_resid = 0;
6653 	sense = &arqs->sts_sensedata;
6654 	bzero(sense, sizeof (struct scsi_extended_sense));
6655 	sata_fixed_sense_data_preset(sense);
6656 	return (sense);
6657 }
6658 
6659 /*
6660  * ATA Pass Through support
6661  * Sets flags indicating that an invalid value was found in some
6662  * field in the command.  It could be something illegal according to
6663  * the SAT-2 spec or it could be a feature that is not (yet?)
6664  * supported.
6665  */
6666 static int
6667 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
6668 {
6669 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6670 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
6671 
6672 	scsipkt->pkt_reason = CMD_CMPLT;
6673 	*scsipkt->pkt_scbp = STATUS_CHECK;
6674 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6675 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6676 
6677 	sense = sata_arq_sense(spx);
6678 	sense->es_key = KEY_ILLEGAL_REQUEST;
6679 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6680 
6681 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6682 	    scsipkt->pkt_comp != NULL)
6683 		/* scsi callback required */
6684 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6685 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6686 		    TQ_SLEEP) == NULL)
6687 			/* Scheduling the callback failed */
6688 			return (TRAN_BUSY);
6689 
6690 	return (TRAN_ACCEPT);
6691 }
6692 
6693 /*
6694  * Emulated SATA Read/Write command completion for zero-length requests.
6695  * This request always succedes, so in synchronous mode it always returns
6696  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
6697  * callback cannot be scheduled.
6698  */
6699 static int
6700 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
6701 {
6702 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6703 
6704 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6705 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6706 	scsipkt->pkt_reason = CMD_CMPLT;
6707 	*scsipkt->pkt_scbp = STATUS_GOOD;
6708 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6709 		/* scsi callback required - have to schedule it */
6710 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6711 		    (task_func_t *)scsipkt->pkt_comp,
6712 		    (void *)scsipkt, TQ_SLEEP) == NULL)
6713 			/* Scheduling the callback failed */
6714 			return (TRAN_BUSY);
6715 	}
6716 	return (TRAN_ACCEPT);
6717 }
6718 
6719 
6720 /*
6721  * Translate completion status of SATA read/write commands into scsi response.
6722  * pkt completion_reason is checked to determine the completion status.
6723  * Do scsi callback if necessary.
6724  *
6725  * Note: this function may be called also for synchronously executed
6726  * commands.
6727  * This function may be used only if scsi_pkt is non-NULL.
6728  */
6729 static void
6730 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
6731 {
6732 	sata_pkt_txlate_t *spx =
6733 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6734 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6735 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6736 	struct scsi_extended_sense *sense;
6737 	uint64_t lba;
6738 	struct buf *bp;
6739 	int rval;
6740 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6741 		/* Normal completion */
6742 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6743 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6744 		scsipkt->pkt_reason = CMD_CMPLT;
6745 		*scsipkt->pkt_scbp = STATUS_GOOD;
6746 		if (spx->txlt_tmp_buf != NULL) {
6747 			/* Temporary buffer was used */
6748 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6749 			if (bp->b_flags & B_READ) {
6750 				rval = ddi_dma_sync(
6751 				    spx->txlt_buf_dma_handle, 0, 0,
6752 				    DDI_DMA_SYNC_FORCPU);
6753 				ASSERT(rval == DDI_SUCCESS);
6754 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6755 				    bp->b_bcount);
6756 			}
6757 		}
6758 	} else {
6759 		/*
6760 		 * Something went wrong - analyze return
6761 		 */
6762 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6763 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6764 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6765 		*scsipkt->pkt_scbp = STATUS_CHECK;
6766 		sense = sata_arq_sense(spx);
6767 		ASSERT(sense != NULL);
6768 
6769 		/*
6770 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
6771 		 * extract from device registers the failing LBA.
6772 		 */
6773 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
6774 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
6775 			    (scmd->satacmd_lba_mid_msb != 0 ||
6776 			    scmd->satacmd_lba_high_msb != 0)) {
6777 				/*
6778 				 * We have problem reporting this cmd LBA
6779 				 * in fixed sense data format, because of
6780 				 * the size of the scsi LBA fields.
6781 				 */
6782 				sense->es_valid = 0;
6783 			} else {
6784 				sata_extract_error_lba(spx, &lba);
6785 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
6786 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
6787 				sense->es_info_3 = (lba & 0xFF00) >> 8;
6788 				sense->es_info_4 = lba & 0xFF;
6789 			}
6790 		} else {
6791 			/* Invalid extended sense info */
6792 			sense->es_valid = 0;
6793 		}
6794 
6795 		switch (sata_pkt->satapkt_reason) {
6796 		case SATA_PKT_PORT_ERROR:
6797 			/* We may want to handle DEV GONE state as well */
6798 			/*
6799 			 * We have no device data. Assume no data transfered.
6800 			 */
6801 			sense->es_key = KEY_HARDWARE_ERROR;
6802 			break;
6803 
6804 		case SATA_PKT_DEV_ERROR:
6805 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6806 			    SATA_STATUS_ERR) {
6807 				/*
6808 				 * determine dev error reason from error
6809 				 * reg content
6810 				 */
6811 				sata_decode_device_error(spx, sense);
6812 				if (sense->es_key == KEY_MEDIUM_ERROR) {
6813 					switch (scmd->satacmd_cmd_reg) {
6814 					case SATAC_READ_DMA:
6815 					case SATAC_READ_DMA_EXT:
6816 					case SATAC_READ_DMA_QUEUED:
6817 					case SATAC_READ_DMA_QUEUED_EXT:
6818 					case SATAC_READ_FPDMA_QUEUED:
6819 						/* Unrecovered read error */
6820 						sense->es_add_code =
6821 						    SD_SCSI_ASC_UNREC_READ_ERR;
6822 						break;
6823 					case SATAC_WRITE_DMA:
6824 					case SATAC_WRITE_DMA_EXT:
6825 					case SATAC_WRITE_DMA_QUEUED:
6826 					case SATAC_WRITE_DMA_QUEUED_EXT:
6827 					case SATAC_WRITE_FPDMA_QUEUED:
6828 						/* Write error */
6829 						sense->es_add_code =
6830 						    SD_SCSI_ASC_WRITE_ERR;
6831 						break;
6832 					default:
6833 						/* Internal error */
6834 						SATA_LOG_D((
6835 						    spx->txlt_sata_hba_inst,
6836 						    CE_WARN,
6837 						    "sata_txlt_rw_completion :"
6838 						    "internal error - invalid "
6839 						    "command 0x%2x",
6840 						    scmd->satacmd_cmd_reg));
6841 						break;
6842 					}
6843 				}
6844 				break;
6845 			}
6846 			/* No extended sense key - no info available */
6847 			scsipkt->pkt_reason = CMD_INCOMPLETE;
6848 			break;
6849 
6850 		case SATA_PKT_TIMEOUT:
6851 			scsipkt->pkt_reason = CMD_TIMEOUT;
6852 			scsipkt->pkt_statistics |=
6853 			    STAT_TIMEOUT | STAT_DEV_RESET;
6854 			sense->es_key = KEY_ABORTED_COMMAND;
6855 			break;
6856 
6857 		case SATA_PKT_ABORTED:
6858 			scsipkt->pkt_reason = CMD_ABORTED;
6859 			scsipkt->pkt_statistics |= STAT_ABORTED;
6860 			sense->es_key = KEY_ABORTED_COMMAND;
6861 			break;
6862 
6863 		case SATA_PKT_RESET:
6864 			scsipkt->pkt_reason = CMD_RESET;
6865 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6866 			sense->es_key = KEY_ABORTED_COMMAND;
6867 			break;
6868 
6869 		default:
6870 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6871 			    "sata_txlt_rw_completion: "
6872 			    "invalid packet completion reason"));
6873 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6874 			break;
6875 		}
6876 	}
6877 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6878 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6879 
6880 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6881 		/* scsi callback required */
6882 		scsi_hba_pkt_comp(scsipkt);
6883 }
6884 
6885 
6886 /*
6887  * Translate completion status of non-data commands (i.e. commands returning
6888  * no data).
6889  * pkt completion_reason is checked to determine the completion status.
6890  * Do scsi callback if necessary (FLAG_NOINTR == 0)
6891  *
6892  * Note: this function may be called also for synchronously executed
6893  * commands.
6894  * This function may be used only if scsi_pkt is non-NULL.
6895  */
6896 
6897 static	void
6898 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
6899 {
6900 	sata_pkt_txlate_t *spx =
6901 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6902 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6903 
6904 	sata_set_arq_data(sata_pkt);
6905 
6906 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6907 		/* scsi callback required */
6908 		scsi_hba_pkt_comp(scsipkt);
6909 }
6910 
6911 /*
6912  * Completion handler for ATA Pass Through command
6913  */
6914 static void
6915 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
6916 {
6917 	sata_pkt_txlate_t *spx =
6918 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6919 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6920 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6921 	struct buf *bp;
6922 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
6923 
6924 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6925 		/* Normal completion */
6926 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6927 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6928 		scsipkt->pkt_reason = CMD_CMPLT;
6929 		*scsipkt->pkt_scbp = STATUS_GOOD;
6930 
6931 		/*
6932 		 * If the command has CK_COND set
6933 		 */
6934 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
6935 			*scsipkt->pkt_scbp = STATUS_CHECK;
6936 			sata_fill_ata_return_desc(sata_pkt,
6937 			    KEY_RECOVERABLE_ERROR,
6938 			    SD_SCSI_ASC_ATP_INFO_AVAIL, 0);
6939 		}
6940 
6941 		if (spx->txlt_tmp_buf != NULL) {
6942 			/* Temporary buffer was used */
6943 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6944 			if (bp->b_flags & B_READ) {
6945 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6946 				    bp->b_bcount);
6947 			}
6948 		}
6949 	} else {
6950 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6951 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6952 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6953 		*scsipkt->pkt_scbp = STATUS_CHECK;
6954 
6955 		/*
6956 		 * If DF or ERR was set, the HBA should have copied out the
6957 		 * status and error registers to the satacmd structure.
6958 		 */
6959 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
6960 			sense_key = KEY_HARDWARE_ERROR;
6961 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
6962 			addl_sense_qual = 0;
6963 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
6964 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
6965 				sense_key = KEY_NOT_READY;
6966 				addl_sense_code =
6967 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
6968 				addl_sense_qual = 0;
6969 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
6970 				sense_key = KEY_MEDIUM_ERROR;
6971 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
6972 				addl_sense_qual = 0;
6973 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
6974 				sense_key = KEY_DATA_PROTECT;
6975 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
6976 				addl_sense_qual = 0;
6977 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
6978 				sense_key = KEY_ILLEGAL_REQUEST;
6979 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6980 				addl_sense_qual = 0;
6981 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
6982 				sense_key = KEY_ABORTED_COMMAND;
6983 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
6984 				addl_sense_qual = 0;
6985 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
6986 				sense_key = KEY_UNIT_ATTENTION;
6987 				addl_sense_code =
6988 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
6989 				addl_sense_qual = 0;
6990 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
6991 				sense_key = KEY_UNIT_ATTENTION;
6992 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
6993 				addl_sense_qual = 0;
6994 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
6995 				sense_key = KEY_ABORTED_COMMAND;
6996 				addl_sense_code =
6997 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
6998 				addl_sense_qual = 0;
6999 			}
7000 		}
7001 
7002 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7003 		    addl_sense_qual);
7004 	}
7005 
7006 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7007 		/* scsi callback required */
7008 		scsi_hba_pkt_comp(scsipkt);
7009 }
7010 
7011 /*
7012  * j
7013  */
7014 static void
7015 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7016     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7017 {
7018 	sata_pkt_txlate_t *spx =
7019 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7020 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7021 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7022 	struct sata_apt_sense_data *apt_sd =
7023 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7024 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7025 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7026 	    &(apt_sd->apt_sd_sense);
7027 	int extend = 0;
7028 
7029 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7030 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7031 		extend = 1;
7032 
7033 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7034 
7035 	/* update the residual count */
7036 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7037 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7038 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7039 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7040 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7041 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7042 	    sizeof (struct sata_apt_sense_data);
7043 
7044 	/*
7045 	 * Fill in the Descriptor sense header
7046 	 */
7047 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7048 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7049 	sds->ds_class = CLASS_EXTENDED_SENSE;
7050 	sds->ds_key = sense_key & 0xf;
7051 	sds->ds_add_code = addl_sense_code;
7052 	sds->ds_qual_code = addl_sense_qual;
7053 	sds->ds_addl_sense_length =
7054 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7055 
7056 	/*
7057 	 * Fill in the ATA Return descriptor sense data
7058 	 */
7059 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7060 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7061 	ata_ret_desc->ars_addl_length = 0xc;
7062 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7063 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7064 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7065 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7066 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7067 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7068 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7069 
7070 	if (extend == 1) {
7071 		ata_ret_desc->ars_extend = 1;
7072 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7073 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7074 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7075 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7076 	} else {
7077 		ata_ret_desc->ars_extend = 0;
7078 		ata_ret_desc->ars_sec_count_msb = 0;
7079 		ata_ret_desc->ars_lba_low_msb = 0;
7080 		ata_ret_desc->ars_lba_mid_msb = 0;
7081 		ata_ret_desc->ars_lba_high_msb = 0;
7082 	}
7083 }
7084 
7085 static	void
7086 sata_set_arq_data(sata_pkt_t *sata_pkt)
7087 {
7088 	sata_pkt_txlate_t *spx =
7089 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7090 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7091 	struct scsi_extended_sense *sense;
7092 
7093 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7094 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7095 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7096 		/* Normal completion */
7097 		scsipkt->pkt_reason = CMD_CMPLT;
7098 		*scsipkt->pkt_scbp = STATUS_GOOD;
7099 	} else {
7100 		/* Something went wrong */
7101 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7102 		*scsipkt->pkt_scbp = STATUS_CHECK;
7103 		sense = sata_arq_sense(spx);
7104 		switch (sata_pkt->satapkt_reason) {
7105 		case SATA_PKT_PORT_ERROR:
7106 			/*
7107 			 * We have no device data. Assume no data transfered.
7108 			 */
7109 			sense->es_key = KEY_HARDWARE_ERROR;
7110 			break;
7111 
7112 		case SATA_PKT_DEV_ERROR:
7113 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7114 			    SATA_STATUS_ERR) {
7115 				/*
7116 				 * determine dev error reason from error
7117 				 * reg content
7118 				 */
7119 				sata_decode_device_error(spx, sense);
7120 				break;
7121 			}
7122 			/* No extended sense key - no info available */
7123 			break;
7124 
7125 		case SATA_PKT_TIMEOUT:
7126 			scsipkt->pkt_reason = CMD_TIMEOUT;
7127 			scsipkt->pkt_statistics |=
7128 			    STAT_TIMEOUT | STAT_DEV_RESET;
7129 			/* No extended sense key ? */
7130 			break;
7131 
7132 		case SATA_PKT_ABORTED:
7133 			scsipkt->pkt_reason = CMD_ABORTED;
7134 			scsipkt->pkt_statistics |= STAT_ABORTED;
7135 			/* No extended sense key ? */
7136 			break;
7137 
7138 		case SATA_PKT_RESET:
7139 			/* pkt aborted by an explicit reset from a host */
7140 			scsipkt->pkt_reason = CMD_RESET;
7141 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7142 			break;
7143 
7144 		default:
7145 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7146 			    "sata_txlt_nodata_cmd_completion: "
7147 			    "invalid packet completion reason %d",
7148 			    sata_pkt->satapkt_reason));
7149 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7150 			break;
7151 		}
7152 
7153 	}
7154 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7155 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7156 }
7157 
7158 
7159 /*
7160  * Build Mode sense R/W recovery page
7161  * NOT IMPLEMENTED
7162  */
7163 
7164 static int
7165 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7166 {
7167 #ifndef __lock_lint
7168 	_NOTE(ARGUNUSED(sdinfo))
7169 	_NOTE(ARGUNUSED(pcntrl))
7170 	_NOTE(ARGUNUSED(buf))
7171 #endif
7172 	return (0);
7173 }
7174 
7175 /*
7176  * Build Mode sense caching page  -  scsi-3 implementation.
7177  * Page length distinguishes previous format from scsi-3 format.
7178  * buf must have space for 0x12 bytes.
7179  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
7180  *
7181  */
7182 static int
7183 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7184 {
7185 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
7186 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7187 
7188 	/*
7189 	 * Most of the fields are set to 0, being not supported and/or disabled
7190 	 */
7191 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
7192 
7193 	/* Saved paramters not supported */
7194 	if (pcntrl == 3)
7195 		return (0);
7196 	if (pcntrl == 0 || pcntrl == 2) {
7197 		/*
7198 		 * For now treat current and default parameters as same
7199 		 * That may have to change, if target driver will complain
7200 		 */
7201 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
7202 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7203 
7204 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
7205 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
7206 			page->dra = 1;		/* Read Ahead disabled */
7207 			page->rcd = 1;		/* Read Cache disabled */
7208 		}
7209 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
7210 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
7211 			page->wce = 1;		/* Write Cache enabled */
7212 	} else {
7213 		/* Changeable parameters */
7214 		page->mode_page.code = MODEPAGE_CACHING;
7215 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7216 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7217 			page->dra = 1;
7218 			page->rcd = 1;
7219 		}
7220 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
7221 			page->wce = 1;
7222 	}
7223 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7224 	    sizeof (struct mode_page));
7225 }
7226 
7227 /*
7228  * Build Mode sense exception cntrl page
7229  */
7230 static int
7231 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7232 {
7233 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
7234 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7235 
7236 	/*
7237 	 * Most of the fields are set to 0, being not supported and/or disabled
7238 	 */
7239 	bzero(buf, PAGELENGTH_INFO_EXCPT);
7240 
7241 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
7242 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
7243 
7244 	/* Indicate that this is page is saveable */
7245 	page->mode_page.ps = 1;
7246 
7247 	/*
7248 	 * We will return the same data for default, current and saved page.
7249 	 * The only changeable bit is dexcpt and that bit is required
7250 	 * by the ATA specification to be preserved across power cycles.
7251 	 */
7252 	if (pcntrl != 1) {
7253 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
7254 		page->mrie = MRIE_ONLY_ON_REQUEST;
7255 	}
7256 	else
7257 		page->dexcpt = 1;	/* Only changeable parameter */
7258 
7259 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
7260 }
7261 
7262 
7263 static int
7264 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7265 {
7266 	struct mode_acoustic_management *page =
7267 	    (struct mode_acoustic_management *)buf;
7268 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7269 
7270 	/*
7271 	 * Most of the fields are set to 0, being not supported and/or disabled
7272 	 */
7273 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
7274 
7275 	switch (pcntrl) {
7276 	case P_CNTRL_DEFAULT:
7277 		/*  default paramters not supported */
7278 		return (0);
7279 
7280 	case P_CNTRL_CURRENT:
7281 	case P_CNTRL_SAVED:
7282 		/* Saved and current are supported and are identical */
7283 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7284 		page->mode_page.length =
7285 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7286 		page->mode_page.ps = 1;
7287 
7288 		/* Word 83 indicates if feature is supported */
7289 		/* If feature is not supported */
7290 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
7291 			page->acoustic_manag_enable =
7292 			    ACOUSTIC_DISABLED;
7293 		} else {
7294 			page->acoustic_manag_enable =
7295 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
7296 			    != 0);
7297 			/* Word 94 inidicates the value */
7298 #ifdef	_LITTLE_ENDIAN
7299 			page->acoustic_manag_level =
7300 			    (uchar_t)sata_id->ai_acoustic;
7301 			page->vendor_recommended_value =
7302 			    sata_id->ai_acoustic >> 8;
7303 #else
7304 			page->acoustic_manag_level =
7305 			    sata_id->ai_acoustic >> 8;
7306 			page->vendor_recommended_value =
7307 			    (uchar_t)sata_id->ai_acoustic;
7308 #endif
7309 		}
7310 		break;
7311 
7312 	case P_CNTRL_CHANGEABLE:
7313 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7314 		page->mode_page.length =
7315 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7316 		page->mode_page.ps = 1;
7317 
7318 		/* Word 83 indicates if the feature is supported */
7319 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
7320 			page->acoustic_manag_enable =
7321 			    ACOUSTIC_ENABLED;
7322 			page->acoustic_manag_level = 0xff;
7323 		}
7324 		break;
7325 	}
7326 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7327 	    sizeof (struct mode_page));
7328 }
7329 
7330 
7331 /*
7332  * Build Mode sense power condition page.
7333  */
7334 static int
7335 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7336 {
7337 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
7338 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7339 
7340 	/*
7341 	 * Most of the fields are set to 0, being not supported and/or disabled
7342 	 * power condition page length was 0x0a
7343 	 */
7344 	bzero(buf, sizeof (struct mode_info_power_cond));
7345 
7346 	if (pcntrl == P_CNTRL_DEFAULT) {
7347 		/*  default paramters not supported */
7348 		return (0);
7349 	}
7350 
7351 	page->mode_page.code = MODEPAGE_POWER_COND;
7352 	page->mode_page.length = sizeof (struct mode_info_power_cond);
7353 
7354 	if (sata_id->ai_cap && SATA_STANDBYTIMER) {
7355 		page->standby = 1;
7356 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
7357 		    sizeof (uchar_t) * 4);
7358 	}
7359 
7360 	return (sizeof (struct mode_info_power_cond));
7361 }
7362 
7363 /*
7364  * Process mode select caching page 8 (scsi3 format only).
7365  * Read Ahead (same as read cache) and Write Cache may be turned on and off
7366  * if these features are supported by the device. If these features are not
7367  * supported, the command will be terminated with STATUS_CHECK.
7368  * This function fails only if the SET FEATURE command sent to
7369  * the device fails. The page format is not varified, assuming that the
7370  * target driver operates correctly - if parameters length is too short,
7371  * we just drop the page.
7372  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
7373  * setting have to be changed.
7374  * SET FEATURE command is executed synchronously, i.e. we wait here until
7375  * it is completed, regardless of the scsi pkt directives.
7376  *
7377  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
7378  * changing DRA will change RCD.
7379  *
7380  * More than one SATA command may be executed to perform operations specified
7381  * by mode select pages. The first error terminates further execution.
7382  * Operations performed successully are not backed-up in such case.
7383  *
7384  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7385  * If operation resulted in changing device setup, dmod flag should be set to
7386  * one (1). If parameters were not changed, dmod flag should be set to 0.
7387  * Upon return, if operation required sending command to the device, the rval
7388  * should be set to the value returned by sata_hba_start. If operation
7389  * did not require device access, rval should be set to TRAN_ACCEPT.
7390  * The pagelen should be set to the length of the page.
7391  *
7392  * This function has to be called with a port mutex held.
7393  *
7394  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7395  */
7396 int
7397 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
7398     int parmlen, int *pagelen, int *rval, int *dmod)
7399 {
7400 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7401 	sata_drive_info_t *sdinfo;
7402 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7403 	sata_id_t *sata_id;
7404 	struct scsi_extended_sense *sense;
7405 	int wce, dra;	/* Current settings */
7406 
7407 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7408 	    &spx->txlt_sata_pkt->satapkt_device);
7409 	sata_id = &sdinfo->satadrv_id;
7410 	*dmod = 0;
7411 
7412 	/* Verify parameters length. If too short, drop it */
7413 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7414 	    sizeof (struct mode_page)) > parmlen) {
7415 		*scsipkt->pkt_scbp = STATUS_CHECK;
7416 		sense = sata_arq_sense(spx);
7417 		sense->es_key = KEY_ILLEGAL_REQUEST;
7418 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7419 		*pagelen = parmlen;
7420 		*rval = TRAN_ACCEPT;
7421 		return (SATA_FAILURE);
7422 	}
7423 
7424 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
7425 
7426 	/* Current setting of Read Ahead (and Read Cache) */
7427 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
7428 		dra = 0;	/* 0 == not disabled */
7429 	else
7430 		dra = 1;
7431 	/* Current setting of Write Cache */
7432 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
7433 		wce = 1;
7434 	else
7435 		wce = 0;
7436 
7437 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
7438 		/* nothing to do */
7439 		*rval = TRAN_ACCEPT;
7440 		return (SATA_SUCCESS);
7441 	}
7442 
7443 	/*
7444 	 * Need to flip some setting
7445 	 * Set-up Internal SET FEATURES command(s)
7446 	 */
7447 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7448 	scmd->satacmd_addr_type = 0;
7449 	scmd->satacmd_device_reg = 0;
7450 	scmd->satacmd_status_reg = 0;
7451 	scmd->satacmd_error_reg = 0;
7452 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7453 	if (page->dra != dra || page->rcd != dra) {
7454 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7455 			/* Need to flip read ahead setting */
7456 			if (dra == 0)
7457 				/* Disable read ahead / read cache */
7458 				scmd->satacmd_features_reg =
7459 				    SATAC_SF_DISABLE_READ_AHEAD;
7460 			else
7461 				/* Enable read ahead  / read cache */
7462 				scmd->satacmd_features_reg =
7463 				    SATAC_SF_ENABLE_READ_AHEAD;
7464 
7465 			/* Transfer command to HBA */
7466 			if (sata_hba_start(spx, rval) != 0)
7467 				/*
7468 				 * Pkt not accepted for execution.
7469 				 */
7470 				return (SATA_FAILURE);
7471 
7472 			*dmod = 1;
7473 
7474 			/* Now process return */
7475 			if (spx->txlt_sata_pkt->satapkt_reason !=
7476 			    SATA_PKT_COMPLETED) {
7477 				goto failure;	/* Terminate */
7478 			}
7479 		} else {
7480 			*scsipkt->pkt_scbp = STATUS_CHECK;
7481 			sense = sata_arq_sense(spx);
7482 			sense->es_key = KEY_ILLEGAL_REQUEST;
7483 			sense->es_add_code =
7484 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7485 			*pagelen = parmlen;
7486 			*rval = TRAN_ACCEPT;
7487 			return (SATA_FAILURE);
7488 		}
7489 	}
7490 
7491 	/* Note that the packet is not removed, so it could be re-used */
7492 	if (page->wce != wce) {
7493 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
7494 			/* Need to flip Write Cache setting */
7495 			if (page->wce == 1)
7496 				/* Enable write cache */
7497 				scmd->satacmd_features_reg =
7498 				    SATAC_SF_ENABLE_WRITE_CACHE;
7499 			else
7500 				/* Disable write cache */
7501 				scmd->satacmd_features_reg =
7502 				    SATAC_SF_DISABLE_WRITE_CACHE;
7503 
7504 			/* Transfer command to HBA */
7505 			if (sata_hba_start(spx, rval) != 0)
7506 				/*
7507 				 * Pkt not accepted for execution.
7508 				 */
7509 				return (SATA_FAILURE);
7510 
7511 			*dmod = 1;
7512 
7513 			/* Now process return */
7514 			if (spx->txlt_sata_pkt->satapkt_reason !=
7515 			    SATA_PKT_COMPLETED) {
7516 				goto failure;
7517 			}
7518 		} else {
7519 			*scsipkt->pkt_scbp = STATUS_CHECK;
7520 			sense = sata_arq_sense(spx);
7521 			sense->es_key = KEY_ILLEGAL_REQUEST;
7522 			sense->es_add_code =
7523 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7524 			*pagelen = parmlen;
7525 			*rval = TRAN_ACCEPT;
7526 			return (SATA_FAILURE);
7527 		}
7528 	}
7529 	return (SATA_SUCCESS);
7530 
7531 failure:
7532 	sata_xlate_errors(spx);
7533 
7534 	return (SATA_FAILURE);
7535 }
7536 
7537 /*
7538  * Process mode select informational exceptions control page 0x1c
7539  *
7540  * The only changeable bit is dexcpt (disable exceptions).
7541  * MRIE (method of reporting informational exceptions) must be
7542  * "only on request".
7543  * This page applies to informational exceptions that report
7544  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
7545  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
7546  * Informational exception conditions occur as the result of background scan
7547  * errors, background self-test errors, or vendor specific events within a
7548  * logical unit. An informational exception condition may occur asynchronous
7549  * to any commands.
7550  *
7551  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7552  * If operation resulted in changing device setup, dmod flag should be set to
7553  * one (1). If parameters were not changed, dmod flag should be set to 0.
7554  * Upon return, if operation required sending command to the device, the rval
7555  * should be set to the value returned by sata_hba_start. If operation
7556  * did not require device access, rval should be set to TRAN_ACCEPT.
7557  * The pagelen should be set to the length of the page.
7558  *
7559  * This function has to be called with a port mutex held.
7560  *
7561  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7562  *
7563  * Cannot be called in the interrupt context.
7564  */
7565 static	int
7566 sata_mode_select_page_1c(
7567 	sata_pkt_txlate_t *spx,
7568 	struct mode_info_excpt_page *page,
7569 	int parmlen,
7570 	int *pagelen,
7571 	int *rval,
7572 	int *dmod)
7573 {
7574 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7575 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7576 	sata_drive_info_t *sdinfo;
7577 	sata_id_t *sata_id;
7578 	struct scsi_extended_sense *sense;
7579 
7580 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7581 	    &spx->txlt_sata_pkt->satapkt_device);
7582 	sata_id = &sdinfo->satadrv_id;
7583 
7584 	*dmod = 0;
7585 
7586 	/* Verify parameters length. If too short, drop it */
7587 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
7588 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
7589 		*scsipkt->pkt_scbp = STATUS_CHECK;
7590 		sense = sata_arq_sense(spx);
7591 		sense->es_key = KEY_ILLEGAL_REQUEST;
7592 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7593 		*pagelen = parmlen;
7594 		*rval = TRAN_ACCEPT;
7595 		return (SATA_FAILURE);
7596 	}
7597 
7598 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
7599 
7600 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
7601 		*scsipkt->pkt_scbp = STATUS_CHECK;
7602 		sense = sata_arq_sense(spx);
7603 		sense->es_key = KEY_ILLEGAL_REQUEST;
7604 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7605 		*pagelen = parmlen;
7606 		*rval = TRAN_ACCEPT;
7607 		return (SATA_FAILURE);
7608 	}
7609 
7610 	/* If already in the state requested, we are done */
7611 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
7612 		/* nothing to do */
7613 		*rval = TRAN_ACCEPT;
7614 		return (SATA_SUCCESS);
7615 	}
7616 
7617 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7618 
7619 	/* Build SMART_ENABLE or SMART_DISABLE command */
7620 	scmd->satacmd_addr_type = 0;		/* N/A */
7621 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
7622 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
7623 	scmd->satacmd_features_reg = page->dexcpt ?
7624 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
7625 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
7626 	scmd->satacmd_cmd_reg = SATAC_SMART;
7627 
7628 	/* Transfer command to HBA */
7629 	if (sata_hba_start(spx, rval) != 0)
7630 		/*
7631 		 * Pkt not accepted for execution.
7632 		 */
7633 		return (SATA_FAILURE);
7634 
7635 	*dmod = 1;	/* At least may have been modified */
7636 
7637 	/* Now process return */
7638 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
7639 		return (SATA_SUCCESS);
7640 
7641 	/* Packet did not complete successfully */
7642 	sata_xlate_errors(spx);
7643 
7644 	return (SATA_FAILURE);
7645 }
7646 
7647 /*
7648  * Process mode select acoustic management control page 0x30
7649  *
7650  *
7651  * This function has to be called with a port mutex held.
7652  *
7653  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7654  *
7655  * Cannot be called in the interrupt context.
7656  */
7657 int
7658 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
7659     mode_acoustic_management *page, int parmlen, int *pagelen,
7660     int *rval, int *dmod)
7661 {
7662 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7663 	sata_drive_info_t *sdinfo;
7664 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7665 	sata_id_t *sata_id;
7666 	struct scsi_extended_sense *sense;
7667 
7668 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7669 	    &spx->txlt_sata_pkt->satapkt_device);
7670 	sata_id = &sdinfo->satadrv_id;
7671 	*dmod = 0;
7672 
7673 	/* If parmlen is too short or the feature is not supported, drop it */
7674 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7675 	    sizeof (struct mode_page)) > parmlen) ||
7676 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
7677 		*scsipkt->pkt_scbp = STATUS_CHECK;
7678 		sense = sata_arq_sense(spx);
7679 		sense->es_key = KEY_ILLEGAL_REQUEST;
7680 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7681 		*pagelen = parmlen;
7682 		*rval = TRAN_ACCEPT;
7683 		return (SATA_FAILURE);
7684 	}
7685 
7686 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7687 	    sizeof (struct mode_page);
7688 
7689 	/*
7690 	 * We can enable and disable acoustice management and
7691 	 * set the acoustic management level.
7692 	 */
7693 
7694 	/*
7695 	 * Set-up Internal SET FEATURES command(s)
7696 	 */
7697 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7698 	scmd->satacmd_addr_type = 0;
7699 	scmd->satacmd_device_reg = 0;
7700 	scmd->satacmd_status_reg = 0;
7701 	scmd->satacmd_error_reg = 0;
7702 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7703 	if (page->acoustic_manag_enable) {
7704 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
7705 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
7706 	} else {	/* disabling acoustic management */
7707 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
7708 	}
7709 
7710 	/* Transfer command to HBA */
7711 	if (sata_hba_start(spx, rval) != 0)
7712 		/*
7713 		 * Pkt not accepted for execution.
7714 		 */
7715 		return (SATA_FAILURE);
7716 
7717 	/* Now process return */
7718 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
7719 		sata_xlate_errors(spx);
7720 		return (SATA_FAILURE);
7721 	}
7722 
7723 	*dmod = 1;
7724 
7725 	return (SATA_SUCCESS);
7726 }
7727 
7728 /*
7729  * Process mode select power condition page 0x1a
7730  *
7731  * This function has to be called with a port mutex held.
7732  *
7733  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7734  *
7735  * Cannot be called in the interrupt context.
7736  */
7737 int
7738 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
7739     mode_info_power_cond *page, int parmlen, int *pagelen,
7740     int *rval, int *dmod)
7741 {
7742 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7743 	sata_drive_info_t *sdinfo;
7744 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7745 	sata_id_t *sata_id;
7746 	struct scsi_extended_sense *sense;
7747 	uint8_t ata_count;
7748 	int i, len;
7749 
7750 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7751 	    &spx->txlt_sata_pkt->satapkt_device);
7752 	sata_id = &sdinfo->satadrv_id;
7753 	*dmod = 0;
7754 
7755 	len = sizeof (struct mode_info_power_cond);
7756 	len += sizeof (struct mode_page);
7757 
7758 	/* If parmlen is too short or the feature is not supported, drop it */
7759 	if ((len < parmlen) || (page->idle == 1) ||
7760 	    (!(sata_id->ai_cap && SATA_STANDBYTIMER) && page->standby == 1)) {
7761 		*scsipkt->pkt_scbp = STATUS_CHECK;
7762 		sense = sata_arq_sense(spx);
7763 		sense->es_key = KEY_ILLEGAL_REQUEST;
7764 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7765 		*pagelen = parmlen;
7766 		*rval = TRAN_ACCEPT;
7767 		return (SATA_FAILURE);
7768 	}
7769 
7770 	*pagelen = len;
7771 
7772 	/*
7773 	 * Set-up Internal STANDBY command(s)
7774 	 */
7775 	if (page->standby == 0)
7776 		goto out;
7777 
7778 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
7779 
7780 	scmd->satacmd_addr_type = 0;
7781 	scmd->satacmd_sec_count_lsb = ata_count;
7782 	scmd->satacmd_lba_low_lsb = 0;
7783 	scmd->satacmd_lba_mid_lsb = 0;
7784 	scmd->satacmd_lba_high_lsb = 0;
7785 	scmd->satacmd_features_reg = 0;
7786 	scmd->satacmd_device_reg = 0;
7787 	scmd->satacmd_status_reg = 0;
7788 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
7789 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
7790 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
7791 
7792 	/* Transfer command to HBA */
7793 	if (sata_hba_start(spx, rval) != 0) {
7794 		return (SATA_FAILURE);
7795 	} else {
7796 		if ((scmd->satacmd_error_reg != 0) ||
7797 		    (spx->txlt_sata_pkt->satapkt_reason !=
7798 		    SATA_PKT_COMPLETED)) {
7799 			sata_xlate_errors(spx);
7800 			return (SATA_FAILURE);
7801 		}
7802 	}
7803 
7804 	for (i = 0; i < 4; i++) {
7805 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
7806 	}
7807 out:
7808 	*dmod = 1;
7809 	return (SATA_SUCCESS);
7810 }
7811 
7812 /*
7813  * sata_build_lsense_page0() is used to create the
7814  * SCSI LOG SENSE page 0 (supported log pages)
7815  *
7816  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
7817  * (supported log pages, self-test results, informational exceptions
7818  * Sun vendor specific ATA SMART data, and start stop cycle counter).
7819  *
7820  * Takes a sata_drive_info t * and the address of a buffer
7821  * in which to create the page information.
7822  *
7823  * Returns the number of bytes valid in the buffer.
7824  */
7825 static	int
7826 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
7827 {
7828 	struct log_parameter *lpp = (struct log_parameter *)buf;
7829 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
7830 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
7831 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7832 
7833 	lpp->param_code[0] = 0;
7834 	lpp->param_code[1] = 0;
7835 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
7836 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
7837 
7838 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
7839 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
7840 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
7841 			++num_pages_supported;
7842 		}
7843 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
7844 		++num_pages_supported;
7845 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
7846 		++num_pages_supported;
7847 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
7848 		++num_pages_supported;
7849 	}
7850 
7851 	lpp->param_len = num_pages_supported;
7852 
7853 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
7854 	    num_pages_supported);
7855 }
7856 
7857 /*
7858  * sata_build_lsense_page_10() is used to create the
7859  * SCSI LOG SENSE page 0x10 (self-test results)
7860  *
7861  * Takes a sata_drive_info t * and the address of a buffer
7862  * in which to create the page information as well as a sata_hba_inst_t *.
7863  *
7864  * Returns the number of bytes valid in the buffer.
7865  *
7866  * Note: Self test and SMART data is accessible in device log pages.
7867  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
7868  * of data can be transferred by a single command), or by the General Purpose
7869  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
7870  * - approximately 33MB - can be transferred by a single command.
7871  * The SCT Command response (either error or command) is the same for both
7872  * the SMART and GPL methods of issuing commands.
7873  * This function uses READ LOG EXT command when drive supports LBA48, and
7874  * SMART READ command otherwise.
7875  *
7876  * Since above commands are executed in a synchronous mode, this function
7877  * should not be called in an interrupt context.
7878  */
7879 static	int
7880 sata_build_lsense_page_10(
7881 	sata_drive_info_t *sdinfo,
7882 	uint8_t *buf,
7883 	sata_hba_inst_t *sata_hba_inst)
7884 {
7885 	struct log_parameter *lpp = (struct log_parameter *)buf;
7886 	int rval;
7887 
7888 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
7889 		struct smart_ext_selftest_log *ext_selftest_log;
7890 
7891 		ext_selftest_log = kmem_zalloc(
7892 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
7893 
7894 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
7895 		    ext_selftest_log, 0);
7896 		if (rval == 0) {
7897 			int index, start_index;
7898 			struct smart_ext_selftest_log_entry *entry;
7899 			static const struct smart_ext_selftest_log_entry empty =
7900 			    {0};
7901 			uint16_t block_num;
7902 			int count;
7903 			boolean_t only_one_block = B_FALSE;
7904 
7905 			index = ext_selftest_log->
7906 			    smart_ext_selftest_log_index[0];
7907 			index |= ext_selftest_log->
7908 			    smart_ext_selftest_log_index[1] << 8;
7909 			if (index == 0)
7910 				goto out;
7911 
7912 			--index;	/* Correct for 0 origin */
7913 			start_index = index;	/* remember where we started */
7914 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7915 			if (block_num != 0) {
7916 				rval = sata_ext_smart_selftest_read_log(
7917 				    sata_hba_inst, sdinfo, ext_selftest_log,
7918 				    block_num);
7919 				if (rval != 0)
7920 					goto out;
7921 			}
7922 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7923 			entry =
7924 			    &ext_selftest_log->
7925 			    smart_ext_selftest_log_entries[index];
7926 
7927 			for (count = 1;
7928 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
7929 			    ++count) {
7930 				uint8_t status;
7931 				uint8_t code;
7932 				uint8_t sense_key;
7933 				uint8_t add_sense_code;
7934 				uint8_t add_sense_code_qual;
7935 
7936 				/* If this is an unused entry, we are done */
7937 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
7938 					/* Broken firmware on some disks */
7939 					if (index + 1 ==
7940 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
7941 						--entry;
7942 						--index;
7943 						if (bcmp(entry, &empty,
7944 						    sizeof (empty)) == 0)
7945 							goto out;
7946 					} else
7947 						goto out;
7948 				}
7949 
7950 				if (only_one_block &&
7951 				    start_index == index)
7952 					goto out;
7953 
7954 				lpp->param_code[0] = 0;
7955 				lpp->param_code[1] = count;
7956 				lpp->param_ctrl_flags =
7957 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
7958 				lpp->param_len =
7959 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
7960 
7961 				status = entry->smart_ext_selftest_log_status;
7962 				status >>= 4;
7963 				switch (status) {
7964 				case 0:
7965 				default:
7966 					sense_key = KEY_NO_SENSE;
7967 					add_sense_code =
7968 					    SD_SCSI_ASC_NO_ADD_SENSE;
7969 					add_sense_code_qual = 0;
7970 					break;
7971 				case 1:
7972 					sense_key = KEY_ABORTED_COMMAND;
7973 					add_sense_code =
7974 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7975 					add_sense_code_qual = SCSI_COMPONENT_81;
7976 					break;
7977 				case 2:
7978 					sense_key = KEY_ABORTED_COMMAND;
7979 					add_sense_code =
7980 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7981 					add_sense_code_qual = SCSI_COMPONENT_82;
7982 					break;
7983 				case 3:
7984 					sense_key = KEY_ABORTED_COMMAND;
7985 					add_sense_code =
7986 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7987 					add_sense_code_qual = SCSI_COMPONENT_83;
7988 					break;
7989 				case 4:
7990 					sense_key = KEY_HARDWARE_ERROR;
7991 					add_sense_code =
7992 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7993 					add_sense_code_qual = SCSI_COMPONENT_84;
7994 					break;
7995 				case 5:
7996 					sense_key = KEY_HARDWARE_ERROR;
7997 					add_sense_code =
7998 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7999 					add_sense_code_qual = SCSI_COMPONENT_85;
8000 					break;
8001 				case 6:
8002 					sense_key = KEY_HARDWARE_ERROR;
8003 					add_sense_code =
8004 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8005 					add_sense_code_qual = SCSI_COMPONENT_86;
8006 					break;
8007 				case 7:
8008 					sense_key = KEY_MEDIUM_ERROR;
8009 					add_sense_code =
8010 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8011 					add_sense_code_qual = SCSI_COMPONENT_87;
8012 					break;
8013 				case 8:
8014 					sense_key = KEY_HARDWARE_ERROR;
8015 					add_sense_code =
8016 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8017 					add_sense_code_qual = SCSI_COMPONENT_88;
8018 					break;
8019 				}
8020 				code = 0;	/* unspecified */
8021 				status |= (code << 4);
8022 				lpp->param_values[0] = status;
8023 				lpp->param_values[1] = 0; /* unspecified */
8024 				lpp->param_values[2] = entry->
8025 				    smart_ext_selftest_log_timestamp[1];
8026 				lpp->param_values[3] = entry->
8027 				    smart_ext_selftest_log_timestamp[0];
8028 				if (status != 0) {
8029 					lpp->param_values[4] = 0;
8030 					lpp->param_values[5] = 0;
8031 					lpp->param_values[6] = entry->
8032 					    smart_ext_selftest_log_failing_lba
8033 					    [5];
8034 					lpp->param_values[7] = entry->
8035 					    smart_ext_selftest_log_failing_lba
8036 					    [4];
8037 					lpp->param_values[8] = entry->
8038 					    smart_ext_selftest_log_failing_lba
8039 					    [3];
8040 					lpp->param_values[9] = entry->
8041 					    smart_ext_selftest_log_failing_lba
8042 					    [2];
8043 					lpp->param_values[10] = entry->
8044 					    smart_ext_selftest_log_failing_lba
8045 					    [1];
8046 					lpp->param_values[11] = entry->
8047 					    smart_ext_selftest_log_failing_lba
8048 					    [0];
8049 				} else {	/* No bad block address */
8050 					lpp->param_values[4] = 0xff;
8051 					lpp->param_values[5] = 0xff;
8052 					lpp->param_values[6] = 0xff;
8053 					lpp->param_values[7] = 0xff;
8054 					lpp->param_values[8] = 0xff;
8055 					lpp->param_values[9] = 0xff;
8056 					lpp->param_values[10] = 0xff;
8057 					lpp->param_values[11] = 0xff;
8058 				}
8059 
8060 				lpp->param_values[12] = sense_key;
8061 				lpp->param_values[13] = add_sense_code;
8062 				lpp->param_values[14] = add_sense_code_qual;
8063 				lpp->param_values[15] = 0; /* undefined */
8064 
8065 				lpp = (struct log_parameter *)
8066 				    (((uint8_t *)lpp) +
8067 				    SCSI_LOG_PARAM_HDR_LEN +
8068 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8069 
8070 				--index;	/* Back up to previous entry */
8071 				if (index < 0) {
8072 					if (block_num > 0) {
8073 						--block_num;
8074 					} else {
8075 						struct read_log_ext_directory
8076 						    logdir;
8077 
8078 						rval =
8079 						    sata_read_log_ext_directory(
8080 						    sata_hba_inst, sdinfo,
8081 						    &logdir);
8082 						if (rval == -1)
8083 							goto out;
8084 						if ((logdir.read_log_ext_vers
8085 						    [0] == 0) &&
8086 						    (logdir.read_log_ext_vers
8087 						    [1] == 0))
8088 							goto out;
8089 						block_num =
8090 						    logdir.read_log_ext_nblks
8091 						    [EXT_SMART_SELFTEST_LOG_PAGE
8092 						    - 1][0];
8093 						block_num |= logdir.
8094 						    read_log_ext_nblks
8095 						    [EXT_SMART_SELFTEST_LOG_PAGE
8096 						    - 1][1] << 8;
8097 						--block_num;
8098 						only_one_block =
8099 						    (block_num == 0);
8100 					}
8101 					rval = sata_ext_smart_selftest_read_log(
8102 					    sata_hba_inst, sdinfo,
8103 					    ext_selftest_log, block_num);
8104 					if (rval != 0)
8105 						goto out;
8106 
8107 					index =
8108 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8109 					    1;
8110 				}
8111 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8112 				entry = &ext_selftest_log->
8113 				    smart_ext_selftest_log_entries[index];
8114 			}
8115 		}
8116 out:
8117 		kmem_free(ext_selftest_log,
8118 		    sizeof (struct smart_ext_selftest_log));
8119 	} else {
8120 		struct smart_selftest_log *selftest_log;
8121 
8122 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8123 		    KM_SLEEP);
8124 
8125 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8126 		    selftest_log);
8127 
8128 		if (rval == 0) {
8129 			int index;
8130 			int count;
8131 			struct smart_selftest_log_entry *entry;
8132 			static const struct smart_selftest_log_entry empty =
8133 			    { 0 };
8134 
8135 			index = selftest_log->smart_selftest_log_index;
8136 			if (index == 0)
8137 				goto done;
8138 			--index;	/* Correct for 0 origin */
8139 			entry = &selftest_log->
8140 			    smart_selftest_log_entries[index];
8141 			for (count = 1;
8142 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8143 			    ++count) {
8144 				uint8_t status;
8145 				uint8_t code;
8146 				uint8_t sense_key;
8147 				uint8_t add_sense_code;
8148 				uint8_t add_sense_code_qual;
8149 
8150 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8151 					goto done;
8152 
8153 				lpp->param_code[0] = 0;
8154 				lpp->param_code[1] = count;
8155 				lpp->param_ctrl_flags =
8156 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8157 				lpp->param_len =
8158 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8159 
8160 				status = entry->smart_selftest_log_status;
8161 				status >>= 4;
8162 				switch (status) {
8163 				case 0:
8164 				default:
8165 					sense_key = KEY_NO_SENSE;
8166 					add_sense_code =
8167 					    SD_SCSI_ASC_NO_ADD_SENSE;
8168 					break;
8169 				case 1:
8170 					sense_key = KEY_ABORTED_COMMAND;
8171 					add_sense_code =
8172 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8173 					add_sense_code_qual = SCSI_COMPONENT_81;
8174 					break;
8175 				case 2:
8176 					sense_key = KEY_ABORTED_COMMAND;
8177 					add_sense_code =
8178 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8179 					add_sense_code_qual = SCSI_COMPONENT_82;
8180 					break;
8181 				case 3:
8182 					sense_key = KEY_ABORTED_COMMAND;
8183 					add_sense_code =
8184 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8185 					add_sense_code_qual = SCSI_COMPONENT_83;
8186 					break;
8187 				case 4:
8188 					sense_key = KEY_HARDWARE_ERROR;
8189 					add_sense_code =
8190 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8191 					add_sense_code_qual = SCSI_COMPONENT_84;
8192 					break;
8193 				case 5:
8194 					sense_key = KEY_HARDWARE_ERROR;
8195 					add_sense_code =
8196 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8197 					add_sense_code_qual = SCSI_COMPONENT_85;
8198 					break;
8199 				case 6:
8200 					sense_key = KEY_HARDWARE_ERROR;
8201 					add_sense_code =
8202 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8203 					add_sense_code_qual = SCSI_COMPONENT_86;
8204 					break;
8205 				case 7:
8206 					sense_key = KEY_MEDIUM_ERROR;
8207 					add_sense_code =
8208 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8209 					add_sense_code_qual = SCSI_COMPONENT_87;
8210 					break;
8211 				case 8:
8212 					sense_key = KEY_HARDWARE_ERROR;
8213 					add_sense_code =
8214 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8215 					add_sense_code_qual = SCSI_COMPONENT_88;
8216 					break;
8217 				}
8218 				code = 0;	/* unspecified */
8219 				status |= (code << 4);
8220 				lpp->param_values[0] = status;
8221 				lpp->param_values[1] = 0; /* unspecified */
8222 				lpp->param_values[2] = entry->
8223 				    smart_selftest_log_timestamp[1];
8224 				lpp->param_values[3] = entry->
8225 				    smart_selftest_log_timestamp[0];
8226 				if (status != 0) {
8227 					lpp->param_values[4] = 0;
8228 					lpp->param_values[5] = 0;
8229 					lpp->param_values[6] = 0;
8230 					lpp->param_values[7] = 0;
8231 					lpp->param_values[8] = entry->
8232 					    smart_selftest_log_failing_lba[3];
8233 					lpp->param_values[9] = entry->
8234 					    smart_selftest_log_failing_lba[2];
8235 					lpp->param_values[10] = entry->
8236 					    smart_selftest_log_failing_lba[1];
8237 					lpp->param_values[11] = entry->
8238 					    smart_selftest_log_failing_lba[0];
8239 				} else {	/* No block address */
8240 					lpp->param_values[4] = 0xff;
8241 					lpp->param_values[5] = 0xff;
8242 					lpp->param_values[6] = 0xff;
8243 					lpp->param_values[7] = 0xff;
8244 					lpp->param_values[8] = 0xff;
8245 					lpp->param_values[9] = 0xff;
8246 					lpp->param_values[10] = 0xff;
8247 					lpp->param_values[11] = 0xff;
8248 				}
8249 				lpp->param_values[12] = sense_key;
8250 				lpp->param_values[13] = add_sense_code;
8251 				lpp->param_values[14] = add_sense_code_qual;
8252 				lpp->param_values[15] = 0; /* undefined */
8253 
8254 				lpp = (struct log_parameter *)
8255 				    (((uint8_t *)lpp) +
8256 				    SCSI_LOG_PARAM_HDR_LEN +
8257 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8258 				--index;	/* back up to previous entry */
8259 				if (index < 0) {
8260 					index =
8261 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
8262 				}
8263 				entry = &selftest_log->
8264 				    smart_selftest_log_entries[index];
8265 			}
8266 		}
8267 done:
8268 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
8269 	}
8270 
8271 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
8272 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
8273 }
8274 
8275 /*
8276  * sata_build_lsense_page_2f() is used to create the
8277  * SCSI LOG SENSE page 0x2f (informational exceptions)
8278  *
8279  * Takes a sata_drive_info t * and the address of a buffer
8280  * in which to create the page information as well as a sata_hba_inst_t *.
8281  *
8282  * Returns the number of bytes valid in the buffer.
8283  *
8284  * Because it invokes function(s) that send synchronously executed command
8285  * to the HBA, it cannot be called in the interrupt context.
8286  */
8287 static	int
8288 sata_build_lsense_page_2f(
8289 	sata_drive_info_t *sdinfo,
8290 	uint8_t *buf,
8291 	sata_hba_inst_t *sata_hba_inst)
8292 {
8293 	struct log_parameter *lpp = (struct log_parameter *)buf;
8294 	int rval;
8295 	uint8_t *smart_data;
8296 	uint8_t temp;
8297 	sata_id_t *sata_id;
8298 #define	SMART_NO_TEMP	0xff
8299 
8300 	lpp->param_code[0] = 0;
8301 	lpp->param_code[1] = 0;
8302 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8303 
8304 	/* Now get the SMART status w.r.t. threshold exceeded */
8305 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
8306 	switch (rval) {
8307 	case 1:
8308 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
8309 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
8310 		break;
8311 	case 0:
8312 	case -1:	/* failed to get data */
8313 		lpp->param_values[0] = 0;	/* No failure predicted */
8314 		lpp->param_values[1] = 0;
8315 		break;
8316 #if defined(SATA_DEBUG)
8317 	default:
8318 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
8319 		/* NOTREACHED */
8320 #endif
8321 	}
8322 
8323 	sata_id = &sdinfo->satadrv_id;
8324 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
8325 		temp = SMART_NO_TEMP;
8326 	else {
8327 		/* Now get the temperature */
8328 		smart_data = kmem_zalloc(512, KM_SLEEP);
8329 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
8330 		    SCT_STATUS_LOG_PAGE, 1);
8331 		if (rval == -1)
8332 			temp = SMART_NO_TEMP;
8333 		else {
8334 			temp = smart_data[200];
8335 			if (temp & 0x80) {
8336 				if (temp & 0x7f)
8337 					temp = 0;
8338 				else
8339 					temp = SMART_NO_TEMP;
8340 			}
8341 		}
8342 		kmem_free(smart_data, 512);
8343 	}
8344 
8345 	lpp->param_values[2] = temp;	/* most recent temperature */
8346 	lpp->param_values[3] = 0;	/* required vendor specific byte */
8347 
8348 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
8349 
8350 
8351 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
8352 }
8353 
8354 /*
8355  * sata_build_lsense_page_30() is used to create the
8356  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
8357  *
8358  * Takes a sata_drive_info t * and the address of a buffer
8359  * in which to create the page information as well as a sata_hba_inst_t *.
8360  *
8361  * Returns the number of bytes valid in the buffer.
8362  */
8363 static int
8364 sata_build_lsense_page_30(
8365 	sata_drive_info_t *sdinfo,
8366 	uint8_t *buf,
8367 	sata_hba_inst_t *sata_hba_inst)
8368 {
8369 	struct smart_data *smart_data = (struct smart_data *)buf;
8370 	int rval;
8371 
8372 	/* Now do the SMART READ DATA */
8373 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
8374 	if (rval == -1)
8375 		return (0);
8376 
8377 	return (sizeof (struct smart_data));
8378 }
8379 
8380 /*
8381  * sata_build_lsense_page_0e() is used to create the
8382  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
8383  *
8384  * Date of Manufacture (0x0001)
8385  *	YEAR = "0000"
8386  *	WEEK = "00"
8387  * Accounting Date (0x0002)
8388  *	6 ASCII space character(20h)
8389  * Specified cycle count over device lifetime
8390  *	VALUE - THRESH - the delta between max and min;
8391  * Accumulated start-stop cycles
8392  *	VALUE - WORST - the accumulated cycles;
8393  *
8394  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
8395  *
8396  * Takes a sata_drive_info t * and the address of a buffer
8397  * in which to create the page information as well as a sata_hba_inst_t *.
8398  *
8399  * Returns the number of bytes valid in the buffer.
8400  */
8401 static	int
8402 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
8403 	sata_pkt_txlate_t *spx)
8404 {
8405 	struct start_stop_cycle_counter_log *log_page;
8406 	int i, rval, index;
8407 	uint8_t smart_data[512], id, value, worst, thresh;
8408 	uint32_t max_count, cycles;
8409 
8410 	/* Now do the SMART READ DATA */
8411 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
8412 	    (struct smart_data *)smart_data);
8413 	if (rval == -1)
8414 		return (0);
8415 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
8416 		index = (i * 12) + 2;
8417 		id = smart_data[index];
8418 		if (id != SMART_START_STOP_COUNT_ID)
8419 			continue;
8420 		else {
8421 			thresh = smart_data[index + 2];
8422 			value = smart_data[index + 3];
8423 			worst = smart_data[index + 4];
8424 			break;
8425 		}
8426 	}
8427 	if (id != SMART_START_STOP_COUNT_ID)
8428 		return (0);
8429 	max_count = value - thresh;
8430 	cycles = value - worst;
8431 
8432 	log_page = (struct start_stop_cycle_counter_log *)buf;
8433 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
8434 	log_page->code = 0x0e;
8435 	log_page->page_len_low = 0x24;
8436 
8437 	log_page->manufactor_date_low = 0x1;
8438 	log_page->param_1.fmt_link = 0x1; /* 01b */
8439 	log_page->param_len_1 = 0x06;
8440 	for (i = 0; i < 4; i++) {
8441 		log_page->year_manu[i] = 0x30;
8442 		if (i < 2)
8443 			log_page->week_manu[i] = 0x30;
8444 	}
8445 
8446 	log_page->account_date_low = 0x02;
8447 	log_page->param_2.fmt_link = 0x01; /* 01b */
8448 	log_page->param_len_2 = 0x06;
8449 	for (i = 0; i < 4; i++) {
8450 		log_page->year_account[i] = 0x20;
8451 		if (i < 2)
8452 			log_page->week_account[i] = 0x20;
8453 	}
8454 
8455 	log_page->lifetime_code_low = 0x03;
8456 	log_page->param_3.fmt_link = 0x03; /* 11b */
8457 	log_page->param_len_3 = 0x04;
8458 	/* VALUE - THRESH - the delta between max and min */
8459 	log_page->cycle_code_low = 0x04;
8460 	log_page->param_4.fmt_link = 0x03; /* 11b */
8461 	log_page->param_len_4 = 0x04;
8462 	/* WORST - THRESH - the distance from 'now' to min */
8463 
8464 	for (i = 0; i < 4; i++) {
8465 		log_page->cycle_lifetime[i] =
8466 		    (max_count >> (8 * (3 - i))) & 0xff;
8467 		log_page->cycle_accumulated[i] =
8468 		    (cycles >> (8 * (3 - i))) & 0xff;
8469 	}
8470 
8471 	return (sizeof (struct start_stop_cycle_counter_log));
8472 }
8473 
8474 /*
8475  * This function was used for build a ATA read verify sector command
8476  */
8477 static void
8478 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
8479 {
8480 	scmd->satacmd_cmd_reg = SATAC_RDVER;
8481 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
8482 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8483 
8484 	scmd->satacmd_sec_count_lsb = sec & 0xff;
8485 	scmd->satacmd_lba_low_lsb = lba & 0xff;
8486 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
8487 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
8488 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
8489 	scmd->satacmd_features_reg = 0;
8490 	scmd->satacmd_status_reg = 0;
8491 	scmd->satacmd_error_reg = 0;
8492 }
8493 
8494 /*
8495  * This function was used for building an ATA
8496  * command, and only command register need to
8497  * be defined, other register will be zero or na.
8498  */
8499 static void
8500 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
8501 {
8502 	scmd->satacmd_addr_type = 0;
8503 	scmd->satacmd_cmd_reg = cmd;
8504 	scmd->satacmd_device_reg = 0;
8505 	scmd->satacmd_sec_count_lsb = 0;
8506 	scmd->satacmd_lba_low_lsb = 0;
8507 	scmd->satacmd_lba_mid_lsb = 0;
8508 	scmd->satacmd_lba_high_lsb = 0;
8509 	scmd->satacmd_features_reg = 0;
8510 	scmd->satacmd_status_reg = 0;
8511 	scmd->satacmd_error_reg = 0;
8512 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8513 }
8514 
8515 /*
8516  * This function was used for changing the standby
8517  * timer format from SCSI to ATA.
8518  */
8519 static uint8_t
8520 sata_get_standby_timer(uint8_t *timer)
8521 {
8522 	uint32_t i = 0, count = 0;
8523 	uint8_t ata_count;
8524 
8525 	for (i = 0; i < 4; i++) {
8526 		count = count << 8 | timer[i];
8527 	}
8528 
8529 	if (count == 0)
8530 		return (0);
8531 
8532 	if (count >= 1 && count <= 12000)
8533 		ata_count = (count -1) / 50 + 1;
8534 	else if (count > 12000 && count <= 12600)
8535 		ata_count = 0xfc;
8536 	else if (count > 12601 && count <= 12750)
8537 		ata_count = 0xff;
8538 	else if (count > 12750 && count <= 17999)
8539 		ata_count = 0xf1;
8540 	else if (count > 18000 && count <= 198000)
8541 		ata_count = count / 18000 + 240;
8542 	else
8543 		ata_count = 0xfd;
8544 	return (ata_count);
8545 }
8546 
8547 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
8548 
8549 /*
8550  * Start command for ATAPI device.
8551  * This function processes scsi_pkt requests.
8552  * Now CD/DVD, tape and ATAPI disk devices are supported.
8553  * Most commands are packet without any translation into Packet Command.
8554  * Some may be trapped and executed as SATA commands (not clear which one).
8555  *
8556  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
8557  * execution).
8558  * Returns other TRAN_XXXX codes if command is not accepted or completed
8559  * (see return values for sata_hba_start()).
8560  *
8561  * Note:
8562  * Inquiry cdb format differs between transport version 2 and 3.
8563  * However, the transport version 3 devices that were checked did not adhere
8564  * to the specification (ignored MSB of the allocation length). Therefore,
8565  * the transport version is not checked, but Inquiry allocation length is
8566  * truncated to 255 bytes if the original allocation length set-up by the
8567  * target driver is greater than 255 bytes.
8568  */
8569 static int
8570 sata_txlt_atapi(sata_pkt_txlate_t *spx)
8571 {
8572 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8573 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8574 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8575 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
8576 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
8577 	    &spx->txlt_sata_pkt->satapkt_device);
8578 	int cport = SATA_TXLT_CPORT(spx);
8579 	int cdblen;
8580 	int rval, reason;
8581 	int synch;
8582 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
8583 
8584 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8585 
8586 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
8587 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
8588 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8589 		return (rval);
8590 	}
8591 
8592 	/*
8593 	 * ATAPI device executes some ATA commands in addition to those
8594 	 * commands sent via PACKET command. These ATA commands may be
8595 	 * executed by the regular SATA translation functions. None needs
8596 	 * to be captured now.
8597 	 *
8598 	 * Commands sent via PACKET command include:
8599 	 *	MMC command set for ATAPI CD/DVD device
8600 	 *	SSC command set for ATAPI TAPE device
8601 	 *	SBC command set for ATAPI disk device
8602 	 *
8603 	 */
8604 
8605 	/* Check the size of cdb */
8606 	cdblen = scsi_cdb_size[GETGROUP(cdbp)];
8607 	if (cdblen > sdinfo->satadrv_atapi_cdb_len) {
8608 		sata_log(NULL, CE_WARN,
8609 		    "sata: invalid ATAPI cdb length %d",
8610 		    scsipkt->pkt_cdblen);
8611 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8612 		return (TRAN_BADPKT);
8613 	}
8614 
8615 	SATAATAPITRACE(spx, cdblen);
8616 
8617 	/*
8618 	 * For non-read/write commands we need to
8619 	 * map buffer
8620 	 */
8621 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
8622 	case SCMD_READ:
8623 	case SCMD_READ_G1:
8624 	case SCMD_READ_G5:
8625 	case SCMD_READ_G4:
8626 	case SCMD_WRITE:
8627 	case SCMD_WRITE_G1:
8628 	case SCMD_WRITE_G5:
8629 	case SCMD_WRITE_G4:
8630 		break;
8631 	default:
8632 		if (bp != NULL) {
8633 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
8634 				bp_mapin(bp);
8635 		}
8636 		break;
8637 	}
8638 	/*
8639 	 * scmd->satacmd_flags.sata_data_direction default -
8640 	 * SATA_DIR_NODATA_XFER - is set by
8641 	 * sata_txlt_generic_pkt_info().
8642 	 */
8643 	if (scmd->satacmd_bp) {
8644 		if (scmd->satacmd_bp->b_flags & B_READ) {
8645 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8646 		} else {
8647 			scmd->satacmd_flags.sata_data_direction =
8648 			    SATA_DIR_WRITE;
8649 		}
8650 	}
8651 
8652 	/*
8653 	 * Set up ATAPI packet command.
8654 	 */
8655 
8656 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8657 
8658 	/* Copy cdb into sata_cmd */
8659 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8660 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
8661 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
8662 
8663 	/* See note in the command header */
8664 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
8665 		if (scmd->satacmd_acdb[3] != 0)
8666 			scmd->satacmd_acdb[4] = 255;
8667 	}
8668 
8669 #ifdef SATA_DEBUG
8670 	if (sata_debug_flags & SATA_DBG_ATAPI) {
8671 		uint8_t *p = scmd->satacmd_acdb;
8672 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
8673 
8674 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
8675 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
8676 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
8677 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
8678 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
8679 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
8680 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
8681 	}
8682 #endif
8683 
8684 	/*
8685 	 * Preset request sense data to NO SENSE.
8686 	 * If there is no way to get error information via Request Sense,
8687 	 * the packet request sense data would not have to be modified by HBA,
8688 	 * but it could be returned as is.
8689 	 */
8690 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8691 	sata_fixed_sense_data_preset(
8692 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8693 
8694 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
8695 		/* Need callback function */
8696 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
8697 		synch = FALSE;
8698 	} else
8699 		synch = TRUE;
8700 
8701 	/* Transfer command to HBA */
8702 	if (sata_hba_start(spx, &rval) != 0) {
8703 		/* Pkt not accepted for execution */
8704 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8705 		return (rval);
8706 	}
8707 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8708 	/*
8709 	 * If execution is non-synchronous,
8710 	 * a callback function will handle potential errors, translate
8711 	 * the response and will do a callback to a target driver.
8712 	 * If it was synchronous, use the same framework callback to check
8713 	 * an execution status.
8714 	 */
8715 	if (synch) {
8716 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
8717 		    "synchronous execution status %x\n",
8718 		    spx->txlt_sata_pkt->satapkt_reason);
8719 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
8720 	}
8721 	return (TRAN_ACCEPT);
8722 }
8723 
8724 
8725 /*
8726  * ATAPI Packet command completion.
8727  *
8728  * Failure of the command passed via Packet command are considered device
8729  * error. SATA HBA driver would have to retrieve error data (via Request
8730  * Sense command delivered via error retrieval sata packet) and copy it
8731  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
8732  */
8733 static void
8734 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
8735 {
8736 	sata_pkt_txlate_t *spx =
8737 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
8738 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8739 	struct scsi_extended_sense *sense;
8740 	struct buf *bp;
8741 	int rval;
8742 
8743 #ifdef SATA_DEBUG
8744 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
8745 #endif
8746 
8747 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
8748 	    STATE_SENT_CMD | STATE_GOT_STATUS;
8749 
8750 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
8751 		/* Normal completion */
8752 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
8753 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
8754 		scsipkt->pkt_reason = CMD_CMPLT;
8755 		*scsipkt->pkt_scbp = STATUS_GOOD;
8756 		if (spx->txlt_tmp_buf != NULL) {
8757 			/* Temporary buffer was used */
8758 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8759 			if (bp->b_flags & B_READ) {
8760 				rval = ddi_dma_sync(
8761 				    spx->txlt_buf_dma_handle, 0, 0,
8762 				    DDI_DMA_SYNC_FORCPU);
8763 				ASSERT(rval == DDI_SUCCESS);
8764 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
8765 				    bp->b_bcount);
8766 			}
8767 		}
8768 	} else {
8769 		/*
8770 		 * Something went wrong - analyze return
8771 		 */
8772 		*scsipkt->pkt_scbp = STATUS_CHECK;
8773 		sense = sata_arq_sense(spx);
8774 
8775 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
8776 			/*
8777 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
8778 			 * Under this condition ERR bit is set for ATA command,
8779 			 * and CHK bit set for ATAPI command.
8780 			 *
8781 			 * Please check st_intr & sdintr about how pkt_reason
8782 			 * is used.
8783 			 */
8784 			scsipkt->pkt_reason = CMD_CMPLT;
8785 
8786 			/*
8787 			 * We may not have ARQ data if there was a double
8788 			 * error. But sense data in sata packet was pre-set
8789 			 * with NO SENSE so it is valid even if HBA could
8790 			 * not retrieve a real sense data.
8791 			 * Just copy this sense data into scsi pkt sense area.
8792 			 */
8793 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
8794 			    SATA_ATAPI_MIN_RQSENSE_LEN);
8795 #ifdef SATA_DEBUG
8796 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
8797 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
8798 				    "sata_txlt_atapi_completion: %02x\n"
8799 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
8800 				    "          %02x %02x %02x %02x %02x %02x "
8801 				    "          %02x %02x %02x %02x %02x %02x\n",
8802 				    scsipkt->pkt_reason,
8803 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
8804 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
8805 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
8806 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
8807 				    rqsp[16], rqsp[17]);
8808 			}
8809 #endif
8810 		} else {
8811 			switch (sata_pkt->satapkt_reason) {
8812 			case SATA_PKT_PORT_ERROR:
8813 				/*
8814 				 * We have no device data.
8815 				 */
8816 				scsipkt->pkt_reason = CMD_INCOMPLETE;
8817 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8818 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8819 				    STATE_GOT_STATUS);
8820 				sense->es_key = KEY_HARDWARE_ERROR;
8821 				break;
8822 
8823 			case SATA_PKT_TIMEOUT:
8824 				scsipkt->pkt_reason = CMD_TIMEOUT;
8825 				scsipkt->pkt_statistics |=
8826 				    STAT_TIMEOUT | STAT_DEV_RESET;
8827 				/*
8828 				 * Need to check if HARDWARE_ERROR/
8829 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
8830 				 * appropriate.
8831 				 */
8832 				break;
8833 
8834 			case SATA_PKT_ABORTED:
8835 				scsipkt->pkt_reason = CMD_ABORTED;
8836 				scsipkt->pkt_statistics |= STAT_ABORTED;
8837 				/* Should we set key COMMAND_ABPRTED? */
8838 				break;
8839 
8840 			case SATA_PKT_RESET:
8841 				scsipkt->pkt_reason = CMD_RESET;
8842 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
8843 				/*
8844 				 * May be we should set Unit Attention /
8845 				 * Reset. Perhaps the same should be
8846 				 * returned for disks....
8847 				 */
8848 				sense->es_key = KEY_UNIT_ATTENTION;
8849 				sense->es_add_code = SD_SCSI_ASC_RESET;
8850 				break;
8851 
8852 			default:
8853 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8854 				    "sata_txlt_atapi_completion: "
8855 				    "invalid packet completion reason"));
8856 				scsipkt->pkt_reason = CMD_TRAN_ERR;
8857 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8858 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8859 				    STATE_GOT_STATUS);
8860 				break;
8861 			}
8862 		}
8863 	}
8864 
8865 	SATAATAPITRACE(spx, 0);
8866 
8867 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
8868 	    scsipkt->pkt_comp != NULL) {
8869 		/* scsi callback required */
8870 		(*scsipkt->pkt_comp)(scsipkt);
8871 	}
8872 }
8873 
8874 /*
8875  * Set up error retrieval sata command for ATAPI Packet Command error data
8876  * recovery.
8877  *
8878  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
8879  * returns SATA_FAILURE otherwise.
8880  */
8881 
8882 static int
8883 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
8884 {
8885 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
8886 	sata_cmd_t *scmd;
8887 	struct buf *bp;
8888 
8889 	/*
8890 	 * Allocate dma-able buffer error data.
8891 	 * Buffer allocation will take care of buffer alignment and other DMA
8892 	 * attributes.
8893 	 */
8894 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
8895 	if (bp == NULL) {
8896 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
8897 		    "sata_get_err_retrieval_pkt: "
8898 		    "cannot allocate buffer for error data", NULL);
8899 		return (SATA_FAILURE);
8900 	}
8901 	bp_mapin(bp); /* make data buffer accessible */
8902 
8903 	/* Operation modes are up to the caller */
8904 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
8905 
8906 	/* Synchronous mode, no callback - may be changed by the caller */
8907 	spkt->satapkt_comp = NULL;
8908 	spkt->satapkt_time = sata_default_pkt_time;
8909 
8910 	scmd = &spkt->satapkt_cmd;
8911 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8912 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
8913 
8914 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8915 
8916 	/*
8917 	 * Set-up acdb. Request Sense CDB (packet command content) is
8918 	 * not in DMA-able buffer. Its handling is HBA-specific (how
8919 	 * it is transfered into packet FIS).
8920 	 */
8921 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8922 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
8923 	/* Following zeroing of pad bytes may not be necessary */
8924 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
8925 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
8926 
8927 	/*
8928 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
8929 	 * before accessing it. Handle is in usual place in translate struct.
8930 	 */
8931 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
8932 
8933 	/*
8934 	 * Preset request sense data to NO SENSE.
8935 	 * Here it is redundant, only for a symetry with scsi-originated
8936 	 * packets. It should not be used for anything but debugging.
8937 	 */
8938 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8939 	sata_fixed_sense_data_preset(
8940 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8941 
8942 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
8943 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
8944 
8945 	return (SATA_SUCCESS);
8946 }
8947 
8948 /*
8949  * Set-up ATAPI packet command.
8950  * Data transfer direction has to be set-up in sata_cmd structure prior to
8951  * calling this function.
8952  *
8953  * Returns void
8954  */
8955 
8956 static void
8957 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
8958 {
8959 	scmd->satacmd_addr_type = 0;		/* N/A */
8960 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
8961 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
8962 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
8963 	scmd->satacmd_lba_high_lsb =
8964 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
8965 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
8966 
8967 	/*
8968 	 * We want all data to be transfered via DMA.
8969 	 * But specify it only if drive supports DMA and DMA mode is
8970 	 * selected - some drives are sensitive about it.
8971 	 * Hopefully it wil work for all drives....
8972 	 */
8973 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
8974 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
8975 
8976 	/*
8977 	 * Features register requires special care for devices that use
8978 	 * Serial ATA bridge - they need an explicit specification of
8979 	 * the data transfer direction for Packet DMA commands.
8980 	 * Setting this bit is harmless if DMA is not used.
8981 	 *
8982 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
8983 	 * spec they follow.
8984 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
8985 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
8986 	 * ATA/ATAPI-7 support is explicitly indicated.
8987 	 */
8988 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
8989 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
8990 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
8991 		/*
8992 		 * Specification of major version is valid and version 7
8993 		 * is supported. It does automatically imply that all
8994 		 * spec features are supported. For now, we assume that
8995 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
8996 		 */
8997 		if ((sdinfo->satadrv_id.ai_dirdma &
8998 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
8999 			if (scmd->satacmd_flags.sata_data_direction ==
9000 			    SATA_DIR_READ)
9001 			scmd->satacmd_features_reg |=
9002 			    SATA_ATAPI_F_DATA_DIR_READ;
9003 		}
9004 	}
9005 }
9006 
9007 
9008 #ifdef SATA_DEBUG
9009 
9010 /* Display 18 bytes of Inquiry data */
9011 static void
9012 sata_show_inqry_data(uint8_t *buf)
9013 {
9014 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9015 	uint8_t *p;
9016 
9017 	cmn_err(CE_NOTE, "Inquiry data:");
9018 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9019 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9020 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9021 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9022 	    SATA_ATAPI_TRANS_VERSION(inq));
9023 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9024 	    inq->inq_rdf, inq->inq_aenc);
9025 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9026 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9027 	p = (uint8_t *)inq->inq_vid;
9028 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9029 	    "%02x %02x %02x %02x",
9030 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9031 	p = (uint8_t *)inq->inq_vid;
9032 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9033 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9034 
9035 	p = (uint8_t *)inq->inq_pid;
9036 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9037 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9038 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9039 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9040 	p = (uint8_t *)inq->inq_pid;
9041 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9042 	    "%c %c %c %c %c %c %c %c",
9043 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9044 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9045 
9046 	p = (uint8_t *)inq->inq_revision;
9047 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9048 	    p[0], p[1], p[2], p[3]);
9049 	p = (uint8_t *)inq->inq_revision;
9050 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9051 	    p[0], p[1], p[2], p[3]);
9052 
9053 }
9054 
9055 
9056 static void
9057 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9058 {
9059 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9060 
9061 	if (scsi_pkt == NULL)
9062 		return;
9063 	if (count != 0) {
9064 		/* saving cdb */
9065 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9066 		    SATA_ATAPI_MAX_CDB_LEN);
9067 		bcopy(scsi_pkt->pkt_cdbp,
9068 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9069 	} else {
9070 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9071 		    sts_sensedata,
9072 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9073 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9074 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9075 		    scsi_pkt->pkt_reason;
9076 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9077 		    spx->txlt_sata_pkt->satapkt_reason;
9078 
9079 		if (++sata_atapi_trace_index >= 64)
9080 			sata_atapi_trace_index = 0;
9081 	}
9082 }
9083 
9084 #endif
9085 
9086 /*
9087  * Fetch inquiry data from ATAPI device
9088  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
9089  *
9090  * Note:
9091  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9092  * where the caller expects to see the inquiry data.
9093  *
9094  */
9095 
9096 static int
9097 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9098     sata_address_t *saddr, struct scsi_inquiry *inq)
9099 {
9100 	sata_pkt_txlate_t *spx;
9101 	sata_pkt_t *spkt;
9102 	struct buf *bp;
9103 	sata_drive_info_t *sdinfo;
9104 	sata_cmd_t *scmd;
9105 	int rval;
9106 	uint8_t *rqsp;
9107 #ifdef SATA_DEBUG
9108 	char msg_buf[MAXPATHLEN];
9109 #endif
9110 
9111 	ASSERT(sata_hba != NULL);
9112 
9113 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9114 	spx->txlt_sata_hba_inst = sata_hba;
9115 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9116 	spkt = sata_pkt_alloc(spx, NULL);
9117 	if (spkt == NULL) {
9118 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9119 		return (SATA_FAILURE);
9120 	}
9121 	/* address is needed now */
9122 	spkt->satapkt_device.satadev_addr = *saddr;
9123 
9124 	/* scsi_inquiry size buffer */
9125 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9126 	if (bp == NULL) {
9127 		sata_pkt_free(spx);
9128 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9129 		SATA_LOG_D((sata_hba, CE_WARN,
9130 		    "sata_get_atapi_inquiry_data: "
9131 		    "cannot allocate data buffer"));
9132 		return (SATA_FAILURE);
9133 	}
9134 	bp_mapin(bp); /* make data buffer accessible */
9135 
9136 	scmd = &spkt->satapkt_cmd;
9137 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9138 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9139 
9140 	/* Use synchronous mode */
9141 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9142 	spkt->satapkt_comp = NULL;
9143 	spkt->satapkt_time = sata_default_pkt_time;
9144 
9145 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9146 
9147 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9148 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9149 
9150 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
9151 	sdinfo = sata_get_device_info(sata_hba,
9152 	    &spx->txlt_sata_pkt->satapkt_device);
9153 	if (sdinfo == NULL) {
9154 		/* we have to be carefull about the disapearing device */
9155 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9156 		rval = SATA_FAILURE;
9157 		goto cleanup;
9158 	}
9159 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9160 
9161 	/*
9162 	 * Set-up acdb. This works for atapi transport version 2 and later.
9163 	 */
9164 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9165 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9166 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9167 	scmd->satacmd_acdb[1] = 0x00;
9168 	scmd->satacmd_acdb[2] = 0x00;
9169 	scmd->satacmd_acdb[3] = 0x00;
9170 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9171 	scmd->satacmd_acdb[5] = 0x00;
9172 
9173 	sata_fixed_sense_data_preset(
9174 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9175 
9176 	/* Transfer command to HBA */
9177 	if (sata_hba_start(spx, &rval) != 0) {
9178 		/* Pkt not accepted for execution */
9179 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9180 		    "sata_get_atapi_inquiry_data: "
9181 		    "Packet not accepted for execution - ret: %02x", rval);
9182 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9183 		rval = SATA_FAILURE;
9184 		goto cleanup;
9185 	}
9186 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9187 
9188 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9189 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9190 		    "sata_get_atapi_inquiry_data: "
9191 		    "Packet completed successfully - ret: %02x", rval);
9192 		if (spx->txlt_buf_dma_handle != NULL) {
9193 			/*
9194 			 * Sync buffer. Handle is in usual place in translate
9195 			 * struct.
9196 			 */
9197 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9198 			    DDI_DMA_SYNC_FORCPU);
9199 			ASSERT(rval == DDI_SUCCESS);
9200 		}
9201 		/*
9202 		 * Normal completion - copy data into caller's buffer
9203 		 */
9204 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
9205 		    sizeof (struct scsi_inquiry));
9206 #ifdef SATA_DEBUG
9207 		if (sata_debug_flags & SATA_DBG_ATAPI) {
9208 			sata_show_inqry_data((uint8_t *)inq);
9209 		}
9210 #endif
9211 		rval = SATA_SUCCESS;
9212 	} else {
9213 		/*
9214 		 * Something went wrong - analyze return - check rqsense data
9215 		 */
9216 		rval = SATA_FAILURE;
9217 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9218 			/*
9219 			 * ARQ data hopefull show something other than NO SENSE
9220 			 */
9221 			rqsp = scmd->satacmd_rqsense;
9222 #ifdef SATA_DEBUG
9223 			if (sata_debug_flags & SATA_DBG_ATAPI) {
9224 				msg_buf[0] = '\0';
9225 				(void) snprintf(msg_buf, MAXPATHLEN,
9226 				    "ATAPI packet completion reason: %02x\n"
9227 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
9228 				    "          %02x %02x %02x %02x %02x %02x\n"
9229 				    "          %02x %02x %02x %02x %02x %02x",
9230 				    spkt->satapkt_reason,
9231 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9232 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9233 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9234 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9235 				    rqsp[16], rqsp[17]);
9236 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9237 				    "%s", msg_buf);
9238 			}
9239 #endif
9240 		} else {
9241 			switch (spkt->satapkt_reason) {
9242 			case SATA_PKT_PORT_ERROR:
9243 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9244 				    "sata_get_atapi_inquiry_data: "
9245 				    "packet reason: port error", NULL);
9246 				break;
9247 
9248 			case SATA_PKT_TIMEOUT:
9249 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9250 				    "sata_get_atapi_inquiry_data: "
9251 				    "packet reason: timeout", NULL);
9252 				break;
9253 
9254 			case SATA_PKT_ABORTED:
9255 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9256 				    "sata_get_atapi_inquiry_data: "
9257 				    "packet reason: aborted", NULL);
9258 				break;
9259 
9260 			case SATA_PKT_RESET:
9261 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9262 				    "sata_get_atapi_inquiry_data: "
9263 				    "packet reason: reset\n", NULL);
9264 				break;
9265 			default:
9266 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9267 				    "sata_get_atapi_inquiry_data: "
9268 				    "invalid packet reason: %02x\n",
9269 				    spkt->satapkt_reason);
9270 				break;
9271 			}
9272 		}
9273 	}
9274 cleanup:
9275 	sata_free_local_buffer(spx);
9276 	sata_pkt_free(spx);
9277 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9278 	return (rval);
9279 }
9280 
9281 
9282 
9283 
9284 
9285 #if 0
9286 #ifdef SATA_DEBUG
9287 
9288 /*
9289  * Test ATAPI packet command.
9290  * Single threaded test: send packet command in synch mode, process completion
9291  *
9292  */
9293 static void
9294 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
9295 {
9296 	sata_pkt_txlate_t *spx;
9297 	sata_pkt_t *spkt;
9298 	struct buf *bp;
9299 	sata_device_t sata_device;
9300 	sata_drive_info_t *sdinfo;
9301 	sata_cmd_t *scmd;
9302 	int rval;
9303 	uint8_t *rqsp;
9304 
9305 	ASSERT(sata_hba_inst != NULL);
9306 	sata_device.satadev_addr.cport = cport;
9307 	sata_device.satadev_addr.pmport = 0;
9308 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
9309 	sata_device.satadev_rev = SATA_DEVICE_REV;
9310 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9311 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
9312 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9313 	if (sdinfo == NULL) {
9314 		sata_log(sata_hba_inst, CE_WARN,
9315 		    "sata_test_atapi_packet_command: "
9316 		    "no device info for cport %d",
9317 		    sata_device.satadev_addr.cport);
9318 		return;
9319 	}
9320 
9321 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9322 	spx->txlt_sata_hba_inst = sata_hba_inst;
9323 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9324 	spkt = sata_pkt_alloc(spx, NULL);
9325 	if (spkt == NULL) {
9326 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9327 		return;
9328 	}
9329 	/* address is needed now */
9330 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
9331 
9332 	/* 1024k buffer */
9333 	bp = sata_alloc_local_buffer(spx, 1024);
9334 	if (bp == NULL) {
9335 		sata_pkt_free(spx);
9336 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9337 		sata_log(sata_hba_inst, CE_WARN,
9338 		    "sata_test_atapi_packet_command: "
9339 		    "cannot allocate data buffer");
9340 		return;
9341 	}
9342 	bp_mapin(bp); /* make data buffer accessible */
9343 
9344 	scmd = &spkt->satapkt_cmd;
9345 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9346 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9347 
9348 	/* Use synchronous mode */
9349 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9350 
9351 	/* Synchronous mode, no callback - may be changed by the caller */
9352 	spkt->satapkt_comp = NULL;
9353 	spkt->satapkt_time = sata_default_pkt_time;
9354 
9355 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9356 
9357 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9358 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9359 
9360 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9361 
9362 	/* Set-up acdb. */
9363 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9364 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9365 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9366 	scmd->satacmd_acdb[1] = 0x00;
9367 	scmd->satacmd_acdb[2] = 0x00;
9368 	scmd->satacmd_acdb[3] = 0x00;
9369 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9370 	scmd->satacmd_acdb[5] = 0x00;
9371 
9372 	sata_fixed_sense_data_preset(
9373 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9374 
9375 	/* Transfer command to HBA */
9376 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9377 	if (sata_hba_start(spx, &rval) != 0) {
9378 		/* Pkt not accepted for execution */
9379 		sata_log(sata_hba_inst, CE_WARN,
9380 		    "sata_test_atapi_packet_command: "
9381 		    "Packet not accepted for execution - ret: %02x", rval);
9382 		mutex_exit(
9383 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9384 		goto cleanup;
9385 	}
9386 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9387 
9388 	if (spx->txlt_buf_dma_handle != NULL) {
9389 		/*
9390 		 * Sync buffer. Handle is in usual place in translate struct.
9391 		 */
9392 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9393 		    DDI_DMA_SYNC_FORCPU);
9394 		ASSERT(rval == DDI_SUCCESS);
9395 	}
9396 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9397 		sata_log(sata_hba_inst, CE_WARN,
9398 		    "sata_test_atapi_packet_command: "
9399 		    "Packet completed successfully");
9400 		/*
9401 		 * Normal completion - show inquiry data
9402 		 */
9403 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
9404 	} else {
9405 		/*
9406 		 * Something went wrong - analyze return - check rqsense data
9407 		 */
9408 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9409 			/*
9410 			 * ARQ data hopefull show something other than NO SENSE
9411 			 */
9412 			rqsp = scmd->satacmd_rqsense;
9413 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9414 			    "ATAPI packet completion reason: %02x\n"
9415 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9416 			    "          %02x %02x %02x %02x %02x %02x "
9417 			    "          %02x %02x %02x %02x %02x %02x\n",
9418 			    spkt->satapkt_reason,
9419 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9420 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9421 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9422 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9423 			    rqsp[16], rqsp[17]);
9424 		} else {
9425 			switch (spkt->satapkt_reason) {
9426 			case SATA_PKT_PORT_ERROR:
9427 				sata_log(sata_hba_inst, CE_WARN,
9428 				    "sata_test_atapi_packet_command: "
9429 				    "packet reason: port error\n");
9430 				break;
9431 
9432 			case SATA_PKT_TIMEOUT:
9433 				sata_log(sata_hba_inst, CE_WARN,
9434 				    "sata_test_atapi_packet_command: "
9435 				    "packet reason: timeout\n");
9436 				break;
9437 
9438 			case SATA_PKT_ABORTED:
9439 				sata_log(sata_hba_inst, CE_WARN,
9440 				    "sata_test_atapi_packet_command: "
9441 				    "packet reason: aborted\n");
9442 				break;
9443 
9444 			case SATA_PKT_RESET:
9445 				sata_log(sata_hba_inst, CE_WARN,
9446 				    "sata_test_atapi_packet_command: "
9447 				    "packet reason: reset\n");
9448 				break;
9449 			default:
9450 				sata_log(sata_hba_inst, CE_WARN,
9451 				    "sata_test_atapi_packet_command: "
9452 				    "invalid packet reason: %02x\n",
9453 				    spkt->satapkt_reason);
9454 				break;
9455 			}
9456 		}
9457 	}
9458 cleanup:
9459 	sata_free_local_buffer(spx);
9460 	sata_pkt_free(spx);
9461 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9462 }
9463 
9464 #endif /* SATA_DEBUG */
9465 #endif /* 1 */
9466 
9467 
9468 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
9469 
9470 /*
9471  * Validate sata_tran info
9472  * SATA_FAILURE returns if structure is inconsistent or structure revision
9473  * does not match one used by the framework.
9474  *
9475  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
9476  * required function pointers.
9477  * Returns SATA_FAILURE otherwise.
9478  */
9479 static int
9480 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
9481 {
9482 	/*
9483 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
9484 	 * of the SATA interface.
9485 	 */
9486 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
9487 		sata_log(NULL, CE_WARN,
9488 		    "sata: invalid sata_hba_tran version %d for driver %s",
9489 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
9490 		return (SATA_FAILURE);
9491 	}
9492 
9493 	if (dip != sata_tran->sata_tran_hba_dip) {
9494 		SATA_LOG_D((NULL, CE_WARN,
9495 		    "sata: inconsistent sata_tran_hba_dip "
9496 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
9497 		return (SATA_FAILURE);
9498 	}
9499 
9500 	if (sata_tran->sata_tran_probe_port == NULL ||
9501 	    sata_tran->sata_tran_start == NULL ||
9502 	    sata_tran->sata_tran_abort == NULL ||
9503 	    sata_tran->sata_tran_reset_dport == NULL ||
9504 	    sata_tran->sata_tran_hotplug_ops == NULL ||
9505 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
9506 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
9507 	    NULL) {
9508 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
9509 		    "required functions"));
9510 	}
9511 	return (SATA_SUCCESS);
9512 }
9513 
9514 /*
9515  * Remove HBA instance from sata_hba_list.
9516  */
9517 static void
9518 sata_remove_hba_instance(dev_info_t *dip)
9519 {
9520 	sata_hba_inst_t	*sata_hba_inst;
9521 
9522 	mutex_enter(&sata_mutex);
9523 	for (sata_hba_inst = sata_hba_list;
9524 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
9525 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9526 		if (sata_hba_inst->satahba_dip == dip)
9527 			break;
9528 	}
9529 
9530 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
9531 #ifdef SATA_DEBUG
9532 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
9533 		    "unknown HBA instance\n");
9534 #endif
9535 		ASSERT(FALSE);
9536 	}
9537 	if (sata_hba_inst == sata_hba_list) {
9538 		sata_hba_list = sata_hba_inst->satahba_next;
9539 		if (sata_hba_list) {
9540 			sata_hba_list->satahba_prev =
9541 			    (struct sata_hba_inst *)NULL;
9542 		}
9543 		if (sata_hba_inst == sata_hba_list_tail) {
9544 			sata_hba_list_tail = NULL;
9545 		}
9546 	} else if (sata_hba_inst == sata_hba_list_tail) {
9547 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
9548 		if (sata_hba_list_tail) {
9549 			sata_hba_list_tail->satahba_next =
9550 			    (struct sata_hba_inst *)NULL;
9551 		}
9552 	} else {
9553 		sata_hba_inst->satahba_prev->satahba_next =
9554 		    sata_hba_inst->satahba_next;
9555 		sata_hba_inst->satahba_next->satahba_prev =
9556 		    sata_hba_inst->satahba_prev;
9557 	}
9558 	mutex_exit(&sata_mutex);
9559 }
9560 
9561 /*
9562  * Probe all SATA ports of the specified HBA instance.
9563  * The assumption is that there are no target and attachment point minor nodes
9564  * created by the boot subsystems, so we do not need to prune device tree.
9565  *
9566  * This function is called only from sata_hba_attach(). It does not have to
9567  * be protected by controller mutex, because the hba_attached flag is not set
9568  * yet and no one would be touching this HBA instance other than this thread.
9569  * Determines if port is active and what type of the device is attached
9570  * (if any). Allocates necessary structures for each port.
9571  *
9572  * An AP (Attachement Point) node is created for each SATA device port even
9573  * when there is no device attached.
9574  */
9575 
9576 static 	void
9577 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
9578 {
9579 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9580 	int			ncport;
9581 	sata_cport_info_t 	*cportinfo;
9582 	sata_drive_info_t	*drive;
9583 	sata_device_t		sata_device;
9584 	int			rval;
9585 	dev_t			minor_number;
9586 	char			name[16];
9587 	clock_t			start_time, cur_time;
9588 
9589 	/*
9590 	 * Probe controller ports first, to find port status and
9591 	 * any port multiplier attached.
9592 	 */
9593 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
9594 		/* allocate cport structure */
9595 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
9596 		ASSERT(cportinfo != NULL);
9597 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
9598 
9599 		mutex_enter(&cportinfo->cport_mutex);
9600 
9601 		cportinfo->cport_addr.cport = ncport;
9602 		cportinfo->cport_addr.pmport = 0;
9603 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
9604 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
9605 		cportinfo->cport_state |= SATA_STATE_PROBING;
9606 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
9607 
9608 		/*
9609 		 * Regardless if a port is usable or not, create
9610 		 * an attachment point
9611 		 */
9612 		mutex_exit(&cportinfo->cport_mutex);
9613 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
9614 		    ncport, 0, SATA_ADDR_CPORT);
9615 		(void) sprintf(name, "%d", ncport);
9616 		if (ddi_create_minor_node(dip, name, S_IFCHR,
9617 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
9618 		    DDI_SUCCESS) {
9619 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
9620 			    "cannot create SATA attachment point for port %d",
9621 			    ncport);
9622 		}
9623 
9624 		/* Probe port */
9625 		start_time = ddi_get_lbolt();
9626 	reprobe_cport:
9627 		sata_device.satadev_addr.cport = ncport;
9628 		sata_device.satadev_addr.pmport = 0;
9629 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
9630 		sata_device.satadev_rev = SATA_DEVICE_REV;
9631 
9632 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9633 		    (dip, &sata_device);
9634 
9635 		mutex_enter(&cportinfo->cport_mutex);
9636 		cportinfo->cport_scr = sata_device.satadev_scr;
9637 		if (rval != SATA_SUCCESS) {
9638 			/* Something went wrong? Fail the port */
9639 			cportinfo->cport_state = SATA_PSTATE_FAILED;
9640 			mutex_exit(&cportinfo->cport_mutex);
9641 			continue;
9642 		}
9643 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
9644 		cportinfo->cport_state |= SATA_STATE_PROBED;
9645 		cportinfo->cport_dev_type = sata_device.satadev_type;
9646 
9647 		cportinfo->cport_state |= SATA_STATE_READY;
9648 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
9649 			mutex_exit(&cportinfo->cport_mutex);
9650 			continue;
9651 		}
9652 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
9653 			/*
9654 			 * There is some device attached.
9655 			 * Allocate device info structure
9656 			 */
9657 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
9658 				mutex_exit(&cportinfo->cport_mutex);
9659 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
9660 				    kmem_zalloc(sizeof (sata_drive_info_t),
9661 				    KM_SLEEP);
9662 				mutex_enter(&cportinfo->cport_mutex);
9663 			}
9664 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
9665 			drive->satadrv_addr = cportinfo->cport_addr;
9666 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
9667 			drive->satadrv_type = cportinfo->cport_dev_type;
9668 			drive->satadrv_state = SATA_STATE_UNKNOWN;
9669 
9670 			mutex_exit(&cportinfo->cport_mutex);
9671 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
9672 			    SATA_SUCCESS) {
9673 				/*
9674 				 * Plugged device was not correctly identified.
9675 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
9676 				 */
9677 				cur_time = ddi_get_lbolt();
9678 				if ((cur_time - start_time) <
9679 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
9680 					/* sleep for a while */
9681 					delay(drv_usectohz(
9682 					    SATA_DEV_RETRY_DLY));
9683 					goto reprobe_cport;
9684 				}
9685 			}
9686 		} else { /* SATA_DTYPE_PMULT */
9687 			mutex_exit(&cportinfo->cport_mutex);
9688 
9689 			/* Allocate sata_pmult_info and sata_pmport_info */
9690 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
9691 			    SATA_SUCCESS)
9692 				continue;
9693 
9694 			/* Log the information of the port multiplier */
9695 			sata_show_pmult_info(sata_hba_inst, &sata_device);
9696 
9697 			/* Probe its pmports */
9698 			sata_probe_pmports(sata_hba_inst, ncport);
9699 		}
9700 	}
9701 }
9702 
9703 /*
9704  * Probe all device ports behind a port multiplier.
9705  *
9706  * PMult-related structure should be allocated before by sata_alloc_pmult().
9707  *
9708  * NOTE1: Only called from sata_probe_ports()
9709  * NOTE2: No mutex should be hold.
9710  */
9711 static void
9712 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
9713 {
9714 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9715 	sata_pmult_info_t	*pmultinfo = NULL;
9716 	sata_pmport_info_t 	*pmportinfo = NULL;
9717 	sata_drive_info_t	*drive = NULL;
9718 	sata_device_t		sata_device;
9719 
9720 	clock_t			start_time, cur_time;
9721 	int			npmport;
9722 	int			rval;
9723 
9724 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
9725 
9726 	/* Probe Port Multiplier ports */
9727 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
9728 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
9729 		start_time = ddi_get_lbolt();
9730 reprobe_pmport:
9731 		sata_device.satadev_addr.cport = ncport;
9732 		sata_device.satadev_addr.pmport = npmport;
9733 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
9734 		sata_device.satadev_rev = SATA_DEVICE_REV;
9735 
9736 		/* Let HBA driver probe it. */
9737 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9738 		    (dip, &sata_device);
9739 		mutex_enter(&pmportinfo->pmport_mutex);
9740 
9741 		pmportinfo->pmport_scr = sata_device.satadev_scr;
9742 
9743 		if (rval != SATA_SUCCESS) {
9744 			pmportinfo->pmport_state =
9745 			    SATA_PSTATE_FAILED;
9746 			mutex_exit(&pmportinfo->pmport_mutex);
9747 			continue;
9748 		}
9749 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
9750 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
9751 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
9752 
9753 		pmportinfo->pmport_state |= SATA_STATE_READY;
9754 		if (pmportinfo->pmport_dev_type ==
9755 		    SATA_DTYPE_NONE) {
9756 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
9757 			    "no device found at port %d:%d", ncport, npmport);
9758 			mutex_exit(&pmportinfo->pmport_mutex);
9759 			continue;
9760 		}
9761 		/* Port multipliers cannot be chained */
9762 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
9763 		/*
9764 		 * There is something attached to Port
9765 		 * Multiplier device port
9766 		 * Allocate device info structure
9767 		 */
9768 		if (pmportinfo->pmport_sata_drive == NULL) {
9769 			mutex_exit(&pmportinfo->pmport_mutex);
9770 			pmportinfo->pmport_sata_drive =
9771 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
9772 			mutex_enter(&pmportinfo->pmport_mutex);
9773 		}
9774 		drive = pmportinfo->pmport_sata_drive;
9775 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
9776 		drive->satadrv_addr.pmport = npmport;
9777 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
9778 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
9779 		drive->satadrv_state = SATA_STATE_UNKNOWN;
9780 
9781 		mutex_exit(&pmportinfo->pmport_mutex);
9782 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
9783 
9784 		if (rval != SATA_SUCCESS) {
9785 			/*
9786 			 * Plugged device was not correctly identified.
9787 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
9788 			 */
9789 			cur_time = ddi_get_lbolt();
9790 			if ((cur_time - start_time) < drv_usectohz(
9791 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
9792 				/* sleep for a while */
9793 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
9794 				goto reprobe_pmport;
9795 			}
9796 		}
9797 	}
9798 }
9799 
9800 /*
9801  * Add SATA device for specified HBA instance & port (SCSI target
9802  * device nodes).
9803  * This function is called (indirectly) only from sata_hba_attach().
9804  * A target node is created when there is a supported type device attached,
9805  * but may be removed if it cannot be put online.
9806  *
9807  * This function cannot be called from an interrupt context.
9808  *
9809  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
9810  *
9811  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
9812  * device identification failed - adding a device could be retried.
9813  *
9814  */
9815 static 	int
9816 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
9817     sata_device_t *sata_device)
9818 {
9819 	sata_cport_info_t 	*cportinfo;
9820 	sata_pmult_info_t	*pminfo;
9821 	sata_pmport_info_t	*pmportinfo;
9822 	dev_info_t		*cdip;		/* child dip */
9823 	sata_address_t		*saddr = &sata_device->satadev_addr;
9824 	uint8_t			cport, pmport;
9825 	int			rval;
9826 
9827 	cport = saddr->cport;
9828 	pmport = saddr->pmport;
9829 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
9830 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
9831 
9832 	/*
9833 	 * Some device is attached to a controller port.
9834 	 * We rely on controllers distinquishing between no-device,
9835 	 * attached port multiplier and other kind of attached device.
9836 	 * We need to get Identify Device data and determine
9837 	 * positively the dev type before trying to attach
9838 	 * the target driver.
9839 	 */
9840 	sata_device->satadev_rev = SATA_DEVICE_REV;
9841 	switch (saddr->qual) {
9842 	case SATA_ADDR_CPORT:
9843 		/*
9844 		 * Add a non-port-multiplier device at controller port.
9845 		 */
9846 		saddr->qual = SATA_ADDR_DCPORT;
9847 
9848 		rval = sata_probe_device(sata_hba_inst, sata_device);
9849 		if (rval != SATA_SUCCESS ||
9850 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
9851 			return (SATA_FAILURE);
9852 
9853 		mutex_enter(&cportinfo->cport_mutex);
9854 		sata_show_drive_info(sata_hba_inst,
9855 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
9856 
9857 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
9858 			/*
9859 			 * Could not determine device type or
9860 			 * a device is not supported.
9861 			 * Degrade this device to unknown.
9862 			 */
9863 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
9864 			mutex_exit(&cportinfo->cport_mutex);
9865 			return (SATA_SUCCESS);
9866 		}
9867 		cportinfo->cport_dev_type = sata_device->satadev_type;
9868 		cportinfo->cport_tgtnode_clean = B_TRUE;
9869 		mutex_exit(&cportinfo->cport_mutex);
9870 
9871 		/*
9872 		 * Initialize device to the desired state. Even if it
9873 		 * fails, the device will still attach but syslog
9874 		 * will show the warning.
9875 		 */
9876 		if (sata_initialize_device(sata_hba_inst,
9877 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
9878 			/* Retry */
9879 			rval = sata_initialize_device(sata_hba_inst,
9880 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
9881 
9882 			if (rval == SATA_RETRY)
9883 				sata_log(sata_hba_inst, CE_WARN,
9884 				    "SATA device at port %d - "
9885 				    "default device features could not be set."
9886 				    " Device may not operate as expected.",
9887 				    cport);
9888 		}
9889 
9890 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
9891 		if (cdip == NULL) {
9892 			/*
9893 			 * Attaching target node failed.
9894 			 * We retain sata_drive_info structure...
9895 			 */
9896 			return (SATA_SUCCESS);
9897 		}
9898 
9899 		mutex_enter(&cportinfo->cport_mutex);
9900 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
9901 		    satadrv_state = SATA_STATE_READY;
9902 		mutex_exit(&cportinfo->cport_mutex);
9903 
9904 		break;
9905 
9906 	case SATA_ADDR_PMPORT:
9907 		saddr->qual = SATA_ADDR_DPMPORT;
9908 
9909 		mutex_enter(&cportinfo->cport_mutex);
9910 		/* It must be a Port Multiplier at the controller port */
9911 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
9912 
9913 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
9914 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
9915 		mutex_exit(&cportinfo->cport_mutex);
9916 
9917 		rval = sata_probe_device(sata_hba_inst, sata_device);
9918 		if (rval != SATA_SUCCESS ||
9919 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
9920 			return (SATA_FAILURE);
9921 		}
9922 
9923 		mutex_enter(&pmportinfo->pmport_mutex);
9924 		sata_show_drive_info(sata_hba_inst,
9925 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
9926 
9927 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
9928 			/*
9929 			 * Could not determine device type.
9930 			 * Degrade this device to unknown.
9931 			 */
9932 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
9933 			mutex_exit(&pmportinfo->pmport_mutex);
9934 			return (SATA_SUCCESS);
9935 		}
9936 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
9937 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
9938 		mutex_exit(&pmportinfo->pmport_mutex);
9939 
9940 		/*
9941 		 * Initialize device to the desired state.
9942 		 * Even if it fails, the device will still
9943 		 * attach but syslog will show the warning.
9944 		 */
9945 		if (sata_initialize_device(sata_hba_inst,
9946 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
9947 			/* Retry */
9948 			rval = sata_initialize_device(sata_hba_inst,
9949 			    pmportinfo->pmport_sata_drive);
9950 
9951 			if (rval == SATA_RETRY)
9952 				sata_log(sata_hba_inst, CE_WARN,
9953 				    "SATA device at port %d:%d - "
9954 				    "default device features could not be set."
9955 				    " Device may not operate as expected.",
9956 				    cport, pmport);
9957 		}
9958 
9959 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
9960 		if (cdip == NULL) {
9961 			/*
9962 			 * Attaching target node failed.
9963 			 * We retain sata_drive_info structure...
9964 			 */
9965 			return (SATA_SUCCESS);
9966 		}
9967 		mutex_enter(&pmportinfo->pmport_mutex);
9968 		pmportinfo->pmport_sata_drive->satadrv_state |=
9969 		    SATA_STATE_READY;
9970 		mutex_exit(&pmportinfo->pmport_mutex);
9971 
9972 		break;
9973 
9974 	default:
9975 		return (SATA_FAILURE);
9976 	}
9977 
9978 	return (SATA_SUCCESS);
9979 }
9980 
9981 /*
9982  * Clean up target node at specific address.
9983  *
9984  * NOTE: No Mutex should be hold.
9985  */
9986 static int
9987 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
9988     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
9989 {
9990 	uint8_t cport, pmport, qual;
9991 	dev_info_t *tdip;
9992 
9993 	cport = sata_device->satadev_addr.cport;
9994 	pmport = sata_device->satadev_addr.pmport;
9995 	qual = sata_device->satadev_addr.qual;
9996 
9997 	if (qual == SATA_ADDR_DCPORT) {
9998 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9999 		    "sata_hba_ioctl: disconnect device at port %d", cport));
10000 	} else {
10001 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10002 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10003 		    cport, pmport));
10004 	}
10005 
10006 	/* We are addressing attached device, not a port */
10007 	sata_device->satadev_addr.qual =
10008 	    sdinfo->satadrv_addr.qual;
10009 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10010 	    &sata_device->satadev_addr);
10011 	if (tdip != NULL && ndi_devi_offline(tdip,
10012 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10013 		/*
10014 		 * Problem :
10015 		 * The target node remained attached.
10016 		 * This happens when the device file was open
10017 		 * or a node was waiting for resources.
10018 		 * Cannot do anything about it.
10019 		 */
10020 		if (qual == SATA_ADDR_DCPORT) {
10021 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10022 			    "sata_hba_ioctl: disconnect: could "
10023 			    "not unconfigure device before "
10024 			    "disconnecting the SATA port %d",
10025 			    cport));
10026 		} else {
10027 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10028 			    "sata_hba_ioctl: disconnect: could "
10029 			    "not unconfigure device before "
10030 			    "disconnecting the SATA port %d:%d",
10031 			    cport, pmport));
10032 		}
10033 		/*
10034 		 * Set DEVICE REMOVED state in the target
10035 		 * node. It will prevent access to the device
10036 		 * even when a new device is attached, until
10037 		 * the old target node is released, removed and
10038 		 * recreated for a new  device.
10039 		 */
10040 		sata_set_device_removed(tdip);
10041 
10042 		/*
10043 		 * Instruct event daemon to try the target
10044 		 * node cleanup later.
10045 		 */
10046 		sata_set_target_node_cleanup(
10047 		    sata_hba_inst, &sata_device->satadev_addr);
10048 	}
10049 
10050 
10051 	return (SATA_SUCCESS);
10052 }
10053 
10054 
10055 /*
10056  * Create scsi target node for attached device, create node properties and
10057  * attach the node.
10058  * The node could be removed if the device onlining fails.
10059  *
10060  * A dev_info_t pointer is returned if operation is successful, NULL is
10061  * returned otherwise.
10062  */
10063 
10064 static dev_info_t *
10065 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10066 			sata_address_t *sata_addr)
10067 {
10068 	dev_info_t *cdip = NULL;
10069 	int rval;
10070 	char *nname = NULL;
10071 	char **compatible = NULL;
10072 	int ncompatible;
10073 	struct scsi_inquiry inq;
10074 	sata_device_t sata_device;
10075 	sata_drive_info_t *sdinfo;
10076 	int target;
10077 	int i;
10078 
10079 	sata_device.satadev_rev = SATA_DEVICE_REV;
10080 	sata_device.satadev_addr = *sata_addr;
10081 
10082 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10083 
10084 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10085 
10086 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10087 	    sata_addr->pmport, sata_addr->qual);
10088 
10089 	if (sdinfo == NULL) {
10090 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10091 		    sata_addr->cport)));
10092 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10093 		    "sata_create_target_node: no sdinfo for target %x",
10094 		    target));
10095 		return (NULL);
10096 	}
10097 
10098 	/*
10099 	 * create or get scsi inquiry data, expected by
10100 	 * scsi_hba_nodename_compatible_get()
10101 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10102 	 * ATAPI devices respond directly to Inquiry request.
10103 	 */
10104 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10105 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10106 		    (uint8_t *)&inq);
10107 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10108 		    sata_addr->cport)));
10109 	} else { /* Assume supported ATAPI device */
10110 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10111 		    sata_addr->cport)));
10112 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10113 		    &inq) == SATA_FAILURE)
10114 			return (NULL);
10115 		/*
10116 		 * Save supported ATAPI transport version
10117 		 */
10118 		sdinfo->satadrv_atapi_trans_ver =
10119 		    SATA_ATAPI_TRANS_VERSION(&inq);
10120 	}
10121 
10122 	/* determine the node name and compatible */
10123 	scsi_hba_nodename_compatible_get(&inq, NULL,
10124 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10125 
10126 #ifdef SATA_DEBUG
10127 	if (sata_debug_flags & SATA_DBG_NODES) {
10128 		if (nname == NULL) {
10129 			cmn_err(CE_NOTE, "sata_create_target_node: "
10130 			    "cannot determine nodename for target %d\n",
10131 			    target);
10132 		} else {
10133 			cmn_err(CE_WARN, "sata_create_target_node: "
10134 			    "target %d nodename: %s\n", target, nname);
10135 		}
10136 		if (compatible == NULL) {
10137 			cmn_err(CE_WARN,
10138 			    "sata_create_target_node: no compatible name\n");
10139 		} else {
10140 			for (i = 0; i < ncompatible; i++) {
10141 				cmn_err(CE_WARN, "sata_create_target_node: "
10142 				    "compatible name: %s\n", compatible[i]);
10143 			}
10144 		}
10145 	}
10146 #endif
10147 
10148 	/* if nodename can't be determined, log error and exit */
10149 	if (nname == NULL) {
10150 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10151 		    "sata_create_target_node: cannot determine nodename "
10152 		    "for target %d\n", target));
10153 		scsi_hba_nodename_compatible_free(nname, compatible);
10154 		return (NULL);
10155 	}
10156 	/*
10157 	 * Create scsi target node
10158 	 */
10159 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
10160 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10161 	    "device-type", "scsi");
10162 
10163 	if (rval != DDI_PROP_SUCCESS) {
10164 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10165 		    "updating device_type prop failed %d", rval));
10166 		goto fail;
10167 	}
10168 
10169 	/*
10170 	 * Create target node properties: target & lun
10171 	 */
10172 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
10173 	if (rval != DDI_PROP_SUCCESS) {
10174 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10175 		    "updating target prop failed %d", rval));
10176 		goto fail;
10177 	}
10178 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
10179 	if (rval != DDI_PROP_SUCCESS) {
10180 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10181 		    "updating target prop failed %d", rval));
10182 		goto fail;
10183 	}
10184 
10185 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10186 		/*
10187 		 * Add "variant" property
10188 		 */
10189 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10190 		    "variant", "atapi");
10191 		if (rval != DDI_PROP_SUCCESS) {
10192 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10193 			    "sata_create_target_node: variant atapi "
10194 			    "property could not be created: %d", rval));
10195 			goto fail;
10196 		}
10197 	}
10198 	/* decorate the node with compatible */
10199 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
10200 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
10201 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10202 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
10203 		    (void *)cdip));
10204 		goto fail;
10205 	}
10206 
10207 
10208 	/*
10209 	 * Now, try to attach the driver. If probing of the device fails,
10210 	 * the target node may be removed
10211 	 */
10212 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
10213 
10214 	scsi_hba_nodename_compatible_free(nname, compatible);
10215 
10216 	if (rval == NDI_SUCCESS)
10217 		return (cdip);
10218 
10219 	/* target node was removed - are we sure? */
10220 	return (NULL);
10221 
10222 fail:
10223 	scsi_hba_nodename_compatible_free(nname, compatible);
10224 	ddi_prop_remove_all(cdip);
10225 	rval = ndi_devi_free(cdip);
10226 	if (rval != NDI_SUCCESS) {
10227 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10228 		    "node removal failed %d", rval));
10229 	}
10230 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
10231 	    "cannot create target node for SATA device at port %d",
10232 	    sata_addr->cport);
10233 	return (NULL);
10234 }
10235 
10236 /*
10237  * Remove a target node.
10238  */
10239 static void
10240 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
10241 			sata_address_t *sata_addr)
10242 {
10243 	dev_info_t *tdip;
10244 	uint8_t cport = sata_addr->cport;
10245 	uint8_t pmport = sata_addr->pmport;
10246 	uint8_t qual = sata_addr->qual;
10247 
10248 	/* Note the sata daemon uses the address of the port/pmport */
10249 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10250 
10251 	/* Remove target node */
10252 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
10253 	if (tdip != NULL) {
10254 		/*
10255 		 * Target node exists.  Unconfigure device
10256 		 * then remove the target node (one ndi
10257 		 * operation).
10258 		 */
10259 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10260 			/*
10261 			 * PROBLEM - no device, but target node remained. This
10262 			 * happens when the file was open or node was waiting
10263 			 * for resources.
10264 			 */
10265 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10266 			    "sata_remove_target_node: "
10267 			    "Failed to remove target node for "
10268 			    "detached SATA device."));
10269 			/*
10270 			 * Set target node state to DEVI_DEVICE_REMOVED. But
10271 			 * re-check first that the node still exists.
10272 			 */
10273 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
10274 			    cport, pmport);
10275 			if (tdip != NULL) {
10276 				sata_set_device_removed(tdip);
10277 				/*
10278 				 * Instruct event daemon to retry the cleanup
10279 				 * later.
10280 				 */
10281 				sata_set_target_node_cleanup(sata_hba_inst,
10282 				    sata_addr);
10283 			}
10284 		}
10285 
10286 		if (qual == SATA_ADDR_CPORT)
10287 			sata_log(sata_hba_inst, CE_WARN,
10288 			    "SATA device detached at port %d", cport);
10289 		else
10290 			sata_log(sata_hba_inst, CE_WARN,
10291 			    "SATA device detached at port %d:%d",
10292 			    cport, pmport);
10293 	}
10294 #ifdef SATA_DEBUG
10295 	else {
10296 		if (qual == SATA_ADDR_CPORT)
10297 			sata_log(sata_hba_inst, CE_WARN,
10298 			    "target node not found at port %d", cport);
10299 		else
10300 			sata_log(sata_hba_inst, CE_WARN,
10301 			    "target node not found at port %d:%d",
10302 			    cport, pmport);
10303 	}
10304 #endif
10305 }
10306 
10307 
10308 /*
10309  * Re-probe sata port, check for a device and attach info
10310  * structures when necessary. Identify Device data is fetched, if possible.
10311  * Assumption: sata address is already validated.
10312  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10313  * the presence of a device and its type.
10314  *
10315  * flag arg specifies that the function should try multiple times to identify
10316  * device type and to initialize it, or it should return immediately on failure.
10317  * SATA_DEV_IDENTIFY_RETRY - retry
10318  * SATA_DEV_IDENTIFY_NORETRY - no retry
10319  *
10320  * SATA_FAILURE is returned if one of the operations failed.
10321  *
10322  * This function cannot be called in interrupt context - it may sleep.
10323  *
10324  * Note: Port multiplier is supported.
10325  */
10326 static int
10327 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10328     int flag)
10329 {
10330 	sata_cport_info_t *cportinfo;
10331 	sata_pmult_info_t *pmultinfo;
10332 	sata_drive_info_t *sdinfo, *osdinfo;
10333 	boolean_t init_device = B_FALSE;
10334 	int prev_device_type = SATA_DTYPE_NONE;
10335 	int prev_device_settings = 0;
10336 	int prev_device_state = 0;
10337 	clock_t start_time;
10338 	int retry = B_FALSE;
10339 	uint8_t cport = sata_device->satadev_addr.cport;
10340 	int rval_probe, rval_init;
10341 
10342 	/*
10343 	 * If target is pmport, sata_reprobe_pmport() will handle it.
10344 	 */
10345 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
10346 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
10347 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
10348 
10349 	/* We only care about host sata cport for now */
10350 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10351 	    sata_device->satadev_addr.cport);
10352 
10353 	/*
10354 	 * If a port multiplier was previously attached (we have no idea it
10355 	 * still there or not), sata_reprobe_pmult() will handle it.
10356 	 */
10357 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
10358 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
10359 
10360 	/* Store sata_drive_info when a non-pmult device was attached. */
10361 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10362 	if (osdinfo != NULL) {
10363 		/*
10364 		 * We are re-probing port with a previously attached device.
10365 		 * Save previous device type and settings.
10366 		 */
10367 		prev_device_type = cportinfo->cport_dev_type;
10368 		prev_device_settings = osdinfo->satadrv_settings;
10369 		prev_device_state = osdinfo->satadrv_state;
10370 	}
10371 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
10372 		start_time = ddi_get_lbolt();
10373 		retry = B_TRUE;
10374 	}
10375 retry_probe:
10376 
10377 	/* probe port */
10378 	mutex_enter(&cportinfo->cport_mutex);
10379 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10380 	cportinfo->cport_state |= SATA_STATE_PROBING;
10381 	mutex_exit(&cportinfo->cport_mutex);
10382 
10383 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10384 	    (SATA_DIP(sata_hba_inst), sata_device);
10385 
10386 	mutex_enter(&cportinfo->cport_mutex);
10387 	if (rval_probe != SATA_SUCCESS) {
10388 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10389 		mutex_exit(&cportinfo->cport_mutex);
10390 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
10391 		    "SATA port %d probing failed",
10392 		    cportinfo->cport_addr.cport));
10393 		return (SATA_FAILURE);
10394 	}
10395 
10396 	/*
10397 	 * update sata port state and set device type
10398 	 */
10399 	sata_update_port_info(sata_hba_inst, sata_device);
10400 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10401 
10402 	/*
10403 	 * Sanity check - Port is active? Is the link active?
10404 	 * Is there any device attached?
10405 	 */
10406 	if ((cportinfo->cport_state &
10407 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10408 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10409 	    SATA_PORT_DEVLINK_UP) {
10410 		/*
10411 		 * Port in non-usable state or no link active/no device.
10412 		 * Free info structure if necessary (direct attached drive
10413 		 * only, for now!
10414 		 */
10415 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10416 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10417 		/* Add here differentiation for device attached or not */
10418 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10419 		mutex_exit(&cportinfo->cport_mutex);
10420 		if (sdinfo != NULL)
10421 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10422 		return (SATA_SUCCESS);
10423 	}
10424 
10425 	cportinfo->cport_state |= SATA_STATE_READY;
10426 	cportinfo->cport_state |= SATA_STATE_PROBED;
10427 
10428 	cportinfo->cport_dev_type = sata_device->satadev_type;
10429 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10430 
10431 	/*
10432 	 * If we are re-probing the port, there may be
10433 	 * sata_drive_info structure attached
10434 	 */
10435 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10436 
10437 		/*
10438 		 * There is no device, so remove device info structure,
10439 		 * if necessary.
10440 		 */
10441 		/* Device change: Drive -> None */
10442 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10443 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10444 		if (sdinfo != NULL) {
10445 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10446 			sata_log(sata_hba_inst, CE_WARN,
10447 			    "SATA device detached "
10448 			    "from port %d", cportinfo->cport_addr.cport);
10449 		}
10450 		mutex_exit(&cportinfo->cport_mutex);
10451 		return (SATA_SUCCESS);
10452 
10453 	}
10454 
10455 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10456 
10457 		/* Device (may) change: Drive -> Drive */
10458 		if (sdinfo == NULL) {
10459 			/*
10460 			 * There is some device attached, but there is
10461 			 * no sata_drive_info structure - allocate one
10462 			 */
10463 			mutex_exit(&cportinfo->cport_mutex);
10464 			sdinfo = kmem_zalloc(
10465 			    sizeof (sata_drive_info_t), KM_SLEEP);
10466 			mutex_enter(&cportinfo->cport_mutex);
10467 			/*
10468 			 * Recheck, that the port state did not change when we
10469 			 * released mutex.
10470 			 */
10471 			if (cportinfo->cport_state & SATA_STATE_READY) {
10472 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
10473 				sdinfo->satadrv_addr = cportinfo->cport_addr;
10474 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
10475 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10476 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10477 			} else {
10478 				/*
10479 				 * Port is not in ready state, we
10480 				 * cannot attach a device.
10481 				 */
10482 				mutex_exit(&cportinfo->cport_mutex);
10483 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
10484 				return (SATA_SUCCESS);
10485 			}
10486 			/*
10487 			 * Since we are adding device, presumably new one,
10488 			 * indicate that it  should be initalized,
10489 			 * as well as some internal framework states).
10490 			 */
10491 			init_device = B_TRUE;
10492 		}
10493 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10494 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10495 	} else {
10496 		/* Device change: Drive -> PMult */
10497 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10498 		if (sdinfo != NULL) {
10499 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10500 			sata_log(sata_hba_inst, CE_WARN,
10501 			    "SATA device detached "
10502 			    "from port %d", cportinfo->cport_addr.cport);
10503 		}
10504 
10505 		sata_log(sata_hba_inst, CE_WARN,
10506 		    "SATA port multiplier detected at port %d",
10507 		    cportinfo->cport_addr.cport);
10508 
10509 		mutex_exit(&cportinfo->cport_mutex);
10510 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
10511 		    SATA_SUCCESS)
10512 			return (SATA_FAILURE);
10513 		sata_show_pmult_info(sata_hba_inst, sata_device);
10514 		mutex_enter(&cportinfo->cport_mutex);
10515 
10516 		/*
10517 		 * Mark all the port multiplier port behind the port
10518 		 * multiplier behind with link events, so that the sata daemon
10519 		 * will update their status.
10520 		 */
10521 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10522 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10523 		mutex_exit(&cportinfo->cport_mutex);
10524 		return (SATA_SUCCESS);
10525 	}
10526 	mutex_exit(&cportinfo->cport_mutex);
10527 
10528 	/*
10529 	 * Figure out what kind of device we are really
10530 	 * dealing with. Failure of identifying device does not fail this
10531 	 * function.
10532 	 */
10533 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
10534 	rval_init = SATA_FAILURE;
10535 	mutex_enter(&cportinfo->cport_mutex);
10536 	if (rval_probe == SATA_SUCCESS) {
10537 		/*
10538 		 * If we are dealing with the same type of a device as before,
10539 		 * restore its settings flags.
10540 		 */
10541 		if (osdinfo != NULL &&
10542 		    sata_device->satadev_type == prev_device_type)
10543 			sdinfo->satadrv_settings = prev_device_settings;
10544 
10545 		mutex_exit(&cportinfo->cport_mutex);
10546 		rval_init = SATA_SUCCESS;
10547 		/* Set initial device features, if necessary */
10548 		if (init_device == B_TRUE) {
10549 			rval_init = sata_initialize_device(sata_hba_inst,
10550 			    sdinfo);
10551 		}
10552 		if (rval_init == SATA_SUCCESS)
10553 			return (rval_init);
10554 		/* else we will retry if retry was asked for */
10555 
10556 	} else {
10557 		/*
10558 		 * If there was some device info before we probe the device,
10559 		 * restore previous device setting, so we can retry from scratch
10560 		 * later. Providing, of course, that device has not disapear
10561 		 * during probing process.
10562 		 */
10563 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10564 			if (osdinfo != NULL) {
10565 				cportinfo->cport_dev_type = prev_device_type;
10566 				sdinfo->satadrv_type = prev_device_type;
10567 				sdinfo->satadrv_state = prev_device_state;
10568 			}
10569 		} else {
10570 			/* device is gone */
10571 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10572 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10573 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10574 			mutex_exit(&cportinfo->cport_mutex);
10575 			return (SATA_SUCCESS);
10576 		}
10577 		mutex_exit(&cportinfo->cport_mutex);
10578 	}
10579 
10580 	if (retry) {
10581 		clock_t cur_time = ddi_get_lbolt();
10582 		/*
10583 		 * A device was not successfully identified or initialized.
10584 		 * Track retry time for device identification.
10585 		 */
10586 		if ((cur_time - start_time) <
10587 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10588 			/* sleep for a while */
10589 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10590 			goto retry_probe;
10591 		}
10592 		/* else no more retries */
10593 		mutex_enter(&cportinfo->cport_mutex);
10594 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10595 			if (rval_init == SATA_RETRY) {
10596 				/*
10597 				 * Setting drive features have failed, but
10598 				 * because the drive is still accessible,
10599 				 * keep it and emit a warning message.
10600 				 */
10601 				sata_log(sata_hba_inst, CE_WARN,
10602 				    "SATA device at port %d - desired "
10603 				    "drive features could not be set. "
10604 				    "Device may not operate as expected.",
10605 				    cportinfo->cport_addr.cport);
10606 			} else {
10607 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
10608 				    satadrv_state = SATA_DSTATE_FAILED;
10609 			}
10610 		}
10611 		mutex_exit(&cportinfo->cport_mutex);
10612 	}
10613 	return (SATA_SUCCESS);
10614 }
10615 
10616 /*
10617  * Reprobe a controller port that connected to a port multiplier.
10618  *
10619  * NOTE: No Mutex should be hold.
10620  */
10621 static int
10622 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10623     int flag)
10624 {
10625 	_NOTE(ARGUNUSED(flag))
10626 	sata_cport_info_t *cportinfo;
10627 	sata_pmult_info_t *pmultinfo;
10628 	uint8_t cport = sata_device->satadev_addr.cport;
10629 	int rval_probe;
10630 
10631 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10632 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10633 
10634 	/* probe port */
10635 	mutex_enter(&cportinfo->cport_mutex);
10636 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10637 	cportinfo->cport_state |= SATA_STATE_PROBING;
10638 	mutex_exit(&cportinfo->cport_mutex);
10639 
10640 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10641 	    (SATA_DIP(sata_hba_inst), sata_device);
10642 
10643 	mutex_enter(&cportinfo->cport_mutex);
10644 	if (rval_probe != SATA_SUCCESS) {
10645 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10646 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
10647 		    "SATA port %d probing failed", cport));
10648 		sata_log(sata_hba_inst, CE_WARN,
10649 		    "SATA port multiplier detached at port %d", cport);
10650 		mutex_exit(&cportinfo->cport_mutex);
10651 		sata_free_pmult(sata_hba_inst, sata_device);
10652 		return (SATA_FAILURE);
10653 	}
10654 
10655 	/*
10656 	 * update sata port state and set device type
10657 	 */
10658 	sata_update_port_info(sata_hba_inst, sata_device);
10659 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10660 	cportinfo->cport_state |= SATA_STATE_PROBED;
10661 
10662 	/*
10663 	 * Sanity check - Port is active? Is the link active?
10664 	 * Is there any device attached?
10665 	 */
10666 	if ((cportinfo->cport_state &
10667 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10668 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10669 	    SATA_PORT_DEVLINK_UP ||
10670 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
10671 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10672 		mutex_exit(&cportinfo->cport_mutex);
10673 		sata_free_pmult(sata_hba_inst, sata_device);
10674 		sata_log(sata_hba_inst, CE_WARN,
10675 		    "SATA port multiplier detached at port %d", cport);
10676 		return (SATA_SUCCESS);
10677 	}
10678 
10679 	/*
10680 	 * Device changed: PMult -> Non-PMult
10681 	 *
10682 	 * This situation is uncommon, most possibly being caused by errors
10683 	 * after which the port multiplier is not correct initialized and
10684 	 * recognized. In that case the new device will be marked as unknown
10685 	 * and will not be automatically probed in this routine. Instead
10686 	 * system administrator could manually restart it via cfgadm(1M).
10687 	 */
10688 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10689 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10690 		mutex_exit(&cportinfo->cport_mutex);
10691 		sata_free_pmult(sata_hba_inst, sata_device);
10692 		sata_log(sata_hba_inst, CE_WARN,
10693 		    "SATA port multiplier detached at port %d", cport);
10694 		return (SATA_FAILURE);
10695 	}
10696 
10697 	/*
10698 	 * Now we know it is a port multiplier. However, if this is not the
10699 	 * previously attached port multiplier - they may have different
10700 	 * pmport numbers - we need to re-allocate data structures for every
10701 	 * pmport and drive.
10702 	 *
10703 	 * Port multipliers of the same model have identical values in these
10704 	 * registers, so it is still necessary to update the information of
10705 	 * all drives attached to the previous port multiplier afterwards.
10706 	 */
10707 	/* Device changed: PMult -> another PMult */
10708 	mutex_exit(&cportinfo->cport_mutex);
10709 	sata_free_pmult(sata_hba_inst, sata_device);
10710 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
10711 		return (SATA_FAILURE);
10712 	mutex_enter(&cportinfo->cport_mutex);
10713 
10714 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
10715 	    "SATA port multiplier [changed] at port %d", cport);
10716 	sata_log(sata_hba_inst, CE_WARN,
10717 	    "SATA port multiplier detected at port %d", cport);
10718 
10719 	/*
10720 	 * Mark all the port multiplier port behind the port
10721 	 * multiplier behind with link events, so that the sata daemon
10722 	 * will update their status.
10723 	 */
10724 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10725 	mutex_exit(&cportinfo->cport_mutex);
10726 
10727 	return (SATA_SUCCESS);
10728 }
10729 
10730 /*
10731  * Re-probe a port multiplier port, check for a device and attach info
10732  * structures when necessary. Identify Device data is fetched, if possible.
10733  * Assumption: sata address is already validated as port multiplier port.
10734  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10735  * the presence of a device and its type.
10736  *
10737  * flag arg specifies that the function should try multiple times to identify
10738  * device type and to initialize it, or it should return immediately on failure.
10739  * SATA_DEV_IDENTIFY_RETRY - retry
10740  * SATA_DEV_IDENTIFY_NORETRY - no retry
10741  *
10742  * SATA_FAILURE is returned if one of the operations failed.
10743  *
10744  * This function cannot be called in interrupt context - it may sleep.
10745  *
10746  * NOTE: Should be only called by sata_probe_port() in case target port is a
10747  *       port multiplier port.
10748  * NOTE: No Mutex should be hold.
10749  */
10750 static int
10751 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10752     int flag)
10753 {
10754 	sata_cport_info_t *cportinfo = NULL;
10755 	sata_pmport_info_t *pmportinfo = NULL;
10756 	sata_drive_info_t *sdinfo, *osdinfo;
10757 	sata_device_t sdevice;
10758 	boolean_t init_device = B_FALSE;
10759 	int prev_device_type = SATA_DTYPE_NONE;
10760 	int prev_device_settings = 0;
10761 	int prev_device_state = 0;
10762 	clock_t start_time;
10763 	uint8_t cport = sata_device->satadev_addr.cport;
10764 	uint8_t pmport = sata_device->satadev_addr.pmport;
10765 	int rval;
10766 
10767 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10768 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
10769 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10770 
10771 	if (osdinfo != NULL) {
10772 		/*
10773 		 * We are re-probing port with a previously attached device.
10774 		 * Save previous device type and settings.
10775 		 */
10776 		prev_device_type = pmportinfo->pmport_dev_type;
10777 		prev_device_settings = osdinfo->satadrv_settings;
10778 		prev_device_state = osdinfo->satadrv_state;
10779 	}
10780 
10781 	start_time = ddi_get_lbolt();
10782 
10783 	/* check parent status */
10784 	mutex_enter(&cportinfo->cport_mutex);
10785 	if ((cportinfo->cport_state &
10786 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10787 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10788 	    SATA_PORT_DEVLINK_UP) {
10789 		mutex_exit(&cportinfo->cport_mutex);
10790 		return (SATA_FAILURE);
10791 	}
10792 	mutex_exit(&cportinfo->cport_mutex);
10793 
10794 retry_probe_pmport:
10795 
10796 	/* probe port */
10797 	mutex_enter(&pmportinfo->pmport_mutex);
10798 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10799 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
10800 	mutex_exit(&pmportinfo->pmport_mutex);
10801 
10802 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10803 	    (SATA_DIP(sata_hba_inst), sata_device);
10804 
10805 	/* might need retry because we cannot touch registers. */
10806 	if (rval == SATA_FAILURE) {
10807 		mutex_enter(&pmportinfo->pmport_mutex);
10808 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
10809 		mutex_exit(&pmportinfo->pmport_mutex);
10810 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10811 		    "SATA port %d:%d probing failed",
10812 		    cport, pmport));
10813 		return (SATA_FAILURE);
10814 	} else if (rval == SATA_RETRY) {
10815 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10816 		    "SATA port %d:%d probing failed, retrying...",
10817 		    cport, pmport));
10818 		clock_t cur_time = ddi_get_lbolt();
10819 		/*
10820 		 * A device was not successfully identified or initialized.
10821 		 * Track retry time for device identification.
10822 		 */
10823 		if ((cur_time - start_time) <
10824 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10825 			/* sleep for a while */
10826 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10827 			goto retry_probe_pmport;
10828 		} else {
10829 			mutex_enter(&pmportinfo->pmport_mutex);
10830 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
10831 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
10832 				    satadrv_state = SATA_DSTATE_FAILED;
10833 			mutex_exit(&pmportinfo->pmport_mutex);
10834 			return (SATA_SUCCESS);
10835 		}
10836 	}
10837 
10838 	/*
10839 	 * Sanity check - Controller port is active? Is the link active?
10840 	 * Is it still a port multiplier?
10841 	 */
10842 	if ((cportinfo->cport_state &
10843 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10844 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10845 	    SATA_PORT_DEVLINK_UP ||
10846 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
10847 		/*
10848 		 * Port in non-usable state or no link active/no
10849 		 * device. Free info structure.
10850 		 */
10851 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10852 
10853 		sdevice.satadev_addr.cport = cport;
10854 		sdevice.satadev_addr.pmport = pmport;
10855 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
10856 		mutex_exit(&cportinfo->cport_mutex);
10857 
10858 		sata_free_pmult(sata_hba_inst, &sdevice);
10859 		return (SATA_FAILURE);
10860 	}
10861 
10862 	/* SATA_SUCCESS NOW */
10863 	/*
10864 	 * update sata port state and set device type
10865 	 */
10866 	mutex_enter(&pmportinfo->pmport_mutex);
10867 	sata_update_pmport_info(sata_hba_inst, sata_device);
10868 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
10869 
10870 	/*
10871 	 * Sanity check - Port is active? Is the link active?
10872 	 * Is there any device attached?
10873 	 */
10874 	if ((pmportinfo->pmport_state &
10875 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10876 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10877 	    SATA_PORT_DEVLINK_UP) {
10878 		/*
10879 		 * Port in non-usable state or no link active/no device.
10880 		 * Free info structure if necessary (direct attached drive
10881 		 * only, for now!
10882 		 */
10883 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10884 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10885 		/* Add here differentiation for device attached or not */
10886 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10887 		mutex_exit(&pmportinfo->pmport_mutex);
10888 		if (sdinfo != NULL)
10889 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10890 		return (SATA_SUCCESS);
10891 	}
10892 
10893 	pmportinfo->pmport_state |= SATA_STATE_READY;
10894 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
10895 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10896 
10897 	/*
10898 	 * If we are re-probing the port, there may be
10899 	 * sata_drive_info structure attached
10900 	 * (or sata_pm_info, if PMult is supported).
10901 	 */
10902 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10903 		/*
10904 		 * There is no device, so remove device info structure,
10905 		 * if necessary.
10906 		 */
10907 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10908 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10909 		if (sdinfo != NULL) {
10910 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10911 			sata_log(sata_hba_inst, CE_WARN,
10912 			    "SATA device detached from port %d:%d",
10913 			    cport, pmport);
10914 		}
10915 		mutex_exit(&pmportinfo->pmport_mutex);
10916 		return (SATA_SUCCESS);
10917 	}
10918 
10919 	/* this should not be a pmult */
10920 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
10921 	if (sdinfo == NULL) {
10922 		/*
10923 		 * There is some device attached, but there is
10924 		 * no sata_drive_info structure - allocate one
10925 		 */
10926 		mutex_exit(&pmportinfo->pmport_mutex);
10927 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
10928 		    KM_SLEEP);
10929 		mutex_enter(&pmportinfo->pmport_mutex);
10930 		/*
10931 		 * Recheck, that the port state did not change when we
10932 		 * released mutex.
10933 		 */
10934 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
10935 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
10936 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
10937 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
10938 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10939 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10940 		} else {
10941 			/*
10942 			 * Port is not in ready state, we
10943 			 * cannot attach a device.
10944 			 */
10945 			mutex_exit(&pmportinfo->pmport_mutex);
10946 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10947 			return (SATA_SUCCESS);
10948 		}
10949 		/*
10950 		 * Since we are adding device, presumably new one,
10951 		 * indicate that it  should be initalized,
10952 		 * as well as some internal framework states).
10953 		 */
10954 		init_device = B_TRUE;
10955 	}
10956 
10957 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10958 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10959 
10960 	mutex_exit(&pmportinfo->pmport_mutex);
10961 	/*
10962 	 * Figure out what kind of device we are really
10963 	 * dealing with.
10964 	 */
10965 	rval = sata_probe_device(sata_hba_inst, sata_device);
10966 
10967 	mutex_enter(&pmportinfo->pmport_mutex);
10968 	if (rval == SATA_SUCCESS) {
10969 		/*
10970 		 * If we are dealing with the same type of a device as before,
10971 		 * restore its settings flags.
10972 		 */
10973 		if (osdinfo != NULL &&
10974 		    sata_device->satadev_type == prev_device_type)
10975 			sdinfo->satadrv_settings = prev_device_settings;
10976 
10977 		mutex_exit(&pmportinfo->pmport_mutex);
10978 		/* Set initial device features, if necessary */
10979 		if (init_device == B_TRUE) {
10980 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
10981 		}
10982 		if (rval == SATA_SUCCESS)
10983 			return (rval);
10984 	} else {
10985 		/*
10986 		 * If there was some device info before we probe the device,
10987 		 * restore previous device setting, so we can retry from scratch
10988 		 * later. Providing, of course, that device has not disappeared
10989 		 * during probing process.
10990 		 */
10991 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10992 			if (osdinfo != NULL) {
10993 				pmportinfo->pmport_dev_type = prev_device_type;
10994 				sdinfo->satadrv_type = prev_device_type;
10995 				sdinfo->satadrv_state = prev_device_state;
10996 			}
10997 		} else {
10998 			/* device is gone */
10999 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11000 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11001 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11002 			mutex_exit(&pmportinfo->pmport_mutex);
11003 			return (SATA_SUCCESS);
11004 		}
11005 		mutex_exit(&pmportinfo->pmport_mutex);
11006 	}
11007 
11008 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11009 		clock_t cur_time = ddi_get_lbolt();
11010 		/*
11011 		 * A device was not successfully identified or initialized.
11012 		 * Track retry time for device identification.
11013 		 */
11014 		if ((cur_time - start_time) <
11015 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11016 			/* sleep for a while */
11017 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11018 			goto retry_probe_pmport;
11019 		} else {
11020 			mutex_enter(&pmportinfo->pmport_mutex);
11021 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11022 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11023 				    satadrv_state = SATA_DSTATE_FAILED;
11024 			mutex_exit(&pmportinfo->pmport_mutex);
11025 		}
11026 	}
11027 	return (SATA_SUCCESS);
11028 }
11029 
11030 /*
11031  * Allocated related structure for a port multiplier and its device ports
11032  *
11033  * Port multiplier should be ready and probed, and related information like
11034  * the number of the device ports should be store in sata_device_t.
11035  *
11036  * NOTE: No Mutex should be hold.
11037  */
11038 static int
11039 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11040 {
11041 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11042 	sata_cport_info_t *cportinfo = NULL;
11043 	sata_pmult_info_t *pmultinfo = NULL;
11044 	sata_pmport_info_t *pmportinfo = NULL;
11045 	sata_device_t sd;
11046 	dev_t minor_number;
11047 	char name[16];
11048 	uint8_t cport = sata_device->satadev_addr.cport;
11049 	int rval;
11050 	int npmport;
11051 
11052 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11053 
11054 	/* This function might be called while a port-mult is hot-plugged. */
11055 	mutex_enter(&cportinfo->cport_mutex);
11056 
11057 	/* dev_type's not updated when get called from sata_reprobe_port() */
11058 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11059 		/* Create a pmult_info structure */
11060 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11061 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11062 	}
11063 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11064 
11065 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11066 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11067 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11068 
11069 	/*
11070 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11071 	 * The HBA driver should initialize and register the port multiplier,
11072 	 * sata_register_pmult() will fill following fields,
11073 	 *   + sata_pmult_info.pmult_gscr
11074 	 *   + sata_pmult_info.pmult_num_dev_ports
11075 	 */
11076 	sd.satadev_addr = sata_device->satadev_addr;
11077 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11078 	mutex_exit(&cportinfo->cport_mutex);
11079 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11080 	    (SATA_DIP(sata_hba_inst), &sd);
11081 	mutex_enter(&cportinfo->cport_mutex);
11082 
11083 	if (rval != SATA_SUCCESS ||
11084 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11085 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11086 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11087 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11088 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11089 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11090 		mutex_exit(&cportinfo->cport_mutex);
11091 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11092 		    "sata_alloc_pmult: failed to initialize pmult "
11093 		    "at port %d.", cport)
11094 		return (SATA_FAILURE);
11095 	}
11096 
11097 	/* Initialize pmport_info structure */
11098 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11099 	    npmport++) {
11100 
11101 		/* if everything is allocated, skip */
11102 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11103 			continue;
11104 
11105 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11106 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11107 		mutex_exit(&cportinfo->cport_mutex);
11108 
11109 		mutex_enter(&pmportinfo->pmport_mutex);
11110 		pmportinfo->pmport_addr.cport = cport;
11111 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11112 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11113 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11114 		mutex_exit(&pmportinfo->pmport_mutex);
11115 
11116 		mutex_enter(&cportinfo->cport_mutex);
11117 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11118 
11119 		/* Create an attachment point */
11120 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
11121 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
11122 		(void) sprintf(name, "%d.%d", cport, npmport);
11123 
11124 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
11125 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
11126 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
11127 			    "cannot create SATA attachment point for "
11128 			    "port %d:%d", cport, npmport);
11129 		}
11130 	}
11131 
11132 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
11133 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
11134 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
11135 
11136 	mutex_exit(&cportinfo->cport_mutex);
11137 	return (SATA_SUCCESS);
11138 }
11139 
11140 /*
11141  * Free data structures when a port multiplier is removed.
11142  *
11143  * NOTE: No Mutex should be hold.
11144  */
11145 static void
11146 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11147 {
11148 	sata_cport_info_t *cportinfo;
11149 	sata_pmult_info_t *pmultinfo;
11150 	sata_pmport_info_t *pmportinfo;
11151 	sata_device_t pmport_device;
11152 	sata_drive_info_t *sdinfo;
11153 	dev_info_t *tdip;
11154 	char name[16];
11155 	uint8_t cport = sata_device->satadev_addr.cport;
11156 	int npmport;
11157 
11158 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11159 
11160 	/* This function might be called while port-mult is hot plugged. */
11161 	mutex_enter(&cportinfo->cport_mutex);
11162 
11163 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11164 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11165 	ASSERT(pmultinfo != NULL);
11166 
11167 	/* Free pmport_info structure */
11168 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11169 	    npmport++) {
11170 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
11171 		if (pmportinfo == NULL)
11172 			continue;
11173 		mutex_exit(&cportinfo->cport_mutex);
11174 
11175 		mutex_enter(&pmportinfo->pmport_mutex);
11176 		sdinfo = pmportinfo->pmport_sata_drive;
11177 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11178 		mutex_exit(&pmportinfo->pmport_mutex);
11179 
11180 		/* Remove attachment point. */
11181 		name[0] = '\0';
11182 		(void) sprintf(name, "%d.%d", cport, npmport);
11183 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
11184 		sata_log(sata_hba_inst, CE_NOTE,
11185 		    "Remove attachment point of port %d:%d",
11186 		    cport, npmport);
11187 
11188 		/*
11189 		 * Rumove target node
11190 		 */
11191 		bzero(&pmport_device, sizeof (sata_device_t));
11192 		pmport_device.satadev_rev = SATA_DEVICE_REV;
11193 		pmport_device.satadev_addr.cport = cport;
11194 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
11195 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
11196 
11197 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11198 		    &(pmport_device.satadev_addr));
11199 		if (tdip != NULL && ndi_devi_offline(tdip,
11200 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11201 			/*
11202 			 * Problem :
11203 			 * The target node remained attached.
11204 			 * This happens when the device file was open
11205 			 * or a node was waiting for resources.
11206 			 * Cannot do anything about it.
11207 			 */
11208 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11209 			    "sata_free_pmult: could not unconfigure device "
11210 			    "before disconnecting the SATA port %d:%d",
11211 			    cport, npmport));
11212 
11213 			/*
11214 			 * Set DEVICE REMOVED state in the target
11215 			 * node. It will prevent access to the device
11216 			 * even when a new device is attached, until
11217 			 * the old target node is released, removed and
11218 			 * recreated for a new  device.
11219 			 */
11220 			sata_set_device_removed(tdip);
11221 
11222 			/*
11223 			 * Instruct event daemon to try the target
11224 			 * node cleanup later.
11225 			 */
11226 			sata_set_target_node_cleanup(
11227 			    sata_hba_inst, &(pmport_device.satadev_addr));
11228 
11229 		}
11230 		mutex_enter(&cportinfo->cport_mutex);
11231 
11232 		/*
11233 		 * Add here differentiation for device attached or not
11234 		 */
11235 		if (sdinfo != NULL)  {
11236 			sata_log(sata_hba_inst, CE_WARN,
11237 			    "SATA device detached from port %d:%d",
11238 			    cport, npmport);
11239 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11240 		}
11241 
11242 		mutex_destroy(&pmportinfo->pmport_mutex);
11243 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
11244 	}
11245 
11246 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11247 
11248 	cportinfo->cport_devp.cport_sata_pmult = NULL;
11249 
11250 	sata_log(sata_hba_inst, CE_WARN,
11251 	    "SATA port multiplier detached at port %d", cport);
11252 
11253 	mutex_exit(&cportinfo->cport_mutex);
11254 }
11255 
11256 /*
11257  * Initialize device
11258  * Specified device is initialized to a default state.
11259  *
11260  * Returns SATA_SUCCESS if all device features are set successfully,
11261  * SATA_RETRY if device is accessible but device features were not set
11262  * successfully, and SATA_FAILURE otherwise.
11263  */
11264 static int
11265 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
11266     sata_drive_info_t *sdinfo)
11267 {
11268 	int rval;
11269 
11270 	sata_save_drive_settings(sdinfo);
11271 
11272 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
11273 
11274 	sata_init_write_cache_mode(sdinfo);
11275 
11276 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
11277 
11278 	/* Determine current data transfer mode */
11279 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
11280 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11281 	} else if ((sdinfo->satadrv_id.ai_validinfo &
11282 	    SATA_VALIDINFO_88) != 0 &&
11283 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
11284 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11285 	} else if ((sdinfo->satadrv_id.ai_dworddma &
11286 	    SATA_MDMA_SEL_MASK) != 0) {
11287 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11288 	} else
11289 		/* DMA supported, not no DMA transfer mode is selected !? */
11290 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11291 
11292 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
11293 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
11294 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
11295 	else
11296 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
11297 
11298 	return (rval);
11299 }
11300 
11301 
11302 /*
11303  * Initialize write cache mode.
11304  *
11305  * The default write cache setting for SATA HDD is provided by sata_write_cache
11306  * static variable. ATAPI CD/DVDs devices have write cache default is
11307  * determined by sata_atapicdvd_write_cache static variable.
11308  * ATAPI tape devices have write cache default is determined by
11309  * sata_atapitape_write_cache static variable.
11310  * ATAPI disk devices have write cache default is determined by
11311  * sata_atapidisk_write_cache static variable.
11312  * 1 - enable
11313  * 0 - disable
11314  * any other value - current drive setting
11315  *
11316  * Although there is not reason to disable write cache on CD/DVD devices,
11317  * tape devices and ATAPI disk devices, the default setting control is provided
11318  * for the maximun flexibility.
11319  *
11320  * In the future, it may be overridden by the
11321  * disk-write-cache-enable property setting, if it is defined.
11322  * Returns SATA_SUCCESS if all device features are set successfully,
11323  * SATA_FAILURE otherwise.
11324  */
11325 static void
11326 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
11327 {
11328 	switch (sdinfo->satadrv_type) {
11329 	case SATA_DTYPE_ATADISK:
11330 		if (sata_write_cache == 1)
11331 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11332 		else if (sata_write_cache == 0)
11333 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11334 		/*
11335 		 * When sata_write_cache value is not 0 or 1,
11336 		 * a current setting of the drive's write cache is used.
11337 		 */
11338 		break;
11339 	case SATA_DTYPE_ATAPICD:
11340 		if (sata_atapicdvd_write_cache == 1)
11341 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11342 		else if (sata_atapicdvd_write_cache == 0)
11343 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11344 		/*
11345 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
11346 		 * a current setting of the drive's write cache is used.
11347 		 */
11348 		break;
11349 	case SATA_DTYPE_ATAPITAPE:
11350 		if (sata_atapitape_write_cache == 1)
11351 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11352 		else if (sata_atapitape_write_cache == 0)
11353 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11354 		/*
11355 		 * When sata_atapitape_write_cache value is not 0 or 1,
11356 		 * a current setting of the drive's write cache is used.
11357 		 */
11358 		break;
11359 	case SATA_DTYPE_ATAPIDISK:
11360 		if (sata_atapidisk_write_cache == 1)
11361 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11362 		else if (sata_atapidisk_write_cache == 0)
11363 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11364 		/*
11365 		 * When sata_atapidisk_write_cache value is not 0 or 1,
11366 		 * a current setting of the drive's write cache is used.
11367 		 */
11368 		break;
11369 	}
11370 }
11371 
11372 
11373 /*
11374  * Validate sata address.
11375  * Specified cport, pmport and qualifier has to match
11376  * passed sata_scsi configuration info.
11377  * The presence of an attached device is not verified.
11378  *
11379  * Returns 0 when address is valid, -1 otherwise.
11380  */
11381 static int
11382 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
11383 	int pmport, int qual)
11384 {
11385 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
11386 		goto invalid_address;
11387 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11388 		goto invalid_address;
11389 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
11390 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
11391 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
11392 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
11393 		goto invalid_address;
11394 
11395 	return (0);
11396 
11397 invalid_address:
11398 	return (-1);
11399 
11400 }
11401 
11402 /*
11403  * Validate scsi address
11404  * SCSI target address is translated into SATA cport/pmport and compared
11405  * with a controller port/device configuration. LUN has to be 0.
11406  * Returns 0 if a scsi target refers to an attached device,
11407  * returns 1 if address is valid but no valid device is attached,
11408  * returns 2 if address is valid but device type is unknown (not valid device),
11409  * returns -1 if bad address or device is of an unsupported type.
11410  * Upon return sata_device argument is set.
11411  *
11412  * Port multiplier is supported now.
11413  */
11414 static int
11415 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
11416 	struct scsi_address *ap, sata_device_t *sata_device)
11417 {
11418 	int cport, pmport, qual, rval;
11419 
11420 	rval = -1;	/* Invalid address */
11421 	if (ap->a_lun != 0)
11422 		goto out;
11423 
11424 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
11425 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
11426 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
11427 
11428 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
11429 		goto out;
11430 
11431 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
11432 	    0) {
11433 
11434 		sata_cport_info_t *cportinfo;
11435 		sata_pmult_info_t *pmultinfo;
11436 		sata_drive_info_t *sdinfo = NULL;
11437 
11438 		sata_device->satadev_addr.qual = qual;
11439 		sata_device->satadev_addr.cport = cport;
11440 		sata_device->satadev_addr.pmport = pmport;
11441 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
11442 
11443 		rval = 1;	/* Valid sata address */
11444 
11445 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11446 		if (qual == SATA_ADDR_DCPORT) {
11447 			if (cportinfo == NULL ||
11448 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11449 				goto out;
11450 
11451 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11452 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
11453 			    sdinfo != NULL) {
11454 				rval = 2;
11455 				goto out;
11456 			}
11457 
11458 			if ((cportinfo->cport_dev_type &
11459 			    SATA_VALID_DEV_TYPE) == 0) {
11460 				rval = -1;
11461 				goto out;
11462 			}
11463 
11464 		} else if (qual == SATA_ADDR_DPMPORT) {
11465 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11466 			if (pmultinfo == NULL) {
11467 				rval = -1;
11468 				goto out;
11469 			}
11470 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
11471 			    NULL ||
11472 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11473 			    pmport) == SATA_DTYPE_NONE)
11474 				goto out;
11475 
11476 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
11477 			    pmport);
11478 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11479 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
11480 				rval = 2;
11481 				goto out;
11482 			}
11483 
11484 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11485 			    pmport) && SATA_VALID_DEV_TYPE) == 0) {
11486 				rval = -1;
11487 				goto out;
11488 			}
11489 
11490 		} else {
11491 			rval = -1;
11492 			goto out;
11493 		}
11494 		if ((sdinfo == NULL) ||
11495 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
11496 			goto out;
11497 
11498 		sata_device->satadev_type = sdinfo->satadrv_type;
11499 
11500 		return (0);
11501 	}
11502 out:
11503 	if (rval > 0) {
11504 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
11505 		    "sata_validate_scsi_address: no valid target %x lun %x",
11506 		    ap->a_target, ap->a_lun);
11507 	}
11508 	return (rval);
11509 }
11510 
11511 /*
11512  * Find dip corresponding to passed device number
11513  *
11514  * Returns NULL if invalid device number is passed or device cannot be found,
11515  * Returns dip is device is found.
11516  */
11517 static dev_info_t *
11518 sata_devt_to_devinfo(dev_t dev)
11519 {
11520 	dev_info_t *dip;
11521 #ifndef __lock_lint
11522 	struct devnames *dnp;
11523 	major_t major = getmajor(dev);
11524 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
11525 
11526 	if (major >= devcnt)
11527 		return (NULL);
11528 
11529 	dnp = &devnamesp[major];
11530 	LOCK_DEV_OPS(&(dnp->dn_lock));
11531 	dip = dnp->dn_head;
11532 	while (dip && (ddi_get_instance(dip) != instance)) {
11533 		dip = ddi_get_next(dip);
11534 	}
11535 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
11536 #endif
11537 
11538 	return (dip);
11539 }
11540 
11541 
11542 /*
11543  * Probe device.
11544  * This function issues Identify Device command and initializes local
11545  * sata_drive_info structure if the device can be identified.
11546  * The device type is determined by examining Identify Device
11547  * command response.
11548  * If the sata_hba_inst has linked drive info structure for this
11549  * device address, the Identify Device data is stored into sata_drive_info
11550  * structure linked to the port info structure.
11551  *
11552  * sata_device has to refer to the valid sata port(s) for HBA described
11553  * by sata_hba_inst structure.
11554  *
11555  * Returns:
11556  *	SATA_SUCCESS if device type was successfully probed and port-linked
11557  *		drive info structure was updated;
11558  * 	SATA_FAILURE if there is no device, or device was not probed
11559  *		successully;
11560  *	SATA_RETRY if device probe can be retried later.
11561  * If a device cannot be identified, sata_device's dev_state and dev_type
11562  * fields are set to unknown.
11563  * There are no retries in this function. Any retries should be managed by
11564  * the caller.
11565  */
11566 
11567 
11568 static int
11569 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11570 {
11571 	sata_pmport_info_t *pmportinfo;
11572 	sata_drive_info_t *sdinfo;
11573 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
11574 	int rval;
11575 
11576 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
11577 	    sata_device->satadev_addr.cport) &
11578 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
11579 
11580 	sata_device->satadev_type = SATA_DTYPE_NONE;
11581 
11582 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11583 	    sata_device->satadev_addr.cport)));
11584 
11585 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
11586 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
11587 		    sata_device->satadev_addr.cport,
11588 		    sata_device->satadev_addr.pmport);
11589 		ASSERT(pmportinfo != NULL);
11590 	}
11591 
11592 	/* Get pointer to port-linked sata device info structure */
11593 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11594 	if (sdinfo != NULL) {
11595 		sdinfo->satadrv_state &=
11596 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
11597 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
11598 	} else {
11599 		/* No device to probe */
11600 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11601 		    sata_device->satadev_addr.cport)));
11602 		sata_device->satadev_type = SATA_DTYPE_NONE;
11603 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
11604 		return (SATA_FAILURE);
11605 	}
11606 	/*
11607 	 * Need to issue both types of identify device command and
11608 	 * determine device type by examining retreived data/status.
11609 	 * First, ATA Identify Device.
11610 	 */
11611 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
11612 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
11613 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11614 	    sata_device->satadev_addr.cport)));
11615 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
11616 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11617 	if (rval == SATA_RETRY) {
11618 		/* We may try to check for ATAPI device */
11619 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
11620 			/*
11621 			 * HBA supports ATAPI - try to issue Identify Packet
11622 			 * Device command.
11623 			 */
11624 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
11625 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11626 		}
11627 	}
11628 	if (rval == SATA_SUCCESS) {
11629 		/*
11630 		 * Got something responding positively to ATA Identify Device
11631 		 * or to Identify Packet Device cmd.
11632 		 * Save last used device type.
11633 		 */
11634 		sata_device->satadev_type = new_sdinfo.satadrv_type;
11635 
11636 		/* save device info, if possible */
11637 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11638 		    sata_device->satadev_addr.cport)));
11639 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11640 		if (sdinfo == NULL) {
11641 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11642 			    sata_device->satadev_addr.cport)));
11643 			return (SATA_FAILURE);
11644 		}
11645 		/*
11646 		 * Copy drive info into the port-linked drive info structure.
11647 		 */
11648 		*sdinfo = new_sdinfo;
11649 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11650 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11651 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11652 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11653 			    sata_device->satadev_addr.cport) =
11654 			    sdinfo->satadrv_type;
11655 		else { /* SATA_ADDR_DPMPORT */
11656 			mutex_enter(&pmportinfo->pmport_mutex);
11657 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11658 			    sata_device->satadev_addr.cport,
11659 			    sata_device->satadev_addr.pmport) =
11660 			    sdinfo->satadrv_type;
11661 			mutex_exit(&pmportinfo->pmport_mutex);
11662 		}
11663 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11664 		    sata_device->satadev_addr.cport)));
11665 		return (SATA_SUCCESS);
11666 	}
11667 
11668 	/*
11669 	 * It may be SATA_RETRY or SATA_FAILURE return.
11670 	 * Looks like we cannot determine the device type at this time.
11671 	 */
11672 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11673 	    sata_device->satadev_addr.cport)));
11674 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11675 	if (sdinfo != NULL) {
11676 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
11677 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11678 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11679 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11680 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11681 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11682 			    sata_device->satadev_addr.cport) =
11683 			    SATA_DTYPE_UNKNOWN;
11684 		else {
11685 			/* SATA_ADDR_DPMPORT */
11686 			mutex_enter(&pmportinfo->pmport_mutex);
11687 			if ((SATA_PMULT_INFO(sata_hba_inst,
11688 			    sata_device->satadev_addr.cport) != NULL) &&
11689 			    (SATA_PMPORT_INFO(sata_hba_inst,
11690 			    sata_device->satadev_addr.cport,
11691 			    sata_device->satadev_addr.pmport) != NULL))
11692 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11693 				    sata_device->satadev_addr.cport,
11694 				    sata_device->satadev_addr.pmport) =
11695 				    SATA_DTYPE_UNKNOWN;
11696 			mutex_exit(&pmportinfo->pmport_mutex);
11697 		}
11698 	}
11699 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11700 	    sata_device->satadev_addr.cport)));
11701 	return (rval);
11702 }
11703 
11704 
11705 /*
11706  * Get pointer to sata_drive_info structure.
11707  *
11708  * The sata_device has to contain address (cport, pmport and qualifier) for
11709  * specified sata_scsi structure.
11710  *
11711  * Returns NULL if device address is not valid for this HBA configuration.
11712  * Otherwise, returns a pointer to sata_drive_info structure.
11713  *
11714  * This function should be called with a port mutex held.
11715  */
11716 static sata_drive_info_t *
11717 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
11718     sata_device_t *sata_device)
11719 {
11720 	uint8_t cport = sata_device->satadev_addr.cport;
11721 	uint8_t pmport = sata_device->satadev_addr.pmport;
11722 	uint8_t qual = sata_device->satadev_addr.qual;
11723 
11724 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11725 		return (NULL);
11726 
11727 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
11728 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
11729 		/* Port not probed yet */
11730 		return (NULL);
11731 
11732 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
11733 		return (NULL);
11734 
11735 	if (qual == SATA_ADDR_DCPORT) {
11736 		/* Request for a device on a controller port */
11737 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
11738 		    SATA_DTYPE_PMULT)
11739 			/* Port multiplier attached */
11740 			return (NULL);
11741 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
11742 	}
11743 	if (qual == SATA_ADDR_DPMPORT) {
11744 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
11745 		    SATA_DTYPE_PMULT)
11746 			return (NULL);
11747 
11748 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
11749 			return (NULL);
11750 
11751 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
11752 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
11753 			/* Port multiplier port not probed yet */
11754 			return (NULL);
11755 
11756 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
11757 	}
11758 
11759 	/* we should not get here */
11760 	return (NULL);
11761 }
11762 
11763 
11764 /*
11765  * sata_identify_device.
11766  * Send Identify Device command to SATA HBA driver.
11767  * If command executes successfully, update sata_drive_info structure pointed
11768  * to by sdinfo argument, including Identify Device data.
11769  * If command fails, invalidate data in sata_drive_info.
11770  *
11771  * Cannot be called from interrupt level.
11772  *
11773  * Returns:
11774  * SATA_SUCCESS if the device was identified as a supported device,
11775  * SATA_RETRY if the device was not identified but could be retried,
11776  * SATA_FAILURE if the device was not identified and identify attempt
11777  *	should not be retried.
11778  */
11779 static int
11780 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
11781     sata_drive_info_t *sdinfo)
11782 {
11783 	uint16_t cfg_word;
11784 	int rval;
11785 
11786 	/* fetch device identify data */
11787 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
11788 	    sdinfo)) != SATA_SUCCESS)
11789 		goto fail_unknown;
11790 
11791 	cfg_word = sdinfo->satadrv_id.ai_config;
11792 
11793 	/* Set the correct device type */
11794 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
11795 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11796 	} else if (cfg_word == SATA_CFA_TYPE) {
11797 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
11798 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11799 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
11800 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
11801 		case SATA_ATAPI_CDROM_DEV:
11802 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
11803 			break;
11804 		case SATA_ATAPI_SQACC_DEV:
11805 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
11806 			break;
11807 		case SATA_ATAPI_DIRACC_DEV:
11808 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
11809 			break;
11810 		default:
11811 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11812 		}
11813 	} else {
11814 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11815 	}
11816 
11817 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11818 		if (sdinfo->satadrv_capacity == 0) {
11819 			/* Non-LBA disk. Too bad... */
11820 			sata_log(sata_hba_inst, CE_WARN,
11821 			    "SATA disk device at port %d does not support LBA",
11822 			    sdinfo->satadrv_addr.cport);
11823 			rval = SATA_FAILURE;
11824 			goto fail_unknown;
11825 		}
11826 	}
11827 #if 0
11828 	/* Left for historical reason */
11829 	/*
11830 	 * Some initial version of SATA spec indicated that at least
11831 	 * UDMA mode 4 has to be supported. It is not metioned in
11832 	 * SerialATA 2.6, so this restriction is removed.
11833 	 */
11834 	/* Check for Ultra DMA modes 6 through 0 being supported */
11835 	for (i = 6; i >= 0; --i) {
11836 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
11837 			break;
11838 	}
11839 
11840 	/*
11841 	 * At least UDMA 4 mode has to be supported. If mode 4 or
11842 	 * higher are not supported by the device, fail this
11843 	 * device.
11844 	 */
11845 	if (i < 4) {
11846 		/* No required Ultra DMA mode supported */
11847 		sata_log(sata_hba_inst, CE_WARN,
11848 		    "SATA disk device at port %d does not support UDMA "
11849 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
11850 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11851 		    "mode 4 or higher required, %d supported", i));
11852 		rval = SATA_FAILURE;
11853 		goto fail_unknown;
11854 	}
11855 #endif
11856 
11857 	/*
11858 	 * For Disk devices, if it doesn't support UDMA mode, we would
11859 	 * like to return failure directly.
11860 	 */
11861 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
11862 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
11863 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
11864 		sata_log(sata_hba_inst, CE_WARN,
11865 		    "SATA disk device at port %d does not support UDMA",
11866 		    sdinfo->satadrv_addr.cport);
11867 		rval = SATA_FAILURE;
11868 		goto fail_unknown;
11869 	}
11870 
11871 	return (SATA_SUCCESS);
11872 
11873 fail_unknown:
11874 	/* Invalidate sata_drive_info ? */
11875 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11876 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11877 	return (rval);
11878 }
11879 
11880 /*
11881  * Log/display device information
11882  */
11883 static void
11884 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
11885     sata_drive_info_t *sdinfo)
11886 {
11887 	int valid_version;
11888 	char msg_buf[MAXPATHLEN];
11889 	int i;
11890 
11891 	/* Show HBA path */
11892 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
11893 
11894 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
11895 
11896 	switch (sdinfo->satadrv_type) {
11897 	case SATA_DTYPE_ATADISK:
11898 		(void) sprintf(msg_buf, "SATA disk device at");
11899 		break;
11900 
11901 	case SATA_DTYPE_ATAPICD:
11902 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
11903 		break;
11904 
11905 	case SATA_DTYPE_ATAPITAPE:
11906 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
11907 		break;
11908 
11909 	case SATA_DTYPE_ATAPIDISK:
11910 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
11911 		break;
11912 
11913 	case SATA_DTYPE_UNKNOWN:
11914 		(void) sprintf(msg_buf,
11915 		    "Unsupported SATA device type (cfg 0x%x) at ",
11916 		    sdinfo->satadrv_id.ai_config);
11917 		break;
11918 	}
11919 
11920 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
11921 		cmn_err(CE_CONT, "?\t%s port %d\n",
11922 		    msg_buf, sdinfo->satadrv_addr.cport);
11923 	else
11924 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
11925 		    msg_buf, sdinfo->satadrv_addr.cport,
11926 		    sdinfo->satadrv_addr.pmport);
11927 
11928 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
11929 	    sizeof (sdinfo->satadrv_id.ai_model));
11930 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
11931 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
11932 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
11933 
11934 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
11935 	    sizeof (sdinfo->satadrv_id.ai_fw));
11936 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
11937 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
11938 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
11939 
11940 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
11941 	    sizeof (sdinfo->satadrv_id.ai_drvser));
11942 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
11943 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
11944 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11945 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
11946 	} else {
11947 		/*
11948 		 * Some drives do not implement serial number and may
11949 		 * violate the spec by providing spaces rather than zeros
11950 		 * in serial number field. Scan the buffer to detect it.
11951 		 */
11952 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
11953 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
11954 				break;
11955 		}
11956 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
11957 			cmn_err(CE_CONT, "?\tserial number - none\n");
11958 		} else {
11959 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
11960 		}
11961 	}
11962 
11963 #ifdef SATA_DEBUG
11964 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
11965 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
11966 		int i;
11967 		for (i = 14; i >= 2; i--) {
11968 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
11969 				valid_version = i;
11970 				break;
11971 			}
11972 		}
11973 		cmn_err(CE_CONT,
11974 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
11975 		    valid_version,
11976 		    sdinfo->satadrv_id.ai_majorversion,
11977 		    sdinfo->satadrv_id.ai_minorversion);
11978 	}
11979 #endif
11980 	/* Log some info */
11981 	cmn_err(CE_CONT, "?\tsupported features:\n");
11982 	msg_buf[0] = '\0';
11983 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11984 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
11985 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
11986 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
11987 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
11988 	}
11989 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
11990 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
11991 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
11992 		(void) strlcat(msg_buf, ", Native Command Queueing",
11993 		    MAXPATHLEN);
11994 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
11995 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
11996 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
11997 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
11998 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
11999 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
12000 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
12001 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12002 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12003 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12004 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12005 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12006 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12007 	if (sdinfo->satadrv_features_support &
12008 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12009 		msg_buf[0] = '\0';
12010 		(void) snprintf(msg_buf, MAXPATHLEN,
12011 		    "Supported queue depth %d",
12012 		    sdinfo->satadrv_queue_depth);
12013 		if (!(sata_func_enable &
12014 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12015 			(void) strlcat(msg_buf,
12016 			    " - queueing disabled globally", MAXPATHLEN);
12017 		else if (sdinfo->satadrv_queue_depth >
12018 		    sdinfo->satadrv_max_queue_depth) {
12019 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12020 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12021 			    (int)sdinfo->satadrv_max_queue_depth);
12022 		}
12023 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12024 	}
12025 
12026 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12027 #ifdef __i386
12028 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12029 		    sdinfo->satadrv_capacity);
12030 #else
12031 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12032 		    sdinfo->satadrv_capacity);
12033 #endif
12034 		cmn_err(CE_CONT, "?%s", msg_buf);
12035 	}
12036 }
12037 
12038 /*
12039  * Log/display port multiplier information
12040  * No Mutex should be hold.
12041  */
12042 static void
12043 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12044     sata_device_t *sata_device)
12045 {
12046 	_NOTE(ARGUNUSED(sata_hba_inst))
12047 
12048 	int cport = sata_device->satadev_addr.cport;
12049 	sata_pmult_info_t *pmultinfo;
12050 	char msg_buf[MAXPATHLEN];
12051 	uint32_t gscr0, gscr1, gscr2, gscr64;
12052 
12053 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12054 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12055 	if (pmultinfo == NULL) {
12056 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12057 		return;
12058 	}
12059 
12060 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12061 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12062 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12063 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12064 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12065 
12066 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12067 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12068 
12069 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12070 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12071 	cmn_err(CE_CONT, "?%s", msg_buf);
12072 
12073 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12074 	if (gscr1 & (1 << 3))
12075 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12076 	else if (gscr1 & (1 << 2))
12077 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12078 	else if (gscr1 & (1 << 1))
12079 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12080 	else
12081 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12082 	cmn_err(CE_CONT, "?%s", msg_buf);
12083 
12084 	(void) strcpy(msg_buf, "\tSupport ");
12085 	if (gscr64 & (1 << 3))
12086 		(void) strlcat(msg_buf, "Asy-Notif, ",
12087 		    MAXPATHLEN);
12088 	if (gscr64 & (1 << 2))
12089 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12090 	if (gscr64 & (1 << 1))
12091 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12092 	if (gscr64 & (1 << 0))
12093 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12094 	if ((gscr64 & 0xf) == 0)
12095 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12096 	cmn_err(CE_CONT, "?%s", msg_buf);
12097 
12098 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12099 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12100 	cmn_err(CE_CONT, "?%s", msg_buf);
12101 }
12102 
12103 /*
12104  * sata_save_drive_settings extracts current setting of the device and stores
12105  * it for future reference, in case the device setup would need to be restored
12106  * after the device reset.
12107  *
12108  * For all devices read ahead and write cache settings are saved, if the
12109  * device supports these features at all.
12110  * For ATAPI devices the Removable Media Status Notification setting is saved.
12111  */
12112 static void
12113 sata_save_drive_settings(sata_drive_info_t *sdinfo)
12114 {
12115 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
12116 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
12117 
12118 		/* Current setting of Read Ahead (and Read Cache) */
12119 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
12120 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12121 		else
12122 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
12123 
12124 		/* Current setting of Write Cache */
12125 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
12126 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12127 		else
12128 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12129 	}
12130 
12131 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
12132 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
12133 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
12134 		else
12135 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
12136 	}
12137 }
12138 
12139 
12140 /*
12141  * sata_check_capacity function determines a disk capacity
12142  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
12143  *
12144  * NOTE: CHS mode is not supported! If a device does not support LBA,
12145  * this function is not called.
12146  *
12147  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
12148  */
12149 static uint64_t
12150 sata_check_capacity(sata_drive_info_t *sdinfo)
12151 {
12152 	uint64_t capacity = 0;
12153 	int i;
12154 
12155 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
12156 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
12157 		/* Capacity valid only for LBA-addressable disk devices */
12158 		return (0);
12159 
12160 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
12161 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
12162 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
12163 		/* LBA48 mode supported and enabled */
12164 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
12165 		    SATA_DEV_F_LBA28;
12166 		for (i = 3;  i >= 0;  --i) {
12167 			capacity <<= 16;
12168 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
12169 		}
12170 	} else {
12171 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
12172 		capacity <<= 16;
12173 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
12174 		if (capacity >= 0x1000000)
12175 			/* LBA28 mode */
12176 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
12177 	}
12178 	return (capacity);
12179 }
12180 
12181 
12182 /*
12183  * Allocate consistent buffer for DMA transfer
12184  *
12185  * Cannot be called from interrupt level or with mutex held - it may sleep.
12186  *
12187  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
12188  */
12189 static struct buf *
12190 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
12191 {
12192 	struct scsi_address ap;
12193 	struct buf *bp;
12194 	ddi_dma_attr_t	cur_dma_attr;
12195 
12196 	ASSERT(spx->txlt_sata_pkt != NULL);
12197 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
12198 	ap.a_target = SATA_TO_SCSI_TARGET(
12199 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
12200 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
12201 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
12202 	ap.a_lun = 0;
12203 
12204 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
12205 	    B_READ, SLEEP_FUNC, NULL);
12206 
12207 	if (bp != NULL) {
12208 		/* Allocate DMA resources for this buffer */
12209 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
12210 		/*
12211 		 * We use a local version of the dma_attr, to account
12212 		 * for a device addressing limitations.
12213 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
12214 		 * will cause dma attributes to be adjusted to a lowest
12215 		 * acceptable level.
12216 		 */
12217 		sata_adjust_dma_attr(NULL,
12218 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
12219 
12220 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
12221 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
12222 			scsi_free_consistent_buf(bp);
12223 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12224 			bp = NULL;
12225 		}
12226 	}
12227 	return (bp);
12228 }
12229 
12230 /*
12231  * Release local buffer (consistent buffer for DMA transfer) allocated
12232  * via sata_alloc_local_buffer().
12233  */
12234 static void
12235 sata_free_local_buffer(sata_pkt_txlate_t *spx)
12236 {
12237 	ASSERT(spx->txlt_sata_pkt != NULL);
12238 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
12239 
12240 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
12241 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
12242 
12243 	sata_common_free_dma_rsrcs(spx);
12244 
12245 	/* Free buffer */
12246 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
12247 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12248 }
12249 
12250 /*
12251  * Allocate sata_pkt
12252  * Pkt structure version and embedded strcutures version are initialized.
12253  * sata_pkt and sata_pkt_txlate structures are cross-linked.
12254  *
12255  * Since this may be called in interrupt context by sata_scsi_init_pkt,
12256  * callback argument determines if it can sleep or not.
12257  * Hence, it should not be called from interrupt context.
12258  *
12259  * If successful, non-NULL pointer to a sata pkt is returned.
12260  * Upon failure, NULL pointer is returned.
12261  */
12262 static sata_pkt_t *
12263 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
12264 {
12265 	sata_pkt_t *spkt;
12266 	int kmsflag;
12267 
12268 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
12269 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
12270 	if (spkt == NULL) {
12271 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12272 		    "sata_pkt_alloc: failed"));
12273 		return (NULL);
12274 	}
12275 	spkt->satapkt_rev = SATA_PKT_REV;
12276 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
12277 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
12278 	spkt->satapkt_framework_private = spx;
12279 	spx->txlt_sata_pkt = spkt;
12280 	return (spkt);
12281 }
12282 
12283 /*
12284  * Free sata pkt allocated via sata_pkt_alloc()
12285  */
12286 static void
12287 sata_pkt_free(sata_pkt_txlate_t *spx)
12288 {
12289 	ASSERT(spx->txlt_sata_pkt != NULL);
12290 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
12291 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
12292 	spx->txlt_sata_pkt = NULL;
12293 }
12294 
12295 
12296 /*
12297  * Adjust DMA attributes.
12298  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
12299  * from 8 bits to 16 bits, depending on a command being used.
12300  * Limiting max block count arbitrarily to 256 for all read/write
12301  * commands may affects performance, so check both the device and
12302  * controller capability before adjusting dma attributes.
12303  */
12304 void
12305 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
12306     ddi_dma_attr_t *adj_dma_attr)
12307 {
12308 	uint32_t count_max;
12309 
12310 	/* Copy original attributes */
12311 	*adj_dma_attr = *dma_attr;
12312 	/*
12313 	 * Things to consider: device addressing capability,
12314 	 * "excessive" controller DMA capabilities.
12315 	 * If a device is being probed/initialized, there are
12316 	 * no device info - use default limits then.
12317 	 */
12318 	if (sdinfo == NULL) {
12319 		count_max = dma_attr->dma_attr_granular * 0x100;
12320 		if (dma_attr->dma_attr_count_max > count_max)
12321 			adj_dma_attr->dma_attr_count_max = count_max;
12322 		if (dma_attr->dma_attr_maxxfer > count_max)
12323 			adj_dma_attr->dma_attr_maxxfer = count_max;
12324 		return;
12325 	}
12326 
12327 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12328 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
12329 			/*
12330 			 * 16-bit sector count may be used - we rely on
12331 			 * the assumption that only read and write cmds
12332 			 * will request more than 256 sectors worth of data
12333 			 */
12334 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
12335 		} else {
12336 			/*
12337 			 * 8-bit sector count will be used - default limits
12338 			 * for dma attributes
12339 			 */
12340 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
12341 		}
12342 		/*
12343 		 * Adjust controler dma attributes, if necessary
12344 		 */
12345 		if (dma_attr->dma_attr_count_max > count_max)
12346 			adj_dma_attr->dma_attr_count_max = count_max;
12347 		if (dma_attr->dma_attr_maxxfer > count_max)
12348 			adj_dma_attr->dma_attr_maxxfer = count_max;
12349 	}
12350 }
12351 
12352 
12353 /*
12354  * Allocate DMA resources for the buffer
12355  * This function handles initial DMA resource allocation as well as
12356  * DMA window shift and may be called repeatedly for the same DMA window
12357  * until all DMA cookies in the DMA window are processed.
12358  * To guarantee that there is always a coherent set of cookies to process
12359  * by SATA HBA driver (observing alignment, device granularity, etc.),
12360  * the number of slots for DMA cookies is equal to lesser of  a number of
12361  * cookies in a DMA window and a max number of scatter/gather entries.
12362  *
12363  * Returns DDI_SUCCESS upon successful operation.
12364  * Return failure code of a failing command or DDI_FAILURE when
12365  * internal cleanup failed.
12366  */
12367 static int
12368 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
12369     int (*callback)(caddr_t), caddr_t arg,
12370     ddi_dma_attr_t *cur_dma_attr)
12371 {
12372 	int	rval;
12373 	off_t	offset;
12374 	size_t	size;
12375 	int	max_sg_len, req_len, i;
12376 	uint_t	dma_flags;
12377 	struct buf	*bp;
12378 	uint64_t	cur_txfer_len;
12379 
12380 
12381 	ASSERT(spx->txlt_sata_pkt != NULL);
12382 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
12383 	ASSERT(bp != NULL);
12384 
12385 
12386 	if (spx->txlt_buf_dma_handle == NULL) {
12387 		/*
12388 		 * No DMA resources allocated so far - this is a first call
12389 		 * for this sata pkt.
12390 		 */
12391 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
12392 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
12393 
12394 		if (rval != DDI_SUCCESS) {
12395 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12396 			    "sata_dma_buf_setup: no buf DMA resources %x",
12397 			    rval));
12398 			return (rval);
12399 		}
12400 
12401 		if (bp->b_flags & B_READ)
12402 			dma_flags = DDI_DMA_READ;
12403 		else
12404 			dma_flags = DDI_DMA_WRITE;
12405 
12406 		if (flags & PKT_CONSISTENT)
12407 			dma_flags |= DDI_DMA_CONSISTENT;
12408 
12409 		if (flags & PKT_DMA_PARTIAL)
12410 			dma_flags |= DDI_DMA_PARTIAL;
12411 
12412 		/*
12413 		 * Check buffer alignment and size against dma attributes
12414 		 * Consider dma_attr_align only. There may be requests
12415 		 * with the size lower than device granularity, but they
12416 		 * will not read/write from/to the device, so no adjustment
12417 		 * is necessary. The dma_attr_minxfer theoretically should
12418 		 * be considered, but no HBA driver is checking it.
12419 		 */
12420 		if (IS_P2ALIGNED(bp->b_un.b_addr,
12421 		    cur_dma_attr->dma_attr_align)) {
12422 			rval = ddi_dma_buf_bind_handle(
12423 			    spx->txlt_buf_dma_handle,
12424 			    bp, dma_flags, callback, arg,
12425 			    &spx->txlt_dma_cookie,
12426 			    &spx->txlt_curwin_num_dma_cookies);
12427 		} else { /* Buffer is not aligned */
12428 
12429 			int	(*ddicallback)(caddr_t);
12430 			size_t	bufsz;
12431 
12432 			/* Check id sleeping is allowed */
12433 			ddicallback = (callback == NULL_FUNC) ?
12434 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
12435 
12436 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12437 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
12438 			    (void *)bp->b_un.b_addr, bp->b_bcount);
12439 
12440 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
12441 				/*
12442 				 * CPU will need to access data in the buffer
12443 				 * (for copying) so map it.
12444 				 */
12445 				bp_mapin(bp);
12446 
12447 			ASSERT(spx->txlt_tmp_buf == NULL);
12448 
12449 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
12450 			rval = ddi_dma_mem_alloc(
12451 			    spx->txlt_buf_dma_handle,
12452 			    bp->b_bcount,
12453 			    &sata_acc_attr,
12454 			    DDI_DMA_STREAMING,
12455 			    ddicallback, NULL,
12456 			    &spx->txlt_tmp_buf,
12457 			    &bufsz,
12458 			    &spx->txlt_tmp_buf_handle);
12459 
12460 			if (rval != DDI_SUCCESS) {
12461 				/* DMA mapping failed */
12462 				(void) ddi_dma_free_handle(
12463 				    &spx->txlt_buf_dma_handle);
12464 				spx->txlt_buf_dma_handle = NULL;
12465 #ifdef SATA_DEBUG
12466 				mbuffail_count++;
12467 #endif
12468 				SATADBG1(SATA_DBG_DMA_SETUP,
12469 				    spx->txlt_sata_hba_inst,
12470 				    "sata_dma_buf_setup: "
12471 				    "buf dma mem alloc failed %x\n", rval);
12472 				return (rval);
12473 			}
12474 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
12475 			    cur_dma_attr->dma_attr_align));
12476 
12477 #ifdef SATA_DEBUG
12478 			mbuf_count++;
12479 
12480 			if (bp->b_bcount != bufsz)
12481 				/*
12482 				 * This will require special handling, because
12483 				 * DMA cookies will be based on the temporary
12484 				 * buffer size, not the original buffer
12485 				 * b_bcount, so the residue may have to
12486 				 * be counted differently.
12487 				 */
12488 				SATADBG2(SATA_DBG_DMA_SETUP,
12489 				    spx->txlt_sata_hba_inst,
12490 				    "sata_dma_buf_setup: bp size %x != "
12491 				    "bufsz %x\n", bp->b_bcount, bufsz);
12492 #endif
12493 			if (dma_flags & DDI_DMA_WRITE) {
12494 				/*
12495 				 * Write operation - copy data into
12496 				 * an aligned temporary buffer. Buffer will be
12497 				 * synced for device by ddi_dma_addr_bind_handle
12498 				 */
12499 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
12500 				    bp->b_bcount);
12501 			}
12502 
12503 			rval = ddi_dma_addr_bind_handle(
12504 			    spx->txlt_buf_dma_handle,
12505 			    NULL,
12506 			    spx->txlt_tmp_buf,
12507 			    bufsz, dma_flags, ddicallback, 0,
12508 			    &spx->txlt_dma_cookie,
12509 			    &spx->txlt_curwin_num_dma_cookies);
12510 		}
12511 
12512 		switch (rval) {
12513 		case DDI_DMA_PARTIAL_MAP:
12514 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12515 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
12516 			/*
12517 			 * Partial DMA mapping.
12518 			 * Retrieve number of DMA windows for this request.
12519 			 */
12520 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
12521 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
12522 				if (spx->txlt_tmp_buf != NULL) {
12523 					ddi_dma_mem_free(
12524 					    &spx->txlt_tmp_buf_handle);
12525 					spx->txlt_tmp_buf = NULL;
12526 				}
12527 				(void) ddi_dma_unbind_handle(
12528 				    spx->txlt_buf_dma_handle);
12529 				(void) ddi_dma_free_handle(
12530 				    &spx->txlt_buf_dma_handle);
12531 				spx->txlt_buf_dma_handle = NULL;
12532 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12533 				    "sata_dma_buf_setup: numwin failed\n"));
12534 				return (DDI_FAILURE);
12535 			}
12536 			SATADBG2(SATA_DBG_DMA_SETUP,
12537 			    spx->txlt_sata_hba_inst,
12538 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
12539 			    spx->txlt_num_dma_win,
12540 			    spx->txlt_curwin_num_dma_cookies);
12541 			spx->txlt_cur_dma_win = 0;
12542 			break;
12543 
12544 		case DDI_DMA_MAPPED:
12545 			/* DMA fully mapped */
12546 			spx->txlt_num_dma_win = 1;
12547 			spx->txlt_cur_dma_win = 0;
12548 			SATADBG1(SATA_DBG_DMA_SETUP,
12549 			    spx->txlt_sata_hba_inst,
12550 			    "sata_dma_buf_setup: windows: 1 "
12551 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
12552 			break;
12553 
12554 		default:
12555 			/* DMA mapping failed */
12556 			if (spx->txlt_tmp_buf != NULL) {
12557 				ddi_dma_mem_free(
12558 				    &spx->txlt_tmp_buf_handle);
12559 				spx->txlt_tmp_buf = NULL;
12560 			}
12561 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12562 			spx->txlt_buf_dma_handle = NULL;
12563 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12564 			    "sata_dma_buf_setup: buf dma handle binding "
12565 			    "failed %x\n", rval));
12566 			return (rval);
12567 		}
12568 		spx->txlt_curwin_processed_dma_cookies = 0;
12569 		spx->txlt_dma_cookie_list = NULL;
12570 	} else {
12571 		/*
12572 		 * DMA setup is reused. Check if we need to process more
12573 		 * cookies in current window, or to get next window, if any.
12574 		 */
12575 
12576 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
12577 		    spx->txlt_curwin_num_dma_cookies);
12578 
12579 		if (spx->txlt_curwin_processed_dma_cookies ==
12580 		    spx->txlt_curwin_num_dma_cookies) {
12581 			/*
12582 			 * All cookies from current DMA window were processed.
12583 			 * Get next DMA window.
12584 			 */
12585 			spx->txlt_cur_dma_win++;
12586 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
12587 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
12588 				    spx->txlt_cur_dma_win, &offset, &size,
12589 				    &spx->txlt_dma_cookie,
12590 				    &spx->txlt_curwin_num_dma_cookies);
12591 				spx->txlt_curwin_processed_dma_cookies = 0;
12592 			} else {
12593 				/* No more windows! End of request! */
12594 				/* What to do? - panic for now */
12595 				ASSERT(spx->txlt_cur_dma_win >=
12596 				    spx->txlt_num_dma_win);
12597 
12598 				spx->txlt_curwin_num_dma_cookies = 0;
12599 				spx->txlt_curwin_processed_dma_cookies = 0;
12600 				spx->txlt_sata_pkt->
12601 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
12602 				return (DDI_SUCCESS);
12603 			}
12604 		}
12605 	}
12606 	/* There better be at least one DMA cookie outstanding */
12607 	ASSERT((spx->txlt_curwin_num_dma_cookies -
12608 	    spx->txlt_curwin_processed_dma_cookies) > 0);
12609 
12610 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
12611 		/* The default cookie slot was used in previous run */
12612 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
12613 		spx->txlt_dma_cookie_list = NULL;
12614 		spx->txlt_dma_cookie_list_len = 0;
12615 	}
12616 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
12617 		/*
12618 		 * Processing a new DMA window - set-up dma cookies list.
12619 		 * We may reuse previously allocated cookie array if it is
12620 		 * possible.
12621 		 */
12622 		if (spx->txlt_dma_cookie_list != NULL &&
12623 		    spx->txlt_dma_cookie_list_len <
12624 		    spx->txlt_curwin_num_dma_cookies) {
12625 			/*
12626 			 * New DMA window contains more cookies than
12627 			 * the previous one. We need larger cookie list - free
12628 			 * the old one.
12629 			 */
12630 			(void) kmem_free(spx->txlt_dma_cookie_list,
12631 			    spx->txlt_dma_cookie_list_len *
12632 			    sizeof (ddi_dma_cookie_t));
12633 			spx->txlt_dma_cookie_list = NULL;
12634 			spx->txlt_dma_cookie_list_len = 0;
12635 		}
12636 		if (spx->txlt_dma_cookie_list == NULL) {
12637 			/*
12638 			 * Calculate lesser of number of cookies in this
12639 			 * DMA window and number of s/g entries.
12640 			 */
12641 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
12642 			req_len = MIN(max_sg_len,
12643 			    spx->txlt_curwin_num_dma_cookies);
12644 
12645 			/* Allocate new dma cookie array if necessary */
12646 			if (req_len == 1) {
12647 				/* Only one cookie - no need for a list */
12648 				spx->txlt_dma_cookie_list =
12649 				    &spx->txlt_dma_cookie;
12650 				spx->txlt_dma_cookie_list_len = 1;
12651 			} else {
12652 				/*
12653 				 * More than one cookie - try to allocate space.
12654 				 */
12655 				spx->txlt_dma_cookie_list = kmem_zalloc(
12656 				    sizeof (ddi_dma_cookie_t) * req_len,
12657 				    callback == NULL_FUNC ? KM_NOSLEEP :
12658 				    KM_SLEEP);
12659 				if (spx->txlt_dma_cookie_list == NULL) {
12660 					SATADBG1(SATA_DBG_DMA_SETUP,
12661 					    spx->txlt_sata_hba_inst,
12662 					    "sata_dma_buf_setup: cookie list "
12663 					    "allocation failed\n", NULL);
12664 					/*
12665 					 * We could not allocate space for
12666 					 * neccessary number of dma cookies in
12667 					 * this window, so we fail this request.
12668 					 * Next invocation would try again to
12669 					 * allocate space for cookie list.
12670 					 * Note:Packet residue was not modified.
12671 					 */
12672 					return (DDI_DMA_NORESOURCES);
12673 				} else {
12674 					spx->txlt_dma_cookie_list_len = req_len;
12675 				}
12676 			}
12677 		}
12678 		/*
12679 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
12680 		 * First cookie was already fetched.
12681 		 */
12682 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
12683 		cur_txfer_len =
12684 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
12685 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
12686 		spx->txlt_curwin_processed_dma_cookies++;
12687 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
12688 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
12689 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12690 			    &spx->txlt_dma_cookie_list[i]);
12691 			cur_txfer_len +=
12692 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12693 			spx->txlt_curwin_processed_dma_cookies++;
12694 			spx->txlt_sata_pkt->
12695 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
12696 		}
12697 	} else {
12698 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12699 		    "sata_dma_buf_setup: sliding within DMA window, "
12700 		    "cur cookie %d, total cookies %d\n",
12701 		    spx->txlt_curwin_processed_dma_cookies,
12702 		    spx->txlt_curwin_num_dma_cookies);
12703 
12704 		/*
12705 		 * Not all cookies from the current dma window were used because
12706 		 * of s/g limitation.
12707 		 * There is no need to re-size the list - it was set at
12708 		 * optimal size, or only default entry is used (s/g = 1).
12709 		 */
12710 		if (spx->txlt_dma_cookie_list == NULL) {
12711 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
12712 			spx->txlt_dma_cookie_list_len = 1;
12713 		}
12714 		/*
12715 		 * Since we are processing remaining cookies in a DMA window,
12716 		 * there may be less of them than the number of entries in the
12717 		 * current dma cookie list.
12718 		 */
12719 		req_len = MIN(spx->txlt_dma_cookie_list_len,
12720 		    (spx->txlt_curwin_num_dma_cookies -
12721 		    spx->txlt_curwin_processed_dma_cookies));
12722 
12723 		/* Fetch the next batch of cookies */
12724 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
12725 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12726 			    &spx->txlt_dma_cookie_list[i]);
12727 			cur_txfer_len +=
12728 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12729 			spx->txlt_sata_pkt->
12730 			    satapkt_cmd.satacmd_num_dma_cookies++;
12731 			spx->txlt_curwin_processed_dma_cookies++;
12732 		}
12733 	}
12734 
12735 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
12736 
12737 	/* Point sata_cmd to the cookie list */
12738 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
12739 	    &spx->txlt_dma_cookie_list[0];
12740 
12741 	/* Remember number of DMA cookies passed in sata packet */
12742 	spx->txlt_num_dma_cookies =
12743 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
12744 
12745 	ASSERT(cur_txfer_len != 0);
12746 	if (cur_txfer_len <= bp->b_bcount)
12747 		spx->txlt_total_residue -= cur_txfer_len;
12748 	else {
12749 		/*
12750 		 * Temporary DMA buffer has been padded by
12751 		 * ddi_dma_mem_alloc()!
12752 		 * This requires special handling, because DMA cookies are
12753 		 * based on the temporary buffer size, not the b_bcount,
12754 		 * and we have extra bytes to transfer - but the packet
12755 		 * residue has to stay correct because we will copy only
12756 		 * the requested number of bytes.
12757 		 */
12758 		spx->txlt_total_residue -= bp->b_bcount;
12759 	}
12760 
12761 	return (DDI_SUCCESS);
12762 }
12763 
12764 /*
12765  * Common routine for releasing DMA resources
12766  */
12767 static void
12768 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
12769 {
12770 	if (spx->txlt_buf_dma_handle != NULL) {
12771 		if (spx->txlt_tmp_buf != NULL)  {
12772 			/*
12773 			 * Intermediate DMA buffer was allocated.
12774 			 * Free allocated buffer and associated access handle.
12775 			 */
12776 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
12777 			spx->txlt_tmp_buf = NULL;
12778 		}
12779 		/*
12780 		 * Free DMA resources - cookies and handles
12781 		 */
12782 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
12783 		if (spx->txlt_dma_cookie_list != NULL) {
12784 			if (spx->txlt_dma_cookie_list !=
12785 			    &spx->txlt_dma_cookie) {
12786 				(void) kmem_free(spx->txlt_dma_cookie_list,
12787 				    spx->txlt_dma_cookie_list_len *
12788 				    sizeof (ddi_dma_cookie_t));
12789 				spx->txlt_dma_cookie_list = NULL;
12790 			}
12791 		}
12792 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
12793 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12794 		spx->txlt_buf_dma_handle = NULL;
12795 	}
12796 }
12797 
12798 /*
12799  * Free DMA resources
12800  * Used by the HBA driver to release DMA resources that it does not use.
12801  *
12802  * Returns Void
12803  */
12804 void
12805 sata_free_dma_resources(sata_pkt_t *sata_pkt)
12806 {
12807 	sata_pkt_txlate_t *spx;
12808 
12809 	if (sata_pkt == NULL)
12810 		return;
12811 
12812 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
12813 
12814 	sata_common_free_dma_rsrcs(spx);
12815 }
12816 
12817 /*
12818  * Fetch Device Identify data.
12819  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
12820  * command to a device and get the device identify data.
12821  * The device_info structure has to be set to device type (for selecting proper
12822  * device identify command).
12823  *
12824  * Returns:
12825  * SATA_SUCCESS if cmd succeeded
12826  * SATA_RETRY if cmd was rejected and could be retried,
12827  * SATA_FAILURE if cmd failed and should not be retried (port error)
12828  *
12829  * Cannot be called in an interrupt context.
12830  */
12831 
12832 static int
12833 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
12834     sata_drive_info_t *sdinfo)
12835 {
12836 	struct buf *bp;
12837 	sata_pkt_t *spkt;
12838 	sata_cmd_t *scmd;
12839 	sata_pkt_txlate_t *spx;
12840 	int rval;
12841 
12842 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12843 	spx->txlt_sata_hba_inst = sata_hba_inst;
12844 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
12845 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12846 	if (spkt == NULL) {
12847 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12848 		return (SATA_RETRY); /* may retry later */
12849 	}
12850 	/* address is needed now */
12851 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12852 
12853 	/*
12854 	 * Allocate buffer for Identify Data return data
12855 	 */
12856 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
12857 	if (bp == NULL) {
12858 		sata_pkt_free(spx);
12859 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12860 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12861 		    "sata_fetch_device_identify_data: "
12862 		    "cannot allocate buffer for ID"));
12863 		return (SATA_RETRY); /* may retry later */
12864 	}
12865 
12866 	/* Fill sata_pkt */
12867 	sdinfo->satadrv_state = SATA_STATE_PROBING;
12868 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12869 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12870 	/* Synchronous mode, no callback */
12871 	spkt->satapkt_comp = NULL;
12872 	/* Timeout 30s */
12873 	spkt->satapkt_time = sata_default_pkt_time;
12874 
12875 	scmd = &spkt->satapkt_cmd;
12876 	scmd->satacmd_bp = bp;
12877 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
12878 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
12879 
12880 	/* Build Identify Device cmd in the sata_pkt */
12881 	scmd->satacmd_addr_type = 0;		/* N/A */
12882 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
12883 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
12884 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
12885 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
12886 	scmd->satacmd_features_reg = 0;		/* N/A */
12887 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
12888 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
12889 		/* Identify Packet Device cmd */
12890 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
12891 	} else {
12892 		/* Identify Device cmd - mandatory for all other devices */
12893 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
12894 	}
12895 
12896 	/* Send pkt to SATA HBA driver */
12897 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
12898 
12899 #ifdef SATA_INJECT_FAULTS
12900 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
12901 #endif
12902 
12903 	if (rval == SATA_TRAN_ACCEPTED &&
12904 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
12905 		if (spx->txlt_buf_dma_handle != NULL) {
12906 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
12907 			    DDI_DMA_SYNC_FORKERNEL);
12908 			ASSERT(rval == DDI_SUCCESS);
12909 		}
12910 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
12911 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
12912 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12913 			    "SATA disk device at port %d - "
12914 			    "partial Identify Data",
12915 			    sdinfo->satadrv_addr.cport));
12916 			rval = SATA_RETRY; /* may retry later */
12917 			goto fail;
12918 		}
12919 		/* Update sata_drive_info */
12920 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
12921 		    sizeof (sata_id_t));
12922 
12923 		sdinfo->satadrv_features_support = 0;
12924 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12925 			/*
12926 			 * Retrieve capacity (disks only) and addressing mode
12927 			 */
12928 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
12929 		} else {
12930 			/*
12931 			 * For ATAPI devices one would have to issue
12932 			 * Get Capacity cmd for media capacity. Not here.
12933 			 */
12934 			sdinfo->satadrv_capacity = 0;
12935 			/*
12936 			 * Check what cdb length is supported
12937 			 */
12938 			if ((sdinfo->satadrv_id.ai_config &
12939 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
12940 				sdinfo->satadrv_atapi_cdb_len = 16;
12941 			else
12942 				sdinfo->satadrv_atapi_cdb_len = 12;
12943 		}
12944 		/* Setup supported features flags */
12945 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
12946 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
12947 
12948 		/* Check for SATA GEN and NCQ support */
12949 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
12950 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
12951 			/* SATA compliance */
12952 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
12953 				sdinfo->satadrv_features_support |=
12954 				    SATA_DEV_F_NCQ;
12955 			if (sdinfo->satadrv_id.ai_satacap &
12956 			    (SATA_1_SPEED | SATA_2_SPEED)) {
12957 				if (sdinfo->satadrv_id.ai_satacap &
12958 				    SATA_2_SPEED)
12959 					sdinfo->satadrv_features_support |=
12960 					    SATA_DEV_F_SATA2;
12961 				if (sdinfo->satadrv_id.ai_satacap &
12962 				    SATA_1_SPEED)
12963 					sdinfo->satadrv_features_support |=
12964 					    SATA_DEV_F_SATA1;
12965 			} else {
12966 				sdinfo->satadrv_features_support |=
12967 				    SATA_DEV_F_SATA1;
12968 			}
12969 		}
12970 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
12971 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
12972 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
12973 
12974 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
12975 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
12976 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
12977 			++sdinfo->satadrv_queue_depth;
12978 			/* Adjust according to controller capabilities */
12979 			sdinfo->satadrv_max_queue_depth = MIN(
12980 			    sdinfo->satadrv_queue_depth,
12981 			    SATA_QDEPTH(sata_hba_inst));
12982 			/* Adjust according to global queue depth limit */
12983 			sdinfo->satadrv_max_queue_depth = MIN(
12984 			    sdinfo->satadrv_max_queue_depth,
12985 			    sata_current_max_qdepth);
12986 			if (sdinfo->satadrv_max_queue_depth == 0)
12987 				sdinfo->satadrv_max_queue_depth = 1;
12988 		} else
12989 			sdinfo->satadrv_max_queue_depth = 1;
12990 
12991 		rval = SATA_SUCCESS;
12992 	} else {
12993 		/*
12994 		 * Woops, no Identify Data.
12995 		 */
12996 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
12997 			rval = SATA_RETRY; /* may retry later */
12998 		} else if (rval == SATA_TRAN_ACCEPTED) {
12999 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
13000 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
13001 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13002 			    spkt->satapkt_reason == SATA_PKT_RESET)
13003 				rval = SATA_RETRY; /* may retry later */
13004 			else
13005 				rval = SATA_FAILURE;
13006 		} else {
13007 			rval = SATA_FAILURE;
13008 		}
13009 	}
13010 fail:
13011 	/* Free allocated resources */
13012 	sata_free_local_buffer(spx);
13013 	sata_pkt_free(spx);
13014 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13015 
13016 	return (rval);
13017 }
13018 
13019 
13020 /*
13021  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13022  * UDMA mode is checked first, followed by MWDMA mode.
13023  * set correctly, so this function is setting it to the highest supported level.
13024  * Older SATA spec required that the device supports at least DMA 4 mode and
13025  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13026  * restriction has been removed.
13027  *
13028  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13029  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13030  *
13031  * NOTE: This function should be called only if DMA mode is supported.
13032  */
13033 static int
13034 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13035 {
13036 	sata_pkt_t *spkt;
13037 	sata_cmd_t *scmd;
13038 	sata_pkt_txlate_t *spx;
13039 	int i, mode;
13040 	uint8_t subcmd;
13041 	int rval = SATA_SUCCESS;
13042 
13043 	ASSERT(sdinfo != NULL);
13044 	ASSERT(sata_hba_inst != NULL);
13045 
13046 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13047 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13048 		/* Find highest Ultra DMA mode supported */
13049 		for (mode = 6; mode >= 0; --mode) {
13050 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13051 				break;
13052 		}
13053 #if 0
13054 		/* Left for historical reasons */
13055 		/*
13056 		 * Some initial version of SATA spec indicated that at least
13057 		 * UDMA mode 4 has to be supported. It is not mentioned in
13058 		 * SerialATA 2.6, so this restriction is removed.
13059 		 */
13060 		if (mode < 4)
13061 			return (SATA_FAILURE);
13062 #endif
13063 
13064 		/*
13065 		 * For disk, we're still going to set DMA mode whatever is
13066 		 * selected by default
13067 		 *
13068 		 * We saw an old maxtor sata drive will select Ultra DMA and
13069 		 * Multi-Word DMA simultaneouly by default, which is going
13070 		 * to cause DMA command timed out, so we need to select DMA
13071 		 * mode even when it's already done by default
13072 		 */
13073 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13074 
13075 			/* Find UDMA mode currently selected */
13076 			for (i = 6; i >= 0; --i) {
13077 				if (sdinfo->satadrv_id.ai_ultradma &
13078 				    (1 << (i + 8)))
13079 					break;
13080 			}
13081 			if (i >= mode)
13082 				/* Nothing to do */
13083 				return (SATA_SUCCESS);
13084 		}
13085 
13086 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13087 
13088 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13089 		/* Find highest MultiWord DMA mode supported */
13090 		for (mode = 2; mode >= 0; --mode) {
13091 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13092 				break;
13093 		}
13094 
13095 		/*
13096 		 * For disk, We're still going to set DMA mode whatever is
13097 		 * selected by default
13098 		 *
13099 		 * We saw an old maxtor sata drive will select Ultra DMA and
13100 		 * Multi-Word DMA simultaneouly by default, which is going
13101 		 * to cause DMA command timed out, so we need to select DMA
13102 		 * mode even when it's already done by default
13103 		 */
13104 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13105 
13106 			/* Find highest MultiWord DMA mode selected */
13107 			for (i = 2; i >= 0; --i) {
13108 				if (sdinfo->satadrv_id.ai_dworddma &
13109 				    (1 << (i + 8)))
13110 					break;
13111 			}
13112 			if (i >= mode)
13113 				/* Nothing to do */
13114 				return (SATA_SUCCESS);
13115 		}
13116 
13117 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
13118 	} else
13119 		return (SATA_SUCCESS);
13120 
13121 	/*
13122 	 * Set DMA mode via SET FEATURES COMMAND.
13123 	 * Prepare packet for SET FEATURES COMMAND.
13124 	 */
13125 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13126 	spx->txlt_sata_hba_inst = sata_hba_inst;
13127 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13128 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13129 	if (spkt == NULL) {
13130 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13131 		    "sata_set_dma_mode: could not set DMA mode %", mode));
13132 		rval = SATA_FAILURE;
13133 		goto done;
13134 	}
13135 	/* Fill sata_pkt */
13136 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13137 	/* Timeout 30s */
13138 	spkt->satapkt_time = sata_default_pkt_time;
13139 	/* Synchronous mode, no callback, interrupts */
13140 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13141 	spkt->satapkt_comp = NULL;
13142 	scmd = &spkt->satapkt_cmd;
13143 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13144 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13145 	scmd->satacmd_addr_type = 0;
13146 	scmd->satacmd_device_reg = 0;
13147 	scmd->satacmd_status_reg = 0;
13148 	scmd->satacmd_error_reg = 0;
13149 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13150 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
13151 	scmd->satacmd_sec_count_lsb = subcmd | mode;
13152 
13153 	/* Transfer command to HBA */
13154 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
13155 	    spkt) != SATA_TRAN_ACCEPTED ||
13156 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13157 		/* Pkt execution failed */
13158 		rval = SATA_FAILURE;
13159 	}
13160 done:
13161 
13162 	/* Free allocated resources */
13163 	if (spkt != NULL)
13164 		sata_pkt_free(spx);
13165 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13166 
13167 	return (rval);
13168 }
13169 
13170 
13171 /*
13172  * Set device caching mode.
13173  * One of the following operations should be specified:
13174  * SATAC_SF_ENABLE_READ_AHEAD
13175  * SATAC_SF_DISABLE_READ_AHEAD
13176  * SATAC_SF_ENABLE_WRITE_CACHE
13177  * SATAC_SF_DISABLE_WRITE_CACHE
13178  *
13179  * If operation fails, system log messgage is emitted.
13180  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
13181  * command was sent but did not succeed, and SATA_FAILURE otherwise.
13182  */
13183 
13184 static int
13185 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13186     int cache_op)
13187 {
13188 	sata_pkt_t *spkt;
13189 	sata_cmd_t *scmd;
13190 	sata_pkt_txlate_t *spx;
13191 	int rval = SATA_SUCCESS;
13192 	int hba_rval;
13193 	char *infop;
13194 
13195 	ASSERT(sdinfo != NULL);
13196 	ASSERT(sata_hba_inst != NULL);
13197 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
13198 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
13199 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
13200 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
13201 
13202 
13203 	/* Prepare packet for SET FEATURES COMMAND */
13204 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13205 	spx->txlt_sata_hba_inst = sata_hba_inst;
13206 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13207 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13208 	if (spkt == NULL) {
13209 		rval = SATA_FAILURE;
13210 		goto failure;
13211 	}
13212 	/* Fill sata_pkt */
13213 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13214 	/* Timeout 30s */
13215 	spkt->satapkt_time = sata_default_pkt_time;
13216 	/* Synchronous mode, no callback, interrupts */
13217 	spkt->satapkt_op_mode =
13218 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13219 	spkt->satapkt_comp = NULL;
13220 	scmd = &spkt->satapkt_cmd;
13221 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13222 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13223 	scmd->satacmd_addr_type = 0;
13224 	scmd->satacmd_device_reg = 0;
13225 	scmd->satacmd_status_reg = 0;
13226 	scmd->satacmd_error_reg = 0;
13227 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13228 	scmd->satacmd_features_reg = cache_op;
13229 
13230 	/* Transfer command to HBA */
13231 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
13232 	    SATA_DIP(sata_hba_inst), spkt);
13233 
13234 #ifdef SATA_INJECT_FAULTS
13235 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13236 #endif
13237 
13238 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
13239 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13240 		/* Pkt execution failed */
13241 		switch (cache_op) {
13242 		case SATAC_SF_ENABLE_READ_AHEAD:
13243 			infop = "enabling read ahead failed";
13244 			break;
13245 		case SATAC_SF_DISABLE_READ_AHEAD:
13246 			infop = "disabling read ahead failed";
13247 			break;
13248 		case SATAC_SF_ENABLE_WRITE_CACHE:
13249 			infop = "enabling write cache failed";
13250 			break;
13251 		case SATAC_SF_DISABLE_WRITE_CACHE:
13252 			infop = "disabling write cache failed";
13253 			break;
13254 		}
13255 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13256 		rval = SATA_RETRY;
13257 	}
13258 failure:
13259 	/* Free allocated resources */
13260 	if (spkt != NULL)
13261 		sata_pkt_free(spx);
13262 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13263 	return (rval);
13264 }
13265 
13266 /*
13267  * Set Removable Media Status Notification (enable/disable)
13268  * state == 0 , disable
13269  * state != 0 , enable
13270  *
13271  * If operation fails, system log messgage is emitted.
13272  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
13273  */
13274 
13275 static int
13276 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13277     int state)
13278 {
13279 	sata_pkt_t *spkt;
13280 	sata_cmd_t *scmd;
13281 	sata_pkt_txlate_t *spx;
13282 	int rval = SATA_SUCCESS;
13283 	char *infop;
13284 
13285 	ASSERT(sdinfo != NULL);
13286 	ASSERT(sata_hba_inst != NULL);
13287 
13288 	/* Prepare packet for SET FEATURES COMMAND */
13289 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13290 	spx->txlt_sata_hba_inst = sata_hba_inst;
13291 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13292 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13293 	if (spkt == NULL) {
13294 		rval = SATA_FAILURE;
13295 		goto failure;
13296 	}
13297 	/* Fill sata_pkt */
13298 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13299 	/* Timeout 30s */
13300 	spkt->satapkt_time = sata_default_pkt_time;
13301 	/* Synchronous mode, no callback, interrupts */
13302 	spkt->satapkt_op_mode =
13303 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13304 	spkt->satapkt_comp = NULL;
13305 	scmd = &spkt->satapkt_cmd;
13306 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13307 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13308 	scmd->satacmd_addr_type = 0;
13309 	scmd->satacmd_device_reg = 0;
13310 	scmd->satacmd_status_reg = 0;
13311 	scmd->satacmd_error_reg = 0;
13312 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13313 	if (state == 0)
13314 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
13315 	else
13316 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
13317 
13318 	/* Transfer command to HBA */
13319 	if (((*SATA_START_FUNC(sata_hba_inst))(
13320 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
13321 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13322 		/* Pkt execution failed */
13323 		if (state == 0)
13324 			infop = "disabling Removable Media Status "
13325 			    "Notification failed";
13326 		else
13327 			infop = "enabling Removable Media Status "
13328 			    "Notification failed";
13329 
13330 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13331 		rval = SATA_FAILURE;
13332 	}
13333 failure:
13334 	/* Free allocated resources */
13335 	if (spkt != NULL)
13336 		sata_pkt_free(spx);
13337 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13338 	return (rval);
13339 }
13340 
13341 
13342 /*
13343  * Update state and copy port ss* values from passed sata_device structure.
13344  * sata_address is validated - if not valid, nothing is changed in sata_scsi
13345  * configuration struct.
13346  *
13347  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
13348  * regardless of the state in device argument.
13349  *
13350  * Port mutex should be held while calling this function.
13351  */
13352 static void
13353 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
13354     sata_device_t *sata_device)
13355 {
13356 	sata_cport_info_t *cportinfo;
13357 
13358 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
13359 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
13360 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
13361 		    sata_device->satadev_addr.cport)
13362 			return;
13363 
13364 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
13365 		    sata_device->satadev_addr.cport);
13366 
13367 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
13368 		cportinfo->cport_scr = sata_device->satadev_scr;
13369 
13370 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
13371 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
13372 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13373 		cportinfo->cport_state |=
13374 		    sata_device->satadev_state & SATA_PSTATE_VALID;
13375 	}
13376 }
13377 
13378 void
13379 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
13380     sata_device_t *sata_device)
13381 {
13382 	sata_pmport_info_t *pmportinfo;
13383 
13384 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
13385 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
13386 	    SATA_NUM_PMPORTS(sata_hba_inst,
13387 	    sata_device->satadev_addr.cport) <
13388 	    sata_device->satadev_addr.pmport) {
13389 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
13390 		    "sata_update_port_info: error address %p.",
13391 		    &sata_device->satadev_addr);
13392 		return;
13393 	}
13394 
13395 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
13396 	    sata_device->satadev_addr.cport,
13397 	    sata_device->satadev_addr.pmport);
13398 
13399 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
13400 	pmportinfo->pmport_scr = sata_device->satadev_scr;
13401 
13402 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
13403 	pmportinfo->pmport_state &=
13404 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13405 	pmportinfo->pmport_state |=
13406 	    sata_device->satadev_state & SATA_PSTATE_VALID;
13407 }
13408 
13409 /*
13410  * Extract SATA port specification from an IOCTL argument.
13411  *
13412  * This function return the port the user land send us as is, unless it
13413  * cannot retrieve port spec, then -1 is returned.
13414  *
13415  * Support port multiplier.
13416  */
13417 static int32_t
13418 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
13419 {
13420 	int32_t port;
13421 
13422 	/* Extract port number from nvpair in dca structure  */
13423 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
13424 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
13425 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
13426 		    port));
13427 		port = -1;
13428 	}
13429 
13430 	return (port);
13431 }
13432 
13433 /*
13434  * Get dev_info_t pointer to the device node pointed to by port argument.
13435  * NOTE: target argument is a value used in ioctls to identify
13436  * the AP - it is not a sata_address.
13437  * It is a combination of cport, pmport and address qualifier, encodded same
13438  * way as a scsi target number.
13439  * At this moment it carries only cport number.
13440  *
13441  * PMult hotplug is supported now.
13442  *
13443  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13444  */
13445 
13446 static dev_info_t *
13447 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
13448 {
13449 	dev_info_t	*cdip = NULL;
13450 	int		target, tgt;
13451 	int 		circ;
13452 	uint8_t		qual;
13453 
13454 	sata_hba_inst_t	*sata_hba_inst;
13455 	scsi_hba_tran_t *scsi_hba_tran;
13456 
13457 	/* Get target id */
13458 	scsi_hba_tran = ddi_get_driver_private(dip);
13459 	if (scsi_hba_tran == NULL)
13460 		return (NULL);
13461 
13462 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
13463 
13464 	if (sata_hba_inst == NULL)
13465 		return (NULL);
13466 
13467 	/* Identify a port-mult by cport_info.cport_dev_type */
13468 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
13469 		qual = SATA_ADDR_DPMPORT;
13470 	else
13471 		qual = SATA_ADDR_DCPORT;
13472 
13473 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
13474 
13475 	/* Retrieve target dip */
13476 	ndi_devi_enter(dip, &circ);
13477 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13478 		dev_info_t *next = ddi_get_next_sibling(cdip);
13479 
13480 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13481 		    DDI_PROP_DONTPASS, "target", -1);
13482 		if (tgt == -1) {
13483 			/*
13484 			 * This is actually an error condition, but not
13485 			 * a fatal one. Just continue the search.
13486 			 */
13487 			cdip = next;
13488 			continue;
13489 		}
13490 
13491 		if (tgt == target)
13492 			break;
13493 
13494 		cdip = next;
13495 	}
13496 	ndi_devi_exit(dip, circ);
13497 
13498 	return (cdip);
13499 }
13500 
13501 /*
13502  * Get dev_info_t pointer to the device node pointed to by port argument.
13503  * NOTE: target argument is a value used in ioctls to identify
13504  * the AP - it is not a sata_address.
13505  * It is a combination of cport, pmport and address qualifier, encoded same
13506  * way as a scsi target number.
13507  *
13508  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13509  */
13510 
13511 static dev_info_t *
13512 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
13513 {
13514 	dev_info_t	*cdip = NULL;
13515 	int		target, tgt;
13516 	int 		circ;
13517 
13518 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
13519 
13520 	ndi_devi_enter(dip, &circ);
13521 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13522 		dev_info_t *next = ddi_get_next_sibling(cdip);
13523 
13524 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13525 		    DDI_PROP_DONTPASS, "target", -1);
13526 		if (tgt == -1) {
13527 			/*
13528 			 * This is actually an error condition, but not
13529 			 * a fatal one. Just continue the search.
13530 			 */
13531 			cdip = next;
13532 			continue;
13533 		}
13534 
13535 		if (tgt == target)
13536 			break;
13537 
13538 		cdip = next;
13539 	}
13540 	ndi_devi_exit(dip, circ);
13541 
13542 	return (cdip);
13543 }
13544 
13545 /*
13546  * Process sata port disconnect request.
13547  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
13548  * before this request. Nevertheless, if a device is still configured,
13549  * we need to attempt to offline and unconfigure device.
13550  * Regardless of the unconfigure operation results the port is marked as
13551  * deactivated and no access to the attached device is possible.
13552  * If the target node remains because unconfigure operation failed, its state
13553  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
13554  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
13555  * the device and remove old target node.
13556  *
13557  * This function invokes sata_hba_inst->satahba_tran->
13558  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13559  * If successful, the device structure (if any) attached to the specified port
13560  * is removed and state of the port marked appropriately.
13561  * Failure of the port_deactivate may keep port in the physically active state,
13562  * or may fail the port.
13563  *
13564  * NOTE: Port multiplier is supported.
13565  */
13566 
13567 static int
13568 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
13569     sata_device_t *sata_device)
13570 {
13571 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
13572 	sata_cport_info_t *cportinfo = NULL;
13573 	sata_pmport_info_t *pmportinfo = NULL;
13574 	sata_pmult_info_t *pmultinfo = NULL;
13575 	sata_device_t subsdevice;
13576 	int cport, pmport, qual;
13577 	int rval = SATA_SUCCESS;
13578 	int npmport = 0;
13579 	int rv = 0;
13580 
13581 	cport = sata_device->satadev_addr.cport;
13582 	pmport = sata_device->satadev_addr.pmport;
13583 	qual = sata_device->satadev_addr.qual;
13584 
13585 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13586 	if (qual == SATA_ADDR_DCPORT)
13587 		qual = SATA_ADDR_CPORT;
13588 	else
13589 		qual = SATA_ADDR_PMPORT;
13590 
13591 	/*
13592 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
13593 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13594 	 * Do the sanity check.
13595 	 */
13596 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
13597 		/* No physical port deactivation supported. */
13598 		return (EINVAL);
13599 	}
13600 
13601 	/* Check the current state of the port */
13602 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
13603 	    (SATA_DIP(sata_hba_inst), sata_device);
13604 
13605 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13606 
13607 	/*
13608 	 * Processing port mulitiplier
13609 	 */
13610 	if (qual == SATA_ADDR_CPORT &&
13611 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
13612 		mutex_enter(&cportinfo->cport_mutex);
13613 
13614 		/* Check controller port status */
13615 		sata_update_port_info(sata_hba_inst, sata_device);
13616 		if (rval != SATA_SUCCESS ||
13617 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13618 			/*
13619 			 * Device port status is unknown or it is in failed
13620 			 * state
13621 			 */
13622 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13623 			    SATA_PSTATE_FAILED;
13624 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13625 			    "sata_hba_ioctl: connect: failed to deactivate "
13626 			    "SATA port %d", cport);
13627 			mutex_exit(&cportinfo->cport_mutex);
13628 			return (EIO);
13629 		}
13630 
13631 		/* Disconnect all sub-devices. */
13632 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13633 		if (pmultinfo != NULL) {
13634 
13635 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
13636 			    sata_hba_inst, cport); npmport ++) {
13637 				subsdinfo = SATA_PMPORT_DRV_INFO(
13638 				    sata_hba_inst, cport, npmport);
13639 				if (subsdinfo == NULL)
13640 					continue;
13641 
13642 				subsdevice.satadev_addr = subsdinfo->
13643 				    satadrv_addr;
13644 
13645 				mutex_exit(&cportinfo->cport_mutex);
13646 				if (sata_ioctl_disconnect(sata_hba_inst,
13647 				    &subsdevice) == SATA_SUCCESS) {
13648 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
13649 					"[Remove] device at port %d:%d "
13650 					"successfully.", cport, npmport);
13651 				}
13652 				mutex_enter(&cportinfo->cport_mutex);
13653 			}
13654 		}
13655 
13656 		/* Disconnect the port multiplier */
13657 		cportinfo->cport_state &= ~SATA_STATE_READY;
13658 		mutex_exit(&cportinfo->cport_mutex);
13659 
13660 		sata_device->satadev_addr.qual = qual;
13661 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13662 		    (SATA_DIP(sata_hba_inst), sata_device);
13663 
13664 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13665 		    SE_NO_HINT);
13666 
13667 		mutex_enter(&cportinfo->cport_mutex);
13668 		sata_update_port_info(sata_hba_inst, sata_device);
13669 		if (rval != SATA_SUCCESS &&
13670 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13671 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13672 			rv = EIO;
13673 		} else {
13674 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13675 		}
13676 		mutex_exit(&cportinfo->cport_mutex);
13677 
13678 		return (rv);
13679 	}
13680 
13681 	/*
13682 	 * Process non-port-multiplier device - it could be a drive connected
13683 	 * to a port multiplier port or a controller port.
13684 	 */
13685 	if (qual == SATA_ADDR_PMPORT) {
13686 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13687 		mutex_enter(&pmportinfo->pmport_mutex);
13688 		sata_update_pmport_info(sata_hba_inst, sata_device);
13689 		if (rval != SATA_SUCCESS ||
13690 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13691 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
13692 			    SATA_PSTATE_FAILED;
13693 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13694 			    "sata_hba_ioctl: connect: failed to deactivate "
13695 			    "SATA port %d:%d", cport, pmport);
13696 			mutex_exit(&pmportinfo->pmport_mutex);
13697 			return (EIO);
13698 		}
13699 
13700 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
13701 			sdinfo = pmportinfo->pmport_sata_drive;
13702 			ASSERT(sdinfo != NULL);
13703 		}
13704 
13705 		/*
13706 		 * Set port's dev_state to not ready - this will disable
13707 		 * an access to a potentially attached device.
13708 		 */
13709 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
13710 
13711 		/* Remove and release sata_drive info structure. */
13712 		if (sdinfo != NULL) {
13713 			if ((sdinfo->satadrv_type &
13714 			    SATA_VALID_DEV_TYPE) != 0) {
13715 				/*
13716 				 * If a target node exists, try to offline
13717 				 * a device and remove target node.
13718 				 */
13719 				mutex_exit(&pmportinfo->pmport_mutex);
13720 				(void) sata_offline_device(sata_hba_inst,
13721 				    sata_device, sdinfo);
13722 				mutex_enter(&pmportinfo->pmport_mutex);
13723 			}
13724 
13725 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
13726 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
13727 			(void) kmem_free((void *)sdinfo,
13728 			    sizeof (sata_drive_info_t));
13729 		}
13730 		mutex_exit(&pmportinfo->pmport_mutex);
13731 
13732 	} else if (qual == SATA_ADDR_CPORT) {
13733 		mutex_enter(&cportinfo->cport_mutex);
13734 		sata_update_port_info(sata_hba_inst, sata_device);
13735 		if (rval != SATA_SUCCESS ||
13736 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13737 			/*
13738 			 * Device port status is unknown or it is in failed
13739 			 * state
13740 			 */
13741 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13742 			    SATA_PSTATE_FAILED;
13743 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13744 			    "sata_hba_ioctl: connect: failed to deactivate "
13745 			    "SATA port %d", cport);
13746 			mutex_exit(&cportinfo->cport_mutex);
13747 			return (EIO);
13748 		}
13749 
13750 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
13751 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13752 			ASSERT(pmultinfo != NULL);
13753 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
13754 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
13755 			ASSERT(sdinfo != NULL);
13756 		}
13757 		cportinfo->cport_state &= ~SATA_STATE_READY;
13758 
13759 		if (sdinfo != NULL) {
13760 			if ((sdinfo->satadrv_type &
13761 			    SATA_VALID_DEV_TYPE) != 0) {
13762 				/*
13763 				 * If a target node exists, try to offline
13764 				 * a device and remove target node.
13765 				 */
13766 				mutex_exit(&cportinfo->cport_mutex);
13767 				(void) sata_offline_device(sata_hba_inst,
13768 				    sata_device, sdinfo);
13769 				mutex_enter(&cportinfo->cport_mutex);
13770 			}
13771 
13772 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
13773 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
13774 			(void) kmem_free((void *)sdinfo,
13775 			    sizeof (sata_drive_info_t));
13776 		}
13777 		mutex_exit(&cportinfo->cport_mutex);
13778 	}
13779 
13780 	/* Just ask HBA driver to deactivate port */
13781 	sata_device->satadev_addr.qual = qual;
13782 
13783 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13784 	    (SATA_DIP(sata_hba_inst), sata_device);
13785 
13786 	/*
13787 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13788 	 * without the hint (to force listener to investivate the state).
13789 	 */
13790 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13791 	    SE_NO_HINT);
13792 
13793 	if (qual == SATA_ADDR_PMPORT) {
13794 		mutex_enter(&pmportinfo->pmport_mutex);
13795 		sata_update_pmport_info(sata_hba_inst, sata_device);
13796 
13797 		if (rval != SATA_SUCCESS &&
13798 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13799 			/*
13800 			 * Port deactivation failure - do not change port
13801 			 * state unless the state returned by HBA indicates a
13802 			 * port failure.
13803 			 *
13804 			 * NOTE: device structures were released, so devices
13805 			 * now are invisible! Port reset is needed to
13806 			 * re-enumerate devices.
13807 			 */
13808 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
13809 			rv = EIO;
13810 		} else {
13811 			/*
13812 			 * Deactivation succeded. From now on the sata framework
13813 			 * will not care what is happening to the device, until
13814 			 * the port is activated again.
13815 			 */
13816 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
13817 		}
13818 		mutex_exit(&pmportinfo->pmport_mutex);
13819 	} else if (qual == SATA_ADDR_CPORT) {
13820 		mutex_enter(&cportinfo->cport_mutex);
13821 		sata_update_port_info(sata_hba_inst, sata_device);
13822 
13823 		if (rval != SATA_SUCCESS &&
13824 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13825 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13826 			rv = EIO;
13827 		} else {
13828 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13829 		}
13830 		mutex_exit(&cportinfo->cport_mutex);
13831 	}
13832 
13833 	return (rv);
13834 }
13835 
13836 
13837 
13838 /*
13839  * Process sata port connect request
13840  * The sata cfgadm pluging will invoke this operation only if port was found
13841  * in the disconnect state (failed state is also treated as the disconnected
13842  * state).
13843  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
13844  * sata_tran_hotplug_ops->sata_tran_port_activate().
13845  * If successful and a device is found attached to the port,
13846  * the initialization sequence is executed to attach a device structure to
13847  * a port structure. The state of the port and a device would be set
13848  * appropriately.
13849  * The device is not set in configured state (system-wise) by this operation.
13850  *
13851  * Note, that activating the port may generate link events,
13852  * so it is important that following processing and the
13853  * event processing does not interfere with each other!
13854  *
13855  * This operation may remove port failed state and will
13856  * try to make port active and in good standing.
13857  *
13858  * NOTE: Port multiplier is supported.
13859  */
13860 
13861 static int
13862 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
13863     sata_device_t *sata_device)
13864 {
13865 	sata_pmport_info_t	*pmportinfo = NULL;
13866 	uint8_t cport, pmport, qual;
13867 	int rv = 0;
13868 
13869 	cport = sata_device->satadev_addr.cport;
13870 	pmport = sata_device->satadev_addr.pmport;
13871 	qual = sata_device->satadev_addr.qual;
13872 
13873 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13874 	if (qual == SATA_ADDR_DCPORT)
13875 		qual = SATA_ADDR_CPORT;
13876 	else
13877 		qual = SATA_ADDR_PMPORT;
13878 
13879 	if (qual == SATA_ADDR_PMPORT)
13880 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13881 
13882 	/*
13883 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
13884 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
13885 	 * Perform sanity check now.
13886 	 */
13887 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
13888 		/* No physical port activation supported. */
13889 		return (EINVAL);
13890 	}
13891 
13892 	/* Just ask HBA driver to activate port */
13893 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
13894 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
13895 		/*
13896 		 * Port activation failure.
13897 		 */
13898 		if (qual == SATA_ADDR_CPORT) {
13899 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13900 			    cport)->cport_mutex);
13901 			sata_update_port_info(sata_hba_inst, sata_device);
13902 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13903 				SATA_CPORT_STATE(sata_hba_inst, cport) =
13904 				    SATA_PSTATE_FAILED;
13905 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13906 				    "sata_hba_ioctl: connect: failed to "
13907 				    "activate SATA port %d", cport);
13908 			}
13909 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13910 			    cport)->cport_mutex);
13911 		} else { /* port multiplier device port */
13912 			mutex_enter(&pmportinfo->pmport_mutex);
13913 			sata_update_pmport_info(sata_hba_inst, sata_device);
13914 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13915 				SATA_PMPORT_STATE(sata_hba_inst, cport,
13916 				    pmport) = SATA_PSTATE_FAILED;
13917 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13918 				    "sata_hba_ioctl: connect: failed to "
13919 				    "activate SATA port %d:%d", cport, pmport);
13920 			}
13921 			mutex_exit(&pmportinfo->pmport_mutex);
13922 		}
13923 		return (EIO);
13924 	}
13925 
13926 	/* Virgin port state - will be updated by the port re-probe. */
13927 	if (qual == SATA_ADDR_CPORT) {
13928 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13929 		    cport)->cport_mutex);
13930 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
13931 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13932 		    cport)->cport_mutex);
13933 	} else { /* port multiplier device port */
13934 		mutex_enter(&pmportinfo->pmport_mutex);
13935 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
13936 		mutex_exit(&pmportinfo->pmport_mutex);
13937 	}
13938 
13939 	/*
13940 	 * Probe the port to find its state and attached device.
13941 	 */
13942 	if (sata_reprobe_port(sata_hba_inst, sata_device,
13943 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
13944 		rv = EIO;
13945 
13946 	/*
13947 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13948 	 * without the hint
13949 	 */
13950 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13951 	    SE_NO_HINT);
13952 
13953 	/*
13954 	 * If there is a device attached to the port, emit
13955 	 * a message.
13956 	 */
13957 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
13958 
13959 		if (qual == SATA_ADDR_CPORT) {
13960 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
13961 				sata_log(sata_hba_inst, CE_WARN,
13962 				    "SATA port multiplier detected "
13963 				    "at port %d", cport);
13964 			} else {
13965 				sata_log(sata_hba_inst, CE_WARN,
13966 				    "SATA device detected at port %d", cport);
13967 				if (sata_device->satadev_type ==
13968 				    SATA_DTYPE_UNKNOWN) {
13969 				/*
13970 				 * A device was not successfully identified
13971 				 */
13972 				sata_log(sata_hba_inst, CE_WARN,
13973 				    "Could not identify SATA "
13974 				    "device at port %d", cport);
13975 				}
13976 			}
13977 		} else { /* port multiplier device port */
13978 			sata_log(sata_hba_inst, CE_WARN,
13979 			    "SATA device detected at port %d:%d",
13980 			    cport, pmport);
13981 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
13982 				/*
13983 				 * A device was not successfully identified
13984 				 */
13985 				sata_log(sata_hba_inst, CE_WARN,
13986 				    "Could not identify SATA "
13987 				    "device at port %d:%d", cport, pmport);
13988 			}
13989 		}
13990 	}
13991 
13992 	return (rv);
13993 }
13994 
13995 
13996 /*
13997  * Process sata device unconfigure request.
13998  * The unconfigure operation uses generic nexus operation to
13999  * offline a device. It leaves a target device node attached.
14000  * and obviously sata_drive_info attached as well, because
14001  * from the hardware point of view nothing has changed.
14002  */
14003 static int
14004 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14005     sata_device_t *sata_device)
14006 {
14007 	int rv = 0;
14008 	dev_info_t *tdip;
14009 
14010 	/* We are addressing attached device, not a port */
14011 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14012 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14013 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14014 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14015 
14016 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14017 	    &sata_device->satadev_addr)) != NULL) {
14018 
14019 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14020 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14021 			    "sata_hba_ioctl: unconfigure: "
14022 			    "failed to unconfigure device at SATA port %d:%d",
14023 			    sata_device->satadev_addr.cport,
14024 			    sata_device->satadev_addr.pmport));
14025 			rv = EIO;
14026 		}
14027 		/*
14028 		 * The target node devi_state should be marked with
14029 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14030 		 * This would be the indication for cfgadm that
14031 		 * the AP node occupant state is 'unconfigured'.
14032 		 */
14033 
14034 	} else {
14035 		/*
14036 		 * This would indicate a failure on the part of cfgadm
14037 		 * to detect correct state of the node prior to this
14038 		 * call - one cannot unconfigure non-existing device.
14039 		 */
14040 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14041 		    "sata_hba_ioctl: unconfigure: "
14042 		    "attempt to unconfigure non-existing device "
14043 		    "at SATA port %d:%d",
14044 		    sata_device->satadev_addr.cport,
14045 		    sata_device->satadev_addr.pmport));
14046 		rv = ENXIO;
14047 	}
14048 	return (rv);
14049 }
14050 
14051 /*
14052  * Process sata device configure request
14053  * If port is in a failed state, operation is aborted - one has to use
14054  * an explicit connect or port activate request to try to get a port into
14055  * non-failed mode. Port reset wil also work in such situation.
14056  * If the port is in disconnected (shutdown) state, the connect operation is
14057  * attempted prior to any other action.
14058  * When port is in the active state, there is a device attached and the target
14059  * node exists, a device was most likely offlined.
14060  * If target node does not exist, a new target node is created. In both cases
14061  * an attempt is made to online (configure) the device.
14062  *
14063  * NOTE: Port multiplier is supported.
14064  */
14065 static int
14066 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14067     sata_device_t *sata_device)
14068 {
14069 	int cport, pmport, qual;
14070 	int rval;
14071 	boolean_t target = TRUE;
14072 	sata_cport_info_t *cportinfo;
14073 	sata_pmport_info_t *pmportinfo = NULL;
14074 	dev_info_t *tdip;
14075 	sata_drive_info_t *sdinfo;
14076 
14077 	cport = sata_device->satadev_addr.cport;
14078 	pmport = sata_device->satadev_addr.pmport;
14079 	qual = sata_device->satadev_addr.qual;
14080 
14081 	/* Get current port state */
14082 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14083 	    (SATA_DIP(sata_hba_inst), sata_device);
14084 
14085 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14086 	if (qual == SATA_ADDR_DPMPORT) {
14087 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14088 		mutex_enter(&pmportinfo->pmport_mutex);
14089 		sata_update_pmport_info(sata_hba_inst, sata_device);
14090 		if (rval != SATA_SUCCESS ||
14091 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14092 			/*
14093 			 * Obviously, device on a failed port is not visible
14094 			 */
14095 			mutex_exit(&pmportinfo->pmport_mutex);
14096 			return (ENXIO);
14097 		}
14098 		mutex_exit(&pmportinfo->pmport_mutex);
14099 	} else {
14100 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14101 		    cport)->cport_mutex);
14102 		sata_update_port_info(sata_hba_inst, sata_device);
14103 		if (rval != SATA_SUCCESS ||
14104 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14105 			/*
14106 			 * Obviously, device on a failed port is not visible
14107 			 */
14108 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14109 			    cport)->cport_mutex);
14110 			return (ENXIO);
14111 		}
14112 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14113 		    cport)->cport_mutex);
14114 	}
14115 
14116 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
14117 		/* need to activate port */
14118 		target = FALSE;
14119 
14120 		/* Sanity check */
14121 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14122 			return (ENXIO);
14123 
14124 		/* Just let HBA driver to activate port */
14125 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14126 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14127 			/*
14128 			 * Port activation failure - do not change port state
14129 			 * unless the state returned by HBA indicates a port
14130 			 * failure.
14131 			 */
14132 			if (qual == SATA_ADDR_DPMPORT) {
14133 				mutex_enter(&pmportinfo->pmport_mutex);
14134 				sata_update_pmport_info(sata_hba_inst,
14135 				    sata_device);
14136 				if (sata_device->satadev_state &
14137 				    SATA_PSTATE_FAILED)
14138 					pmportinfo->pmport_state =
14139 					    SATA_PSTATE_FAILED;
14140 				mutex_exit(&pmportinfo->pmport_mutex);
14141 			} else {
14142 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14143 				    cport)->cport_mutex);
14144 				sata_update_port_info(sata_hba_inst,
14145 				    sata_device);
14146 				if (sata_device->satadev_state &
14147 				    SATA_PSTATE_FAILED)
14148 					cportinfo->cport_state =
14149 					    SATA_PSTATE_FAILED;
14150 				mutex_exit(&SATA_CPORT_INFO(
14151 				    sata_hba_inst, cport)->cport_mutex);
14152 			}
14153 		}
14154 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14155 		    "sata_hba_ioctl: configure: "
14156 		    "failed to activate SATA port %d:%d",
14157 		    cport, pmport));
14158 		return (EIO);
14159 	}
14160 	/*
14161 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14162 	 * without the hint.
14163 	 */
14164 	sata_gen_sysevent(sata_hba_inst,
14165 	    &sata_device->satadev_addr, SE_NO_HINT);
14166 
14167 	/* Virgin port state */
14168 	if (qual == SATA_ADDR_DPMPORT) {
14169 		mutex_enter(&pmportinfo->pmport_mutex);
14170 		pmportinfo->pmport_state = 0;
14171 		mutex_exit(&pmportinfo->pmport_mutex);
14172 	} else {
14173 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14174 		    cport)-> cport_mutex);
14175 		cportinfo->cport_state = 0;
14176 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14177 		    cport)->cport_mutex);
14178 	}
14179 	/*
14180 	 * Always reprobe port, to get current device info.
14181 	 */
14182 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14183 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14184 		return (EIO);
14185 
14186 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
14187 		if (qual == SATA_ADDR_DPMPORT) {
14188 			/*
14189 			 * That's the transition from "inactive" port
14190 			 * to active one with device attached.
14191 			 */
14192 			sata_log(sata_hba_inst, CE_WARN,
14193 			    "SATA device detected at port %d:%d",
14194 			    cport, pmport);
14195 		} else {
14196 			/*
14197 			 * When PM is attached to the cport and cport is
14198 			 * activated, every PM device port needs to be reprobed.
14199 			 * We need to emit message for all devices detected
14200 			 * at port multiplier's device ports.
14201 			 * Add such code here.
14202 			 * For now, just inform about device attached to
14203 			 * cport.
14204 			 */
14205 			sata_log(sata_hba_inst, CE_WARN,
14206 			    "SATA device detected at port %d", cport);
14207 		}
14208 	}
14209 
14210 	/*
14211 	 * This is where real configuration operation starts.
14212 	 *
14213 	 * When PM is attached to the cport and cport is activated,
14214 	 * devices attached PM device ports may have to be configured
14215 	 * explicitly. This may change when port multiplier is supported.
14216 	 * For now, configure only disks and other valid target devices.
14217 	 */
14218 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
14219 		if (qual == SATA_ADDR_DCPORT) {
14220 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14221 				/*
14222 				 * A device was not successfully identified
14223 				 */
14224 				sata_log(sata_hba_inst, CE_WARN,
14225 				    "Could not identify SATA "
14226 				    "device at port %d", cport);
14227 			}
14228 		} else { /* port multiplier device port */
14229 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14230 				/*
14231 				 * A device was not successfully identified
14232 				 */
14233 				sata_log(sata_hba_inst, CE_WARN,
14234 				    "Could not identify SATA "
14235 				    "device at port %d:%d", cport, pmport);
14236 			}
14237 		}
14238 		return (ENXIO);		/* No device to configure */
14239 	}
14240 
14241 	/*
14242 	 * Here we may have a device in reset condition,
14243 	 * but because we are just configuring it, there is
14244 	 * no need to process the reset other than just
14245 	 * to clear device reset condition in the HBA driver.
14246 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
14247 	 * cause a first command sent the HBA driver with the request
14248 	 * to clear device reset condition.
14249 	 */
14250 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14251 	if (qual == SATA_ADDR_DPMPORT)
14252 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14253 	else
14254 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14255 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14256 	if (sdinfo == NULL) {
14257 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14258 		return (ENXIO);
14259 	}
14260 	if (sdinfo->satadrv_event_flags &
14261 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14262 		sdinfo->satadrv_event_flags = 0;
14263 	}
14264 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14265 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14266 
14267 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14268 	    &sata_device->satadev_addr)) != NULL) {
14269 		/*
14270 		 * Target node exists. Verify, that it belongs
14271 		 * to existing, attached device and not to
14272 		 * a removed device.
14273 		 */
14274 		if (sata_check_device_removed(tdip) == B_TRUE) {
14275 			if (qual == SATA_ADDR_DPMPORT)
14276 				sata_log(sata_hba_inst, CE_WARN,
14277 				    "SATA device at port %d cannot be "
14278 				    "configured. "
14279 				    "Application(s) accessing "
14280 				    "previously attached device "
14281 				    "have to release it before newly "
14282 				    "inserted device can be made accessible.",
14283 				    cport);
14284 			else
14285 				sata_log(sata_hba_inst, CE_WARN,
14286 				    "SATA device at port %d:%d cannot be"
14287 				    "configured. "
14288 				    "Application(s) accessing "
14289 				    "previously attached device "
14290 				    "have to release it before newly "
14291 				    "inserted device can be made accessible.",
14292 				    cport, pmport);
14293 			return (EIO);
14294 		}
14295 		/*
14296 		 * Device was not removed and re-inserted.
14297 		 * Try to online it.
14298 		 */
14299 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
14300 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14301 			    "sata_hba_ioctl: configure: "
14302 			    "onlining device at SATA port "
14303 			    "%d:%d failed", cport, pmport));
14304 			return (EIO);
14305 		}
14306 
14307 		if (qual == SATA_ADDR_DPMPORT) {
14308 			mutex_enter(&pmportinfo->pmport_mutex);
14309 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14310 			mutex_exit(&pmportinfo->pmport_mutex);
14311 		} else {
14312 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14313 			    cport)->cport_mutex);
14314 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14315 			mutex_exit(&SATA_CPORT_INFO(
14316 			    sata_hba_inst, cport)->cport_mutex);
14317 		}
14318 	} else {
14319 		/*
14320 		 * No target node - need to create a new target node.
14321 		 */
14322 		if (qual == SATA_ADDR_DPMPORT) {
14323 			mutex_enter(&pmportinfo->pmport_mutex);
14324 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14325 			mutex_exit(&pmportinfo->pmport_mutex);
14326 		} else {
14327 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14328 			    cport_mutex);
14329 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14330 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14331 			    cport_mutex);
14332 		}
14333 
14334 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
14335 		    sata_hba_inst, &sata_device->satadev_addr);
14336 		if (tdip == NULL) {
14337 			/* Configure operation failed */
14338 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14339 			    "sata_hba_ioctl: configure: "
14340 			    "configuring SATA device at port %d:%d "
14341 			    "failed", cport, pmport));
14342 			return (EIO);
14343 		}
14344 	}
14345 	return (0);
14346 }
14347 
14348 
14349 /*
14350  * Process ioctl deactivate port request.
14351  * Arbitrarily unconfigure attached device, if any.
14352  * Even if the unconfigure fails, proceed with the
14353  * port deactivation.
14354  *
14355  * NOTE: Port Multiplier is supported now.
14356  */
14357 
14358 static int
14359 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
14360     sata_device_t *sata_device)
14361 {
14362 	int cport, pmport, qual;
14363 	int rval, rv = 0;
14364 	int npmport;
14365 	sata_cport_info_t *cportinfo;
14366 	sata_pmport_info_t *pmportinfo;
14367 	sata_pmult_info_t *pmultinfo;
14368 	dev_info_t *tdip;
14369 	sata_drive_info_t *sdinfo = NULL;
14370 	sata_device_t subsdevice;
14371 
14372 	/* Sanity check */
14373 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
14374 		return (ENOTSUP);
14375 
14376 	cport = sata_device->satadev_addr.cport;
14377 	pmport = sata_device->satadev_addr.pmport;
14378 	qual = sata_device->satadev_addr.qual;
14379 
14380 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
14381 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14382 	if (qual == SATA_ADDR_DCPORT)
14383 		qual = SATA_ADDR_CPORT;
14384 	else
14385 		qual = SATA_ADDR_PMPORT;
14386 
14387 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14388 	if (qual == SATA_ADDR_PMPORT)
14389 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14390 
14391 	/*
14392 	 * Processing port multiplier
14393 	 */
14394 	if (qual == SATA_ADDR_CPORT &&
14395 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14396 		mutex_enter(&cportinfo->cport_mutex);
14397 
14398 		/* Deactivate all sub-deices */
14399 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14400 		if (pmultinfo != NULL) {
14401 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14402 			    sata_hba_inst, cport); npmport++) {
14403 
14404 				subsdevice.satadev_addr.cport = cport;
14405 				subsdevice.satadev_addr.pmport =
14406 				    (uint8_t)npmport;
14407 				subsdevice.satadev_addr.qual =
14408 				    SATA_ADDR_DPMPORT;
14409 
14410 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14411 				    "sata_hba_ioctl: deactivate: trying to "
14412 				    "deactivate SATA port %d:%d",
14413 				    cport, npmport);
14414 
14415 				mutex_exit(&cportinfo->cport_mutex);
14416 				if (sata_ioctl_deactivate(sata_hba_inst,
14417 				    &subsdevice) == SATA_SUCCESS) {
14418 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14419 					    "[Deactivate] device at port %d:%d "
14420 					    "successfully.", cport, npmport);
14421 				}
14422 				mutex_enter(&cportinfo->cport_mutex);
14423 			}
14424 		}
14425 
14426 		/* Deactivate the port multiplier now. */
14427 		cportinfo->cport_state &= ~SATA_STATE_READY;
14428 		mutex_exit(&cportinfo->cport_mutex);
14429 
14430 		sata_device->satadev_addr.qual = qual;
14431 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14432 		    (SATA_DIP(sata_hba_inst), sata_device);
14433 
14434 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14435 		    SE_NO_HINT);
14436 
14437 		mutex_enter(&cportinfo->cport_mutex);
14438 		sata_update_port_info(sata_hba_inst, sata_device);
14439 		if (rval != SATA_SUCCESS) {
14440 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14441 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14442 			}
14443 			rv = EIO;
14444 		} else {
14445 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14446 		}
14447 		mutex_exit(&cportinfo->cport_mutex);
14448 
14449 		return (rv);
14450 	}
14451 
14452 	/*
14453 	 * Process non-port-multiplier device - it could be a drive connected
14454 	 * to a port multiplier port or a controller port.
14455 	 */
14456 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14457 	if (qual == SATA_ADDR_CPORT) {
14458 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14459 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14460 			/* deal only with valid devices */
14461 			if ((cportinfo->cport_dev_type &
14462 			    SATA_VALID_DEV_TYPE) != 0)
14463 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14464 		}
14465 		cportinfo->cport_state &= ~SATA_STATE_READY;
14466 	} else {
14467 		/* Port multiplier device port */
14468 		mutex_enter(&pmportinfo->pmport_mutex);
14469 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14470 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
14471 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
14472 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
14473 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14474 		mutex_exit(&pmportinfo->pmport_mutex);
14475 	}
14476 
14477 	if (sdinfo != NULL) {
14478 		/*
14479 		 * If a target node exists, try to offline a device and
14480 		 * to remove a target node.
14481 		 */
14482 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14483 		    cport_mutex);
14484 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14485 		    &sata_device->satadev_addr);
14486 		if (tdip != NULL) {
14487 			/* target node exist */
14488 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14489 			    "sata_hba_ioctl: port deactivate: "
14490 			    "target node exists.", NULL);
14491 
14492 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
14493 			    NDI_SUCCESS) {
14494 				SATA_LOG_D((sata_hba_inst, CE_WARN,
14495 				    "sata_hba_ioctl: port deactivate: "
14496 				    "failed to unconfigure device at port "
14497 				    "%d:%d before deactivating the port",
14498 				    cport, pmport));
14499 				/*
14500 				 * Set DEVICE REMOVED state in the target
14501 				 * node. It will prevent an access to
14502 				 * the device even when a new device is
14503 				 * attached, until the old target node is
14504 				 * released, removed and recreated for a new
14505 				 * device.
14506 				 */
14507 				sata_set_device_removed(tdip);
14508 
14509 				/*
14510 				 * Instruct the event daemon to try the
14511 				 * target node cleanup later.
14512 				 */
14513 				sata_set_target_node_cleanup(sata_hba_inst,
14514 				    &sata_device->satadev_addr);
14515 			}
14516 		}
14517 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14518 		    cport_mutex);
14519 		/*
14520 		 * In any case, remove and release sata_drive_info
14521 		 * structure.
14522 		 */
14523 		if (qual == SATA_ADDR_CPORT) {
14524 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14525 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14526 		} else { /* port multiplier device port */
14527 			mutex_enter(&pmportinfo->pmport_mutex);
14528 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14529 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14530 			mutex_exit(&pmportinfo->pmport_mutex);
14531 		}
14532 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
14533 	}
14534 
14535 	if (qual == SATA_ADDR_CPORT) {
14536 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
14537 		    SATA_STATE_PROBING);
14538 	} else if (qual == SATA_ADDR_PMPORT) {
14539 		mutex_enter(&pmportinfo->pmport_mutex);
14540 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
14541 		    SATA_STATE_PROBING);
14542 		mutex_exit(&pmportinfo->pmport_mutex);
14543 	}
14544 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14545 
14546 	/* Just let HBA driver to deactivate port */
14547 	sata_device->satadev_addr.qual = qual;
14548 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14549 	    (SATA_DIP(sata_hba_inst), sata_device);
14550 
14551 	/*
14552 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14553 	 * without the hint
14554 	 */
14555 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14556 	    SE_NO_HINT);
14557 
14558 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14559 	sata_update_port_info(sata_hba_inst, sata_device);
14560 	if (qual == SATA_ADDR_CPORT) {
14561 		if (rval != SATA_SUCCESS) {
14562 			/*
14563 			 * Port deactivation failure - do not change port state
14564 			 * unless the state returned by HBA indicates a port
14565 			 * failure.
14566 			 */
14567 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14568 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14569 				    SATA_PSTATE_FAILED;
14570 			}
14571 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14572 			    "sata_hba_ioctl: port deactivate: "
14573 			    "cannot deactivate SATA port %d", cport));
14574 			rv = EIO;
14575 		} else {
14576 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14577 		}
14578 	} else {
14579 		mutex_enter(&pmportinfo->pmport_mutex);
14580 		if (rval != SATA_SUCCESS) {
14581 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14582 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14583 				    pmport) = SATA_PSTATE_FAILED;
14584 			}
14585 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14586 			    "sata_hba_ioctl: port deactivate: "
14587 			    "cannot deactivate SATA port %d:%d",
14588 			    cport, pmport));
14589 			rv = EIO;
14590 		} else {
14591 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14592 		}
14593 		mutex_exit(&pmportinfo->pmport_mutex);
14594 	}
14595 
14596 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14597 
14598 	return (rv);
14599 }
14600 
14601 /*
14602  * Process ioctl port activate request.
14603  *
14604  * NOTE: Port multiplier is supported now.
14605  */
14606 static int
14607 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
14608     sata_device_t *sata_device)
14609 {
14610 	int cport, pmport, qual;
14611 	sata_cport_info_t *cportinfo;
14612 	sata_pmport_info_t *pmportinfo = NULL;
14613 	boolean_t dev_existed = TRUE;
14614 
14615 	/* Sanity check */
14616 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14617 		return (ENOTSUP);
14618 
14619 	cport = sata_device->satadev_addr.cport;
14620 	pmport = sata_device->satadev_addr.pmport;
14621 	qual = sata_device->satadev_addr.qual;
14622 
14623 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14624 
14625 	/*
14626 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14627 	 * is a device. But what we are dealing with is port/pmport.
14628 	 */
14629 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14630 	if (qual == SATA_ADDR_DCPORT)
14631 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14632 	else
14633 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14634 
14635 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14636 	if (qual == SATA_ADDR_PMPORT) {
14637 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14638 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
14639 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
14640 			dev_existed = FALSE;
14641 	} else { /* cport */
14642 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
14643 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
14644 			dev_existed = FALSE;
14645 	}
14646 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14647 
14648 	/* Just let HBA driver to activate port, if necessary */
14649 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14650 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14651 		/*
14652 		 * Port activation failure - do not change port state unless
14653 		 * the state returned by HBA indicates a port failure.
14654 		 */
14655 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14656 		    cport)->cport_mutex);
14657 		sata_update_port_info(sata_hba_inst, sata_device);
14658 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14659 			if (qual == SATA_ADDR_PMPORT) {
14660 				mutex_enter(&pmportinfo->pmport_mutex);
14661 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14662 				mutex_exit(&pmportinfo->pmport_mutex);
14663 			} else
14664 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14665 
14666 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14667 			    cport)->cport_mutex);
14668 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14669 			    "sata_hba_ioctl: port activate: cannot activate "
14670 			    "SATA port %d:%d", cport, pmport));
14671 			return (EIO);
14672 		}
14673 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14674 	}
14675 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14676 	if (qual == SATA_ADDR_PMPORT) {
14677 		mutex_enter(&pmportinfo->pmport_mutex);
14678 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
14679 		mutex_exit(&pmportinfo->pmport_mutex);
14680 	} else
14681 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
14682 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14683 
14684 	/*
14685 	 * Re-probe port to find its current state and possibly attached device.
14686 	 * Port re-probing may change the cportinfo device type if device is
14687 	 * found attached.
14688 	 * If port probing failed, the device type would be set to
14689 	 * SATA_DTYPE_NONE.
14690 	 */
14691 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
14692 	    SATA_DEV_IDENTIFY_RETRY);
14693 
14694 	/*
14695 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14696 	 * without the hint.
14697 	 */
14698 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14699 	    SE_NO_HINT);
14700 
14701 	if (dev_existed == FALSE) {
14702 		if (qual == SATA_ADDR_PMPORT &&
14703 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14704 			/*
14705 			 * That's the transition from the "inactive" port state
14706 			 * or the active port without a device attached to the
14707 			 * active port state with a device attached.
14708 			 */
14709 			sata_log(sata_hba_inst, CE_WARN,
14710 			    "SATA device detected at port %d:%d",
14711 			    cport, pmport);
14712 		} else if (qual == SATA_ADDR_CPORT &&
14713 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14714 			/*
14715 			 * That's the transition from the "inactive" port state
14716 			 * or the active port without a device attached to the
14717 			 * active port state with a device attached.
14718 			 */
14719 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
14720 				sata_log(sata_hba_inst, CE_WARN,
14721 				    "SATA device detected at port %d", cport);
14722 			} else {
14723 				sata_log(sata_hba_inst, CE_WARN,
14724 				    "SATA port multiplier detected at port %d",
14725 				    cport);
14726 			}
14727 		}
14728 	}
14729 	return (0);
14730 }
14731 
14732 
14733 
14734 /*
14735  * Process ioctl reset port request.
14736  *
14737  * NOTE: Port-Multiplier is supported.
14738  */
14739 static int
14740 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
14741     sata_device_t *sata_device)
14742 {
14743 	int cport, pmport, qual;
14744 	int rv = 0;
14745 
14746 	cport = sata_device->satadev_addr.cport;
14747 	pmport = sata_device->satadev_addr.pmport;
14748 	qual = sata_device->satadev_addr.qual;
14749 
14750 	/*
14751 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14752 	 * is a device. But what we are dealing with is port/pmport.
14753 	 */
14754 	if (qual == SATA_ADDR_DCPORT)
14755 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14756 	else
14757 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14758 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
14759 
14760 	/* Sanity check */
14761 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14762 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14763 		    "sata_hba_ioctl: sata_hba_tran missing required "
14764 		    "function sata_tran_reset_dport"));
14765 		return (ENOTSUP);
14766 	}
14767 
14768 	/* Ask HBA to reset port */
14769 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
14770 	    sata_device) != SATA_SUCCESS) {
14771 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14772 		    "sata_hba_ioctl: reset port: failed %d:%d",
14773 		    cport, pmport));
14774 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14775 		    cport_mutex);
14776 		sata_update_port_info(sata_hba_inst, sata_device);
14777 		if (qual == SATA_ADDR_CPORT)
14778 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14779 			    SATA_PSTATE_FAILED;
14780 		else {
14781 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14782 			    pmport));
14783 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14784 			    SATA_PSTATE_FAILED;
14785 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14786 			    pmport));
14787 		}
14788 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14789 		    cport_mutex);
14790 		rv = EIO;
14791 	}
14792 	/*
14793 	 * Beacuse the port was reset, it should be probed and
14794 	 * attached device reinitialized. At this point the
14795 	 * port state is unknown - it's state is HBA-specific.
14796 	 * Re-probe port to get its state.
14797 	 */
14798 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14799 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
14800 		rv = EIO;
14801 	}
14802 	return (rv);
14803 }
14804 
14805 /*
14806  * Process ioctl reset device request.
14807  *
14808  * NOTE: Port multiplier is supported.
14809  */
14810 static int
14811 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
14812     sata_device_t *sata_device)
14813 {
14814 	sata_drive_info_t *sdinfo = NULL;
14815 	sata_pmult_info_t *pmultinfo = NULL;
14816 	int cport, pmport;
14817 	int rv = 0;
14818 
14819 	/* Sanity check */
14820 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14821 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14822 		    "sata_hba_ioctl: sata_hba_tran missing required "
14823 		    "function sata_tran_reset_dport"));
14824 		return (ENOTSUP);
14825 	}
14826 
14827 	cport = sata_device->satadev_addr.cport;
14828 	pmport = sata_device->satadev_addr.pmport;
14829 
14830 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14831 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
14832 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
14833 		    SATA_DTYPE_PMULT)
14834 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
14835 			    cport_devp.cport_sata_pmult;
14836 		else
14837 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
14838 			    sata_device->satadev_addr.cport);
14839 	} else { /* port multiplier */
14840 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14841 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
14842 		    sata_device->satadev_addr.cport,
14843 		    sata_device->satadev_addr.pmport);
14844 	}
14845 	if (sdinfo == NULL && pmultinfo == NULL) {
14846 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14847 		return (EINVAL);
14848 	}
14849 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14850 
14851 	/* Ask HBA to reset device */
14852 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
14853 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14854 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14855 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
14856 		    cport, pmport));
14857 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14858 		    cport_mutex);
14859 		sata_update_port_info(sata_hba_inst, sata_device);
14860 		/*
14861 		 * Device info structure remains attached. Another device reset
14862 		 * or port disconnect/connect and re-probing is
14863 		 * needed to change it's state
14864 		 */
14865 		if (sdinfo != NULL) {
14866 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
14867 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
14868 		} else if (pmultinfo != NULL) {
14869 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
14870 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
14871 		}
14872 
14873 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14874 		rv = EIO;
14875 	}
14876 	/*
14877 	 * If attached device was a port multiplier, some extra processing
14878 	 * may be needed to bring it back. SATA specification requies a
14879 	 * mandatory software reset on host port to reliably enumerate a port
14880 	 * multiplier, the HBA driver should handle that after reset
14881 	 * operation.
14882 	 */
14883 	return (rv);
14884 }
14885 
14886 
14887 /*
14888  * Process ioctl reset all request.
14889  */
14890 static int
14891 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
14892 {
14893 	sata_device_t sata_device;
14894 	int rv = 0;
14895 	int tcport;
14896 	int tpmport = 0;
14897 
14898 	sata_device.satadev_rev = SATA_DEVICE_REV;
14899 
14900 	/*
14901 	 * There is no protection here for configured devices.
14902 	 */
14903 	/* Sanity check */
14904 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14905 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14906 		    "sata_hba_ioctl: sata_hba_tran missing required "
14907 		    "function sata_tran_reset_dport"));
14908 		return (ENOTSUP);
14909 	}
14910 
14911 	/*
14912 	 * Need to lock all ports, not just one.
14913 	 * If any port is locked by event processing, fail the whole operation.
14914 	 * One port is already locked, but for simplicity lock it again.
14915 	 */
14916 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
14917 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14918 		    cport_mutex);
14919 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
14920 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
14921 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14922 			    cport_mutex);
14923 			rv = EBUSY;
14924 			break;
14925 		} else {
14926 			/*
14927 			 * It is enough to lock cport in command-based
14928 			 * switching mode.
14929 			 */
14930 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
14931 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
14932 		}
14933 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14934 		    cport_mutex);
14935 	}
14936 
14937 	if (rv == 0) {
14938 		/*
14939 		 * All cports were successfully locked.
14940 		 * Reset main SATA controller.
14941 		 * Set the device address to port 0, to have a valid device
14942 		 * address.
14943 		 */
14944 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
14945 		sata_device.satadev_addr.cport = 0;
14946 		sata_device.satadev_addr.pmport = 0;
14947 
14948 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
14949 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
14950 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14951 			    "sata_hba_ioctl: reset controller failed"));
14952 			return (EIO);
14953 		}
14954 		/*
14955 		 * Because ports were reset, port states are unknown.
14956 		 * They should be re-probed to get their state and
14957 		 * attached devices should be reinitialized.
14958 		 */
14959 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
14960 		    tcport++) {
14961 			sata_device.satadev_addr.cport = tcport;
14962 			sata_device.satadev_addr.pmport = tpmport;
14963 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
14964 
14965 			/*
14966 			 * The sata_reprobe_port() will mark a
14967 			 * SATA_EVNT_DEVICE_RESET event on the port
14968 			 * multiplier, all its sub-ports will be probed by
14969 			 * sata daemon afterwards.
14970 			 */
14971 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
14972 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14973 				rv = EIO;
14974 		}
14975 	}
14976 	/*
14977 	 * Unlock all ports
14978 	 */
14979 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
14980 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14981 		    cport_mutex);
14982 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
14983 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
14984 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14985 		    cport_mutex);
14986 	}
14987 
14988 	/*
14989 	 * This operation returns EFAULT if either reset
14990 	 * controller failed or a re-probing of any port failed.
14991 	 */
14992 	return (rv);
14993 }
14994 
14995 
14996 /*
14997  * Process ioctl port self test request.
14998  *
14999  * NOTE: Port multiplier code is not completed nor tested.
15000  */
15001 static int
15002 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15003     sata_device_t *sata_device)
15004 {
15005 	int cport, pmport, qual;
15006 	int rv = 0;
15007 
15008 	/* Sanity check */
15009 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15010 		return (ENOTSUP);
15011 
15012 	cport = sata_device->satadev_addr.cport;
15013 	pmport = sata_device->satadev_addr.pmport;
15014 	qual = sata_device->satadev_addr.qual;
15015 
15016 	/*
15017 	 * There is no protection here for a configured
15018 	 * device attached to this port.
15019 	 */
15020 
15021 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15022 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15023 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15024 		    "sata_hba_ioctl: port selftest: "
15025 		    "failed port %d:%d", cport, pmport));
15026 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15027 		    cport_mutex);
15028 		sata_update_port_info(sata_hba_inst, sata_device);
15029 		if (qual == SATA_ADDR_CPORT)
15030 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15031 			    SATA_PSTATE_FAILED;
15032 		else { /* port multiplier device port */
15033 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15034 			    cport, pmport));
15035 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15036 			    SATA_PSTATE_FAILED;
15037 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15038 			    cport, pmport));
15039 		}
15040 
15041 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15042 		    cport_mutex);
15043 		return (EIO);
15044 	}
15045 	/*
15046 	 * Beacuse the port was reset in the course of testing, it should be
15047 	 * re-probed and attached device state should be restored. At this
15048 	 * point the port state is unknown - it's state is HBA-specific.
15049 	 * Force port re-probing to get it into a known state.
15050 	 */
15051 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15052 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15053 		rv = EIO;
15054 	return (rv);
15055 }
15056 
15057 
15058 /*
15059  * sata_cfgadm_state:
15060  * Use the sata port state and state of the target node to figure out
15061  * the cfgadm_state.
15062  *
15063  * The port argument is a value with encoded cport,
15064  * pmport and address qualifier, in the same manner as a scsi target number.
15065  * SCSI_TO_SATA_CPORT macro extracts cport number,
15066  * SCSI_TO_SATA_PMPORT extracts pmport number and
15067  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15068  *
15069  * Port multiplier is supported.
15070  */
15071 
15072 static void
15073 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15074     devctl_ap_state_t *ap_state)
15075 {
15076 	uint8_t		cport, pmport, qual;
15077 	uint32_t	port_state, pmult_state;
15078 	uint32_t	dev_type;
15079 	sata_drive_info_t *sdinfo;
15080 
15081 	cport = SCSI_TO_SATA_CPORT(port);
15082 	pmport = SCSI_TO_SATA_PMPORT(port);
15083 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15084 
15085 	/* Check cport state */
15086 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15087 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15088 	    port_state & SATA_PSTATE_FAILED) {
15089 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15090 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15091 		if (port_state & SATA_PSTATE_FAILED)
15092 			ap_state->ap_condition = AP_COND_FAILED;
15093 		else
15094 			ap_state->ap_condition = AP_COND_UNKNOWN;
15095 
15096 		return;
15097 	}
15098 
15099 	/* cport state is okay. Now check pmport state */
15100 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15101 		/* Sanity check */
15102 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15103 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15104 		    cport, pmport) == NULL)
15105 			return;
15106 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15107 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15108 		    port_state & SATA_PSTATE_FAILED) {
15109 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15110 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15111 			if (port_state & SATA_PSTATE_FAILED)
15112 				ap_state->ap_condition = AP_COND_FAILED;
15113 			else
15114 				ap_state->ap_condition = AP_COND_UNKNOWN;
15115 
15116 			return;
15117 		}
15118 	}
15119 
15120 	/* Port is enabled and ready */
15121 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15122 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15123 	else
15124 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15125 
15126 	switch (dev_type) {
15127 	case SATA_DTYPE_NONE:
15128 	{
15129 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15130 		ap_state->ap_condition = AP_COND_OK;
15131 		/* No device attached */
15132 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
15133 		break;
15134 	}
15135 	case SATA_DTYPE_PMULT:
15136 	{
15137 		/* Need to check port multiplier state */
15138 		ASSERT(qual == SATA_ADDR_DCPORT);
15139 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
15140 		    pmult_state;
15141 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
15142 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15143 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15144 			if (pmult_state & SATA_PSTATE_FAILED)
15145 				ap_state->ap_condition = AP_COND_FAILED;
15146 			else
15147 				ap_state->ap_condition = AP_COND_UNKNOWN;
15148 
15149 			return;
15150 		}
15151 
15152 		/* Port multiplier is not configurable */
15153 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
15154 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15155 		ap_state->ap_condition = AP_COND_OK;
15156 		break;
15157 	}
15158 
15159 	case SATA_DTYPE_ATADISK:
15160 	case SATA_DTYPE_ATAPICD:
15161 	case SATA_DTYPE_ATAPITAPE:
15162 	case SATA_DTYPE_ATAPIDISK:
15163 	{
15164 		dev_info_t *tdip = NULL;
15165 		dev_info_t *dip = NULL;
15166 		int circ;
15167 
15168 		dip = SATA_DIP(sata_hba_inst);
15169 		tdip = sata_get_target_dip(dip, cport, pmport);
15170 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15171 		if (tdip != NULL) {
15172 			ndi_devi_enter(dip, &circ);
15173 			mutex_enter(&(DEVI(tdip)->devi_lock));
15174 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
15175 				/*
15176 				 * There could be the case where previously
15177 				 * configured and opened device was removed
15178 				 * and unknown device was plugged.
15179 				 * In such case we want to show a device, and
15180 				 * its configured or unconfigured state but
15181 				 * indicate unusable condition untill the
15182 				 * old target node is released and removed.
15183 				 */
15184 				ap_state->ap_condition = AP_COND_UNUSABLE;
15185 			} else {
15186 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
15187 				    cport));
15188 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15189 				    cport);
15190 				if (sdinfo != NULL) {
15191 					if ((sdinfo->satadrv_state &
15192 					    SATA_DSTATE_FAILED) != 0)
15193 						ap_state->ap_condition =
15194 						    AP_COND_FAILED;
15195 					else
15196 						ap_state->ap_condition =
15197 						    AP_COND_OK;
15198 				} else {
15199 					ap_state->ap_condition =
15200 					    AP_COND_UNKNOWN;
15201 				}
15202 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
15203 				    cport));
15204 			}
15205 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
15206 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
15207 				ap_state->ap_ostate =
15208 				    AP_OSTATE_UNCONFIGURED;
15209 			} else {
15210 				ap_state->ap_ostate =
15211 				    AP_OSTATE_CONFIGURED;
15212 			}
15213 			mutex_exit(&(DEVI(tdip)->devi_lock));
15214 			ndi_devi_exit(dip, circ);
15215 		} else {
15216 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15217 			ap_state->ap_condition = AP_COND_UNKNOWN;
15218 		}
15219 		break;
15220 	}
15221 	default:
15222 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15223 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15224 		ap_state->ap_condition = AP_COND_UNKNOWN;
15225 		/*
15226 		 * This is actually internal error condition (non fatal),
15227 		 * because we have already checked all defined device types.
15228 		 */
15229 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15230 		    "sata_cfgadm_state: Internal error: "
15231 		    "unknown device type"));
15232 		break;
15233 	}
15234 }
15235 
15236 
15237 /*
15238  * Process ioctl get device path request.
15239  *
15240  * NOTE: Port multiplier has no target dip. Devices connected to port
15241  * multiplier have target node attached to the HBA node. The only difference
15242  * between them and the directly-attached device node is a target address.
15243  */
15244 static int
15245 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
15246     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15247 {
15248 	char path[MAXPATHLEN];
15249 	uint32_t size;
15250 	dev_info_t *tdip;
15251 
15252 	(void) strcpy(path, "/devices");
15253 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15254 	    &sata_device->satadev_addr)) == NULL) {
15255 		/*
15256 		 * No such device. If this is a request for a size, do not
15257 		 * return EINVAL for non-existing target, because cfgadm
15258 		 * will then indicate a meaningless ioctl failure.
15259 		 * If this is a request for a path, indicate invalid
15260 		 * argument.
15261 		 */
15262 		if (ioc->get_size == 0)
15263 			return (EINVAL);
15264 	} else {
15265 		(void) ddi_pathname(tdip, path + strlen(path));
15266 	}
15267 	size = strlen(path) + 1;
15268 
15269 	if (ioc->get_size != 0) {
15270 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
15271 		    mode) != 0)
15272 			return (EFAULT);
15273 	} else {
15274 		if (ioc->bufsiz != size)
15275 			return (EINVAL);
15276 
15277 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
15278 		    mode) != 0)
15279 			return (EFAULT);
15280 	}
15281 	return (0);
15282 }
15283 
15284 /*
15285  * Process ioctl get attachment point type request.
15286  *
15287  * NOTE: Port multiplier is supported.
15288  */
15289 static	int
15290 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
15291     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15292 {
15293 	uint32_t	type_len;
15294 	const char	*ap_type;
15295 	int		dev_type;
15296 
15297 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15298 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
15299 		    sata_device->satadev_addr.cport);
15300 	else /* pmport */
15301 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
15302 		    sata_device->satadev_addr.cport,
15303 		    sata_device->satadev_addr.pmport);
15304 
15305 	switch (dev_type) {
15306 	case SATA_DTYPE_NONE:
15307 		ap_type = "port";
15308 		break;
15309 
15310 	case SATA_DTYPE_ATADISK:
15311 	case SATA_DTYPE_ATAPIDISK:
15312 		ap_type = "disk";
15313 		break;
15314 
15315 	case SATA_DTYPE_ATAPICD:
15316 		ap_type = "cd/dvd";
15317 		break;
15318 
15319 	case SATA_DTYPE_ATAPITAPE:
15320 		ap_type = "tape";
15321 		break;
15322 
15323 	case SATA_DTYPE_PMULT:
15324 		ap_type = "sata-pmult";
15325 		break;
15326 
15327 	case SATA_DTYPE_UNKNOWN:
15328 		ap_type = "unknown";
15329 		break;
15330 
15331 	default:
15332 		ap_type = "unsupported";
15333 		break;
15334 
15335 	} /* end of dev_type switch */
15336 
15337 	type_len = strlen(ap_type) + 1;
15338 
15339 	if (ioc->get_size) {
15340 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
15341 		    mode) != 0)
15342 			return (EFAULT);
15343 	} else {
15344 		if (ioc->bufsiz != type_len)
15345 			return (EINVAL);
15346 
15347 		if (ddi_copyout((void *)ap_type, ioc->buf,
15348 		    ioc->bufsiz, mode) != 0)
15349 			return (EFAULT);
15350 	}
15351 	return (0);
15352 
15353 }
15354 
15355 /*
15356  * Process ioctl get device model info request.
15357  * This operation should return to cfgadm the device model
15358  * information string
15359  *
15360  * NOTE: Port multiplier is supported.
15361  */
15362 static	int
15363 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
15364     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15365 {
15366 	sata_drive_info_t *sdinfo;
15367 	uint32_t info_len;
15368 	char ap_info[SATA_ID_MODEL_LEN + 1];
15369 
15370 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15371 	    sata_device->satadev_addr.cport)->cport_mutex);
15372 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15373 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15374 		    sata_device->satadev_addr.cport);
15375 	else /* port multiplier */
15376 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15377 		    sata_device->satadev_addr.cport,
15378 		    sata_device->satadev_addr.pmport);
15379 	if (sdinfo == NULL) {
15380 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15381 		    sata_device->satadev_addr.cport)->cport_mutex);
15382 		return (EINVAL);
15383 	}
15384 
15385 #ifdef	_LITTLE_ENDIAN
15386 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15387 #else	/* _LITTLE_ENDIAN */
15388 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15389 #endif	/* _LITTLE_ENDIAN */
15390 
15391 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15392 	    sata_device->satadev_addr.cport)->cport_mutex);
15393 
15394 	ap_info[SATA_ID_MODEL_LEN] = '\0';
15395 
15396 	info_len = strlen(ap_info) + 1;
15397 
15398 	if (ioc->get_size) {
15399 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15400 		    mode) != 0)
15401 			return (EFAULT);
15402 	} else {
15403 		if (ioc->bufsiz < info_len)
15404 			return (EINVAL);
15405 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15406 		    mode) != 0)
15407 			return (EFAULT);
15408 	}
15409 	return (0);
15410 }
15411 
15412 
15413 /*
15414  * Process ioctl get device firmware revision info request.
15415  * This operation should return to cfgadm the device firmware revision
15416  * information string
15417  *
15418  * Port multiplier is supported.
15419  */
15420 static	int
15421 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
15422     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15423 {
15424 	sata_drive_info_t *sdinfo;
15425 	uint32_t info_len;
15426 	char ap_info[SATA_ID_FW_LEN + 1];
15427 
15428 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15429 	    sata_device->satadev_addr.cport)->cport_mutex);
15430 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15431 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15432 		    sata_device->satadev_addr.cport);
15433 	else /* port multiplier */
15434 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15435 		    sata_device->satadev_addr.cport,
15436 		    sata_device->satadev_addr.pmport);
15437 	if (sdinfo == NULL) {
15438 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15439 		    sata_device->satadev_addr.cport)->cport_mutex);
15440 		return (EINVAL);
15441 	}
15442 
15443 #ifdef	_LITTLE_ENDIAN
15444 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15445 #else	/* _LITTLE_ENDIAN */
15446 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15447 #endif	/* _LITTLE_ENDIAN */
15448 
15449 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15450 	    sata_device->satadev_addr.cport)->cport_mutex);
15451 
15452 	ap_info[SATA_ID_FW_LEN] = '\0';
15453 
15454 	info_len = strlen(ap_info) + 1;
15455 
15456 	if (ioc->get_size) {
15457 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15458 		    mode) != 0)
15459 			return (EFAULT);
15460 	} else {
15461 		if (ioc->bufsiz < info_len)
15462 			return (EINVAL);
15463 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15464 		    mode) != 0)
15465 			return (EFAULT);
15466 	}
15467 	return (0);
15468 }
15469 
15470 
15471 /*
15472  * Process ioctl get device serial number info request.
15473  * This operation should return to cfgadm the device serial number string.
15474  *
15475  * NOTE: Port multiplier is supported.
15476  */
15477 static	int
15478 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
15479     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15480 {
15481 	sata_drive_info_t *sdinfo;
15482 	uint32_t info_len;
15483 	char ap_info[SATA_ID_SERIAL_LEN + 1];
15484 
15485 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15486 	    sata_device->satadev_addr.cport)->cport_mutex);
15487 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15488 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15489 		    sata_device->satadev_addr.cport);
15490 	else /* port multiplier */
15491 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15492 		    sata_device->satadev_addr.cport,
15493 		    sata_device->satadev_addr.pmport);
15494 	if (sdinfo == NULL) {
15495 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15496 		    sata_device->satadev_addr.cport)->cport_mutex);
15497 		return (EINVAL);
15498 	}
15499 
15500 #ifdef	_LITTLE_ENDIAN
15501 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15502 #else	/* _LITTLE_ENDIAN */
15503 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15504 #endif	/* _LITTLE_ENDIAN */
15505 
15506 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15507 	    sata_device->satadev_addr.cport)->cport_mutex);
15508 
15509 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
15510 
15511 	info_len = strlen(ap_info) + 1;
15512 
15513 	if (ioc->get_size) {
15514 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15515 		    mode) != 0)
15516 			return (EFAULT);
15517 	} else {
15518 		if (ioc->bufsiz < info_len)
15519 			return (EINVAL);
15520 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15521 		    mode) != 0)
15522 			return (EFAULT);
15523 	}
15524 	return (0);
15525 }
15526 
15527 
15528 /*
15529  * Preset scsi extended sense data (to NO SENSE)
15530  * First 18 bytes of the sense data are preset to current valid sense
15531  * with a key NO SENSE data.
15532  *
15533  * Returns void
15534  */
15535 static void
15536 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
15537 {
15538 	sense->es_valid = 1;		/* Valid sense */
15539 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
15540 	sense->es_key = KEY_NO_SENSE;
15541 	sense->es_info_1 = 0;
15542 	sense->es_info_2 = 0;
15543 	sense->es_info_3 = 0;
15544 	sense->es_info_4 = 0;
15545 	sense->es_add_len = 10;	/* Additional length - replace with a def */
15546 	sense->es_cmd_info[0] = 0;
15547 	sense->es_cmd_info[1] = 0;
15548 	sense->es_cmd_info[2] = 0;
15549 	sense->es_cmd_info[3] = 0;
15550 	sense->es_add_code = 0;
15551 	sense->es_qual_code = 0;
15552 }
15553 
15554 /*
15555  * Register a legacy cmdk-style devid for the target (disk) device.
15556  *
15557  * Note: This function is called only when the HBA devinfo node has the
15558  * property "use-cmdk-devid-format" set. This property indicates that
15559  * devid compatible with old cmdk (target) driver is to be generated
15560  * for any target device attached to this controller. This will take
15561  * precedence over the devid generated by sd (target) driver.
15562  * This function is derived from cmdk_devid_setup() function in cmdk.c.
15563  */
15564 static void
15565 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
15566 {
15567 	char	*hwid;
15568 	int	modlen;
15569 	int	serlen;
15570 	int	rval;
15571 	ddi_devid_t	devid;
15572 
15573 	/*
15574 	 * device ID is a concatanation of model number, "=", serial number.
15575 	 */
15576 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
15577 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
15578 	    sizeof (sdinfo->satadrv_id.ai_model));
15579 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
15580 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
15581 	if (modlen == 0)
15582 		goto err;
15583 	hwid[modlen++] = '=';
15584 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
15585 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15586 	swab(&hwid[modlen], &hwid[modlen],
15587 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15588 	serlen = sata_check_modser(&hwid[modlen],
15589 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15590 	if (serlen == 0)
15591 		goto err;
15592 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
15593 
15594 	/* initialize/register devid */
15595 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
15596 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
15597 		rval = ddi_devid_register(dip, devid);
15598 		/*
15599 		 * Free up the allocated devid buffer.
15600 		 * NOTE: This doesn't mean unregistering devid.
15601 		 */
15602 		ddi_devid_free(devid);
15603 	}
15604 
15605 	if (rval != DDI_SUCCESS)
15606 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
15607 		    " on port %d", sdinfo->satadrv_addr.cport);
15608 err:
15609 	kmem_free(hwid, LEGACY_HWID_LEN);
15610 }
15611 
15612 /*
15613  * valid model/serial string must contain a non-zero non-space characters.
15614  * trim trailing spaces/NULLs.
15615  */
15616 static int
15617 sata_check_modser(char *buf, int buf_len)
15618 {
15619 	boolean_t ret;
15620 	char *s;
15621 	int i;
15622 	int tb;
15623 	char ch;
15624 
15625 	ret = B_FALSE;
15626 	s = buf;
15627 	for (i = 0; i < buf_len; i++) {
15628 		ch = *s++;
15629 		if (ch != ' ' && ch != '\0')
15630 			tb = i + 1;
15631 		if (ch != ' ' && ch != '\0' && ch != '0')
15632 			ret = B_TRUE;
15633 	}
15634 
15635 	if (ret == B_FALSE)
15636 		return (0); /* invalid string */
15637 
15638 	return (tb); /* return length */
15639 }
15640 
15641 /*
15642  * sata_set_drive_features function compares current device features setting
15643  * with the saved device features settings and, if there is a difference,
15644  * it restores device features setting to the previously saved state.
15645  * It also arbitrarily tries to select the highest supported DMA mode.
15646  * Device Identify or Identify Packet Device data has to be current.
15647  * At the moment read ahead and write cache are considered for all devices.
15648  * For atapi devices, Removable Media Status Notification is set in addition
15649  * to common features.
15650  *
15651  * This function cannot be called in the interrupt context (it may sleep).
15652  *
15653  * The input argument sdinfo should point to the drive info structure
15654  * to be updated after features are set. Note, that only
15655  * device (packet) identify data is updated, not the flags indicating the
15656  * supported features.
15657  *
15658  * Returns SATA_SUCCESS if successful or there was nothing to do.
15659  * Device Identify data in the drive info structure pointed to by the sdinfo
15660  * arguments is updated even when no features were set or changed.
15661  *
15662  * Returns SATA_FAILURE if device features could not be set or DMA mode
15663  * for a disk cannot be set and device identify data cannot be fetched.
15664  *
15665  * Returns SATA_RETRY if device features could not be set (other than disk
15666  * DMA mode) but the device identify data was fetched successfully.
15667  *
15668  * Note: This function may fail the port, making it inaccessible.
15669  * In such case the explicit port disconnect/connect or physical device
15670  * detach/attach is required to re-evaluate port state again.
15671  */
15672 
15673 static int
15674 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
15675     sata_drive_info_t *sdinfo, int restore)
15676 {
15677 	int rval = SATA_SUCCESS;
15678 	int rval_set;
15679 	sata_drive_info_t new_sdinfo;
15680 	char *finfo = "sata_set_drive_features: cannot";
15681 	char *finfox;
15682 	int cache_op;
15683 
15684 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
15685 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
15686 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
15687 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15688 		/*
15689 		 * Cannot get device identification - caller may retry later
15690 		 */
15691 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15692 		    "%s fetch device identify data\n", finfo);
15693 		return (SATA_FAILURE);
15694 	}
15695 	finfox = (restore != 0) ? " restore device features" :
15696 	    " initialize device features\n";
15697 
15698 	switch (sdinfo->satadrv_type) {
15699 	case SATA_DTYPE_ATADISK:
15700 		/* Arbitrarily set UDMA mode */
15701 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15702 		    SATA_SUCCESS) {
15703 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15704 			    "%s set UDMA mode\n", finfo));
15705 			return (SATA_FAILURE);
15706 		}
15707 		break;
15708 	case SATA_DTYPE_ATAPICD:
15709 	case SATA_DTYPE_ATAPITAPE:
15710 	case SATA_DTYPE_ATAPIDISK:
15711 		/*  Set Removable Media Status Notification, if necessary */
15712 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
15713 		    restore != 0) {
15714 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
15715 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
15716 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
15717 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
15718 				/* Current setting does not match saved one */
15719 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
15720 				    sdinfo->satadrv_settings &
15721 				    SATA_DEV_RMSN) != SATA_SUCCESS)
15722 					rval = SATA_FAILURE;
15723 			}
15724 		}
15725 		/*
15726 		 * We have to set Multiword DMA or UDMA, if it is supported, as
15727 		 * we want to use DMA transfer mode whenever possible.
15728 		 * Some devices require explicit setting of the DMA mode.
15729 		 */
15730 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
15731 			/* Set highest supported DMA mode */
15732 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15733 			    SATA_SUCCESS) {
15734 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15735 				    "%s set UDMA mode\n", finfo));
15736 				rval = SATA_FAILURE;
15737 			}
15738 		}
15739 		break;
15740 	}
15741 
15742 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
15743 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15744 		/*
15745 		 * neither READ AHEAD nor WRITE CACHE is supported
15746 		 * - do nothing
15747 		 */
15748 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15749 		    "settable features not supported\n", NULL);
15750 		goto update_sdinfo;
15751 	}
15752 
15753 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
15754 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
15755 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
15756 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
15757 		/*
15758 		 * both READ AHEAD and WRITE CACHE are enabled
15759 		 * - Nothing to do
15760 		 */
15761 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15762 		    "no device features to set\n", NULL);
15763 		goto update_sdinfo;
15764 	}
15765 
15766 	cache_op = 0;
15767 
15768 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
15769 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15770 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15771 			/* Enable read ahead / read cache */
15772 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
15773 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15774 			    "enabling read cache\n", NULL);
15775 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15776 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15777 			/* Disable read ahead  / read cache */
15778 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
15779 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15780 			    "disabling read cache\n", NULL);
15781 		}
15782 
15783 		if (cache_op != 0) {
15784 			/* Try to set read cache mode */
15785 			rval_set = sata_set_cache_mode(sata_hba_inst,
15786 			    &new_sdinfo, cache_op);
15787 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15788 				rval = rval_set;
15789 		}
15790 	}
15791 
15792 	cache_op = 0;
15793 
15794 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15795 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15796 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15797 			/* Enable write cache */
15798 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
15799 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15800 			    "enabling write cache\n", NULL);
15801 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15802 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15803 			/* Disable write cache */
15804 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
15805 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15806 			    "disabling write cache\n", NULL);
15807 		}
15808 
15809 		if (cache_op != 0) {
15810 			/* Try to set write 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 	if (rval != SATA_SUCCESS)
15818 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15819 		    "%s %s", finfo, finfox));
15820 
15821 update_sdinfo:
15822 	/*
15823 	 * We need to fetch Device Identify data again
15824 	 */
15825 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15826 		/*
15827 		 * Cannot get device identification - retry later
15828 		 */
15829 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15830 		    "%s re-fetch device identify data\n", finfo));
15831 		rval = SATA_FAILURE;
15832 	}
15833 	/* Copy device sata info. */
15834 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
15835 
15836 	return (rval);
15837 }
15838 
15839 
15840 /*
15841  *
15842  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
15843  * unable to determine.
15844  *
15845  * Cannot be called in an interrupt context.
15846  *
15847  * Called by sata_build_lsense_page_2f()
15848  */
15849 
15850 static int
15851 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
15852     sata_drive_info_t *sdinfo)
15853 {
15854 	sata_pkt_t *spkt;
15855 	sata_cmd_t *scmd;
15856 	sata_pkt_txlate_t *spx;
15857 	int rval;
15858 
15859 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15860 	spx->txlt_sata_hba_inst = sata_hba_inst;
15861 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15862 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15863 	if (spkt == NULL) {
15864 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15865 		return (-1);
15866 	}
15867 	/* address is needed now */
15868 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15869 
15870 
15871 	/* Fill sata_pkt */
15872 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15873 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15874 	/* Synchronous mode, no callback */
15875 	spkt->satapkt_comp = NULL;
15876 	/* Timeout 30s */
15877 	spkt->satapkt_time = sata_default_pkt_time;
15878 
15879 	scmd = &spkt->satapkt_cmd;
15880 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
15881 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
15882 
15883 	/* Set up which registers need to be returned */
15884 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
15885 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
15886 
15887 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
15888 	scmd->satacmd_addr_type = 0;		/* N/A */
15889 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
15890 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
15891 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
15892 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
15893 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
15894 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
15895 	scmd->satacmd_cmd_reg = SATAC_SMART;
15896 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
15897 	    sdinfo->satadrv_addr.cport)));
15898 
15899 
15900 	/* Send pkt to SATA HBA driver */
15901 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
15902 	    SATA_TRAN_ACCEPTED ||
15903 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15904 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15905 		    sdinfo->satadrv_addr.cport)));
15906 		/*
15907 		 * Whoops, no SMART RETURN STATUS
15908 		 */
15909 		rval = -1;
15910 	} else {
15911 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15912 		    sdinfo->satadrv_addr.cport)));
15913 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
15914 			rval = -1;
15915 			goto fail;
15916 		}
15917 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
15918 			rval = -1;
15919 			goto fail;
15920 		}
15921 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
15922 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
15923 			rval = 0;
15924 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
15925 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
15926 			rval = 1;
15927 		else {
15928 			rval = -1;
15929 			goto fail;
15930 		}
15931 	}
15932 fail:
15933 	/* Free allocated resources */
15934 	sata_pkt_free(spx);
15935 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
15936 
15937 	return (rval);
15938 }
15939 
15940 /*
15941  *
15942  * Returns 0 if succeeded, -1 otherwise
15943  *
15944  * Cannot be called in an interrupt context.
15945  *
15946  */
15947 static int
15948 sata_fetch_smart_data(
15949 	sata_hba_inst_t *sata_hba_inst,
15950 	sata_drive_info_t *sdinfo,
15951 	struct smart_data *smart_data)
15952 {
15953 	sata_pkt_t *spkt;
15954 	sata_cmd_t *scmd;
15955 	sata_pkt_txlate_t *spx;
15956 	int rval;
15957 
15958 #if ! defined(lint)
15959 	ASSERT(sizeof (struct smart_data) == 512);
15960 #endif
15961 
15962 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15963 	spx->txlt_sata_hba_inst = sata_hba_inst;
15964 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15965 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15966 	if (spkt == NULL) {
15967 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15968 		return (-1);
15969 	}
15970 	/* address is needed now */
15971 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15972 
15973 
15974 	/* Fill sata_pkt */
15975 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15976 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15977 	/* Synchronous mode, no callback */
15978 	spkt->satapkt_comp = NULL;
15979 	/* Timeout 30s */
15980 	spkt->satapkt_time = sata_default_pkt_time;
15981 
15982 	scmd = &spkt->satapkt_cmd;
15983 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
15984 
15985 	/*
15986 	 * Allocate buffer for SMART data
15987 	 */
15988 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
15989 	    sizeof (struct smart_data));
15990 	if (scmd->satacmd_bp == NULL) {
15991 		sata_pkt_free(spx);
15992 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15993 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15994 		    "sata_fetch_smart_data: "
15995 		    "cannot allocate buffer"));
15996 		return (-1);
15997 	}
15998 
15999 
16000 	/* Build SMART_READ_DATA cmd in the sata_pkt */
16001 	scmd->satacmd_addr_type = 0;		/* N/A */
16002 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16003 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16004 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16005 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16006 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16007 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16008 	scmd->satacmd_cmd_reg = SATAC_SMART;
16009 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16010 	    sdinfo->satadrv_addr.cport)));
16011 
16012 	/* Send pkt to SATA HBA driver */
16013 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16014 	    SATA_TRAN_ACCEPTED ||
16015 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16016 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16017 		    sdinfo->satadrv_addr.cport)));
16018 		/*
16019 		 * Whoops, no SMART DATA available
16020 		 */
16021 		rval = -1;
16022 		goto fail;
16023 	} else {
16024 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16025 		    sdinfo->satadrv_addr.cport)));
16026 		if (spx->txlt_buf_dma_handle != NULL) {
16027 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16028 			    DDI_DMA_SYNC_FORKERNEL);
16029 			ASSERT(rval == DDI_SUCCESS);
16030 		}
16031 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16032 		    sizeof (struct smart_data));
16033 	}
16034 
16035 fail:
16036 	/* Free allocated resources */
16037 	sata_free_local_buffer(spx);
16038 	sata_pkt_free(spx);
16039 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16040 
16041 	return (rval);
16042 }
16043 
16044 /*
16045  * Used by LOG SENSE page 0x10
16046  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16047  * Note: cannot be called in the interrupt context.
16048  *
16049  * return 0 for success, -1 otherwise
16050  *
16051  */
16052 static int
16053 sata_ext_smart_selftest_read_log(
16054 	sata_hba_inst_t *sata_hba_inst,
16055 	sata_drive_info_t *sdinfo,
16056 	struct smart_ext_selftest_log *ext_selftest_log,
16057 	uint16_t block_num)
16058 {
16059 	sata_pkt_txlate_t *spx;
16060 	sata_pkt_t *spkt;
16061 	sata_cmd_t *scmd;
16062 	int rval;
16063 
16064 #if ! defined(lint)
16065 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16066 #endif
16067 
16068 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16069 	spx->txlt_sata_hba_inst = sata_hba_inst;
16070 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16071 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16072 	if (spkt == NULL) {
16073 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16074 		return (-1);
16075 	}
16076 	/* address is needed now */
16077 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16078 
16079 
16080 	/* Fill sata_pkt */
16081 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16082 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16083 	/* Synchronous mode, no callback */
16084 	spkt->satapkt_comp = NULL;
16085 	/* Timeout 30s */
16086 	spkt->satapkt_time = sata_default_pkt_time;
16087 
16088 	scmd = &spkt->satapkt_cmd;
16089 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16090 
16091 	/*
16092 	 * Allocate buffer for SMART extended self-test log
16093 	 */
16094 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16095 	    sizeof (struct smart_ext_selftest_log));
16096 	if (scmd->satacmd_bp == NULL) {
16097 		sata_pkt_free(spx);
16098 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16099 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16100 		    "sata_ext_smart_selftest_log: "
16101 		    "cannot allocate buffer"));
16102 		return (-1);
16103 	}
16104 
16105 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16106 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16107 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16108 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16109 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16110 	scmd->satacmd_lba_low_msb = 0;
16111 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16112 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16113 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16114 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16115 
16116 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16117 	    sdinfo->satadrv_addr.cport)));
16118 
16119 	/* Send pkt to SATA HBA driver */
16120 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16121 	    SATA_TRAN_ACCEPTED ||
16122 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16123 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16124 		    sdinfo->satadrv_addr.cport)));
16125 
16126 		/*
16127 		 * Whoops, no SMART selftest log info available
16128 		 */
16129 		rval = -1;
16130 		goto fail;
16131 	} else {
16132 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16133 		    sdinfo->satadrv_addr.cport)));
16134 
16135 		if (spx->txlt_buf_dma_handle != NULL) {
16136 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16137 			    DDI_DMA_SYNC_FORKERNEL);
16138 			ASSERT(rval == DDI_SUCCESS);
16139 		}
16140 		bcopy(scmd->satacmd_bp->b_un.b_addr,
16141 		    (uint8_t *)ext_selftest_log,
16142 		    sizeof (struct smart_ext_selftest_log));
16143 		rval = 0;
16144 	}
16145 
16146 fail:
16147 	/* Free allocated resources */
16148 	sata_free_local_buffer(spx);
16149 	sata_pkt_free(spx);
16150 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16151 
16152 	return (rval);
16153 }
16154 
16155 /*
16156  * Returns 0 for success, -1 otherwise
16157  *
16158  * SMART self-test log data is returned in buffer pointed to by selftest_log
16159  */
16160 static int
16161 sata_smart_selftest_log(
16162 	sata_hba_inst_t *sata_hba_inst,
16163 	sata_drive_info_t *sdinfo,
16164 	struct smart_selftest_log *selftest_log)
16165 {
16166 	sata_pkt_t *spkt;
16167 	sata_cmd_t *scmd;
16168 	sata_pkt_txlate_t *spx;
16169 	int rval;
16170 
16171 #if ! defined(lint)
16172 	ASSERT(sizeof (struct smart_selftest_log) == 512);
16173 #endif
16174 
16175 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16176 	spx->txlt_sata_hba_inst = sata_hba_inst;
16177 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16178 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16179 	if (spkt == NULL) {
16180 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16181 		return (-1);
16182 	}
16183 	/* address is needed now */
16184 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16185 
16186 
16187 	/* Fill sata_pkt */
16188 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16189 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16190 	/* Synchronous mode, no callback */
16191 	spkt->satapkt_comp = NULL;
16192 	/* Timeout 30s */
16193 	spkt->satapkt_time = sata_default_pkt_time;
16194 
16195 	scmd = &spkt->satapkt_cmd;
16196 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16197 
16198 	/*
16199 	 * Allocate buffer for SMART SELFTEST LOG
16200 	 */
16201 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16202 	    sizeof (struct smart_selftest_log));
16203 	if (scmd->satacmd_bp == NULL) {
16204 		sata_pkt_free(spx);
16205 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16206 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16207 		    "sata_smart_selftest_log: "
16208 		    "cannot allocate buffer"));
16209 		return (-1);
16210 	}
16211 
16212 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16213 	scmd->satacmd_addr_type = 0;		/* N/A */
16214 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
16215 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
16216 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16217 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16218 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16219 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16220 	scmd->satacmd_cmd_reg = SATAC_SMART;
16221 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16222 	    sdinfo->satadrv_addr.cport)));
16223 
16224 	/* Send pkt to SATA HBA driver */
16225 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16226 	    SATA_TRAN_ACCEPTED ||
16227 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16228 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16229 		    sdinfo->satadrv_addr.cport)));
16230 		/*
16231 		 * Whoops, no SMART DATA available
16232 		 */
16233 		rval = -1;
16234 		goto fail;
16235 	} else {
16236 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16237 		    sdinfo->satadrv_addr.cport)));
16238 		if (spx->txlt_buf_dma_handle != NULL) {
16239 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16240 			    DDI_DMA_SYNC_FORKERNEL);
16241 			ASSERT(rval == DDI_SUCCESS);
16242 		}
16243 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
16244 		    sizeof (struct smart_selftest_log));
16245 		rval = 0;
16246 	}
16247 
16248 fail:
16249 	/* Free allocated resources */
16250 	sata_free_local_buffer(spx);
16251 	sata_pkt_free(spx);
16252 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16253 
16254 	return (rval);
16255 }
16256 
16257 
16258 /*
16259  * Returns 0 for success, -1 otherwise
16260  *
16261  * SMART READ LOG data is returned in buffer pointed to by smart_log
16262  */
16263 static int
16264 sata_smart_read_log(
16265 	sata_hba_inst_t *sata_hba_inst,
16266 	sata_drive_info_t *sdinfo,
16267 	uint8_t *smart_log,		/* where the data should be returned */
16268 	uint8_t which_log,		/* which log should be returned */
16269 	uint8_t log_size)		/* # of 512 bytes in log */
16270 {
16271 	sata_pkt_t *spkt;
16272 	sata_cmd_t *scmd;
16273 	sata_pkt_txlate_t *spx;
16274 	int rval;
16275 
16276 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16277 	spx->txlt_sata_hba_inst = sata_hba_inst;
16278 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16279 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16280 	if (spkt == NULL) {
16281 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16282 		return (-1);
16283 	}
16284 	/* address is needed now */
16285 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16286 
16287 
16288 	/* Fill sata_pkt */
16289 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16290 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16291 	/* Synchronous mode, no callback */
16292 	spkt->satapkt_comp = NULL;
16293 	/* Timeout 30s */
16294 	spkt->satapkt_time = sata_default_pkt_time;
16295 
16296 	scmd = &spkt->satapkt_cmd;
16297 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16298 
16299 	/*
16300 	 * Allocate buffer for SMART READ LOG
16301 	 */
16302 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
16303 	if (scmd->satacmd_bp == NULL) {
16304 		sata_pkt_free(spx);
16305 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16306 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16307 		    "sata_smart_read_log: " "cannot allocate buffer"));
16308 		return (-1);
16309 	}
16310 
16311 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16312 	scmd->satacmd_addr_type = 0;		/* N/A */
16313 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
16314 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
16315 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16316 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16317 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16318 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16319 	scmd->satacmd_cmd_reg = SATAC_SMART;
16320 
16321 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16322 	    sdinfo->satadrv_addr.cport)));
16323 
16324 	/* Send pkt to SATA HBA driver */
16325 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16326 	    SATA_TRAN_ACCEPTED ||
16327 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16328 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16329 		    sdinfo->satadrv_addr.cport)));
16330 
16331 		/*
16332 		 * Whoops, no SMART DATA available
16333 		 */
16334 		rval = -1;
16335 		goto fail;
16336 	} else {
16337 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16338 		    sdinfo->satadrv_addr.cport)));
16339 
16340 		if (spx->txlt_buf_dma_handle != NULL) {
16341 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16342 			    DDI_DMA_SYNC_FORKERNEL);
16343 			ASSERT(rval == DDI_SUCCESS);
16344 		}
16345 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
16346 		rval = 0;
16347 	}
16348 
16349 fail:
16350 	/* Free allocated resources */
16351 	sata_free_local_buffer(spx);
16352 	sata_pkt_free(spx);
16353 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16354 
16355 	return (rval);
16356 }
16357 
16358 /*
16359  * Used by LOG SENSE page 0x10
16360  *
16361  * return 0 for success, -1 otherwise
16362  *
16363  */
16364 static int
16365 sata_read_log_ext_directory(
16366 	sata_hba_inst_t *sata_hba_inst,
16367 	sata_drive_info_t *sdinfo,
16368 	struct read_log_ext_directory *logdir)
16369 {
16370 	sata_pkt_txlate_t *spx;
16371 	sata_pkt_t *spkt;
16372 	sata_cmd_t *scmd;
16373 	int rval;
16374 
16375 #if ! defined(lint)
16376 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
16377 #endif
16378 
16379 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16380 	spx->txlt_sata_hba_inst = sata_hba_inst;
16381 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16382 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16383 	if (spkt == NULL) {
16384 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16385 		return (-1);
16386 	}
16387 
16388 	/* Fill sata_pkt */
16389 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16390 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16391 	/* Synchronous mode, no callback */
16392 	spkt->satapkt_comp = NULL;
16393 	/* Timeout 30s */
16394 	spkt->satapkt_time = sata_default_pkt_time;
16395 
16396 	scmd = &spkt->satapkt_cmd;
16397 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16398 
16399 	/*
16400 	 * Allocate buffer for SMART READ LOG EXTENDED command
16401 	 */
16402 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16403 	    sizeof (struct read_log_ext_directory));
16404 	if (scmd->satacmd_bp == NULL) {
16405 		sata_pkt_free(spx);
16406 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16407 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16408 		    "sata_read_log_ext_directory: "
16409 		    "cannot allocate buffer"));
16410 		return (-1);
16411 	}
16412 
16413 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
16414 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16415 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
16416 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
16417 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
16418 	scmd->satacmd_lba_low_msb = 0;
16419 	scmd->satacmd_lba_mid_lsb = 0;
16420 	scmd->satacmd_lba_mid_msb = 0;
16421 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16422 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16423 
16424 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16425 	    sdinfo->satadrv_addr.cport)));
16426 
16427 	/* Send pkt to SATA HBA driver */
16428 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16429 	    SATA_TRAN_ACCEPTED ||
16430 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16431 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16432 		    sdinfo->satadrv_addr.cport)));
16433 		/*
16434 		 * Whoops, no SMART selftest log info available
16435 		 */
16436 		rval = -1;
16437 		goto fail;
16438 	} else {
16439 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16440 		    sdinfo->satadrv_addr.cport)));
16441 		if (spx->txlt_buf_dma_handle != NULL) {
16442 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16443 			    DDI_DMA_SYNC_FORKERNEL);
16444 			ASSERT(rval == DDI_SUCCESS);
16445 		}
16446 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
16447 		    sizeof (struct read_log_ext_directory));
16448 		rval = 0;
16449 	}
16450 
16451 fail:
16452 	/* Free allocated resources */
16453 	sata_free_local_buffer(spx);
16454 	sata_pkt_free(spx);
16455 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16456 
16457 	return (rval);
16458 }
16459 
16460 /*
16461  * Set up error retrieval sata command for NCQ command error data
16462  * recovery.
16463  *
16464  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
16465  * returns SATA_FAILURE otherwise.
16466  */
16467 static int
16468 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
16469 {
16470 #ifndef __lock_lint
16471 	_NOTE(ARGUNUSED(sdinfo))
16472 #endif
16473 
16474 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
16475 	sata_cmd_t *scmd;
16476 	struct buf *bp;
16477 
16478 	/* Operation modes are up to the caller */
16479 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16480 
16481 	/* Synchronous mode, no callback - may be changed by the caller */
16482 	spkt->satapkt_comp = NULL;
16483 	spkt->satapkt_time = sata_default_pkt_time;
16484 
16485 	scmd = &spkt->satapkt_cmd;
16486 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
16487 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
16488 
16489 	/*
16490 	 * Allocate dma_able buffer error data.
16491 	 * Buffer allocation will take care of buffer alignment and other DMA
16492 	 * attributes.
16493 	 */
16494 	bp = sata_alloc_local_buffer(spx,
16495 	    sizeof (struct sata_ncq_error_recovery_page));
16496 	if (bp == NULL)
16497 		return (SATA_FAILURE);
16498 
16499 	bp_mapin(bp); /* make data buffer accessible */
16500 	scmd->satacmd_bp = bp;
16501 
16502 	/*
16503 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
16504 	 * before accessing it. Handle is in usual place in translate struct.
16505 	 */
16506 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
16507 
16508 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
16509 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
16510 
16511 	return (SATA_SUCCESS);
16512 }
16513 
16514 /*
16515  * sata_xlate_errors() is used to translate (S)ATA error
16516  * information to SCSI information returned in the SCSI
16517  * packet.
16518  */
16519 static void
16520 sata_xlate_errors(sata_pkt_txlate_t *spx)
16521 {
16522 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
16523 	struct scsi_extended_sense *sense;
16524 
16525 	scsipkt->pkt_reason = CMD_INCOMPLETE;
16526 	*scsipkt->pkt_scbp = STATUS_CHECK;
16527 	sense = sata_arq_sense(spx);
16528 
16529 	switch (spx->txlt_sata_pkt->satapkt_reason) {
16530 	case SATA_PKT_PORT_ERROR:
16531 		/*
16532 		 * We have no device data. Assume no data transfered.
16533 		 */
16534 		sense->es_key = KEY_HARDWARE_ERROR;
16535 		break;
16536 
16537 	case SATA_PKT_DEV_ERROR:
16538 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
16539 		    SATA_STATUS_ERR) {
16540 			/*
16541 			 * determine dev error reason from error
16542 			 * reg content
16543 			 */
16544 			sata_decode_device_error(spx, sense);
16545 			break;
16546 		}
16547 		/* No extended sense key - no info available */
16548 		break;
16549 
16550 	case SATA_PKT_TIMEOUT:
16551 		scsipkt->pkt_reason = CMD_TIMEOUT;
16552 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
16553 		/* No extended sense key */
16554 		break;
16555 
16556 	case SATA_PKT_ABORTED:
16557 		scsipkt->pkt_reason = CMD_ABORTED;
16558 		scsipkt->pkt_statistics |= STAT_ABORTED;
16559 		/* No extended sense key */
16560 		break;
16561 
16562 	case SATA_PKT_RESET:
16563 		/*
16564 		 * pkt aborted either by an explicit reset request from
16565 		 * a host, or due to error recovery
16566 		 */
16567 		scsipkt->pkt_reason = CMD_RESET;
16568 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
16569 		break;
16570 
16571 	default:
16572 		scsipkt->pkt_reason = CMD_TRAN_ERR;
16573 		break;
16574 	}
16575 }
16576 
16577 
16578 
16579 
16580 /*
16581  * Log sata message
16582  * dev pathname msg line preceeds the logged message.
16583  */
16584 
16585 static	void
16586 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
16587 {
16588 	char pathname[128];
16589 	dev_info_t *dip = NULL;
16590 	va_list ap;
16591 
16592 	mutex_enter(&sata_log_mutex);
16593 
16594 	va_start(ap, fmt);
16595 	(void) vsprintf(sata_log_buf, fmt, ap);
16596 	va_end(ap);
16597 
16598 	if (sata_hba_inst != NULL) {
16599 		dip = SATA_DIP(sata_hba_inst);
16600 		(void) ddi_pathname(dip, pathname);
16601 	} else {
16602 		pathname[0] = 0;
16603 	}
16604 	if (level == CE_CONT) {
16605 		if (sata_debug_flags == 0)
16606 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
16607 		else
16608 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
16609 	} else {
16610 		if (level != CE_NOTE) {
16611 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
16612 		} else if (sata_msg) {
16613 			cmn_err(level, "%s:\n %s", pathname,
16614 			    sata_log_buf);
16615 		}
16616 	}
16617 
16618 	/* sata trace debug */
16619 	sata_trace_debug(dip, sata_log_buf);
16620 
16621 	mutex_exit(&sata_log_mutex);
16622 }
16623 
16624 
16625 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
16626 
16627 /*
16628  * Start or terminate the thread, depending on flag arg and current state
16629  */
16630 static void
16631 sata_event_thread_control(int startstop)
16632 {
16633 	static 	int sata_event_thread_terminating = 0;
16634 	static 	int sata_event_thread_starting = 0;
16635 	int i;
16636 
16637 	mutex_enter(&sata_event_mutex);
16638 
16639 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
16640 	    sata_event_thread_terminating == 1)) {
16641 		mutex_exit(&sata_event_mutex);
16642 		return;
16643 	}
16644 	if (startstop == 1 && sata_event_thread_starting == 1) {
16645 		mutex_exit(&sata_event_mutex);
16646 		return;
16647 	}
16648 	if (startstop == 1 && sata_event_thread_terminating == 1) {
16649 		sata_event_thread_starting = 1;
16650 		/* wait til terminate operation completes */
16651 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16652 		while (sata_event_thread_terminating == 1) {
16653 			if (i-- <= 0) {
16654 				sata_event_thread_starting = 0;
16655 				mutex_exit(&sata_event_mutex);
16656 #ifdef SATA_DEBUG
16657 				cmn_err(CE_WARN, "sata_event_thread_control: "
16658 				    "timeout waiting for thread to terminate");
16659 #endif
16660 				return;
16661 			}
16662 			mutex_exit(&sata_event_mutex);
16663 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16664 			mutex_enter(&sata_event_mutex);
16665 		}
16666 	}
16667 	if (startstop == 1) {
16668 		if (sata_event_thread == NULL) {
16669 			sata_event_thread = thread_create(NULL, 0,
16670 			    (void (*)())sata_event_daemon,
16671 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
16672 		}
16673 		sata_event_thread_starting = 0;
16674 		mutex_exit(&sata_event_mutex);
16675 		return;
16676 	}
16677 
16678 	/*
16679 	 * If we got here, thread may need to be terminated
16680 	 */
16681 	if (sata_event_thread != NULL) {
16682 		int i;
16683 		/* Signal event thread to go away */
16684 		sata_event_thread_terminating = 1;
16685 		sata_event_thread_terminate = 1;
16686 		cv_signal(&sata_event_cv);
16687 		/*
16688 		 * Wait til daemon terminates.
16689 		 */
16690 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16691 		while (sata_event_thread_terminate == 1) {
16692 			mutex_exit(&sata_event_mutex);
16693 			if (i-- <= 0) {
16694 				/* Daemon did not go away !!! */
16695 #ifdef SATA_DEBUG
16696 				cmn_err(CE_WARN, "sata_event_thread_control: "
16697 				    "cannot terminate event daemon thread");
16698 #endif
16699 				mutex_enter(&sata_event_mutex);
16700 				break;
16701 			}
16702 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16703 			mutex_enter(&sata_event_mutex);
16704 		}
16705 		sata_event_thread_terminating = 0;
16706 	}
16707 	ASSERT(sata_event_thread_terminating == 0);
16708 	ASSERT(sata_event_thread_starting == 0);
16709 	mutex_exit(&sata_event_mutex);
16710 }
16711 
16712 
16713 /*
16714  * SATA HBA event notification function.
16715  * Events reported by SATA HBA drivers per HBA instance relate to a change in
16716  * a port and/or device state or a controller itself.
16717  * Events for different addresses/addr types cannot be combined.
16718  * A warning message is generated for each event type.
16719  * Events are not processed by this function, so only the
16720  * event flag(s)is set for an affected entity and the event thread is
16721  * waken up. Event daemon thread processes all events.
16722  *
16723  * NOTE: Since more than one event may be reported at the same time, one
16724  * cannot determine a sequence of events when opposite event are reported, eg.
16725  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
16726  * is taking precedence over reported events, i.e. may cause ignoring some
16727  * events.
16728  */
16729 #define	SATA_EVENT_MAX_MSG_LENGTH	79
16730 
16731 void
16732 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
16733 {
16734 	sata_hba_inst_t *sata_hba_inst = NULL;
16735 	sata_address_t *saddr;
16736 	sata_pmult_info_t *pmultinfo;
16737 	sata_drive_info_t *sdinfo;
16738 	sata_port_stats_t *pstats;
16739 	sata_cport_info_t *cportinfo;
16740 	sata_pmport_info_t *pmportinfo;
16741 	int cport, pmport;
16742 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
16743 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
16744 	char *lcp;
16745 	static char *err_msg_evnt_1 =
16746 	    "sata_hba_event_notify: invalid port event 0x%x ";
16747 	static char *err_msg_evnt_2 =
16748 	    "sata_hba_event_notify: invalid device event 0x%x ";
16749 	int linkevent;
16750 
16751 	/*
16752 	 * There is a possibility that an event will be generated on HBA
16753 	 * that has not completed attachment or is detaching. We still want
16754 	 * to process events until HBA is detached.
16755 	 */
16756 	mutex_enter(&sata_mutex);
16757 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
16758 	    sata_hba_inst = sata_hba_inst->satahba_next) {
16759 		if (SATA_DIP(sata_hba_inst) == dip)
16760 			if (sata_hba_inst->satahba_attached == 1)
16761 				break;
16762 	}
16763 	mutex_exit(&sata_mutex);
16764 	if (sata_hba_inst == NULL)
16765 		/* HBA not attached */
16766 		return;
16767 
16768 	ASSERT(sata_device != NULL);
16769 
16770 	/*
16771 	 * Validate address before - do not proceed with invalid address.
16772 	 */
16773 	saddr = &sata_device->satadev_addr;
16774 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
16775 		return;
16776 
16777 	cport = saddr->cport;
16778 	pmport = saddr->pmport;
16779 
16780 	buf1[0] = buf2[0] = '\0';
16781 
16782 	/*
16783 	 * If event relates to port or device, check port state.
16784 	 * Port has to be initialized, or we cannot accept an event.
16785 	 */
16786 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
16787 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
16788 		mutex_enter(&sata_hba_inst->satahba_mutex);
16789 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
16790 		mutex_exit(&sata_hba_inst->satahba_mutex);
16791 		if (cportinfo == NULL || cportinfo->cport_state == 0)
16792 			return;
16793 	}
16794 
16795 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
16796 	    SATA_ADDR_DPMPORT)) != 0) {
16797 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
16798 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16799 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
16800 			    "is attached to port %d, ignore pmult/pmport "
16801 			    "event 0x%x", cportinfo->cport_dev_type,
16802 			    cport, event));
16803 			return;
16804 		}
16805 
16806 		mutex_enter(&cportinfo->cport_mutex);
16807 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
16808 		mutex_exit(&cportinfo->cport_mutex);
16809 
16810 		/*
16811 		 * The daemon might be processing attachment of port
16812 		 * multiplier, in that case we should ignore events on its
16813 		 * sub-devices.
16814 		 *
16815 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
16816 		 * The pmport_state is checked by sata daemon.
16817 		 */
16818 		if (pmultinfo == NULL ||
16819 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
16820 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16821 			    "sata_hba_event_notify: pmult is not"
16822 			    "available at port %d:%d, ignore event 0x%x",
16823 			    cport, pmport, event));
16824 			return;
16825 		}
16826 	}
16827 
16828 	if ((saddr->qual &
16829 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
16830 
16831 		mutex_enter(&cportinfo->cport_mutex);
16832 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
16833 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16834 			    "sata_hba_event_notify: invalid/"
16835 			    "un-implemented port %d:%d (%d ports), "
16836 			    "ignore event 0x%x", cport, pmport,
16837 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
16838 			mutex_exit(&cportinfo->cport_mutex);
16839 			return;
16840 		}
16841 		mutex_exit(&cportinfo->cport_mutex);
16842 
16843 		mutex_enter(&sata_hba_inst->satahba_mutex);
16844 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
16845 		    cport, pmport);
16846 		mutex_exit(&sata_hba_inst->satahba_mutex);
16847 
16848 		/* pmport is implemented/valid? */
16849 		if (pmportinfo == NULL) {
16850 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16851 			    "sata_hba_event_notify: invalid/"
16852 			    "un-implemented port %d:%d, ignore "
16853 			    "event 0x%x", cport, pmport, event));
16854 			return;
16855 		}
16856 	}
16857 
16858 	/*
16859 	 * Events refer to devices, ports and controllers - each has
16860 	 * unique address. Events for different addresses cannot be combined.
16861 	 */
16862 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
16863 
16864 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16865 
16866 		/* qualify this event(s) */
16867 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
16868 			/* Invalid event for the device port */
16869 			(void) sprintf(buf2, err_msg_evnt_1,
16870 			    event & SATA_EVNT_PORT_EVENTS);
16871 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16872 			goto event_info;
16873 		}
16874 		if (saddr->qual == SATA_ADDR_CPORT) {
16875 			/* Controller's device port event */
16876 
16877 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
16878 			    cport_event_flags |=
16879 			    event & SATA_EVNT_PORT_EVENTS;
16880 			pstats =
16881 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
16882 			    cport_stats;
16883 		} else {
16884 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16885 			mutex_enter(&pmportinfo->pmport_mutex);
16886 			/* Port multiplier's device port event */
16887 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
16888 			    pmport_event_flags |=
16889 			    event & SATA_EVNT_PORT_EVENTS;
16890 			pstats =
16891 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
16892 			    pmport_stats;
16893 			mutex_exit(&pmportinfo->pmport_mutex);
16894 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16895 		}
16896 
16897 		/*
16898 		 * Add to statistics and log the message. We have to do it
16899 		 * here rather than in the event daemon, because there may be
16900 		 * multiple events occuring before they are processed.
16901 		 */
16902 		linkevent = event &
16903 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
16904 		if (linkevent) {
16905 			if (linkevent == (SATA_EVNT_LINK_LOST |
16906 			    SATA_EVNT_LINK_ESTABLISHED)) {
16907 				/* This is likely event combination */
16908 				(void) strlcat(buf1, "link lost/established, ",
16909 				    SATA_EVENT_MAX_MSG_LENGTH);
16910 
16911 				if (pstats->link_lost < 0xffffffffffffffffULL)
16912 					pstats->link_lost++;
16913 				if (pstats->link_established <
16914 				    0xffffffffffffffffULL)
16915 					pstats->link_established++;
16916 				linkevent = 0;
16917 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
16918 				(void) strlcat(buf1, "link lost, ",
16919 				    SATA_EVENT_MAX_MSG_LENGTH);
16920 
16921 				if (pstats->link_lost < 0xffffffffffffffffULL)
16922 					pstats->link_lost++;
16923 			} else {
16924 				(void) strlcat(buf1, "link established, ",
16925 				    SATA_EVENT_MAX_MSG_LENGTH);
16926 				if (pstats->link_established <
16927 				    0xffffffffffffffffULL)
16928 					pstats->link_established++;
16929 			}
16930 		}
16931 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
16932 			(void) strlcat(buf1, "device attached, ",
16933 			    SATA_EVENT_MAX_MSG_LENGTH);
16934 			if (pstats->device_attached < 0xffffffffffffffffULL)
16935 				pstats->device_attached++;
16936 		}
16937 		if (event & SATA_EVNT_DEVICE_DETACHED) {
16938 			(void) strlcat(buf1, "device detached, ",
16939 			    SATA_EVENT_MAX_MSG_LENGTH);
16940 			if (pstats->device_detached < 0xffffffffffffffffULL)
16941 				pstats->device_detached++;
16942 		}
16943 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
16944 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
16945 			    "port %d power level changed", cport);
16946 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
16947 				pstats->port_pwr_changed++;
16948 		}
16949 
16950 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
16951 			/* There should be no other events for this address */
16952 			(void) sprintf(buf2, err_msg_evnt_1,
16953 			    event & ~SATA_EVNT_PORT_EVENTS);
16954 		}
16955 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16956 
16957 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
16958 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16959 
16960 		/* qualify this event */
16961 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
16962 			/* Invalid event for a device */
16963 			(void) sprintf(buf2, err_msg_evnt_2,
16964 			    event & SATA_EVNT_DEVICE_RESET);
16965 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16966 			goto event_info;
16967 		}
16968 		/* drive event */
16969 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
16970 		if (sdinfo != NULL) {
16971 			if (event & SATA_EVNT_DEVICE_RESET) {
16972 				(void) strlcat(buf1, "device reset, ",
16973 				    SATA_EVENT_MAX_MSG_LENGTH);
16974 				if (sdinfo->satadrv_stats.drive_reset <
16975 				    0xffffffffffffffffULL)
16976 					sdinfo->satadrv_stats.drive_reset++;
16977 				sdinfo->satadrv_event_flags |=
16978 				    SATA_EVNT_DEVICE_RESET;
16979 			}
16980 		}
16981 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
16982 			/* Invalid event for a device */
16983 			(void) sprintf(buf2, err_msg_evnt_2,
16984 			    event & ~SATA_EVNT_DRIVE_EVENTS);
16985 		}
16986 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16987 	} else if (saddr->qual == SATA_ADDR_PMULT) {
16988 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16989 
16990 		/* qualify this event */
16991 		if ((event & (SATA_EVNT_DEVICE_RESET |
16992 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
16993 			/* Invalid event for a port multiplier */
16994 			(void) sprintf(buf2, err_msg_evnt_2,
16995 			    event & SATA_EVNT_DEVICE_RESET);
16996 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16997 			goto event_info;
16998 		}
16999 
17000 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17001 
17002 		if (event & SATA_EVNT_DEVICE_RESET) {
17003 
17004 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17005 			    "[Reset] port-mult on cport %d", cport);
17006 			pmultinfo->pmult_event_flags |=
17007 			    SATA_EVNT_DEVICE_RESET;
17008 			(void) strlcat(buf1, "pmult reset, ",
17009 			    SATA_EVENT_MAX_MSG_LENGTH);
17010 		}
17011 
17012 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17013 
17014 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17015 			    "pmult link changed on cport %d", cport);
17016 			pmultinfo->pmult_event_flags |=
17017 			    SATA_EVNT_PMULT_LINK_CHANGED;
17018 			(void) strlcat(buf1, "pmult link changed, ",
17019 			    SATA_EVENT_MAX_MSG_LENGTH);
17020 		}
17021 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17022 
17023 	} else {
17024 		if (saddr->qual != SATA_ADDR_NULL) {
17025 			/* Wrong address qualifier */
17026 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17027 			    "sata_hba_event_notify: invalid address 0x%x",
17028 			    *(uint32_t *)saddr));
17029 			return;
17030 		}
17031 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17032 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17033 			/* Invalid event for the controller */
17034 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17035 			    "sata_hba_event_notify: invalid event 0x%x for "
17036 			    "controller",
17037 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17038 			return;
17039 		}
17040 		buf1[0] = '\0';
17041 		/* This may be a frequent and not interesting event */
17042 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17043 		    "controller power level changed\n", NULL);
17044 
17045 		mutex_enter(&sata_hba_inst->satahba_mutex);
17046 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17047 		    0xffffffffffffffffULL)
17048 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17049 
17050 		sata_hba_inst->satahba_event_flags |=
17051 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17052 		mutex_exit(&sata_hba_inst->satahba_mutex);
17053 	}
17054 	/*
17055 	 * If we got here, there is something to do with this HBA
17056 	 * instance.
17057 	 */
17058 	mutex_enter(&sata_hba_inst->satahba_mutex);
17059 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17060 	mutex_exit(&sata_hba_inst->satahba_mutex);
17061 	mutex_enter(&sata_mutex);
17062 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17063 	mutex_exit(&sata_mutex);
17064 
17065 	/* Tickle event thread */
17066 	mutex_enter(&sata_event_mutex);
17067 	if (sata_event_thread_active == 0)
17068 		cv_signal(&sata_event_cv);
17069 	mutex_exit(&sata_event_mutex);
17070 
17071 event_info:
17072 	if (buf1[0] != '\0') {
17073 		lcp = strrchr(buf1, ',');
17074 		if (lcp != NULL)
17075 			*lcp = '\0';
17076 	}
17077 	if (saddr->qual == SATA_ADDR_CPORT ||
17078 	    saddr->qual == SATA_ADDR_DCPORT) {
17079 		if (buf1[0] != '\0') {
17080 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17081 			    cport, buf1);
17082 		}
17083 		if (buf2[0] != '\0') {
17084 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17085 			    cport, buf2);
17086 		}
17087 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
17088 	    saddr->qual == SATA_ADDR_DPMPORT) {
17089 		if (buf1[0] != '\0') {
17090 			sata_log(sata_hba_inst, CE_NOTE,
17091 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
17092 		}
17093 		if (buf2[0] != '\0') {
17094 			sata_log(sata_hba_inst, CE_NOTE,
17095 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
17096 		}
17097 	}
17098 }
17099 
17100 
17101 /*
17102  * Event processing thread.
17103  * Arg is a pointer to the sata_hba_list pointer.
17104  * It is not really needed, because sata_hba_list is global and static
17105  */
17106 static void
17107 sata_event_daemon(void *arg)
17108 {
17109 #ifndef __lock_lint
17110 	_NOTE(ARGUNUSED(arg))
17111 #endif
17112 	sata_hba_inst_t *sata_hba_inst;
17113 	clock_t delta;
17114 
17115 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17116 	    "SATA event daemon started\n", NULL);
17117 loop:
17118 	/*
17119 	 * Process events here. Walk through all registered HBAs
17120 	 */
17121 	mutex_enter(&sata_mutex);
17122 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17123 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17124 		ASSERT(sata_hba_inst != NULL);
17125 		mutex_enter(&sata_hba_inst->satahba_mutex);
17126 		if (sata_hba_inst->satahba_attached == 0 ||
17127 		    (sata_hba_inst->satahba_event_flags &
17128 		    SATA_EVNT_SKIP) != 0) {
17129 			mutex_exit(&sata_hba_inst->satahba_mutex);
17130 			continue;
17131 		}
17132 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
17133 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
17134 			mutex_exit(&sata_hba_inst->satahba_mutex);
17135 			mutex_exit(&sata_mutex);
17136 			/* Got the controller with pending event */
17137 			sata_process_controller_events(sata_hba_inst);
17138 			/*
17139 			 * Since global mutex was released, there is a
17140 			 * possibility that HBA list has changed, so start
17141 			 * over from the top. Just processed controller
17142 			 * will be passed-over because of the SKIP flag.
17143 			 */
17144 			goto loop;
17145 		}
17146 		mutex_exit(&sata_hba_inst->satahba_mutex);
17147 	}
17148 	/* Clear SKIP flag in all controllers */
17149 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17150 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17151 		mutex_enter(&sata_hba_inst->satahba_mutex);
17152 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
17153 		mutex_exit(&sata_hba_inst->satahba_mutex);
17154 	}
17155 	mutex_exit(&sata_mutex);
17156 
17157 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17158 	    "SATA EVENT DAEMON suspending itself", NULL);
17159 
17160 #ifdef SATA_DEBUG
17161 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
17162 		sata_log(sata_hba_inst, CE_WARN,
17163 		    "SATA EVENTS PROCESSING DISABLED\n");
17164 		thread_exit(); /* Daemon will not run again */
17165 	}
17166 #endif
17167 	mutex_enter(&sata_event_mutex);
17168 	sata_event_thread_active = 0;
17169 	mutex_exit(&sata_event_mutex);
17170 	/*
17171 	 * Go to sleep/suspend itself and wake up either because new event or
17172 	 * wait timeout. Exit if there is a termination request (driver
17173 	 * unload).
17174 	 */
17175 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
17176 	do {
17177 		mutex_enter(&sata_event_mutex);
17178 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
17179 		    delta, TR_CLOCK_TICK);
17180 
17181 		if (sata_event_thread_active != 0) {
17182 			mutex_exit(&sata_event_mutex);
17183 			continue;
17184 		}
17185 
17186 		/* Check if it is time to go away */
17187 		if (sata_event_thread_terminate == 1) {
17188 			/*
17189 			 * It is up to the thread setting above flag to make
17190 			 * sure that this thread is not killed prematurely.
17191 			 */
17192 			sata_event_thread_terminate = 0;
17193 			sata_event_thread = NULL;
17194 			mutex_exit(&sata_event_mutex);
17195 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17196 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
17197 			thread_exit();  { _NOTE(NOT_REACHED) }
17198 		}
17199 		mutex_exit(&sata_event_mutex);
17200 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
17201 
17202 	mutex_enter(&sata_event_mutex);
17203 	sata_event_thread_active = 1;
17204 	mutex_exit(&sata_event_mutex);
17205 
17206 	mutex_enter(&sata_mutex);
17207 	sata_event_pending &= ~SATA_EVNT_MAIN;
17208 	mutex_exit(&sata_mutex);
17209 
17210 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17211 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
17212 
17213 	goto loop;
17214 }
17215 
17216 /*
17217  * Specific HBA instance event processing.
17218  *
17219  * NOTE: At the moment, device event processing is limited to hard disks
17220  * only.
17221  * Port multiplier is supported now.
17222  */
17223 static void
17224 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
17225 {
17226 	int ncport;
17227 	uint32_t event_flags;
17228 	sata_address_t *saddr;
17229 	sata_cport_info_t *cportinfo;
17230 	sata_pmult_info_t *pmultinfo;
17231 
17232 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
17233 	    "Processing controller %d event(s)",
17234 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
17235 
17236 	mutex_enter(&sata_hba_inst->satahba_mutex);
17237 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
17238 	event_flags = sata_hba_inst->satahba_event_flags;
17239 	mutex_exit(&sata_hba_inst->satahba_mutex);
17240 	/*
17241 	 * Process controller power change first
17242 	 * HERE
17243 	 */
17244 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
17245 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
17246 
17247 	/*
17248 	 * Search through ports/devices to identify affected port/device.
17249 	 * We may have to process events for more than one port/device.
17250 	 */
17251 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
17252 		/*
17253 		 * Not all ports may be processed in attach by the time we
17254 		 * get an event. Check if port info is initialized.
17255 		 */
17256 		mutex_enter(&sata_hba_inst->satahba_mutex);
17257 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
17258 		mutex_exit(&sata_hba_inst->satahba_mutex);
17259 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
17260 			continue;
17261 
17262 		/* We have initialized controller port info */
17263 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17264 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
17265 		    cport_event_flags;
17266 		/* Check if port was locked by IOCTL processing */
17267 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
17268 			/*
17269 			 * We ignore port events because port is busy
17270 			 * with AP control processing. Set again
17271 			 * controller and main event flag, so that
17272 			 * events may be processed by the next daemon
17273 			 * run.
17274 			 */
17275 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17276 			mutex_enter(&sata_hba_inst->satahba_mutex);
17277 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17278 			mutex_exit(&sata_hba_inst->satahba_mutex);
17279 			mutex_enter(&sata_mutex);
17280 			sata_event_pending |= SATA_EVNT_MAIN;
17281 			mutex_exit(&sata_mutex);
17282 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
17283 			    "Event processing postponed until "
17284 			    "AP control processing completes",
17285 			    NULL);
17286 			/* Check other ports */
17287 			continue;
17288 		} else {
17289 			/*
17290 			 * Set BSY flag so that AP control would not
17291 			 * interfere with events processing for
17292 			 * this port.
17293 			 */
17294 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17295 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
17296 		}
17297 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17298 
17299 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
17300 
17301 		if ((event_flags &
17302 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17303 			/*
17304 			 * Got port event.
17305 			 * We need some hierarchy of event processing as they
17306 			 * are affecting each other:
17307 			 * 1. port failed
17308 			 * 2. device detached/attached
17309 			 * 3. link events - link events may trigger device
17310 			 *    detached or device attached events in some
17311 			 *    circumstances.
17312 			 * 4. port power level changed
17313 			 */
17314 			if (event_flags & SATA_EVNT_PORT_FAILED) {
17315 				sata_process_port_failed_event(sata_hba_inst,
17316 				    saddr);
17317 			}
17318 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17319 				sata_process_device_detached(sata_hba_inst,
17320 				    saddr);
17321 			}
17322 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17323 				sata_process_device_attached(sata_hba_inst,
17324 				    saddr);
17325 			}
17326 			if (event_flags &
17327 			    (SATA_EVNT_LINK_ESTABLISHED |
17328 			    SATA_EVNT_LINK_LOST)) {
17329 				sata_process_port_link_events(sata_hba_inst,
17330 				    saddr);
17331 			}
17332 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
17333 				sata_process_port_pwr_change(sata_hba_inst,
17334 				    saddr);
17335 			}
17336 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17337 				sata_process_target_node_cleanup(
17338 				    sata_hba_inst, saddr);
17339 			}
17340 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
17341 				sata_process_device_autoonline(
17342 				    sata_hba_inst, saddr);
17343 			}
17344 		}
17345 
17346 
17347 		/*
17348 		 * Scan port multiplier and all its sub-ports event flags.
17349 		 * The events are marked by
17350 		 * (1) sata_pmult_info.pmult_event_flags
17351 		 * (2) sata_pmport_info.pmport_event_flags
17352 		 */
17353 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17354 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
17355 			/*
17356 			 * There should be another extra check: this
17357 			 * port multiplier still exists?
17358 			 */
17359 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
17360 			    ncport);
17361 
17362 			if (pmultinfo != NULL) {
17363 				mutex_exit(&(SATA_CPORT_MUTEX(
17364 				    sata_hba_inst, ncport)));
17365 				sata_process_pmult_events(
17366 				    sata_hba_inst, ncport);
17367 				mutex_enter(&(SATA_CPORT_MUTEX(
17368 				    sata_hba_inst, ncport)));
17369 			} else {
17370 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17371 				    "Port-multiplier is gone. "
17372 				    "Ignore all sub-device events "
17373 				    "at port %d.", ncport);
17374 			}
17375 		}
17376 
17377 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
17378 		    SATA_DTYPE_NONE) &&
17379 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
17380 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
17381 			    satadrv_event_flags &
17382 			    (SATA_EVNT_DEVICE_RESET |
17383 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17384 				/* Have device event */
17385 				sata_process_device_reset(sata_hba_inst,
17386 				    saddr);
17387 			}
17388 		}
17389 		/* Release PORT_BUSY flag */
17390 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17391 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17392 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17393 
17394 	} /* End of loop through the controller SATA ports */
17395 }
17396 
17397 /*
17398  * Specific port multiplier instance event processing. At the moment, device
17399  * event processing is limited to link/attach event only.
17400  *
17401  * NOTE: power management event is not supported yet.
17402  */
17403 static void
17404 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
17405 {
17406 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17407 	sata_pmult_info_t *pmultinfo;
17408 	sata_pmport_info_t *pmportinfo;
17409 	sata_address_t *saddr;
17410 	sata_device_t sata_device;
17411 	uint32_t event_flags;
17412 	int npmport;
17413 	int rval;
17414 
17415 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17416 	    "Processing pmult event(s) on cport %d of controller %d",
17417 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17418 
17419 	/* First process events on port multiplier */
17420 	mutex_enter(&cportinfo->cport_mutex);
17421 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17422 	event_flags = pmultinfo->pmult_event_flags;
17423 
17424 	/*
17425 	 * Reset event (of port multiplier) has higher priority because the
17426 	 * port multiplier itself might be failed or removed after reset.
17427 	 */
17428 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
17429 		/*
17430 		 * The status of the sub-links are uncertain,
17431 		 * so mark all sub-ports as RESET
17432 		 */
17433 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
17434 		    sata_hba_inst, cport); npmport ++) {
17435 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17436 			    cport, npmport);
17437 			if (pmportinfo == NULL) {
17438 				/* That's weird. */
17439 				SATA_LOG_D((sata_hba_inst, CE_WARN,
17440 				    "sata_hba_event_notify: "
17441 				    "invalid/un-implemented "
17442 				    "port %d:%d (%d ports), ",
17443 				    cport, npmport, SATA_NUM_PMPORTS(
17444 				    sata_hba_inst, cport)));
17445 				continue;
17446 			}
17447 
17448 			mutex_enter(&pmportinfo->pmport_mutex);
17449 
17450 			/* Mark all pmport to unknow state. */
17451 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
17452 			/* Mark all pmports with link events. */
17453 			pmportinfo->pmport_event_flags =
17454 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
17455 			mutex_exit(&pmportinfo->pmport_mutex);
17456 		}
17457 
17458 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
17459 		/*
17460 		 * We need probe the port multiplier to know what has
17461 		 * happened.
17462 		 */
17463 		bzero(&sata_device, sizeof (sata_device_t));
17464 		sata_device.satadev_rev = SATA_DEVICE_REV;
17465 		sata_device.satadev_addr.cport = cport;
17466 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
17467 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
17468 
17469 		mutex_exit(&cportinfo->cport_mutex);
17470 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17471 		    (SATA_DIP(sata_hba_inst), &sata_device);
17472 		mutex_enter(&cportinfo->cport_mutex);
17473 		if (rval != SATA_SUCCESS) {
17474 			/* Something went wrong? Fail the port */
17475 			cportinfo->cport_state = SATA_PSTATE_FAILED;
17476 			mutex_exit(&cportinfo->cport_mutex);
17477 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17478 			    "SATA port %d probing failed", cport));
17479 
17480 			/* PMult structure must be released.  */
17481 			sata_free_pmult(sata_hba_inst, &sata_device);
17482 			return;
17483 		}
17484 
17485 		sata_update_port_info(sata_hba_inst, &sata_device);
17486 
17487 		/*
17488 		 * Sanity check - Port is active? Is the link active?
17489 		 * The device is still a port multiplier?
17490 		 */
17491 		if ((cportinfo->cport_state &
17492 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
17493 		    ((cportinfo->cport_scr.sstatus &
17494 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
17495 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
17496 			mutex_exit(&cportinfo->cport_mutex);
17497 
17498 			/* PMult structure must be released.  */
17499 			sata_free_pmult(sata_hba_inst, &sata_device);
17500 			return;
17501 		}
17502 
17503 		/* Probed succeed, set port ready. */
17504 		cportinfo->cport_state |=
17505 		    SATA_STATE_PROBED | SATA_STATE_READY;
17506 	}
17507 
17508 	/* Release port multiplier event flags. */
17509 	pmultinfo->pmult_event_flags &=
17510 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
17511 	mutex_exit(&cportinfo->cport_mutex);
17512 
17513 	/*
17514 	 * Check all sub-links.
17515 	 */
17516 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
17517 	    npmport ++) {
17518 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
17519 		mutex_enter(&pmportinfo->pmport_mutex);
17520 		event_flags = pmportinfo->pmport_event_flags;
17521 		mutex_exit(&pmportinfo->pmport_mutex);
17522 		saddr = &pmportinfo->pmport_addr;
17523 
17524 		if ((event_flags &
17525 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17526 			/*
17527 			 * Got port multiplier port event.
17528 			 * We need some hierarchy of event processing as they
17529 			 * are affecting each other:
17530 			 * 1. device detached/attached
17531 			 * 2. link events - link events may trigger device
17532 			 *    detached or device attached events in some
17533 			 *    circumstances.
17534 			 */
17535 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17536 				sata_process_pmdevice_detached(sata_hba_inst,
17537 				    saddr);
17538 			}
17539 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17540 				sata_process_pmdevice_attached(sata_hba_inst,
17541 				    saddr);
17542 			}
17543 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
17544 			    event_flags & SATA_EVNT_LINK_LOST) {
17545 				sata_process_pmport_link_events(sata_hba_inst,
17546 				    saddr);
17547 			}
17548 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17549 				sata_process_target_node_cleanup(
17550 				    sata_hba_inst, saddr);
17551 			}
17552 		}
17553 
17554 		/* Checking drive event(s). */
17555 		mutex_enter(&pmportinfo->pmport_mutex);
17556 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
17557 		    pmportinfo->pmport_sata_drive != NULL) {
17558 			event_flags = pmportinfo->pmport_sata_drive->
17559 			    satadrv_event_flags;
17560 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
17561 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17562 
17563 				/* Have device event */
17564 				sata_process_pmdevice_reset(sata_hba_inst,
17565 				    saddr);
17566 			}
17567 		}
17568 		mutex_exit(&pmportinfo->pmport_mutex);
17569 
17570 		/* Release PORT_BUSY flag */
17571 		mutex_enter(&cportinfo->cport_mutex);
17572 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17573 		mutex_exit(&cportinfo->cport_mutex);
17574 	}
17575 
17576 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17577 	    "[DONE] pmult event(s) on cport %d of controller %d",
17578 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17579 }
17580 
17581 /*
17582  * Process HBA power level change reported by HBA driver.
17583  * Not implemented at this time - event is ignored.
17584  */
17585 static void
17586 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
17587 {
17588 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17589 	    "Processing controller power level change", NULL);
17590 
17591 	/* Ignoring it for now */
17592 	mutex_enter(&sata_hba_inst->satahba_mutex);
17593 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17594 	mutex_exit(&sata_hba_inst->satahba_mutex);
17595 }
17596 
17597 /*
17598  * Process port power level change reported by HBA driver.
17599  * Not implemented at this time - event is ignored.
17600  */
17601 static void
17602 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
17603     sata_address_t *saddr)
17604 {
17605 	sata_cport_info_t *cportinfo;
17606 
17607 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17608 	    "Processing port power level change", NULL);
17609 
17610 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17611 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17612 	/* Reset event flag */
17613 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17614 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17615 }
17616 
17617 /*
17618  * Process port failure reported by HBA driver.
17619  * cports support only - no pmports.
17620  */
17621 static void
17622 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
17623     sata_address_t *saddr)
17624 {
17625 	sata_cport_info_t *cportinfo;
17626 
17627 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17628 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17629 	/* Reset event flag first */
17630 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
17631 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
17632 	if ((cportinfo->cport_state &
17633 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
17634 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17635 		    cport_mutex);
17636 		return;
17637 	}
17638 	/* Fail the port */
17639 	cportinfo->cport_state = SATA_PSTATE_FAILED;
17640 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17641 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
17642 }
17643 
17644 /*
17645  * Device Reset Event processing.
17646  * The seqeunce is managed by 3 stage flags:
17647  * - reset event reported,
17648  * - reset event being processed,
17649  * - request to clear device reset state.
17650  *
17651  * NOTE: This function has to be entered with cport mutex held. It exits with
17652  * mutex held as well, but can release mutex during the processing.
17653  */
17654 static void
17655 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
17656     sata_address_t *saddr)
17657 {
17658 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17659 	sata_drive_info_t *sdinfo;
17660 	sata_cport_info_t *cportinfo;
17661 	sata_device_t sata_device;
17662 	int rval_probe, rval_set;
17663 
17664 	/* We only care about host sata cport for now */
17665 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17666 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17667 	/*
17668 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17669 	 * state, ignore reset event.
17670 	 */
17671 	if (((cportinfo->cport_state &
17672 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17673 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17674 		sdinfo->satadrv_event_flags &=
17675 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17676 		return;
17677 	}
17678 
17679 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
17680 	    SATA_DTYPE_PMULT)) {
17681 		/*
17682 		 * Should not happened: this is already handled in
17683 		 * sata_hba_event_notify()
17684 		 */
17685 		mutex_exit(&cportinfo->cport_mutex);
17686 		goto done;
17687 	}
17688 
17689 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
17690 	    SATA_VALID_DEV_TYPE) == 0) {
17691 		/*
17692 		 * This should not happen - coding error.
17693 		 * But we can recover, so do not panic, just clean up
17694 		 * and if in debug mode, log the message.
17695 		 */
17696 #ifdef SATA_DEBUG
17697 		sata_log(sata_hba_inst, CE_WARN,
17698 		    "sata_process_device_reset: "
17699 		    "Invalid device type with sdinfo!", NULL);
17700 #endif
17701 		sdinfo->satadrv_event_flags = 0;
17702 		return;
17703 	}
17704 
17705 #ifdef SATA_DEBUG
17706 	if ((sdinfo->satadrv_event_flags &
17707 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17708 		/* Nothing to do */
17709 		/* Something is weird - why we are processing dev reset? */
17710 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17711 		    "No device reset event!!!!", NULL);
17712 
17713 		return;
17714 	}
17715 	if ((sdinfo->satadrv_event_flags &
17716 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17717 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17718 		/* Something is weird - new device reset event */
17719 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17720 		    "Overlapping device reset events!", NULL);
17721 	}
17722 #endif
17723 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17724 	    "Processing port %d device reset", saddr->cport);
17725 
17726 	/* Clear event flag */
17727 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17728 
17729 	/* It seems that we always need to check the port state first */
17730 	sata_device.satadev_rev = SATA_DEVICE_REV;
17731 	sata_device.satadev_addr = *saddr;
17732 	/*
17733 	 * We have to exit mutex, because the HBA probe port function may
17734 	 * block on its own mutex.
17735 	 */
17736 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17737 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17738 	    (SATA_DIP(sata_hba_inst), &sata_device);
17739 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17740 	sata_update_port_info(sata_hba_inst, &sata_device);
17741 	if (rval_probe != SATA_SUCCESS) {
17742 		/* Something went wrong? Fail the port */
17743 		cportinfo->cport_state = SATA_PSTATE_FAILED;
17744 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17745 		if (sdinfo != NULL)
17746 			sdinfo->satadrv_event_flags = 0;
17747 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17748 		    cport_mutex);
17749 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17750 		    "SATA port %d probing failed",
17751 		    saddr->cport));
17752 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
17753 		    saddr->cport)->cport_mutex);
17754 		return;
17755 	}
17756 	if ((sata_device.satadev_scr.sstatus  &
17757 	    SATA_PORT_DEVLINK_UP_MASK) !=
17758 	    SATA_PORT_DEVLINK_UP ||
17759 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
17760 		/*
17761 		 * No device to process, anymore. Some other event processing
17762 		 * would or have already performed port info cleanup.
17763 		 * To be safe (HBA may need it), request clearing device
17764 		 * reset condition.
17765 		 */
17766 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17767 		if (sdinfo != NULL) {
17768 			sdinfo->satadrv_event_flags &=
17769 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17770 			sdinfo->satadrv_event_flags |=
17771 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17772 		}
17773 		return;
17774 	}
17775 
17776 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17777 	if (sdinfo == NULL) {
17778 		return;
17779 	}
17780 	if ((sdinfo->satadrv_event_flags &
17781 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
17782 		/*
17783 		 * Start tracking time for device feature restoration and
17784 		 * identification. Save current time (lbolt value).
17785 		 */
17786 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
17787 	}
17788 	/* Mark device reset processing as active */
17789 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
17790 
17791 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
17792 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17793 
17794 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
17795 
17796 	if (rval_set  != SATA_SUCCESS) {
17797 		/*
17798 		 * Restoring drive setting failed.
17799 		 * Probe the port first, to check if the port state has changed
17800 		 */
17801 		sata_device.satadev_rev = SATA_DEVICE_REV;
17802 		sata_device.satadev_addr = *saddr;
17803 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
17804 		/* probe port */
17805 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17806 		    (SATA_DIP(sata_hba_inst), &sata_device);
17807 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17808 		    cport_mutex);
17809 		if (rval_probe == SATA_SUCCESS &&
17810 		    (sata_device.satadev_state &
17811 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
17812 		    (sata_device.satadev_scr.sstatus  &
17813 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
17814 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
17815 			/*
17816 			 * We may retry this a bit later - in-process reset
17817 			 * condition should be already set.
17818 			 * Track retry time for device identification.
17819 			 */
17820 			if ((cportinfo->cport_dev_type &
17821 			    SATA_VALID_DEV_TYPE) != 0 &&
17822 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
17823 			    sdinfo->satadrv_reset_time != 0) {
17824 				clock_t cur_time = ddi_get_lbolt();
17825 				/*
17826 				 * If the retry time limit was not
17827 				 * exceeded, retry.
17828 				 */
17829 				if ((cur_time - sdinfo->satadrv_reset_time) <
17830 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
17831 					mutex_enter(
17832 					    &sata_hba_inst->satahba_mutex);
17833 					sata_hba_inst->satahba_event_flags |=
17834 					    SATA_EVNT_MAIN;
17835 					mutex_exit(
17836 					    &sata_hba_inst->satahba_mutex);
17837 					mutex_enter(&sata_mutex);
17838 					sata_event_pending |= SATA_EVNT_MAIN;
17839 					mutex_exit(&sata_mutex);
17840 					return;
17841 				}
17842 				if (rval_set == SATA_RETRY) {
17843 					/*
17844 					 * Setting drive features failed, but
17845 					 * the drive is still accessible,
17846 					 * so emit a warning message before
17847 					 * return.
17848 					 */
17849 					mutex_exit(&SATA_CPORT_INFO(
17850 					    sata_hba_inst,
17851 					    saddr->cport)->cport_mutex);
17852 					goto done;
17853 				}
17854 			}
17855 			/* Fail the drive */
17856 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
17857 
17858 			sata_log(sata_hba_inst, CE_WARN,
17859 			    "SATA device at port %d - device failed",
17860 			    saddr->cport);
17861 		}
17862 		/*
17863 		 * No point of retrying - device failed or some other event
17864 		 * processing or already did or will do port info cleanup.
17865 		 * To be safe (HBA may need it),
17866 		 * request clearing device reset condition.
17867 		 */
17868 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
17869 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
17870 		sdinfo->satadrv_reset_time = 0;
17871 		return;
17872 	}
17873 done:
17874 	/*
17875 	 * If setting of drive features failed, but the drive is still
17876 	 * accessible, emit a warning message.
17877 	 */
17878 	if (rval_set == SATA_RETRY) {
17879 		sata_log(sata_hba_inst, CE_WARN,
17880 		    "SATA device at port %d - desired setting could not be "
17881 		    "restored after reset. Device may not operate as expected.",
17882 		    saddr->cport);
17883 	}
17884 	/*
17885 	 * Raise the flag indicating that the next sata command could
17886 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
17887 	 * reset is reported.
17888 	 */
17889 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17890 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
17891 		sdinfo->satadrv_reset_time = 0;
17892 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
17893 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
17894 			sdinfo->satadrv_event_flags &=
17895 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17896 			sdinfo->satadrv_event_flags |=
17897 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17898 		}
17899 	}
17900 }
17901 
17902 
17903 /*
17904  * Port Multiplier Port Device Reset Event processing.
17905  *
17906  * NOTE: This function has to be entered with pmport mutex held. It exits with
17907  * mutex held as well, but can release mutex during the processing.
17908  */
17909 static void
17910 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
17911     sata_address_t *saddr)
17912 {
17913 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17914 	sata_drive_info_t *sdinfo = NULL;
17915 	sata_cport_info_t *cportinfo = NULL;
17916 	sata_pmport_info_t *pmportinfo = NULL;
17917 	sata_pmult_info_t *pminfo = NULL;
17918 	sata_device_t sata_device;
17919 	uint8_t cport = saddr->cport;
17920 	uint8_t pmport = saddr->pmport;
17921 	int rval;
17922 
17923 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17924 	    "Processing drive reset at port %d:%d", cport, pmport);
17925 
17926 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17927 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
17928 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
17929 
17930 	/*
17931 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17932 	 * state, ignore reset event.
17933 	 */
17934 	if (((cportinfo->cport_state &
17935 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17936 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17937 		sdinfo->satadrv_event_flags &=
17938 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17939 		return;
17940 	}
17941 
17942 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
17943 		/*
17944 		 * This should not happen - coding error.
17945 		 * But we can recover, so do not panic, just clean up
17946 		 * and if in debug mode, log the message.
17947 		 */
17948 #ifdef SATA_DEBUG
17949 		sata_log(sata_hba_inst, CE_WARN,
17950 		    "sata_process_pmdevice_reset: "
17951 		    "Invalid device type with sdinfo!", NULL);
17952 #endif
17953 		sdinfo->satadrv_event_flags = 0;
17954 		return;
17955 	}
17956 
17957 #ifdef SATA_DEBUG
17958 	if ((sdinfo->satadrv_event_flags &
17959 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17960 		/* Nothing to do */
17961 		/* Something is weird - why we are processing dev reset? */
17962 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17963 		    "No device reset event!!!!", NULL);
17964 
17965 		return;
17966 	}
17967 	if ((sdinfo->satadrv_event_flags &
17968 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17969 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17970 		/* Something is weird - new device reset event */
17971 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17972 		    "Overlapping device reset events!", NULL);
17973 	}
17974 #endif
17975 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17976 	    "Processing port %d:%d device reset", cport, pmport);
17977 
17978 	/* Clear event flag */
17979 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17980 
17981 	/* It seems that we always need to check the port state first */
17982 	sata_device.satadev_rev = SATA_DEVICE_REV;
17983 	sata_device.satadev_addr = *saddr;
17984 	/*
17985 	 * We have to exit mutex, because the HBA probe port function may
17986 	 * block on its own mutex.
17987 	 */
17988 	mutex_exit(&pmportinfo->pmport_mutex);
17989 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17990 	    (SATA_DIP(sata_hba_inst), &sata_device);
17991 	mutex_enter(&pmportinfo->pmport_mutex);
17992 
17993 	sata_update_pmport_info(sata_hba_inst, &sata_device);
17994 	if (rval != SATA_SUCCESS) {
17995 		/* Something went wrong? Fail the port */
17996 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
17997 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
17998 		    saddr->pmport);
17999 		if (sdinfo != NULL)
18000 			sdinfo->satadrv_event_flags = 0;
18001 		mutex_exit(&pmportinfo->pmport_mutex);
18002 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18003 		    "SATA port %d:%d probing failed",
18004 		    saddr->cport, saddr->pmport));
18005 		mutex_enter(&pmportinfo->pmport_mutex);
18006 		return;
18007 	}
18008 	if ((sata_device.satadev_scr.sstatus  &
18009 	    SATA_PORT_DEVLINK_UP_MASK) !=
18010 	    SATA_PORT_DEVLINK_UP ||
18011 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18012 		/*
18013 		 * No device to process, anymore. Some other event processing
18014 		 * would or have already performed port info cleanup.
18015 		 * To be safe (HBA may need it), request clearing device
18016 		 * reset condition.
18017 		 */
18018 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18019 		    saddr->pmport);
18020 		if (sdinfo != NULL) {
18021 			sdinfo->satadrv_event_flags &=
18022 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18023 			/* must clear flags on cport */
18024 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18025 			    saddr->cport);
18026 			pminfo->pmult_event_flags |=
18027 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18028 		}
18029 		return;
18030 	}
18031 
18032 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18033 	    saddr->pmport);
18034 	if (sdinfo == NULL) {
18035 		return;
18036 	}
18037 	if ((sdinfo->satadrv_event_flags &
18038 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18039 		/*
18040 		 * Start tracking time for device feature restoration and
18041 		 * identification. Save current time (lbolt value).
18042 		 */
18043 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18044 	}
18045 	/* Mark device reset processing as active */
18046 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18047 
18048 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18049 	mutex_exit(&pmportinfo->pmport_mutex);
18050 
18051 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18052 	    SATA_FAILURE) {
18053 		/*
18054 		 * Restoring drive setting failed.
18055 		 * Probe the port first, to check if the port state has changed
18056 		 */
18057 		sata_device.satadev_rev = SATA_DEVICE_REV;
18058 		sata_device.satadev_addr = *saddr;
18059 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18060 
18061 		/* probe port */
18062 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18063 		    (SATA_DIP(sata_hba_inst), &sata_device);
18064 		mutex_enter(&pmportinfo->pmport_mutex);
18065 		if (rval == SATA_SUCCESS &&
18066 		    (sata_device.satadev_state &
18067 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18068 		    (sata_device.satadev_scr.sstatus  &
18069 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18070 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18071 			/*
18072 			 * We may retry this a bit later - in-process reset
18073 			 * condition should be already set.
18074 			 * Track retry time for device identification.
18075 			 */
18076 			if ((pmportinfo->pmport_dev_type &
18077 			    SATA_VALID_DEV_TYPE) != 0 &&
18078 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18079 			    sdinfo->satadrv_reset_time != 0) {
18080 				clock_t cur_time = ddi_get_lbolt();
18081 				/*
18082 				 * If the retry time limit was not
18083 				 * exceeded, retry.
18084 				 */
18085 				if ((cur_time - sdinfo->satadrv_reset_time) <
18086 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18087 					mutex_enter(
18088 					    &sata_hba_inst->satahba_mutex);
18089 					sata_hba_inst->satahba_event_flags |=
18090 					    SATA_EVNT_MAIN;
18091 					mutex_exit(
18092 					    &sata_hba_inst->satahba_mutex);
18093 					mutex_enter(&sata_mutex);
18094 					sata_event_pending |= SATA_EVNT_MAIN;
18095 					mutex_exit(&sata_mutex);
18096 					return;
18097 				}
18098 			}
18099 			/* Fail the drive */
18100 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18101 
18102 			sata_log(sata_hba_inst, CE_WARN,
18103 			    "SATA device at port %d:%d - device failed",
18104 			    saddr->cport, saddr->pmport);
18105 		} else {
18106 			/*
18107 			 * No point of retrying - some other event processing
18108 			 * would or already did port info cleanup.
18109 			 * To be safe (HBA may need it),
18110 			 * request clearing device reset condition.
18111 			 */
18112 			sdinfo->satadrv_event_flags |=
18113 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18114 		}
18115 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18116 		sdinfo->satadrv_reset_time = 0;
18117 		return;
18118 	}
18119 	/*
18120 	 * Raise the flag indicating that the next sata command could
18121 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18122 	 * reset is reported.
18123 	 */
18124 	mutex_enter(&pmportinfo->pmport_mutex);
18125 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18126 		sdinfo->satadrv_reset_time = 0;
18127 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
18128 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18129 			sdinfo->satadrv_event_flags &=
18130 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18131 			/* must clear flags on cport */
18132 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18133 			    saddr->cport);
18134 			pminfo->pmult_event_flags |=
18135 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18136 		}
18137 	}
18138 }
18139 
18140 /*
18141  * Port Link Events processing.
18142  * Every link established event may involve device reset (due to
18143  * COMRESET signal, equivalent of the hard reset) so arbitrarily
18144  * set device reset event for an attached device (if any).
18145  * If the port is in SHUTDOWN or FAILED state, ignore link events.
18146  *
18147  * The link established event processing varies, depending on the state
18148  * of the target node, HBA hotplugging capabilities, state of the port.
18149  * If the link is not active, the link established event is ignored.
18150  * If HBA cannot detect device attachment and there is no target node,
18151  * the link established event triggers device attach event processing.
18152  * Else, link established event triggers device reset event processing.
18153  *
18154  * The link lost event processing varies, depending on a HBA hotplugging
18155  * capability and the state of the port (link active or not active).
18156  * If the link is active, the lost link event is ignored.
18157  * If HBA cannot detect device removal, the lost link event triggers
18158  * device detached event processing after link lost timeout.
18159  * Else, the event is ignored.
18160  *
18161  * NOTE: Port multiplier ports events are handled by
18162  * sata_process_pmport_link_events();
18163  */
18164 static void
18165 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
18166     sata_address_t *saddr)
18167 {
18168 	sata_device_t sata_device;
18169 	sata_cport_info_t *cportinfo;
18170 	sata_drive_info_t *sdinfo;
18171 	uint32_t event_flags;
18172 	int rval;
18173 
18174 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18175 	    "Processing port %d link event(s)", saddr->cport);
18176 
18177 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18178 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18179 	event_flags = cportinfo->cport_event_flags;
18180 
18181 	/* Reset event flags first */
18182 	cportinfo->cport_event_flags &=
18183 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18184 
18185 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18186 	if ((cportinfo->cport_state &
18187 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18188 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18189 		    cport_mutex);
18190 		return;
18191 	}
18192 
18193 	/*
18194 	 * For the sanity sake get current port state.
18195 	 * Set device address only. Other sata_device fields should be
18196 	 * set by HBA driver.
18197 	 */
18198 	sata_device.satadev_rev = SATA_DEVICE_REV;
18199 	sata_device.satadev_addr = *saddr;
18200 	/*
18201 	 * We have to exit mutex, because the HBA probe port function may
18202 	 * block on its own mutex.
18203 	 */
18204 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18205 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18206 	    (SATA_DIP(sata_hba_inst), &sata_device);
18207 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18208 	sata_update_port_info(sata_hba_inst, &sata_device);
18209 	if (rval != SATA_SUCCESS) {
18210 		/* Something went wrong? Fail the port */
18211 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18212 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18213 		    cport_mutex);
18214 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18215 		    "SATA port %d probing failed",
18216 		    saddr->cport));
18217 		/*
18218 		 * We may want to release device info structure, but
18219 		 * it is not necessary.
18220 		 */
18221 		return;
18222 	} else {
18223 		/* port probed successfully */
18224 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18225 	}
18226 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18227 
18228 		if ((sata_device.satadev_scr.sstatus &
18229 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18230 			/* Ignore event */
18231 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18232 			    "Ignoring port %d link established event - "
18233 			    "link down",
18234 			    saddr->cport);
18235 			goto linklost;
18236 		}
18237 
18238 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18239 		    "Processing port %d link established event",
18240 		    saddr->cport);
18241 
18242 		/*
18243 		 * For the sanity sake check if a device is attached - check
18244 		 * return state of a port probing.
18245 		 */
18246 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
18247 			/*
18248 			 * HBA port probe indicated that there is a device
18249 			 * attached. Check if the framework had device info
18250 			 * structure attached for this device.
18251 			 */
18252 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
18253 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
18254 				    NULL);
18255 
18256 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18257 				if ((sdinfo->satadrv_type &
18258 				    SATA_VALID_DEV_TYPE) != 0) {
18259 					/*
18260 					 * Dev info structure is present.
18261 					 * If dev_type is set to known type in
18262 					 * the framework's drive info struct
18263 					 * then the device existed before and
18264 					 * the link was probably lost
18265 					 * momentarily - in such case
18266 					 * we may want to check device
18267 					 * identity.
18268 					 * Identity check is not supported now.
18269 					 *
18270 					 * Link established event
18271 					 * triggers device reset event.
18272 					 */
18273 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
18274 					    satadrv_event_flags |=
18275 					    SATA_EVNT_DEVICE_RESET;
18276 				}
18277 			} else if (cportinfo->cport_dev_type ==
18278 			    SATA_DTYPE_NONE) {
18279 				/*
18280 				 * We got new device attached! If HBA does not
18281 				 * generate device attached events, trigger it
18282 				 * here.
18283 				 */
18284 				if (!(SATA_FEATURES(sata_hba_inst) &
18285 				    SATA_CTLF_HOTPLUG)) {
18286 					cportinfo->cport_event_flags |=
18287 					    SATA_EVNT_DEVICE_ATTACHED;
18288 				}
18289 			}
18290 			/* Reset link lost timeout */
18291 			cportinfo->cport_link_lost_time = 0;
18292 		}
18293 	}
18294 linklost:
18295 	if (event_flags & SATA_EVNT_LINK_LOST) {
18296 		if ((sata_device.satadev_scr.sstatus &
18297 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18298 			/* Ignore event */
18299 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18300 			    "Ignoring port %d link lost event - link is up",
18301 			    saddr->cport);
18302 			goto done;
18303 		}
18304 #ifdef SATA_DEBUG
18305 		if (cportinfo->cport_link_lost_time == 0) {
18306 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18307 			    "Processing port %d link lost event",
18308 			    saddr->cport);
18309 		}
18310 #endif
18311 		/*
18312 		 * When HBA cannot generate device attached/detached events,
18313 		 * we need to track link lost time and eventually generate
18314 		 * device detach event.
18315 		 */
18316 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18317 			/* We are tracking link lost time */
18318 			if (cportinfo->cport_link_lost_time == 0) {
18319 				/* save current time (lbolt value) */
18320 				cportinfo->cport_link_lost_time =
18321 				    ddi_get_lbolt();
18322 				/* just keep link lost event */
18323 				cportinfo->cport_event_flags |=
18324 				    SATA_EVNT_LINK_LOST;
18325 			} else {
18326 				clock_t cur_time = ddi_get_lbolt();
18327 				if ((cur_time -
18328 				    cportinfo->cport_link_lost_time) >=
18329 				    drv_usectohz(
18330 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18331 					/* trigger device detach event */
18332 					cportinfo->cport_event_flags |=
18333 					    SATA_EVNT_DEVICE_DETACHED;
18334 					cportinfo->cport_link_lost_time = 0;
18335 					SATADBG1(SATA_DBG_EVENTS,
18336 					    sata_hba_inst,
18337 					    "Triggering port %d "
18338 					    "device detached event",
18339 					    saddr->cport);
18340 				} else {
18341 					/* keep link lost event */
18342 					cportinfo->cport_event_flags |=
18343 					    SATA_EVNT_LINK_LOST;
18344 				}
18345 			}
18346 		}
18347 		/*
18348 		 * We could change port state to disable/delay access to
18349 		 * the attached device until the link is recovered.
18350 		 */
18351 	}
18352 done:
18353 	event_flags = cportinfo->cport_event_flags;
18354 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18355 	if (event_flags != 0) {
18356 		mutex_enter(&sata_hba_inst->satahba_mutex);
18357 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18358 		mutex_exit(&sata_hba_inst->satahba_mutex);
18359 		mutex_enter(&sata_mutex);
18360 		sata_event_pending |= SATA_EVNT_MAIN;
18361 		mutex_exit(&sata_mutex);
18362 	}
18363 }
18364 
18365 /*
18366  * Port Multiplier Port Link Events processing.
18367  */
18368 static void
18369 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
18370     sata_address_t *saddr)
18371 {
18372 	sata_device_t sata_device;
18373 	sata_pmport_info_t *pmportinfo = NULL;
18374 	sata_drive_info_t *sdinfo = NULL;
18375 	uint32_t event_flags;
18376 	uint8_t cport = saddr->cport;
18377 	uint8_t pmport = saddr->pmport;
18378 	int rval;
18379 
18380 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18381 	    "Processing port %d:%d link event(s)",
18382 	    cport, pmport);
18383 
18384 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18385 	mutex_enter(&pmportinfo->pmport_mutex);
18386 	event_flags = pmportinfo->pmport_event_flags;
18387 
18388 	/* Reset event flags first */
18389 	pmportinfo->pmport_event_flags &=
18390 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18391 
18392 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18393 	if ((pmportinfo->pmport_state &
18394 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18395 		mutex_exit(&pmportinfo->pmport_mutex);
18396 		return;
18397 	}
18398 
18399 	/*
18400 	 * For the sanity sake get current port state.
18401 	 * Set device address only. Other sata_device fields should be
18402 	 * set by HBA driver.
18403 	 */
18404 	sata_device.satadev_rev = SATA_DEVICE_REV;
18405 	sata_device.satadev_addr = *saddr;
18406 	/*
18407 	 * We have to exit mutex, because the HBA probe port function may
18408 	 * block on its own mutex.
18409 	 */
18410 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18411 	    saddr->pmport));
18412 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18413 	    (SATA_DIP(sata_hba_inst), &sata_device);
18414 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18415 	    saddr->pmport));
18416 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18417 	if (rval != SATA_SUCCESS) {
18418 		/* Something went wrong? Fail the port */
18419 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18420 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18421 		    saddr->pmport));
18422 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18423 		    "SATA port %d:%d probing failed",
18424 		    saddr->cport, saddr->pmport));
18425 		/*
18426 		 * We may want to release device info structure, but
18427 		 * it is not necessary.
18428 		 */
18429 		return;
18430 	} else {
18431 		/* port probed successfully */
18432 		pmportinfo->pmport_state |=
18433 		    SATA_STATE_PROBED | SATA_STATE_READY;
18434 	}
18435 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
18436 	    saddr->cport, saddr->pmport));
18437 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
18438 	    saddr->cport, saddr->pmport));
18439 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18440 
18441 		if ((sata_device.satadev_scr.sstatus &
18442 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18443 			/* Ignore event */
18444 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18445 			    "Ignoring port %d:%d link established event - "
18446 			    "link down",
18447 			    saddr->cport, saddr->pmport);
18448 			goto linklost;
18449 		}
18450 
18451 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18452 		    "Processing port %d:%d link established event",
18453 		    cport, pmport);
18454 
18455 		/*
18456 		 * For the sanity sake check if a device is attached - check
18457 		 * return state of a port probing.
18458 		 */
18459 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
18460 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
18461 			/*
18462 			 * HBA port probe indicated that there is a device
18463 			 * attached. Check if the framework had device info
18464 			 * structure attached for this device.
18465 			 */
18466 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
18467 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
18468 				    NULL);
18469 
18470 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18471 				if ((sdinfo->satadrv_type &
18472 				    SATA_VALID_DEV_TYPE) != 0) {
18473 					/*
18474 					 * Dev info structure is present.
18475 					 * If dev_type is set to known type in
18476 					 * the framework's drive info struct
18477 					 * then the device existed before and
18478 					 * the link was probably lost
18479 					 * momentarily - in such case
18480 					 * we may want to check device
18481 					 * identity.
18482 					 * Identity check is not supported now.
18483 					 *
18484 					 * Link established event
18485 					 * triggers device reset event.
18486 					 */
18487 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
18488 					    satadrv_event_flags |=
18489 					    SATA_EVNT_DEVICE_RESET;
18490 				}
18491 			} else if (pmportinfo->pmport_dev_type ==
18492 			    SATA_DTYPE_NONE) {
18493 				/*
18494 				 * We got new device attached! If HBA does not
18495 				 * generate device attached events, trigger it
18496 				 * here.
18497 				 */
18498 				if (!(SATA_FEATURES(sata_hba_inst) &
18499 				    SATA_CTLF_HOTPLUG)) {
18500 					pmportinfo->pmport_event_flags |=
18501 					    SATA_EVNT_DEVICE_ATTACHED;
18502 				}
18503 			}
18504 			/* Reset link lost timeout */
18505 			pmportinfo->pmport_link_lost_time = 0;
18506 		}
18507 	}
18508 linklost:
18509 	if (event_flags & SATA_EVNT_LINK_LOST) {
18510 #ifdef SATA_DEBUG
18511 		if (pmportinfo->pmport_link_lost_time == 0) {
18512 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18513 			    "Processing port %d:%d link lost event",
18514 			    saddr->cport, saddr->pmport);
18515 		}
18516 #endif
18517 		if ((sata_device.satadev_scr.sstatus &
18518 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18519 			/* Ignore event */
18520 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18521 			    "Ignoring port %d:%d link lost event - link is up",
18522 			    saddr->cport, saddr->pmport);
18523 			goto done;
18524 		}
18525 		/*
18526 		 * When HBA cannot generate device attached/detached events,
18527 		 * we need to track link lost time and eventually generate
18528 		 * device detach event.
18529 		 */
18530 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18531 			/* We are tracking link lost time */
18532 			if (pmportinfo->pmport_link_lost_time == 0) {
18533 				/* save current time (lbolt value) */
18534 				pmportinfo->pmport_link_lost_time =
18535 				    ddi_get_lbolt();
18536 				/* just keep link lost event */
18537 				pmportinfo->pmport_event_flags |=
18538 				    SATA_EVNT_LINK_LOST;
18539 			} else {
18540 				clock_t cur_time = ddi_get_lbolt();
18541 				if ((cur_time -
18542 				    pmportinfo->pmport_link_lost_time) >=
18543 				    drv_usectohz(
18544 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18545 					/* trigger device detach event */
18546 					pmportinfo->pmport_event_flags |=
18547 					    SATA_EVNT_DEVICE_DETACHED;
18548 					pmportinfo->pmport_link_lost_time = 0;
18549 					SATADBG2(SATA_DBG_EVENTS,
18550 					    sata_hba_inst,
18551 					    "Triggering port %d:%d "
18552 					    "device detached event",
18553 					    saddr->cport, saddr->pmport);
18554 				} else {
18555 					/* keep link lost event */
18556 					pmportinfo->pmport_event_flags |=
18557 					    SATA_EVNT_LINK_LOST;
18558 				}
18559 			}
18560 		}
18561 		/*
18562 		 * We could change port state to disable/delay access to
18563 		 * the attached device until the link is recovered.
18564 		 */
18565 	}
18566 done:
18567 	event_flags = pmportinfo->pmport_event_flags;
18568 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18569 	    saddr->pmport));
18570 	if (event_flags != 0) {
18571 		mutex_enter(&sata_hba_inst->satahba_mutex);
18572 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18573 		mutex_exit(&sata_hba_inst->satahba_mutex);
18574 		mutex_enter(&sata_mutex);
18575 		sata_event_pending |= SATA_EVNT_MAIN;
18576 		mutex_exit(&sata_mutex);
18577 	}
18578 }
18579 
18580 /*
18581  * Device Detached Event processing.
18582  * Port is probed to find if a device is really gone. If so,
18583  * the device info structure is detached from the SATA port info structure
18584  * and released.
18585  * Port status is updated.
18586  *
18587  * NOTE: Port multiplier ports events are handled by
18588  * sata_process_pmdevice_detached()
18589  */
18590 static void
18591 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
18592     sata_address_t *saddr)
18593 {
18594 	sata_cport_info_t *cportinfo;
18595 	sata_pmport_info_t *pmportinfo;
18596 	sata_drive_info_t *sdevinfo;
18597 	sata_device_t sata_device;
18598 	sata_address_t pmport_addr;
18599 	char name[16];
18600 	uint8_t cport = saddr->cport;
18601 	int npmport;
18602 	int rval;
18603 
18604 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18605 	    "Processing port %d device detached", saddr->cport);
18606 
18607 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18608 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18609 	/* Clear event flag */
18610 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18611 
18612 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18613 	if ((cportinfo->cport_state &
18614 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18615 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18616 		    cport_mutex);
18617 		return;
18618 	}
18619 	/* For sanity, re-probe the port */
18620 	sata_device.satadev_rev = SATA_DEVICE_REV;
18621 	sata_device.satadev_addr = *saddr;
18622 
18623 	/*
18624 	 * We have to exit mutex, because the HBA probe port function may
18625 	 * block on its own mutex.
18626 	 */
18627 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18628 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18629 	    (SATA_DIP(sata_hba_inst), &sata_device);
18630 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18631 	sata_update_port_info(sata_hba_inst, &sata_device);
18632 	if (rval != SATA_SUCCESS) {
18633 		/* Something went wrong? Fail the port */
18634 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18635 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18636 		    cport_mutex);
18637 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18638 		    "SATA port %d probing failed",
18639 		    saddr->cport));
18640 		/*
18641 		 * We may want to release device info structure, but
18642 		 * it is not necessary.
18643 		 */
18644 		return;
18645 	} else {
18646 		/* port probed successfully */
18647 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18648 	}
18649 	/*
18650 	 * Check if a device is still attached. For sanity, check also
18651 	 * link status - if no link, there is no device.
18652 	 */
18653 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18654 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18655 	    SATA_DTYPE_NONE) {
18656 		/*
18657 		 * Device is still attached - ignore detach event.
18658 		 */
18659 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18660 		    cport_mutex);
18661 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18662 		    "Ignoring detach - device still attached to port %d",
18663 		    sata_device.satadev_addr.cport);
18664 		return;
18665 	}
18666 	/*
18667 	 * We need to detach and release device info structure here
18668 	 */
18669 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18670 		/*
18671 		 * A port-multiplier is removed.
18672 		 *
18673 		 * Calling sata_process_pmdevice_detached() does not work
18674 		 * here. The port multiplier is gone, so we cannot probe
18675 		 * sub-port any more and all pmult-related data structure must
18676 		 * be de-allocated immediately. Following structure of every
18677 		 * implemented sub-port behind the pmult are required to
18678 		 * released.
18679 		 *
18680 		 *   - attachment point
18681 		 *   - target node
18682 		 *   - sata_drive_info
18683 		 *   - sata_pmport_info
18684 		 */
18685 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
18686 		    cport); npmport ++) {
18687 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
18688 			    sata_hba_inst,
18689 			    "Detaching target node at port %d:%d",
18690 			    cport, npmport);
18691 
18692 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18693 
18694 			/* Remove attachment point. */
18695 			name[0] = '\0';
18696 			(void) sprintf(name, "%d.%d", cport, npmport);
18697 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
18698 			sata_log(sata_hba_inst, CE_NOTE,
18699 			    "Remove attachment point of port %d:%d",
18700 			    cport, npmport);
18701 
18702 			/* Remove target node */
18703 			pmport_addr.cport = cport;
18704 			pmport_addr.pmport = (uint8_t)npmport;
18705 			pmport_addr.qual = SATA_ADDR_PMPORT;
18706 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
18707 
18708 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18709 
18710 			/* Release sata_pmport_info & sata_drive_info. */
18711 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18712 			    cport, npmport);
18713 			ASSERT(pmportinfo != NULL);
18714 
18715 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18716 			if (sdevinfo != NULL) {
18717 				(void) kmem_free((void *) sdevinfo,
18718 				    sizeof (sata_drive_info_t));
18719 			}
18720 
18721 			/* Release sata_pmport_info at last */
18722 			(void) kmem_free((void *) pmportinfo,
18723 			    sizeof (sata_pmport_info_t));
18724 		}
18725 
18726 		/* Finally, release sata_pmult_info */
18727 		(void) kmem_free((void *)
18728 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
18729 		    sizeof (sata_pmult_info_t));
18730 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
18731 
18732 		sata_log(sata_hba_inst, CE_WARN,
18733 		    "SATA port-multiplier detached at port %d", cport);
18734 
18735 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18736 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18737 		    saddr->cport)->cport_mutex);
18738 	} else {
18739 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18740 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18741 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18742 			(void) kmem_free((void *)sdevinfo,
18743 			    sizeof (sata_drive_info_t));
18744 		}
18745 		sata_log(sata_hba_inst, CE_WARN,
18746 		    "SATA device detached at port %d", cport);
18747 
18748 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18749 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18750 		    saddr->cport)->cport_mutex);
18751 
18752 		/*
18753 		 * Try to offline a device and remove target node
18754 		 * if it still exists
18755 		 */
18756 		sata_remove_target_node(sata_hba_inst, saddr);
18757 	}
18758 
18759 
18760 	/*
18761 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18762 	 * with the hint: SE_HINT_REMOVE
18763 	 */
18764 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18765 }
18766 
18767 /*
18768  * Port Multiplier Port Device Deattached Event processing.
18769  *
18770  * NOTE: No Mutex should be hold.
18771  */
18772 static void
18773 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
18774     sata_address_t *saddr)
18775 {
18776 	sata_pmport_info_t *pmportinfo;
18777 	sata_drive_info_t *sdevinfo;
18778 	sata_device_t sata_device;
18779 	int rval;
18780 	uint8_t cport, pmport;
18781 
18782 	cport = saddr->cport;
18783 	pmport = saddr->pmport;
18784 
18785 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18786 	    "Processing port %d:%d device detached",
18787 	    cport, pmport);
18788 
18789 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18790 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18791 
18792 	/* Clear event flag */
18793 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18794 
18795 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18796 	if ((pmportinfo->pmport_state &
18797 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18798 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18799 		return;
18800 	}
18801 	/* For sanity, re-probe the port */
18802 	sata_device.satadev_rev = SATA_DEVICE_REV;
18803 	sata_device.satadev_addr = *saddr;
18804 
18805 	/*
18806 	 * We have to exit mutex, because the HBA probe port function may
18807 	 * block on its own mutex.
18808 	 */
18809 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18810 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18811 	    (SATA_DIP(sata_hba_inst), &sata_device);
18812 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18813 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18814 	if (rval != SATA_SUCCESS) {
18815 		/* Something went wrong? Fail the port */
18816 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18817 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18818 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18819 		    "SATA port %d:%d probing failed",
18820 		    saddr->pmport));
18821 		/*
18822 		 * We may want to release device info structure, but
18823 		 * it is not necessary.
18824 		 */
18825 		return;
18826 	} else {
18827 		/* port probed successfully */
18828 		pmportinfo->pmport_state |=
18829 		    SATA_STATE_PROBED | SATA_STATE_READY;
18830 	}
18831 	/*
18832 	 * Check if a device is still attached. For sanity, check also
18833 	 * link status - if no link, there is no device.
18834 	 */
18835 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18836 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18837 	    SATA_DTYPE_NONE) {
18838 		/*
18839 		 * Device is still attached - ignore detach event.
18840 		 */
18841 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18842 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18843 		    "Ignoring detach - device still attached to port %d",
18844 		    sata_device.satadev_addr.pmport);
18845 		return;
18846 	}
18847 	/*
18848 	 * We need to detach and release device info structure here
18849 	 */
18850 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18851 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18852 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
18853 		(void) kmem_free((void *)sdevinfo,
18854 		    sizeof (sata_drive_info_t));
18855 	}
18856 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
18857 	/*
18858 	 * Device cannot be reached anymore, even if the target node may be
18859 	 * still present.
18860 	 */
18861 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18862 
18863 	/*
18864 	 * Try to offline a device and remove target node if it still exists
18865 	 */
18866 	sata_remove_target_node(sata_hba_inst, saddr);
18867 
18868 	/*
18869 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18870 	 * with the hint: SE_HINT_REMOVE
18871 	 */
18872 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18873 }
18874 
18875 
18876 /*
18877  * Device Attached Event processing.
18878  * Port state is checked to verify that a device is really attached. If so,
18879  * the device info structure is created and attached to the SATA port info
18880  * structure.
18881  *
18882  * If attached device cannot be identified or set-up, the retry for the
18883  * attach processing is set-up. Subsequent daemon run would try again to
18884  * identify the device, until the time limit is reached
18885  * (SATA_DEV_IDENTIFY_TIMEOUT).
18886  *
18887  * This function cannot be called in interrupt context (it may sleep).
18888  *
18889  * NOTE: Port multiplier ports events are handled by
18890  * sata_process_pmdevice_attached()
18891  */
18892 static void
18893 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
18894     sata_address_t *saddr)
18895 {
18896 	sata_cport_info_t *cportinfo = NULL;
18897 	sata_drive_info_t *sdevinfo = NULL;
18898 	sata_pmult_info_t *pmultinfo = NULL;
18899 	sata_pmport_info_t *pmportinfo = NULL;
18900 	sata_device_t sata_device;
18901 	dev_info_t *tdip;
18902 	uint32_t event_flags = 0, pmult_event_flags = 0;
18903 	int rval;
18904 	int npmport;
18905 
18906 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18907 	    "Processing port %d device attached", saddr->cport);
18908 
18909 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18910 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18911 
18912 	/* Clear attach event flag first */
18913 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
18914 
18915 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
18916 	if ((cportinfo->cport_state &
18917 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18918 		cportinfo->cport_dev_attach_time = 0;
18919 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18920 		    cport_mutex);
18921 		return;
18922 	}
18923 
18924 	/*
18925 	 * If the sata_drive_info structure is found attached to the port info,
18926 	 * despite the fact the device was removed and now it is re-attached,
18927 	 * the old drive info structure was not removed.
18928 	 * Arbitrarily release device info structure.
18929 	 */
18930 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18931 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18932 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18933 		(void) kmem_free((void *)sdevinfo,
18934 		    sizeof (sata_drive_info_t));
18935 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18936 		    "Arbitrarily detaching old device info.", NULL);
18937 	}
18938 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18939 
18940 	/* For sanity, re-probe the port */
18941 	sata_device.satadev_rev = SATA_DEVICE_REV;
18942 	sata_device.satadev_addr = *saddr;
18943 
18944 	/*
18945 	 * We have to exit mutex, because the HBA probe port function may
18946 	 * block on its own mutex.
18947 	 */
18948 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18949 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18950 	    (SATA_DIP(sata_hba_inst), &sata_device);
18951 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18952 	sata_update_port_info(sata_hba_inst, &sata_device);
18953 	if (rval != SATA_SUCCESS) {
18954 		/* Something went wrong? Fail the port */
18955 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18956 		cportinfo->cport_dev_attach_time = 0;
18957 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18958 		    cport_mutex);
18959 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18960 		    "SATA port %d probing failed",
18961 		    saddr->cport));
18962 		return;
18963 	} else {
18964 		/* port probed successfully */
18965 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18966 	}
18967 	/*
18968 	 * Check if a device is still attached. For sanity, check also
18969 	 * link status - if no link, there is no device.
18970 	 */
18971 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
18972 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
18973 	    SATA_DTYPE_NONE) {
18974 		/*
18975 		 * No device - ignore attach event.
18976 		 */
18977 		cportinfo->cport_dev_attach_time = 0;
18978 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18979 		    cport_mutex);
18980 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18981 		    "Ignoring attach - no device connected to port %d",
18982 		    sata_device.satadev_addr.cport);
18983 		return;
18984 	}
18985 
18986 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18987 	/*
18988 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18989 	 * with the hint: SE_HINT_INSERT
18990 	 */
18991 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
18992 
18993 	/*
18994 	 * Port reprobing will take care of the creation of the device
18995 	 * info structure and determination of the device type.
18996 	 */
18997 	sata_device.satadev_addr = *saddr;
18998 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
18999 	    SATA_DEV_IDENTIFY_NORETRY);
19000 
19001 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19002 	    cport_mutex);
19003 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19004 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19005 		/* Some device is attached to the port */
19006 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19007 			/*
19008 			 * A device was not successfully attached.
19009 			 * Track retry time for device identification.
19010 			 */
19011 			if (cportinfo->cport_dev_attach_time != 0) {
19012 				clock_t cur_time = ddi_get_lbolt();
19013 				/*
19014 				 * If the retry time limit was not exceeded,
19015 				 * reinstate attach event.
19016 				 */
19017 				if ((cur_time -
19018 				    cportinfo->cport_dev_attach_time) <
19019 				    drv_usectohz(
19020 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19021 					/* OK, restore attach event */
19022 					cportinfo->cport_event_flags |=
19023 					    SATA_EVNT_DEVICE_ATTACHED;
19024 				} else {
19025 					/* Timeout - cannot identify device */
19026 					cportinfo->cport_dev_attach_time = 0;
19027 					sata_log(sata_hba_inst,
19028 					    CE_WARN,
19029 					    "Could not identify SATA device "
19030 					    "at port %d",
19031 					    saddr->cport);
19032 				}
19033 			} else {
19034 				/*
19035 				 * Start tracking time for device
19036 				 * identification.
19037 				 * Save current time (lbolt value).
19038 				 */
19039 				cportinfo->cport_dev_attach_time =
19040 				    ddi_get_lbolt();
19041 				/* Restore attach event */
19042 				cportinfo->cport_event_flags |=
19043 				    SATA_EVNT_DEVICE_ATTACHED;
19044 			}
19045 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19046 			cportinfo->cport_dev_attach_time = 0;
19047 			sata_log(sata_hba_inst, CE_NOTE,
19048 			    "SATA port-multiplier detected at port %d",
19049 			    saddr->cport);
19050 
19051 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19052 				/* Log the info of new port multiplier */
19053 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19054 				    saddr->cport)->cport_mutex);
19055 				sata_show_pmult_info(sata_hba_inst,
19056 				    &sata_device);
19057 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19058 				    saddr->cport)->cport_mutex);
19059 			}
19060 
19061 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19062 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19063 			for (npmport = 0; npmport <
19064 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19065 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19066 				    saddr->cport, npmport);
19067 				ASSERT(pmportinfo != NULL);
19068 
19069 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19070 				    saddr->cport)->cport_mutex);
19071 				mutex_enter(&pmportinfo->pmport_mutex);
19072 				/* Marked all pmports with link events. */
19073 				pmportinfo->pmport_event_flags =
19074 				    SATA_EVNT_LINK_ESTABLISHED;
19075 				pmult_event_flags |=
19076 				    pmportinfo->pmport_event_flags;
19077 				mutex_exit(&pmportinfo->pmport_mutex);
19078 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19079 				    saddr->cport)->cport_mutex);
19080 			}
19081 			/* Auto-online is not available for PMult now. */
19082 
19083 		} else {
19084 			/*
19085 			 * If device was successfully attached, the subsequent
19086 			 * action depends on a state of the
19087 			 * sata_auto_online variable. If it is set to zero.
19088 			 * an explicit 'configure' command will be needed to
19089 			 * configure it. If its value is non-zero, we will
19090 			 * attempt to online (configure) the device.
19091 			 * First, log the message indicating that a device
19092 			 * was attached.
19093 			 */
19094 			cportinfo->cport_dev_attach_time = 0;
19095 			sata_log(sata_hba_inst, CE_WARN,
19096 			    "SATA device detected at port %d", saddr->cport);
19097 
19098 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19099 				sata_drive_info_t new_sdinfo;
19100 
19101 				/* Log device info data */
19102 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
19103 				    cportinfo));
19104 				sata_show_drive_info(sata_hba_inst,
19105 				    &new_sdinfo);
19106 			}
19107 
19108 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19109 			    saddr->cport)->cport_mutex);
19110 
19111 			/*
19112 			 * Make sure that there is no target node for that
19113 			 * device. If so, release it. It should not happen,
19114 			 * unless we had problem removing the node when
19115 			 * device was detached.
19116 			 */
19117 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19118 			    saddr->cport, saddr->pmport);
19119 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19120 			    saddr->cport)->cport_mutex);
19121 			if (tdip != NULL) {
19122 
19123 #ifdef SATA_DEBUG
19124 				if ((cportinfo->cport_event_flags &
19125 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19126 					sata_log(sata_hba_inst, CE_WARN,
19127 					    "sata_process_device_attached: "
19128 					    "old device target node exists!");
19129 #endif
19130 				/*
19131 				 * target node exists - try to unconfigure
19132 				 * device and remove the node.
19133 				 */
19134 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19135 				    saddr->cport)->cport_mutex);
19136 				rval = ndi_devi_offline(tdip,
19137 				    NDI_DEVI_REMOVE);
19138 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19139 				    saddr->cport)->cport_mutex);
19140 
19141 				if (rval == NDI_SUCCESS) {
19142 					cportinfo->cport_event_flags &=
19143 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19144 					cportinfo->cport_tgtnode_clean = B_TRUE;
19145 				} else {
19146 					/*
19147 					 * PROBLEM - the target node remained
19148 					 * and it belongs to a previously
19149 					 * attached device.
19150 					 * This happens when the file was open
19151 					 * or the node was waiting for
19152 					 * resources at the time the
19153 					 * associated device was removed.
19154 					 * Instruct event daemon to retry the
19155 					 * cleanup later.
19156 					 */
19157 					sata_log(sata_hba_inst,
19158 					    CE_WARN,
19159 					    "Application(s) accessing "
19160 					    "previously attached SATA "
19161 					    "device have to release "
19162 					    "it before newly inserted "
19163 					    "device can be made accessible.",
19164 					    saddr->cport);
19165 					cportinfo->cport_event_flags |=
19166 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19167 					cportinfo->cport_tgtnode_clean =
19168 					    B_FALSE;
19169 				}
19170 			}
19171 			if (sata_auto_online != 0) {
19172 				cportinfo->cport_event_flags |=
19173 				    SATA_EVNT_AUTOONLINE_DEVICE;
19174 			}
19175 
19176 		}
19177 	} else {
19178 		cportinfo->cport_dev_attach_time = 0;
19179 	}
19180 
19181 	event_flags = cportinfo->cport_event_flags;
19182 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19183 	if (event_flags != 0 || pmult_event_flags != 0) {
19184 		mutex_enter(&sata_hba_inst->satahba_mutex);
19185 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19186 		mutex_exit(&sata_hba_inst->satahba_mutex);
19187 		mutex_enter(&sata_mutex);
19188 		sata_event_pending |= SATA_EVNT_MAIN;
19189 		mutex_exit(&sata_mutex);
19190 	}
19191 }
19192 
19193 /*
19194  * Port Multiplier Port Device Attached Event processing.
19195  *
19196  * NOTE: No Mutex should be hold.
19197  */
19198 static void
19199 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
19200     sata_address_t *saddr)
19201 {
19202 	sata_pmport_info_t *pmportinfo;
19203 	sata_drive_info_t *sdinfo;
19204 	sata_device_t sata_device;
19205 	dev_info_t *tdip;
19206 	uint32_t event_flags;
19207 	uint8_t cport = saddr->cport;
19208 	uint8_t pmport = saddr->pmport;
19209 	int rval;
19210 
19211 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19212 	    "Processing port %d:%d device attached", cport, pmport);
19213 
19214 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19215 
19216 	mutex_enter(&pmportinfo->pmport_mutex);
19217 
19218 	/* Clear attach event flag first */
19219 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19220 
19221 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19222 	if ((pmportinfo->pmport_state &
19223 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19224 		pmportinfo->pmport_dev_attach_time = 0;
19225 		mutex_exit(&pmportinfo->pmport_mutex);
19226 		return;
19227 	}
19228 
19229 	/*
19230 	 * If the sata_drive_info structure is found attached to the port info,
19231 	 * despite the fact the device was removed and now it is re-attached,
19232 	 * the old drive info structure was not removed.
19233 	 * Arbitrarily release device info structure.
19234 	 */
19235 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19236 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19237 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19238 		(void) kmem_free((void *)sdinfo,
19239 		    sizeof (sata_drive_info_t));
19240 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19241 		    "Arbitrarily detaching old device info.", NULL);
19242 	}
19243 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19244 
19245 	/* For sanity, re-probe the port */
19246 	sata_device.satadev_rev = SATA_DEVICE_REV;
19247 	sata_device.satadev_addr = *saddr;
19248 
19249 	/*
19250 	 * We have to exit mutex, because the HBA probe port function may
19251 	 * block on its own mutex.
19252 	 */
19253 	mutex_exit(&pmportinfo->pmport_mutex);
19254 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19255 	    (SATA_DIP(sata_hba_inst), &sata_device);
19256 	mutex_enter(&pmportinfo->pmport_mutex);
19257 
19258 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19259 	if (rval != SATA_SUCCESS) {
19260 		/* Something went wrong? Fail the port */
19261 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19262 		pmportinfo->pmport_dev_attach_time = 0;
19263 		mutex_exit(&pmportinfo->pmport_mutex);
19264 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19265 		    "SATA port %d:%d probing failed", cport, pmport));
19266 		return;
19267 	} else {
19268 		/* pmport probed successfully */
19269 		pmportinfo->pmport_state |=
19270 		    SATA_STATE_PROBED | SATA_STATE_READY;
19271 	}
19272 	/*
19273 	 * Check if a device is still attached. For sanity, check also
19274 	 * link status - if no link, there is no device.
19275 	 */
19276 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19277 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19278 	    SATA_DTYPE_NONE) {
19279 		/*
19280 		 * No device - ignore attach event.
19281 		 */
19282 		pmportinfo->pmport_dev_attach_time = 0;
19283 		mutex_exit(&pmportinfo->pmport_mutex);
19284 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19285 		    "Ignoring attach - no device connected to port %d:%d",
19286 		    cport, pmport);
19287 		return;
19288 	}
19289 
19290 	mutex_exit(&pmportinfo->pmport_mutex);
19291 	/*
19292 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19293 	 * with the hint: SE_HINT_INSERT
19294 	 */
19295 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19296 
19297 	/*
19298 	 * Port reprobing will take care of the creation of the device
19299 	 * info structure and determination of the device type.
19300 	 */
19301 	sata_device.satadev_addr = *saddr;
19302 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19303 	    SATA_DEV_IDENTIFY_NORETRY);
19304 
19305 	mutex_enter(&pmportinfo->pmport_mutex);
19306 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
19307 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
19308 		/* Some device is attached to the port */
19309 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
19310 			/*
19311 			 * A device was not successfully attached.
19312 			 * Track retry time for device identification.
19313 			 */
19314 			if (pmportinfo->pmport_dev_attach_time != 0) {
19315 				clock_t cur_time = ddi_get_lbolt();
19316 				/*
19317 				 * If the retry time limit was not exceeded,
19318 				 * reinstate attach event.
19319 				 */
19320 				if ((cur_time -
19321 				    pmportinfo->pmport_dev_attach_time) <
19322 				    drv_usectohz(
19323 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19324 					/* OK, restore attach event */
19325 					pmportinfo->pmport_event_flags |=
19326 					    SATA_EVNT_DEVICE_ATTACHED;
19327 				} else {
19328 					/* Timeout - cannot identify device */
19329 					pmportinfo->pmport_dev_attach_time = 0;
19330 					sata_log(sata_hba_inst, CE_WARN,
19331 					    "Could not identify SATA device "
19332 					    "at port %d:%d",
19333 					    cport, pmport);
19334 				}
19335 			} else {
19336 				/*
19337 				 * Start tracking time for device
19338 				 * identification.
19339 				 * Save current time (lbolt value).
19340 				 */
19341 				pmportinfo->pmport_dev_attach_time =
19342 				    ddi_get_lbolt();
19343 				/* Restore attach event */
19344 				pmportinfo->pmport_event_flags |=
19345 				    SATA_EVNT_DEVICE_ATTACHED;
19346 			}
19347 		} else {
19348 			/*
19349 			 * If device was successfully attached, the subsequent
19350 			 * action depends on a state of the
19351 			 * sata_auto_online variable. If it is set to zero.
19352 			 * an explicit 'configure' command will be needed to
19353 			 * configure it. If its value is non-zero, we will
19354 			 * attempt to online (configure) the device.
19355 			 * First, log the message indicating that a device
19356 			 * was attached.
19357 			 */
19358 			pmportinfo->pmport_dev_attach_time = 0;
19359 			sata_log(sata_hba_inst, CE_WARN,
19360 			    "SATA device detected at port %d:%d",
19361 			    cport, pmport);
19362 
19363 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19364 				sata_drive_info_t new_sdinfo;
19365 
19366 				/* Log device info data */
19367 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
19368 				    pmportinfo));
19369 				sata_show_drive_info(sata_hba_inst,
19370 				    &new_sdinfo);
19371 			}
19372 
19373 			mutex_exit(&pmportinfo->pmport_mutex);
19374 
19375 			/*
19376 			 * Make sure that there is no target node for that
19377 			 * device. If so, release it. It should not happen,
19378 			 * unless we had problem removing the node when
19379 			 * device was detached.
19380 			 */
19381 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19382 			    saddr->cport, saddr->pmport);
19383 			mutex_enter(&pmportinfo->pmport_mutex);
19384 			if (tdip != NULL) {
19385 
19386 #ifdef SATA_DEBUG
19387 				if ((pmportinfo->pmport_event_flags &
19388 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19389 					sata_log(sata_hba_inst, CE_WARN,
19390 					    "sata_process_device_attached: "
19391 					    "old device target node exists!");
19392 #endif
19393 				/*
19394 				 * target node exists - try to unconfigure
19395 				 * device and remove the node.
19396 				 */
19397 				mutex_exit(&pmportinfo->pmport_mutex);
19398 				rval = ndi_devi_offline(tdip,
19399 				    NDI_DEVI_REMOVE);
19400 				mutex_enter(&pmportinfo->pmport_mutex);
19401 
19402 				if (rval == NDI_SUCCESS) {
19403 					pmportinfo->pmport_event_flags &=
19404 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19405 					pmportinfo->pmport_tgtnode_clean =
19406 					    B_TRUE;
19407 				} else {
19408 					/*
19409 					 * PROBLEM - the target node remained
19410 					 * and it belongs to a previously
19411 					 * attached device.
19412 					 * This happens when the file was open
19413 					 * or the node was waiting for
19414 					 * resources at the time the
19415 					 * associated device was removed.
19416 					 * Instruct event daemon to retry the
19417 					 * cleanup later.
19418 					 */
19419 					sata_log(sata_hba_inst,
19420 					    CE_WARN,
19421 					    "Application(s) accessing "
19422 					    "previously attached SATA "
19423 					    "device have to release "
19424 					    "it before newly inserted "
19425 					    "device can be made accessible."
19426 					    "at port %d:%d",
19427 					    cport, pmport);
19428 					pmportinfo->pmport_event_flags |=
19429 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19430 					pmportinfo->pmport_tgtnode_clean =
19431 					    B_FALSE;
19432 				}
19433 			}
19434 			if (sata_auto_online != 0) {
19435 				pmportinfo->pmport_event_flags |=
19436 				    SATA_EVNT_AUTOONLINE_DEVICE;
19437 			}
19438 
19439 		}
19440 	} else {
19441 		pmportinfo->pmport_dev_attach_time = 0;
19442 	}
19443 
19444 	event_flags = pmportinfo->pmport_event_flags;
19445 	mutex_exit(&pmportinfo->pmport_mutex);
19446 	if (event_flags != 0) {
19447 		mutex_enter(&sata_hba_inst->satahba_mutex);
19448 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19449 		mutex_exit(&sata_hba_inst->satahba_mutex);
19450 		mutex_enter(&sata_mutex);
19451 		sata_event_pending |= SATA_EVNT_MAIN;
19452 		mutex_exit(&sata_mutex);
19453 	}
19454 
19455 	/* clear the reset_in_progress events */
19456 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19457 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19458 			/* must clear flags on cport */
19459 			sata_pmult_info_t *pminfo =
19460 			    SATA_PMULT_INFO(sata_hba_inst,
19461 			    saddr->cport);
19462 			pminfo->pmult_event_flags |=
19463 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19464 		}
19465 	}
19466 }
19467 
19468 /*
19469  * Device Target Node Cleanup Event processing.
19470  * If the target node associated with a sata port device is in
19471  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
19472  * If the target node cannot be removed, the event flag is left intact,
19473  * so that event daemon may re-run this function later.
19474  *
19475  * This function cannot be called in interrupt context (it may sleep).
19476  *
19477  * NOTE: Processes cport events only, not port multiplier ports.
19478  */
19479 static void
19480 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19481     sata_address_t *saddr)
19482 {
19483 	sata_cport_info_t *cportinfo;
19484 	dev_info_t *tdip;
19485 
19486 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19487 	    "Processing port %d device target node cleanup", saddr->cport);
19488 
19489 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19490 
19491 	/*
19492 	 * Check if there is target node for that device and it is in the
19493 	 * DEVI_DEVICE_REMOVED state. If so, release it.
19494 	 */
19495 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19496 	    saddr->pmport);
19497 	if (tdip != NULL) {
19498 		/*
19499 		 * target node exists - check if it is target node of
19500 		 * a removed device.
19501 		 */
19502 		if (sata_check_device_removed(tdip) == B_TRUE) {
19503 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19504 			    "sata_process_target_node_cleanup: "
19505 			    "old device target node exists!", NULL);
19506 			/*
19507 			 * Unconfigure and remove the target node
19508 			 */
19509 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
19510 			    NDI_SUCCESS) {
19511 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19512 				    saddr->cport)->cport_mutex);
19513 				cportinfo->cport_event_flags &=
19514 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19515 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19516 				    saddr->cport)->cport_mutex);
19517 				return;
19518 			}
19519 			/*
19520 			 * Event daemon will retry the cleanup later.
19521 			 */
19522 			mutex_enter(&sata_hba_inst->satahba_mutex);
19523 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19524 			mutex_exit(&sata_hba_inst->satahba_mutex);
19525 			mutex_enter(&sata_mutex);
19526 			sata_event_pending |= SATA_EVNT_MAIN;
19527 			mutex_exit(&sata_mutex);
19528 		}
19529 	} else {
19530 		if (saddr->qual == SATA_ADDR_CPORT ||
19531 		    saddr->qual == SATA_ADDR_DCPORT) {
19532 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19533 			    saddr->cport)->cport_mutex);
19534 			cportinfo->cport_event_flags &=
19535 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19536 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19537 			    saddr->cport)->cport_mutex);
19538 		} else {
19539 			/* sanity check */
19540 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
19541 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
19542 			    saddr->cport) == NULL)
19543 				return;
19544 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19545 			    saddr->pmport) == NULL)
19546 				return;
19547 
19548 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19549 			    saddr->cport, saddr->pmport)->pmport_mutex);
19550 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19551 			    saddr->pmport)->pmport_event_flags &=
19552 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19553 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19554 			    saddr->cport, saddr->pmport)->pmport_mutex);
19555 		}
19556 	}
19557 }
19558 
19559 /*
19560  * Device AutoOnline Event processing.
19561  * If attached device is to be onlined, an attempt is made to online this
19562  * device, but only if there is no lingering (old) target node present.
19563  * If the device cannot be onlined, the event flag is left intact,
19564  * so that event daemon may re-run this function later.
19565  *
19566  * This function cannot be called in interrupt context (it may sleep).
19567  *
19568  * NOTE: Processes cport events only, not port multiplier ports.
19569  */
19570 static void
19571 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
19572     sata_address_t *saddr)
19573 {
19574 	sata_cport_info_t *cportinfo;
19575 	sata_drive_info_t *sdinfo;
19576 	sata_device_t sata_device;
19577 	dev_info_t *tdip;
19578 
19579 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19580 	    "Processing port %d attached device auto-onlining", saddr->cport);
19581 
19582 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19583 
19584 	/*
19585 	 * Check if device is present and recognized. If not, reset event.
19586 	 */
19587 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19588 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
19589 		/* Nothing to online */
19590 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19591 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19592 		    saddr->cport)->cport_mutex);
19593 		return;
19594 	}
19595 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19596 
19597 	/*
19598 	 * Check if there is target node for this device and if it is in the
19599 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
19600 	 * the event for later processing.
19601 	 */
19602 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19603 	    saddr->pmport);
19604 	if (tdip != NULL) {
19605 		/*
19606 		 * target node exists - check if it is target node of
19607 		 * a removed device.
19608 		 */
19609 		if (sata_check_device_removed(tdip) == B_TRUE) {
19610 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19611 			    "sata_process_device_autoonline: "
19612 			    "old device target node exists!", NULL);
19613 			/*
19614 			 * Event daemon will retry device onlining later.
19615 			 */
19616 			mutex_enter(&sata_hba_inst->satahba_mutex);
19617 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19618 			mutex_exit(&sata_hba_inst->satahba_mutex);
19619 			mutex_enter(&sata_mutex);
19620 			sata_event_pending |= SATA_EVNT_MAIN;
19621 			mutex_exit(&sata_mutex);
19622 			return;
19623 		}
19624 		/*
19625 		 * If the target node is not in the 'removed" state, assume
19626 		 * that it belongs to this device. There is nothing more to do,
19627 		 * but reset the event.
19628 		 */
19629 	} else {
19630 
19631 		/*
19632 		 * Try to online the device
19633 		 * If there is any reset-related event, remove it. We are
19634 		 * configuring the device and no state restoring is needed.
19635 		 */
19636 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19637 		    saddr->cport)->cport_mutex);
19638 		sata_device.satadev_addr = *saddr;
19639 		if (saddr->qual == SATA_ADDR_CPORT)
19640 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
19641 		else
19642 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
19643 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
19644 		if (sdinfo != NULL) {
19645 			if (sdinfo->satadrv_event_flags &
19646 			    (SATA_EVNT_DEVICE_RESET |
19647 			    SATA_EVNT_INPROC_DEVICE_RESET))
19648 				sdinfo->satadrv_event_flags = 0;
19649 			sdinfo->satadrv_event_flags |=
19650 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19651 
19652 			/* Need to create a new target node. */
19653 			cportinfo->cport_tgtnode_clean = B_TRUE;
19654 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19655 			    saddr->cport)->cport_mutex);
19656 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
19657 			    sata_hba_inst, &sata_device.satadev_addr);
19658 			if (tdip == NULL) {
19659 				/*
19660 				 * Configure (onlining) failed.
19661 				 * We will NOT retry
19662 				 */
19663 				SATA_LOG_D((sata_hba_inst, CE_WARN,
19664 				    "sata_process_device_autoonline: "
19665 				    "configuring SATA device at port %d failed",
19666 				    saddr->cport));
19667 			}
19668 		} else {
19669 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19670 			    saddr->cport)->cport_mutex);
19671 		}
19672 
19673 	}
19674 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19675 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19676 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19677 	    saddr->cport)->cport_mutex);
19678 }
19679 
19680 
19681 static void
19682 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
19683     int hint)
19684 {
19685 	char ap[MAXPATHLEN];
19686 	nvlist_t *ev_attr_list = NULL;
19687 	int err;
19688 
19689 	/* Allocate and build sysevent attribute list */
19690 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
19691 	if (err != 0) {
19692 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19693 		    "sata_gen_sysevent: "
19694 		    "cannot allocate memory for sysevent attributes\n"));
19695 		return;
19696 	}
19697 	/* Add hint attribute */
19698 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
19699 	if (err != 0) {
19700 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19701 		    "sata_gen_sysevent: "
19702 		    "failed to add DR_HINT attr for sysevent"));
19703 		nvlist_free(ev_attr_list);
19704 		return;
19705 	}
19706 	/*
19707 	 * Add AP attribute.
19708 	 * Get controller pathname and convert it into AP pathname by adding
19709 	 * a target number.
19710 	 */
19711 	(void) snprintf(ap, MAXPATHLEN, "/devices");
19712 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
19713 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
19714 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
19715 
19716 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
19717 	if (err != 0) {
19718 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19719 		    "sata_gen_sysevent: "
19720 		    "failed to add DR_AP_ID attr for sysevent"));
19721 		nvlist_free(ev_attr_list);
19722 		return;
19723 	}
19724 
19725 	/* Generate/log sysevent */
19726 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
19727 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
19728 	if (err != DDI_SUCCESS) {
19729 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19730 		    "sata_gen_sysevent: "
19731 		    "cannot log sysevent, err code %x\n", err));
19732 	}
19733 
19734 	nvlist_free(ev_attr_list);
19735 }
19736 
19737 
19738 
19739 
19740 /*
19741  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
19742  */
19743 static void
19744 sata_set_device_removed(dev_info_t *tdip)
19745 {
19746 	int circ;
19747 
19748 	ASSERT(tdip != NULL);
19749 
19750 	ndi_devi_enter(tdip, &circ);
19751 	mutex_enter(&DEVI(tdip)->devi_lock);
19752 	DEVI_SET_DEVICE_REMOVED(tdip);
19753 	mutex_exit(&DEVI(tdip)->devi_lock);
19754 	ndi_devi_exit(tdip, circ);
19755 }
19756 
19757 
19758 /*
19759  * Set internal event instructing event daemon to try
19760  * to perform the target node cleanup.
19761  */
19762 static void
19763 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19764     sata_address_t *saddr)
19765 {
19766 	if (saddr->qual == SATA_ADDR_CPORT ||
19767 	    saddr->qual == SATA_ADDR_DCPORT) {
19768 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19769 		    saddr->cport)->cport_mutex);
19770 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
19771 		    SATA_EVNT_TARGET_NODE_CLEANUP;
19772 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19773 		    cport_tgtnode_clean = B_FALSE;
19774 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19775 		    saddr->cport)->cport_mutex);
19776 	} else {
19777 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19778 		    saddr->cport, saddr->pmport)->pmport_mutex);
19779 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
19780 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
19781 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
19782 		    pmport_tgtnode_clean = B_FALSE;
19783 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19784 		    saddr->cport, saddr->pmport)->pmport_mutex);
19785 	}
19786 	mutex_enter(&sata_hba_inst->satahba_mutex);
19787 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19788 	mutex_exit(&sata_hba_inst->satahba_mutex);
19789 	mutex_enter(&sata_mutex);
19790 	sata_event_pending |= SATA_EVNT_MAIN;
19791 	mutex_exit(&sata_mutex);
19792 }
19793 
19794 
19795 /*
19796  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
19797  * i.e. check if the target node state indicates that it belongs to a removed
19798  * device.
19799  *
19800  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
19801  * B_FALSE otherwise.
19802  */
19803 static boolean_t
19804 sata_check_device_removed(dev_info_t *tdip)
19805 {
19806 	ASSERT(tdip != NULL);
19807 
19808 	if (DEVI_IS_DEVICE_REMOVED(tdip))
19809 		return (B_TRUE);
19810 	else
19811 		return (B_FALSE);
19812 }
19813 
19814 /* ************************ FAULT INJECTTION **************************** */
19815 
19816 #ifdef SATA_INJECT_FAULTS
19817 
19818 static	uint32_t sata_fault_count = 0;
19819 static	uint32_t sata_fault_suspend_count = 0;
19820 
19821 /*
19822  * Inject sata pkt fault
19823  * It modifies returned values of the sata packet.
19824  * It returns immediately if:
19825  * pkt fault injection is not enabled (via sata_inject_fault,
19826  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
19827  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
19828  * pkt is not directed to specified fault controller/device
19829  * (sata_fault_ctrl_dev and sata_fault_device).
19830  * If fault controller is not specified, fault injection applies to all
19831  * controllers and devices.
19832  *
19833  * First argument is the pointer to the executed sata packet.
19834  * Second argument is a pointer to a value returned by the HBA tran_start
19835  * function.
19836  * Third argument specifies injected error. Injected sata packet faults
19837  * are the satapkt_reason values.
19838  * SATA_PKT_BUSY		-1	Not completed, busy
19839  * SATA_PKT_DEV_ERROR		1	Device reported error
19840  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
19841  * SATA_PKT_PORT_ERROR		3	Not completed, port error
19842  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
19843  * SATA_PKT_ABORTED		5	Aborted by request
19844  * SATA_PKT_TIMEOUT		6	Operation timeut
19845  * SATA_PKT_RESET		7	Aborted by reset request
19846  *
19847  * Additional global variables affecting the execution:
19848  *
19849  * sata_inject_fault_count variable specifies number of times in row the
19850  * error is injected. Value of -1 specifies permanent fault, ie. every time
19851  * the fault injection point is reached, the fault is injected and a pause
19852  * between fault injection specified by sata_inject_fault_pause_count is
19853  * ignored). Fault injection routine decrements sata_inject_fault_count
19854  * (if greater than zero) until it reaches 0. No fault is injected when
19855  * sata_inject_fault_count is 0 (zero).
19856  *
19857  * sata_inject_fault_pause_count variable specifies number of times a fault
19858  * injection is bypassed (pause between fault injections).
19859  * If set to 0, a fault is injected only a number of times specified by
19860  * sata_inject_fault_count.
19861  *
19862  * The fault counts are static, so for periodic errors they have to be manually
19863  * reset to start repetition sequence from scratch.
19864  * If the original value returned by the HBA tran_start function is not
19865  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
19866  * is injected (to avoid masking real problems);
19867  *
19868  * NOTE: In its current incarnation, this function should be invoked only for
19869  * commands executed in SYNCHRONOUS mode.
19870  */
19871 
19872 
19873 static void
19874 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
19875 {
19876 
19877 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
19878 		return;
19879 
19880 	if (sata_inject_fault_count == 0)
19881 		return;
19882 
19883 	if (fault == 0)
19884 		return;
19885 
19886 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
19887 		return;
19888 
19889 	if (sata_fault_ctrl != NULL) {
19890 		sata_pkt_txlate_t *spx =
19891 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
19892 
19893 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
19894 		    spx->txlt_sata_hba_inst->satahba_dip)
19895 			return;
19896 
19897 		if (sata_fault_device.satadev_addr.cport !=
19898 		    spkt->satapkt_device.satadev_addr.cport ||
19899 		    sata_fault_device.satadev_addr.pmport !=
19900 		    spkt->satapkt_device.satadev_addr.pmport ||
19901 		    sata_fault_device.satadev_addr.qual !=
19902 		    spkt->satapkt_device.satadev_addr.qual)
19903 			return;
19904 	}
19905 
19906 	/* Modify pkt return parameters */
19907 	if (*rval != SATA_TRAN_ACCEPTED ||
19908 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
19909 		sata_fault_count = 0;
19910 		sata_fault_suspend_count = 0;
19911 		return;
19912 	}
19913 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
19914 		/* Pause in the injection */
19915 		sata_fault_suspend_count -= 1;
19916 		return;
19917 	}
19918 
19919 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
19920 		/*
19921 		 * Init inject fault cycle. If fault count is set to -1,
19922 		 * it is a permanent fault.
19923 		 */
19924 		if (sata_inject_fault_count != -1) {
19925 			sata_fault_count = sata_inject_fault_count;
19926 			sata_fault_suspend_count =
19927 			    sata_inject_fault_pause_count;
19928 			if (sata_fault_suspend_count == 0)
19929 				sata_inject_fault_count = 0;
19930 		}
19931 	}
19932 
19933 	if (sata_fault_count != 0)
19934 		sata_fault_count -= 1;
19935 
19936 	switch (fault) {
19937 	case SATA_PKT_BUSY:
19938 		*rval = SATA_TRAN_BUSY;
19939 		spkt->satapkt_reason = SATA_PKT_BUSY;
19940 		break;
19941 
19942 	case SATA_PKT_QUEUE_FULL:
19943 		*rval = SATA_TRAN_QUEUE_FULL;
19944 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
19945 		break;
19946 
19947 	case SATA_PKT_CMD_UNSUPPORTED:
19948 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
19949 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
19950 		break;
19951 
19952 	case SATA_PKT_PORT_ERROR:
19953 		/* This is "rejected" command */
19954 		*rval = SATA_TRAN_PORT_ERROR;
19955 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
19956 		/* Additional error setup could be done here - port state */
19957 		break;
19958 
19959 	case SATA_PKT_DEV_ERROR:
19960 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
19961 		/*
19962 		 * Additional error setup could be done here
19963 		 */
19964 		break;
19965 
19966 	case SATA_PKT_ABORTED:
19967 		spkt->satapkt_reason = SATA_PKT_ABORTED;
19968 		break;
19969 
19970 	case SATA_PKT_TIMEOUT:
19971 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
19972 		/* Additional error setup could be done here */
19973 		break;
19974 
19975 	case SATA_PKT_RESET:
19976 		spkt->satapkt_reason = SATA_PKT_RESET;
19977 		/*
19978 		 * Additional error setup could be done here - device reset
19979 		 */
19980 		break;
19981 
19982 	default:
19983 		break;
19984 	}
19985 }
19986 
19987 #endif
19988 
19989 /*
19990  * SATA Trace Ring Buffer
19991  * ----------------------
19992  *
19993  * Overview
19994  *
19995  * The SATA trace ring buffer is a ring buffer created and managed by
19996  * the SATA framework module that can be used by any module or driver
19997  * within the SATA framework to store debug messages.
19998  *
19999  * Ring Buffer Interfaces:
20000  *
20001  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20002  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20003  *
20004  *	Note that the sata_trace_debug() interface was created to give
20005  *	consumers the flexibilty of sending debug messages to ring buffer
20006  *	as variable arguments.  Consumers can send type va_list debug
20007  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20008  *	and sata_vtrace_debug() relationship is similar to that of
20009  *	cmn_err(9F) and vcmn_err(9F).
20010  *
20011  * Below is a diagram of the SATA trace ring buffer interfaces and
20012  * sample consumers:
20013  *
20014  * +---------------------------------+
20015  * |    o  o  SATA Framework Module  |
20016  * | o  SATA  o     +------------------+      +------------------+
20017  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20018  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20019  * | o        o     +------------------+   |  +------------------+
20020  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20021  * |                        |        |        +------------------+
20022  * |           +------------------+  |
20023  * |           |SATA Debug Message|  |
20024  * |           +------------------+  |
20025  * +---------------------------------+
20026  *
20027  * Supporting Routines:
20028  *
20029  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20030  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20031  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20032  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20033  *
20034  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20035  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20036  * /etc/system to desired size in unit of bytes.
20037  *
20038  * The individual debug message size in the ring buffer is restricted
20039  * to DMSG_BUF_SIZE.
20040  */
20041 void
20042 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20043 {
20044 	sata_trace_dmsg_t *dmsg;
20045 
20046 	if (sata_debug_rbuf == NULL) {
20047 		return;
20048 	}
20049 
20050 	/*
20051 	 * If max size of ring buffer is smaller than size
20052 	 * required for one debug message then just return
20053 	 * since we have no room for the debug message.
20054 	 */
20055 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20056 		return;
20057 	}
20058 
20059 	mutex_enter(&sata_debug_rbuf->lock);
20060 
20061 	/* alloc or reuse on ring buffer */
20062 	dmsg = sata_trace_dmsg_alloc();
20063 
20064 	if (dmsg == NULL) {
20065 		/* resource allocation failed */
20066 		mutex_exit(&sata_debug_rbuf->lock);
20067 		return;
20068 	}
20069 
20070 	dmsg->dip = dip;
20071 	gethrestime(&dmsg->timestamp);
20072 
20073 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
20074 
20075 	mutex_exit(&sata_debug_rbuf->lock);
20076 }
20077 
20078 void
20079 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
20080 {
20081 	va_list ap;
20082 
20083 	va_start(ap, fmt);
20084 	sata_vtrace_debug(dip, fmt, ap);
20085 	va_end(ap);
20086 }
20087 
20088 /*
20089  * This routine is used to manage debug messages
20090  * on ring buffer.
20091  */
20092 static sata_trace_dmsg_t *
20093 sata_trace_dmsg_alloc(void)
20094 {
20095 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
20096 
20097 	if (sata_debug_rbuf->looped == TRUE) {
20098 		sata_debug_rbuf->dmsgp = dmsg->next;
20099 		return (sata_debug_rbuf->dmsgp);
20100 	}
20101 
20102 	/*
20103 	 * If we're looping for the first time,
20104 	 * connect the ring.
20105 	 */
20106 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
20107 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
20108 		dmsg->next = sata_debug_rbuf->dmsgh;
20109 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
20110 		sata_debug_rbuf->looped = TRUE;
20111 		return (sata_debug_rbuf->dmsgp);
20112 	}
20113 
20114 	/* If we've gotten this far then memory allocation is needed */
20115 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
20116 	if (dmsg_alloc == NULL) {
20117 		sata_debug_rbuf->allocfailed++;
20118 		return (dmsg_alloc);
20119 	} else {
20120 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
20121 	}
20122 
20123 	if (sata_debug_rbuf->dmsgp != NULL) {
20124 		dmsg->next = dmsg_alloc;
20125 		sata_debug_rbuf->dmsgp = dmsg->next;
20126 		return (sata_debug_rbuf->dmsgp);
20127 	} else {
20128 		/*
20129 		 * We should only be here if we're initializing
20130 		 * the ring buffer.
20131 		 */
20132 		if (sata_debug_rbuf->dmsgh == NULL) {
20133 			sata_debug_rbuf->dmsgh = dmsg_alloc;
20134 		} else {
20135 			/* Something is wrong */
20136 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
20137 			return (NULL);
20138 		}
20139 
20140 		sata_debug_rbuf->dmsgp = dmsg_alloc;
20141 		return (sata_debug_rbuf->dmsgp);
20142 	}
20143 }
20144 
20145 
20146 /*
20147  * Free all messages on debug ring buffer.
20148  */
20149 static void
20150 sata_trace_dmsg_free(void)
20151 {
20152 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
20153 
20154 	while (dmsg != NULL) {
20155 		dmsg_next = dmsg->next;
20156 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
20157 
20158 		/*
20159 		 * If we've looped around the ring than we're done.
20160 		 */
20161 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
20162 			break;
20163 		} else {
20164 			dmsg = dmsg_next;
20165 		}
20166 	}
20167 }
20168 
20169 
20170 /*
20171  * This function can block
20172  */
20173 static void
20174 sata_trace_rbuf_alloc(void)
20175 {
20176 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
20177 
20178 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
20179 
20180 	if (dmsg_ring_size > 0) {
20181 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
20182 	}
20183 }
20184 
20185 
20186 static void
20187 sata_trace_rbuf_free(void)
20188 {
20189 	sata_trace_dmsg_free();
20190 	mutex_destroy(&sata_debug_rbuf->lock);
20191 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
20192 }
20193 
20194 /*
20195  * If SATA_DEBUG is not defined then this routine is called instead
20196  * of sata_log() via the SATA_LOG_D macro.
20197  */
20198 static void
20199 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
20200     const char *fmt, ...)
20201 {
20202 #ifndef __lock_lint
20203 	_NOTE(ARGUNUSED(level))
20204 #endif
20205 
20206 	dev_info_t *dip = NULL;
20207 	va_list ap;
20208 
20209 	if (sata_hba_inst != NULL) {
20210 		dip = SATA_DIP(sata_hba_inst);
20211 	}
20212 
20213 	va_start(ap, fmt);
20214 	sata_vtrace_debug(dip, fmt, ap);
20215 	va_end(ap);
20216 }
20217