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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
  24  * Copyright 2012 Nexenta Systems, Inc. All rights reserved.
  25  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
  26  */
  27 
  28 /*
  29  * Copyright (c) 2000 to 2010, LSI Corporation.
  30  * All rights reserved.
  31  *
  32  * Redistribution and use in source and binary forms of all code within
  33  * this file that is exclusively owned by LSI, with or without
  34  * modification, is permitted provided that, in addition to the CDDL 1.0
  35  * License requirements, the following conditions are met:
  36  *
  37  *    Neither the name of the author nor the names of its contributors may be
  38  *    used to endorse or promote products derived from this software without
  39  *    specific prior written permission.
  40  *
  41  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  42  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  43  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  44  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  45  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  46  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  47  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  48  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  49  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  50  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  51  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  52  * DAMAGE.
  53  */
  54 
  55 /*
  56  * mptsas - This is a driver based on LSI Logic's MPT2.0 interface.
  57  *
  58  */
  59 
  60 #if defined(lint) || defined(DEBUG)
  61 #define MPTSAS_DEBUG
  62 #endif
  63 
  64 /*
  65  * standard header files.
  66  */
  67 #include <sys/note.h>
  68 #include <sys/scsi/scsi.h>
  69 #include <sys/pci.h>
  70 #include <sys/file.h>
  71 #include <sys/cpuvar.h>
  72 #include <sys/policy.h>
  73 #include <sys/model.h>
  74 #include <sys/sysevent.h>
  75 #include <sys/sysevent/eventdefs.h>
  76 #include <sys/sysevent/dr.h>
  77 #include <sys/sata/sata_defs.h>
  78 #include <sys/scsi/generic/sas.h>
  79 #include <sys/scsi/impl/scsi_sas.h>
  80 
  81 #pragma pack(1)
  82 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_type.h>
  83 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2.h>
  84 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_cnfg.h>
  85 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_init.h>
  86 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_ioc.h>
  87 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_sas.h>
  88 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_tool.h>
  89 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_raid.h>
  90 #pragma pack()
  91 
  92 /*
  93  * private header files.
  94  *
  95  */
  96 #include <sys/scsi/impl/scsi_reset_notify.h>
  97 #include <sys/scsi/adapters/mpt_sas/mptsas_var.h>
  98 #include <sys/scsi/adapters/mpt_sas/mptsas_ioctl.h>
  99 #include <sys/scsi/adapters/mpt_sas/mptsas_smhba.h>
 100 
 101 #include <sys/raidioctl.h>
 102 
 103 #include <sys/fs/dv_node.h>       /* devfs_clean */
 104 
 105 /*
 106  * FMA header files
 107  */
 108 #include <sys/ddifm.h>
 109 #include <sys/fm/protocol.h>
 110 #include <sys/fm/util.h>
 111 #include <sys/fm/io/ddi.h>
 112 
 113 /*
 114  * For anyone who would modify the code in mptsas_driver, it must be awared
 115  * that from snv_145 where CR6910752(mpt_sas driver performance can be
 116  * improved) is integrated, the per_instance mutex m_mutex is not hold
 117  * in the key IO code path, including mptsas_scsi_start(), mptsas_intr()
 118  * and all of the recursive functions called in them, so don't
 119  * make it for granted that all operations are sync/exclude correctly. Before
 120  * doing any modification in key code path, and even other code path such as
 121  * DR, watchsubr, ioctl, passthrough etc, make sure the elements modified have
 122  * no releationship to elements shown in the fastpath
 123  * (function mptsas_handle_io_fastpath()) in ISR and its recursive functions.
 124  * otherwise, you have to use the new introduced mutex to protect them.
 125  * As to how to do correctly, refer to the comments in mptsas_intr().
 126  */
 127 
 128 /*
 129  * autoconfiguration data and routines.
 130  */
 131 static int mptsas_attach(dev_info_t *dip, ddi_attach_cmd_t cmd);
 132 static int mptsas_detach(dev_info_t *devi, ddi_detach_cmd_t cmd);
 133 static int mptsas_power(dev_info_t *dip, int component, int level);
 134 
 135 /*
 136  * cb_ops function
 137  */
 138 static int mptsas_ioctl(dev_t dev, int cmd, intptr_t data, int mode,
 139         cred_t *credp, int *rval);
 140 #ifdef __sparc
 141 static int mptsas_reset(dev_info_t *devi, ddi_reset_cmd_t cmd);
 142 #else  /* __sparc */
 143 static int mptsas_quiesce(dev_info_t *devi);
 144 #endif  /* __sparc */
 145 
 146 /*
 147  * Resource initilaization for hardware
 148  */
 149 static void mptsas_setup_cmd_reg(mptsas_t *mpt);
 150 static void mptsas_disable_bus_master(mptsas_t *mpt);
 151 static void mptsas_hba_fini(mptsas_t *mpt);
 152 static void mptsas_cfg_fini(mptsas_t *mptsas_blkp);
 153 static int mptsas_hba_setup(mptsas_t *mpt);
 154 static void mptsas_hba_teardown(mptsas_t *mpt);
 155 static int mptsas_config_space_init(mptsas_t *mpt);
 156 static void mptsas_config_space_fini(mptsas_t *mpt);
 157 static void mptsas_iport_register(mptsas_t *mpt);
 158 static int mptsas_smp_setup(mptsas_t *mpt);
 159 static void mptsas_smp_teardown(mptsas_t *mpt);
 160 static int mptsas_cache_create(mptsas_t *mpt);
 161 static void mptsas_cache_destroy(mptsas_t *mpt);
 162 static int mptsas_alloc_request_frames(mptsas_t *mpt);
 163 static int mptsas_alloc_reply_frames(mptsas_t *mpt);
 164 static int mptsas_alloc_free_queue(mptsas_t *mpt);
 165 static int mptsas_alloc_post_queue(mptsas_t *mpt);
 166 static void mptsas_alloc_reply_args(mptsas_t *mpt);
 167 static int mptsas_alloc_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd);
 168 static void mptsas_free_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd);
 169 static int mptsas_init_chip(mptsas_t *mpt, int first_time);
 170 
 171 /*
 172  * SCSA function prototypes
 173  */
 174 static int mptsas_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt);
 175 static int mptsas_scsi_reset(struct scsi_address *ap, int level);
 176 static int mptsas_scsi_abort(struct scsi_address *ap, struct scsi_pkt *pkt);
 177 static int mptsas_scsi_getcap(struct scsi_address *ap, char *cap, int tgtonly);
 178 static int mptsas_scsi_setcap(struct scsi_address *ap, char *cap, int value,
 179     int tgtonly);
 180 static void mptsas_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt);
 181 static struct scsi_pkt *mptsas_scsi_init_pkt(struct scsi_address *ap,
 182     struct scsi_pkt *pkt, struct buf *bp, int cmdlen, int statuslen,
 183         int tgtlen, int flags, int (*callback)(), caddr_t arg);
 184 static void mptsas_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt);
 185 static void mptsas_scsi_destroy_pkt(struct scsi_address *ap,
 186     struct scsi_pkt *pkt);
 187 static int mptsas_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
 188     scsi_hba_tran_t *hba_tran, struct scsi_device *sd);
 189 static void mptsas_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
 190     scsi_hba_tran_t *hba_tran, struct scsi_device *sd);
 191 static int mptsas_scsi_reset_notify(struct scsi_address *ap, int flag,
 192     void (*callback)(caddr_t), caddr_t arg);
 193 static int mptsas_get_name(struct scsi_device *sd, char *name, int len);
 194 static int mptsas_get_bus_addr(struct scsi_device *sd, char *name, int len);
 195 static int mptsas_scsi_quiesce(dev_info_t *dip);
 196 static int mptsas_scsi_unquiesce(dev_info_t *dip);
 197 static int mptsas_bus_config(dev_info_t *pdip, uint_t flags,
 198     ddi_bus_config_op_t op, void *arg, dev_info_t **childp);
 199 
 200 /*
 201  * SMP functions
 202  */
 203 static int mptsas_smp_start(struct smp_pkt *smp_pkt);
 204 
 205 /*
 206  * internal function prototypes.
 207  */
 208 static void mptsas_list_add(mptsas_t *mpt);
 209 static void mptsas_list_del(mptsas_t *mpt);
 210 
 211 static int mptsas_quiesce_bus(mptsas_t *mpt);
 212 static int mptsas_unquiesce_bus(mptsas_t *mpt);
 213 
 214 static int mptsas_alloc_handshake_msg(mptsas_t *mpt, size_t alloc_size);
 215 static void mptsas_free_handshake_msg(mptsas_t *mpt);
 216 
 217 static void mptsas_ncmds_checkdrain(void *arg);
 218 
 219 static int mptsas_prepare_pkt(mptsas_cmd_t *cmd);
 220 static int mptsas_accept_pkt(mptsas_t *mpt, mptsas_cmd_t *sp);
 221 
 222 static int mptsas_do_detach(dev_info_t *dev);
 223 static int mptsas_do_scsi_reset(mptsas_t *mpt, uint16_t devhdl);
 224 static int mptsas_do_scsi_abort(mptsas_t *mpt, int target, int lun,
 225     struct scsi_pkt *pkt);
 226 static int mptsas_scsi_capchk(char *cap, int tgtonly, int *cidxp);
 227 
 228 static void mptsas_handle_qfull(mptsas_t *mpt, mptsas_cmd_t *cmd);
 229 static void mptsas_handle_event(void *args);
 230 static int mptsas_handle_event_sync(void *args);
 231 static void mptsas_handle_dr(void *args);
 232 static void mptsas_handle_topo_change(mptsas_topo_change_list_t *topo_node,
 233     dev_info_t *pdip);
 234 
 235 static void mptsas_restart_cmd(void *);
 236 
 237 static void mptsas_flush_hba(mptsas_t *mpt);
 238 static void mptsas_flush_target(mptsas_t *mpt, ushort_t target, int lun,
 239         uint8_t tasktype);
 240 static void mptsas_set_pkt_reason(mptsas_t *mpt, mptsas_cmd_t *cmd,
 241     uchar_t reason, uint_t stat);
 242 
 243 static uint_t mptsas_intr(caddr_t arg1, caddr_t arg2);
 244 static void mptsas_process_intr(mptsas_t *mpt,
 245     pMpi2ReplyDescriptorsUnion_t reply_desc_union);
 246 static int mptsas_handle_io_fastpath(mptsas_t *mpt, uint16_t SMID);
 247 static void mptsas_handle_scsi_io_success(mptsas_t *mpt,
 248     pMpi2ReplyDescriptorsUnion_t reply_desc);
 249 static void mptsas_handle_address_reply(mptsas_t *mpt,
 250     pMpi2ReplyDescriptorsUnion_t reply_desc);
 251 static int mptsas_wait_intr(mptsas_t *mpt, int polltime);
 252 static void mptsas_sge_setup(mptsas_t *mpt, mptsas_cmd_t *cmd,
 253     uint32_t *control, pMpi2SCSIIORequest_t frame, ddi_acc_handle_t acc_hdl);
 254 
 255 static void mptsas_watch(void *arg);
 256 static void mptsas_watchsubr(mptsas_t *mpt);
 257 static void mptsas_cmd_timeout(mptsas_t *mpt, uint16_t devhdl);
 258 
 259 static void mptsas_start_passthru(mptsas_t *mpt, mptsas_cmd_t *cmd);
 260 static int mptsas_do_passthru(mptsas_t *mpt, uint8_t *request, uint8_t *reply,
 261     uint8_t *data, uint32_t request_size, uint32_t reply_size,
 262     uint32_t data_size, uint32_t direction, uint8_t *dataout,
 263     uint32_t dataout_size, short timeout, int mode);
 264 static int mptsas_free_devhdl(mptsas_t *mpt, uint16_t devhdl);
 265 
 266 static uint8_t mptsas_get_fw_diag_buffer_number(mptsas_t *mpt,
 267     uint32_t unique_id);
 268 static void mptsas_start_diag(mptsas_t *mpt, mptsas_cmd_t *cmd);
 269 static int mptsas_post_fw_diag_buffer(mptsas_t *mpt,
 270     mptsas_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code);
 271 static int mptsas_release_fw_diag_buffer(mptsas_t *mpt,
 272     mptsas_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code,
 273     uint32_t diag_type);
 274 static int mptsas_diag_register(mptsas_t *mpt,
 275     mptsas_fw_diag_register_t *diag_register, uint32_t *return_code);
 276 static int mptsas_diag_unregister(mptsas_t *mpt,
 277     mptsas_fw_diag_unregister_t *diag_unregister, uint32_t *return_code);
 278 static int mptsas_diag_query(mptsas_t *mpt, mptsas_fw_diag_query_t *diag_query,
 279     uint32_t *return_code);
 280 static int mptsas_diag_read_buffer(mptsas_t *mpt,
 281     mptsas_diag_read_buffer_t *diag_read_buffer, uint8_t *ioctl_buf,
 282     uint32_t *return_code, int ioctl_mode);
 283 static int mptsas_diag_release(mptsas_t *mpt,
 284     mptsas_fw_diag_release_t *diag_release, uint32_t *return_code);
 285 static int mptsas_do_diag_action(mptsas_t *mpt, uint32_t action,
 286     uint8_t *diag_action, uint32_t length, uint32_t *return_code,
 287     int ioctl_mode);
 288 static int mptsas_diag_action(mptsas_t *mpt, mptsas_diag_action_t *data,
 289     int mode);
 290 
 291 static int mptsas_pkt_alloc_extern(mptsas_t *mpt, mptsas_cmd_t *cmd,
 292     int cmdlen, int tgtlen, int statuslen, int kf);
 293 static void mptsas_pkt_destroy_extern(mptsas_t *mpt, mptsas_cmd_t *cmd);
 294 
 295 static int mptsas_kmem_cache_constructor(void *buf, void *cdrarg, int kmflags);
 296 static void mptsas_kmem_cache_destructor(void *buf, void *cdrarg);
 297 
 298 static int mptsas_cache_frames_constructor(void *buf, void *cdrarg,
 299     int kmflags);
 300 static void mptsas_cache_frames_destructor(void *buf, void *cdrarg);
 301 
 302 static void mptsas_check_scsi_io_error(mptsas_t *mpt, pMpi2SCSIIOReply_t reply,
 303     mptsas_cmd_t *cmd);
 304 static void mptsas_check_task_mgt(mptsas_t *mpt,
 305     pMpi2SCSIManagementReply_t reply, mptsas_cmd_t *cmd);
 306 static int mptsas_send_scsi_cmd(mptsas_t *mpt, struct scsi_address *ap,
 307     mptsas_target_t *ptgt, uchar_t *cdb, int cdblen, struct buf *data_bp,
 308     int *resid);
 309 
 310 static int mptsas_alloc_active_slots(mptsas_t *mpt, int flag);
 311 static void mptsas_free_active_slots(mptsas_t *mpt);
 312 static int mptsas_start_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd);
 313 static int mptsas_start_cmd0(mptsas_t *mpt, mptsas_cmd_t *cmd);
 314 
 315 static void mptsas_restart_hba(mptsas_t *mpt);
 316 
 317 static void mptsas_deliver_doneq_thread(mptsas_t *mpt);
 318 static void mptsas_doneq_add(mptsas_t *mpt, mptsas_cmd_t *cmd);
 319 static inline void mptsas_doneq_add0(mptsas_t *mpt, mptsas_cmd_t *cmd);
 320 static void mptsas_doneq_mv(mptsas_t *mpt, uint64_t t);
 321 
 322 static mptsas_cmd_t *mptsas_doneq_thread_rm(mptsas_t *mpt, uint64_t t);
 323 static void mptsas_doneq_empty(mptsas_t *mpt);
 324 static void mptsas_doneq_thread(mptsas_doneq_thread_arg_t *arg);
 325 
 326 static mptsas_cmd_t *mptsas_waitq_rm(mptsas_t *mpt);
 327 static void mptsas_waitq_delete(mptsas_t *mpt, mptsas_cmd_t *cmd);
 328 
 329 static void mptsas_start_watch_reset_delay();
 330 static void mptsas_setup_bus_reset_delay(mptsas_t *mpt);
 331 static void mptsas_watch_reset_delay(void *arg);
 332 static int mptsas_watch_reset_delay_subr(mptsas_t *mpt);
 333 
 334 static int mptsas_outstanding_cmds_n(mptsas_t *mpt);
 335 /*
 336  * helper functions
 337  */
 338 static void mptsas_dump_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd);
 339 
 340 static dev_info_t *mptsas_find_child(dev_info_t *pdip, char *name);
 341 static dev_info_t *mptsas_find_child_phy(dev_info_t *pdip, uint8_t phy);
 342 static dev_info_t *mptsas_find_child_addr(dev_info_t *pdip, uint64_t sasaddr,
 343     int lun);
 344 static mdi_pathinfo_t *mptsas_find_path_addr(dev_info_t *pdip, uint64_t sasaddr,
 345     int lun);
 346 static mdi_pathinfo_t *mptsas_find_path_phy(dev_info_t *pdip, uint8_t phy);
 347 static dev_info_t *mptsas_find_smp_child(dev_info_t *pdip, char *str_wwn);
 348 
 349 static int mptsas_parse_address(char *name, uint64_t *wwid, uint8_t *phy,
 350     int *lun);
 351 static int mptsas_parse_smp_name(char *name, uint64_t *wwn);
 352 
 353 static mptsas_target_t *mptsas_phy_to_tgt(mptsas_t *mpt, int phymask,
 354     uint8_t phy);
 355 static mptsas_target_t *mptsas_wwid_to_ptgt(mptsas_t *mpt, int phymask,
 356     uint64_t wwid);
 357 static mptsas_smp_t *mptsas_wwid_to_psmp(mptsas_t *mpt, int phymask,
 358     uint64_t wwid);
 359 
 360 static int mptsas_inquiry(mptsas_t *mpt, mptsas_target_t *ptgt, int lun,
 361     uchar_t page, unsigned char *buf, int len, int *rlen, uchar_t evpd);
 362 
 363 static int mptsas_get_target_device_info(mptsas_t *mpt, uint32_t page_address,
 364     uint16_t *handle, mptsas_target_t **pptgt);
 365 static void mptsas_update_phymask(mptsas_t *mpt);
 366 static inline void mptsas_remove_cmd0(mptsas_t *mpt, mptsas_cmd_t *cmd);
 367 
 368 static int mptsas_send_sep(mptsas_t *mpt, mptsas_target_t *ptgt,
 369     uint32_t *status, uint8_t cmd);
 370 static dev_info_t *mptsas_get_dip_from_dev(dev_t dev,
 371     mptsas_phymask_t *phymask);
 372 static mptsas_target_t *mptsas_addr_to_ptgt(mptsas_t *mpt, char *addr,
 373     mptsas_phymask_t phymask);
 374 static int mptsas_set_led_status(mptsas_t *mpt, mptsas_target_t *ptgt,
 375     uint32_t slotstatus);
 376 
 377 
 378 /*
 379  * Enumeration / DR functions
 380  */
 381 static void mptsas_config_all(dev_info_t *pdip);
 382 static int mptsas_config_one_addr(dev_info_t *pdip, uint64_t sasaddr, int lun,
 383     dev_info_t **lundip);
 384 static int mptsas_config_one_phy(dev_info_t *pdip, uint8_t phy, int lun,
 385     dev_info_t **lundip);
 386 
 387 static int mptsas_config_target(dev_info_t *pdip, mptsas_target_t *ptgt);
 388 static int mptsas_offline_target(dev_info_t *pdip, char *name);
 389 
 390 static int mptsas_config_raid(dev_info_t *pdip, uint16_t target,
 391     dev_info_t **dip);
 392 
 393 static int mptsas_config_luns(dev_info_t *pdip, mptsas_target_t *ptgt);
 394 static int mptsas_probe_lun(dev_info_t *pdip, int lun,
 395     dev_info_t **dip, mptsas_target_t *ptgt);
 396 
 397 static int mptsas_create_lun(dev_info_t *pdip, struct scsi_inquiry *sd_inq,
 398     dev_info_t **dip, mptsas_target_t *ptgt, int lun);
 399 
 400 static int mptsas_create_phys_lun(dev_info_t *pdip, struct scsi_inquiry *sd,
 401     char *guid, dev_info_t **dip, mptsas_target_t *ptgt, int lun);
 402 static int mptsas_create_virt_lun(dev_info_t *pdip, struct scsi_inquiry *sd,
 403     char *guid, dev_info_t **dip, mdi_pathinfo_t **pip, mptsas_target_t *ptgt,
 404     int lun);
 405 
 406 static void mptsas_offline_missed_luns(dev_info_t *pdip,
 407     uint16_t *repluns, int lun_cnt, mptsas_target_t *ptgt);
 408 static int mptsas_offline_lun(dev_info_t *pdip, dev_info_t *rdip,
 409     mdi_pathinfo_t *rpip, uint_t flags);
 410 
 411 static int mptsas_config_smp(dev_info_t *pdip, uint64_t sas_wwn,
 412     dev_info_t **smp_dip);
 413 static int mptsas_offline_smp(dev_info_t *pdip, mptsas_smp_t *smp_node,
 414     uint_t flags);
 415 
 416 static int mptsas_event_query(mptsas_t *mpt, mptsas_event_query_t *data,
 417     int mode, int *rval);
 418 static int mptsas_event_enable(mptsas_t *mpt, mptsas_event_enable_t *data,
 419     int mode, int *rval);
 420 static int mptsas_event_report(mptsas_t *mpt, mptsas_event_report_t *data,
 421     int mode, int *rval);
 422 static void mptsas_record_event(void *args);
 423 static int mptsas_reg_access(mptsas_t *mpt, mptsas_reg_access_t *data,
 424     int mode);
 425 
 426 static void mptsas_hash_init(mptsas_hash_table_t *hashtab);
 427 static void mptsas_hash_uninit(mptsas_hash_table_t *hashtab, size_t datalen);
 428 static void mptsas_hash_add(mptsas_hash_table_t *hashtab, void *data);
 429 static void * mptsas_hash_rem(mptsas_hash_table_t *hashtab, uint64_t key1,
 430     mptsas_phymask_t key2);
 431 static void * mptsas_hash_search(mptsas_hash_table_t *hashtab, uint64_t key1,
 432     mptsas_phymask_t key2);
 433 static void * mptsas_hash_traverse(mptsas_hash_table_t *hashtab, int pos);
 434 
 435 mptsas_target_t *mptsas_tgt_alloc(mptsas_hash_table_t *, uint16_t, uint64_t,
 436     uint32_t, mptsas_phymask_t, uint8_t, mptsas_t *);
 437 static mptsas_smp_t *mptsas_smp_alloc(mptsas_hash_table_t *hashtab,
 438     mptsas_smp_t *data);
 439 static void mptsas_smp_free(mptsas_hash_table_t *hashtab, uint64_t wwid,
 440     mptsas_phymask_t phymask);
 441 static void mptsas_tgt_free(mptsas_hash_table_t *, uint64_t, mptsas_phymask_t);
 442 static void * mptsas_search_by_devhdl(mptsas_hash_table_t *, uint16_t);
 443 static int mptsas_online_smp(dev_info_t *pdip, mptsas_smp_t *smp_node,
 444     dev_info_t **smp_dip);
 445 
 446 /*
 447  * Power management functions
 448  */
 449 static int mptsas_get_pci_cap(mptsas_t *mpt);
 450 static int mptsas_init_pm(mptsas_t *mpt);
 451 
 452 /*
 453  * MPT MSI tunable:
 454  *
 455  * By default MSI is enabled on all supported platforms.
 456  */
 457 boolean_t mptsas_enable_msi = B_TRUE;
 458 boolean_t mptsas_physical_bind_failed_page_83 = B_FALSE;
 459 
 460 static int mptsas_register_intrs(mptsas_t *);
 461 static void mptsas_unregister_intrs(mptsas_t *);
 462 static int mptsas_add_intrs(mptsas_t *, int);
 463 static void mptsas_rem_intrs(mptsas_t *);
 464 
 465 /*
 466  * FMA Prototypes
 467  */
 468 static void mptsas_fm_init(mptsas_t *mpt);
 469 static void mptsas_fm_fini(mptsas_t *mpt);
 470 static int mptsas_fm_error_cb(dev_info_t *, ddi_fm_error_t *, const void *);
 471 
 472 extern pri_t minclsyspri, maxclsyspri;
 473 
 474 /*
 475  * This device is created by the SCSI pseudo nexus driver (SCSI vHCI).  It is
 476  * under this device that the paths to a physical device are created when
 477  * MPxIO is used.
 478  */
 479 extern dev_info_t       *scsi_vhci_dip;
 480 
 481 /*
 482  * Tunable timeout value for Inquiry VPD page 0x83
 483  * By default the value is 30 seconds.
 484  */
 485 int mptsas_inq83_retry_timeout = 30;
 486 
 487 /*
 488  * This is used to allocate memory for message frame storage, not for
 489  * data I/O DMA. All message frames must be stored in the first 4G of
 490  * physical memory.
 491  */
 492 ddi_dma_attr_t mptsas_dma_attrs = {
 493         DMA_ATTR_V0,    /* attribute layout version             */
 494         0x0ull,         /* address low - should be 0 (longlong) */
 495         0xffffffffull,  /* address high - 32-bit max range      */
 496         0x00ffffffull,  /* count max - max DMA object size      */
 497         4,              /* allocation alignment requirements    */
 498         0x78,           /* burstsizes - binary encoded values   */
 499         1,              /* minxfer - gran. of DMA engine        */
 500         0x00ffffffull,  /* maxxfer - gran. of DMA engine        */
 501         0xffffffffull,  /* max segment size (DMA boundary)      */
 502         MPTSAS_MAX_DMA_SEGS, /* scatter/gather list length      */
 503         512,            /* granularity - device transfer size   */
 504         0               /* flags, set to 0                      */
 505 };
 506 
 507 /*
 508  * This is used for data I/O DMA memory allocation. (full 64-bit DMA
 509  * physical addresses are supported.)
 510  */
 511 ddi_dma_attr_t mptsas_dma_attrs64 = {
 512         DMA_ATTR_V0,    /* attribute layout version             */
 513         0x0ull,         /* address low - should be 0 (longlong) */
 514         0xffffffffffffffffull,  /* address high - 64-bit max    */
 515         0x00ffffffull,  /* count max - max DMA object size      */
 516         4,              /* allocation alignment requirements    */
 517         0x78,           /* burstsizes - binary encoded values   */
 518         1,              /* minxfer - gran. of DMA engine        */
 519         0x00ffffffull,  /* maxxfer - gran. of DMA engine        */
 520         0xffffffffull,  /* max segment size (DMA boundary)      */
 521         MPTSAS_MAX_DMA_SEGS, /* scatter/gather list length      */
 522         512,            /* granularity - device transfer size   */
 523         DDI_DMA_RELAXED_ORDERING        /* flags, enable relaxed ordering */
 524 };
 525 
 526 ddi_device_acc_attr_t mptsas_dev_attr = {
 527         DDI_DEVICE_ATTR_V1,
 528         DDI_STRUCTURE_LE_ACC,
 529         DDI_STRICTORDER_ACC,
 530         DDI_DEFAULT_ACC
 531 };
 532 
 533 static struct cb_ops mptsas_cb_ops = {
 534         scsi_hba_open,          /* open */
 535         scsi_hba_close,         /* close */
 536         nodev,                  /* strategy */
 537         nodev,                  /* print */
 538         nodev,                  /* dump */
 539         nodev,                  /* read */
 540         nodev,                  /* write */
 541         mptsas_ioctl,           /* ioctl */
 542         nodev,                  /* devmap */
 543         nodev,                  /* mmap */
 544         nodev,                  /* segmap */
 545         nochpoll,               /* chpoll */
 546         ddi_prop_op,            /* cb_prop_op */
 547         NULL,                   /* streamtab */
 548         D_MP,                   /* cb_flag */
 549         CB_REV,                 /* rev */
 550         nodev,                  /* aread */
 551         nodev                   /* awrite */
 552 };
 553 
 554 static struct dev_ops mptsas_ops = {
 555         DEVO_REV,               /* devo_rev, */
 556         0,                      /* refcnt  */
 557         ddi_no_info,            /* info */
 558         nulldev,                /* identify */
 559         nulldev,                /* probe */
 560         mptsas_attach,          /* attach */
 561         mptsas_detach,          /* detach */
 562 #ifdef  __sparc
 563         mptsas_reset,
 564 #else
 565         nodev,                  /* reset */
 566 #endif  /* __sparc */
 567         &mptsas_cb_ops,             /* driver operations */
 568         NULL,                   /* bus operations */
 569         mptsas_power,           /* power management */
 570 #ifdef  __sparc
 571         ddi_quiesce_not_needed
 572 #else
 573         mptsas_quiesce          /* quiesce */
 574 #endif  /* __sparc */
 575 };
 576 
 577 
 578 #define MPTSAS_MOD_STRING "MPTSAS HBA Driver 00.00.00.24"
 579 
 580 static struct modldrv modldrv = {
 581         &mod_driverops,     /* Type of module. This one is a driver */
 582         MPTSAS_MOD_STRING, /* Name of the module. */
 583         &mptsas_ops,        /* driver ops */
 584 };
 585 
 586 static struct modlinkage modlinkage = {
 587         MODREV_1, &modldrv, NULL
 588 };
 589 #define TARGET_PROP     "target"
 590 #define LUN_PROP        "lun"
 591 #define LUN64_PROP      "lun64"
 592 #define SAS_PROP        "sas-mpt"
 593 #define MDI_GUID        "wwn"
 594 #define NDI_GUID        "guid"
 595 #define MPTSAS_DEV_GONE "mptsas_dev_gone"
 596 
 597 /*
 598  * Local static data
 599  */
 600 #if defined(MPTSAS_DEBUG)
 601 uint32_t mptsas_debug_flags = 0;
 602 #endif  /* defined(MPTSAS_DEBUG) */
 603 uint32_t mptsas_debug_resets = 0;
 604 
 605 static kmutex_t         mptsas_global_mutex;
 606 static void             *mptsas_state;          /* soft state ptr */
 607 static krwlock_t        mptsas_global_rwlock;
 608 
 609 static kmutex_t         mptsas_log_mutex;
 610 static char             mptsas_log_buf[256];
 611 _NOTE(MUTEX_PROTECTS_DATA(mptsas_log_mutex, mptsas_log_buf))
 612 
 613 static mptsas_t *mptsas_head, *mptsas_tail;
 614 static clock_t mptsas_scsi_watchdog_tick;
 615 static clock_t mptsas_tick;
 616 static timeout_id_t mptsas_reset_watch;
 617 static timeout_id_t mptsas_timeout_id;
 618 static int mptsas_timeouts_enabled = 0;
 619 /*
 620  * warlock directives
 621  */
 622 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_pkt \
 623         mptsas_cmd NcrTableIndirect buf scsi_cdb scsi_status))
 624 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", smp_pkt))
 625 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device scsi_address))
 626 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mptsas_tgt_private))
 627 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran::tran_tgt_private))
 628 
 629 /*
 630  * SM - HBA statics
 631  */
 632 char    *mptsas_driver_rev = MPTSAS_MOD_STRING;
 633 
 634 #ifdef MPTSAS_DEBUG
 635 void debug_enter(char *);
 636 #endif
 637 
 638 /*
 639  * Notes:
 640  *      - scsi_hba_init(9F) initializes SCSI HBA modules
 641  *      - must call scsi_hba_fini(9F) if modload() fails
 642  */
 643 int
 644 _init(void)
 645 {
 646         int status;
 647         /* CONSTCOND */
 648         ASSERT(NO_COMPETING_THREADS);
 649 
 650         NDBG0(("_init"));
 651 
 652         status = ddi_soft_state_init(&mptsas_state, MPTSAS_SIZE,
 653             MPTSAS_INITIAL_SOFT_SPACE);
 654         if (status != 0) {
 655                 return (status);
 656         }
 657 
 658         if ((status = scsi_hba_init(&modlinkage)) != 0) {
 659                 ddi_soft_state_fini(&mptsas_state);
 660                 return (status);
 661         }
 662 
 663         mutex_init(&mptsas_global_mutex, NULL, MUTEX_DRIVER, NULL);
 664         rw_init(&mptsas_global_rwlock, NULL, RW_DRIVER, NULL);
 665         mutex_init(&mptsas_log_mutex, NULL, MUTEX_DRIVER, NULL);
 666 
 667         if ((status = mod_install(&modlinkage)) != 0) {
 668                 mutex_destroy(&mptsas_log_mutex);
 669                 rw_destroy(&mptsas_global_rwlock);
 670                 mutex_destroy(&mptsas_global_mutex);
 671                 ddi_soft_state_fini(&mptsas_state);
 672                 scsi_hba_fini(&modlinkage);
 673         }
 674 
 675         return (status);
 676 }
 677 
 678 /*
 679  * Notes:
 680  *      - scsi_hba_fini(9F) uninitializes SCSI HBA modules
 681  */
 682 int
 683 _fini(void)
 684 {
 685         int     status;
 686         /* CONSTCOND */
 687         ASSERT(NO_COMPETING_THREADS);
 688 
 689         NDBG0(("_fini"));
 690 
 691         if ((status = mod_remove(&modlinkage)) == 0) {
 692                 ddi_soft_state_fini(&mptsas_state);
 693                 scsi_hba_fini(&modlinkage);
 694                 mutex_destroy(&mptsas_global_mutex);
 695                 rw_destroy(&mptsas_global_rwlock);
 696                 mutex_destroy(&mptsas_log_mutex);
 697         }
 698         return (status);
 699 }
 700 
 701 /*
 702  * The loadable-module _info(9E) entry point
 703  */
 704 int
 705 _info(struct modinfo *modinfop)
 706 {
 707         /* CONSTCOND */
 708         ASSERT(NO_COMPETING_THREADS);
 709         NDBG0(("mptsas _info"));
 710 
 711         return (mod_info(&modlinkage, modinfop));
 712 }
 713 
 714 
 715 static int
 716 mptsas_iport_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
 717 {
 718         dev_info_t              *pdip;
 719         mptsas_t                *mpt;
 720         scsi_hba_tran_t         *hba_tran;
 721         char                    *iport = NULL;
 722         char                    phymask[MPTSAS_MAX_PHYS];
 723         mptsas_phymask_t        phy_mask = 0;
 724         int                     dynamic_port = 0;
 725         uint32_t                page_address;
 726         char                    initiator_wwnstr[MPTSAS_WWN_STRLEN];
 727         int                     rval = DDI_FAILURE;
 728         int                     i = 0;
 729         uint8_t                 numphys = 0;
 730         uint8_t                 phy_id;
 731         uint8_t                 phy_port = 0;
 732         uint16_t                attached_devhdl = 0;
 733         uint32_t                dev_info;
 734         uint64_t                attached_sas_wwn;
 735         uint16_t                dev_hdl;
 736         uint16_t                pdev_hdl;
 737         uint16_t                bay_num, enclosure;
 738         char                    attached_wwnstr[MPTSAS_WWN_STRLEN];
 739 
 740         /* CONSTCOND */
 741         ASSERT(NO_COMPETING_THREADS);
 742 
 743         switch (cmd) {
 744         case DDI_ATTACH:
 745                 break;
 746 
 747         case DDI_RESUME:
 748                 /*
 749                  * If this a scsi-iport node, nothing to do here.
 750                  */
 751                 return (DDI_SUCCESS);
 752 
 753         default:
 754                 return (DDI_FAILURE);
 755         }
 756 
 757         pdip = ddi_get_parent(dip);
 758 
 759         if ((hba_tran = ndi_flavorv_get(pdip, SCSA_FLAVOR_SCSI_DEVICE)) ==
 760             NULL) {
 761                 cmn_err(CE_WARN, "Failed attach iport because fail to "
 762                     "get tran vector for the HBA node");
 763                 return (DDI_FAILURE);
 764         }
 765 
 766         mpt = TRAN2MPT(hba_tran);
 767         ASSERT(mpt != NULL);
 768         if (mpt == NULL)
 769                 return (DDI_FAILURE);
 770 
 771         if ((hba_tran = ndi_flavorv_get(dip, SCSA_FLAVOR_SCSI_DEVICE)) ==
 772             NULL) {
 773                 mptsas_log(mpt, CE_WARN, "Failed attach iport because fail to "
 774                     "get tran vector for the iport node");
 775                 return (DDI_FAILURE);
 776         }
 777 
 778         /*
 779          * Overwrite parent's tran_hba_private to iport's tran vector
 780          */
 781         hba_tran->tran_hba_private = mpt;
 782 
 783         ddi_report_dev(dip);
 784 
 785         /*
 786          * Get SAS address for initiator port according dev_handle
 787          */
 788         iport = ddi_get_name_addr(dip);
 789         if (iport && strncmp(iport, "v0", 2) == 0) {
 790                 if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
 791                     MPTSAS_VIRTUAL_PORT, 1) !=
 792                     DDI_PROP_SUCCESS) {
 793                         (void) ddi_prop_remove(DDI_DEV_T_NONE, dip,
 794                             MPTSAS_VIRTUAL_PORT);
 795                         mptsas_log(mpt, CE_WARN, "mptsas virtual port "
 796                             "prop update failed");
 797                         return (DDI_FAILURE);
 798                 }
 799                 return (DDI_SUCCESS);
 800         }
 801 
 802         mutex_enter(&mpt->m_mutex);
 803         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
 804                 bzero(phymask, sizeof (phymask));
 805                 (void) sprintf(phymask,
 806                     "%x", mpt->m_phy_info[i].phy_mask);
 807                 if (strcmp(phymask, iport) == 0) {
 808                         break;
 809                 }
 810         }
 811 
 812         if (i == MPTSAS_MAX_PHYS) {
 813                 mptsas_log(mpt, CE_WARN, "Failed attach port %s because port"
 814                     "seems not exist", iport);
 815                 mutex_exit(&mpt->m_mutex);
 816                 return (DDI_FAILURE);
 817         }
 818 
 819         phy_mask = mpt->m_phy_info[i].phy_mask;
 820 
 821         if (mpt->m_phy_info[i].port_flags & AUTO_PORT_CONFIGURATION)
 822                 dynamic_port = 1;
 823         else
 824                 dynamic_port = 0;
 825 
 826         /*
 827          * Update PHY info for smhba
 828          */
 829         if (mptsas_smhba_phy_init(mpt)) {
 830                 mutex_exit(&mpt->m_mutex);
 831                 mptsas_log(mpt, CE_WARN, "mptsas phy update "
 832                     "failed");
 833                 return (DDI_FAILURE);
 834         }
 835 
 836         mutex_exit(&mpt->m_mutex);
 837 
 838         numphys = 0;
 839         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
 840                 if ((phy_mask >> i) & 0x01) {
 841                         numphys++;
 842                 }
 843         }
 844 
 845         bzero(initiator_wwnstr, sizeof (initiator_wwnstr));
 846         (void) sprintf(initiator_wwnstr, "w%016"PRIx64,
 847             mpt->un.m_base_wwid);
 848 
 849         if (ddi_prop_update_string(DDI_DEV_T_NONE, dip,
 850             SCSI_ADDR_PROP_INITIATOR_PORT, initiator_wwnstr) !=
 851             DDI_PROP_SUCCESS) {
 852                 (void) ddi_prop_remove(DDI_DEV_T_NONE,
 853                     dip, SCSI_ADDR_PROP_INITIATOR_PORT);
 854                 mptsas_log(mpt, CE_WARN, "mptsas Initiator port "
 855                     "prop update failed");
 856                 return (DDI_FAILURE);
 857         }
 858         if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
 859             MPTSAS_NUM_PHYS, numphys) !=
 860             DDI_PROP_SUCCESS) {
 861                 (void) ddi_prop_remove(DDI_DEV_T_NONE, dip, MPTSAS_NUM_PHYS);
 862                 return (DDI_FAILURE);
 863         }
 864 
 865         if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
 866             "phymask", phy_mask) !=
 867             DDI_PROP_SUCCESS) {
 868                 (void) ddi_prop_remove(DDI_DEV_T_NONE, dip, "phymask");
 869                 mptsas_log(mpt, CE_WARN, "mptsas phy mask "
 870                     "prop update failed");
 871                 return (DDI_FAILURE);
 872         }
 873 
 874         if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
 875             "dynamic-port", dynamic_port) !=
 876             DDI_PROP_SUCCESS) {
 877                 (void) ddi_prop_remove(DDI_DEV_T_NONE, dip, "dynamic-port");
 878                 mptsas_log(mpt, CE_WARN, "mptsas dynamic port "
 879                     "prop update failed");
 880                 return (DDI_FAILURE);
 881         }
 882         if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
 883             MPTSAS_VIRTUAL_PORT, 0) !=
 884             DDI_PROP_SUCCESS) {
 885                 (void) ddi_prop_remove(DDI_DEV_T_NONE, dip,
 886                     MPTSAS_VIRTUAL_PORT);
 887                 mptsas_log(mpt, CE_WARN, "mptsas virtual port "
 888                     "prop update failed");
 889                 return (DDI_FAILURE);
 890         }
 891         mptsas_smhba_set_phy_props(mpt,
 892             iport, dip, numphys, &attached_devhdl);
 893 
 894         mutex_enter(&mpt->m_mutex);
 895         page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
 896             MPI2_SAS_DEVICE_PGAD_FORM_MASK) | (uint32_t)attached_devhdl;
 897         rval = mptsas_get_sas_device_page0(mpt, page_address, &dev_hdl,
 898             &attached_sas_wwn, &dev_info, &phy_port, &phy_id,
 899             &pdev_hdl, &bay_num, &enclosure);
 900         if (rval != DDI_SUCCESS) {
 901                 mptsas_log(mpt, CE_WARN,
 902                     "Failed to get device page0 for handle:%d",
 903                     attached_devhdl);
 904                 mutex_exit(&mpt->m_mutex);
 905                 return (DDI_FAILURE);
 906         }
 907 
 908         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
 909                 bzero(phymask, sizeof (phymask));
 910                 (void) sprintf(phymask, "%x", mpt->m_phy_info[i].phy_mask);
 911                 if (strcmp(phymask, iport) == 0) {
 912                         (void) sprintf(&mpt->m_phy_info[i].smhba_info.path[0],
 913                             "%x",
 914                             mpt->m_phy_info[i].phy_mask);
 915                 }
 916         }
 917         mutex_exit(&mpt->m_mutex);
 918 
 919         bzero(attached_wwnstr, sizeof (attached_wwnstr));
 920         (void) sprintf(attached_wwnstr, "w%016"PRIx64,
 921             attached_sas_wwn);
 922         if (ddi_prop_update_string(DDI_DEV_T_NONE, dip,
 923             SCSI_ADDR_PROP_ATTACHED_PORT, attached_wwnstr) !=
 924             DDI_PROP_SUCCESS) {
 925                 (void) ddi_prop_remove(DDI_DEV_T_NONE,
 926                     dip, SCSI_ADDR_PROP_ATTACHED_PORT);
 927                 return (DDI_FAILURE);
 928         }
 929 
 930         /* Create kstats for each phy on this iport */
 931 
 932         mptsas_create_phy_stats(mpt, iport, dip);
 933 
 934         /*
 935          * register sas hba iport with mdi (MPxIO/vhci)
 936          */
 937         if (mdi_phci_register(MDI_HCI_CLASS_SCSI,
 938             dip, 0) == MDI_SUCCESS) {
 939                 mpt->m_mpxio_enable = TRUE;
 940         }
 941         return (DDI_SUCCESS);
 942 }
 943 
 944 /*
 945  * Notes:
 946  *      Set up all device state and allocate data structures,
 947  *      mutexes, condition variables, etc. for device operation.
 948  *      Add interrupts needed.
 949  *      Return DDI_SUCCESS if device is ready, else return DDI_FAILURE.
 950  */
 951 static int
 952 mptsas_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
 953 {
 954         mptsas_t                *mpt = NULL;
 955         int                     instance, i, j;
 956         int                     doneq_thread_num;
 957         char                    intr_added = 0;
 958         char                    map_setup = 0;
 959         char                    config_setup = 0;
 960         char                    hba_attach_setup = 0;
 961         char                    smp_attach_setup = 0;
 962         char                    mutex_init_done = 0;
 963         char                    event_taskq_create = 0;
 964         char                    dr_taskq_create = 0;
 965         char                    doneq_thread_create = 0;
 966         scsi_hba_tran_t         *hba_tran;
 967         uint_t                  mem_bar = MEM_SPACE;
 968         int                     rval = DDI_FAILURE;
 969 
 970         /* CONSTCOND */
 971         ASSERT(NO_COMPETING_THREADS);
 972 
 973         if (scsi_hba_iport_unit_address(dip)) {
 974                 return (mptsas_iport_attach(dip, cmd));
 975         }
 976 
 977         switch (cmd) {
 978         case DDI_ATTACH:
 979                 break;
 980 
 981         case DDI_RESUME:
 982                 if ((hba_tran = ddi_get_driver_private(dip)) == NULL)
 983                         return (DDI_FAILURE);
 984 
 985                 mpt = TRAN2MPT(hba_tran);
 986 
 987                 if (!mpt) {
 988                         return (DDI_FAILURE);
 989                 }
 990 
 991                 /*
 992                  * Reset hardware and softc to "no outstanding commands"
 993                  * Note that a check condition can result on first command
 994                  * to a target.
 995                  */
 996                 mutex_enter(&mpt->m_mutex);
 997 
 998                 /*
 999                  * raise power.
1000                  */
1001                 if (mpt->m_options & MPTSAS_OPT_PM) {
1002                         mutex_exit(&mpt->m_mutex);
1003                         (void) pm_busy_component(dip, 0);
1004                         rval = pm_power_has_changed(dip, 0, PM_LEVEL_D0);
1005                         if (rval == DDI_SUCCESS) {
1006                                 mutex_enter(&mpt->m_mutex);
1007                         } else {
1008                                 /*
1009                                  * The pm_raise_power() call above failed,
1010                                  * and that can only occur if we were unable
1011                                  * to reset the hardware.  This is probably
1012                                  * due to unhealty hardware, and because
1013                                  * important filesystems(such as the root
1014                                  * filesystem) could be on the attached disks,
1015                                  * it would not be a good idea to continue,
1016                                  * as we won't be entirely certain we are
1017                                  * writing correct data.  So we panic() here
1018                                  * to not only prevent possible data corruption,
1019                                  * but to give developers or end users a hope
1020                                  * of identifying and correcting any problems.
1021                                  */
1022                                 fm_panic("mptsas could not reset hardware "
1023                                     "during resume");
1024                         }
1025                 }
1026 
1027                 mpt->m_suspended = 0;
1028 
1029                 /*
1030                  * Reinitialize ioc
1031                  */
1032                 mpt->m_softstate |= MPTSAS_SS_MSG_UNIT_RESET;
1033                 if (mptsas_init_chip(mpt, FALSE) == DDI_FAILURE) {
1034                         mutex_exit(&mpt->m_mutex);
1035                         if (mpt->m_options & MPTSAS_OPT_PM) {
1036                                 (void) pm_idle_component(dip, 0);
1037                         }
1038                         fm_panic("mptsas init chip fail during resume");
1039                 }
1040                 /*
1041                  * mptsas_update_driver_data needs interrupts so enable them
1042                  * first.
1043                  */
1044                 MPTSAS_ENABLE_INTR(mpt);
1045                 mptsas_update_driver_data(mpt);
1046 
1047                 /* start requests, if possible */
1048                 mptsas_restart_hba(mpt);
1049 
1050                 mutex_exit(&mpt->m_mutex);
1051 
1052                 /*
1053                  * Restart watch thread
1054                  */
1055                 mutex_enter(&mptsas_global_mutex);
1056                 if (mptsas_timeout_id == 0) {
1057                         mptsas_timeout_id = timeout(mptsas_watch, NULL,
1058                             mptsas_tick);
1059                         mptsas_timeouts_enabled = 1;
1060                 }
1061                 mutex_exit(&mptsas_global_mutex);
1062 
1063                 /* report idle status to pm framework */
1064                 if (mpt->m_options & MPTSAS_OPT_PM) {
1065                         (void) pm_idle_component(dip, 0);
1066                 }
1067 
1068                 return (DDI_SUCCESS);
1069 
1070         default:
1071                 return (DDI_FAILURE);
1072 
1073         }
1074 
1075         instance = ddi_get_instance(dip);
1076 
1077         /*
1078          * Allocate softc information.
1079          */
1080         if (ddi_soft_state_zalloc(mptsas_state, instance) != DDI_SUCCESS) {
1081                 mptsas_log(NULL, CE_WARN,
1082                     "mptsas%d: cannot allocate soft state", instance);
1083                 goto fail;
1084         }
1085 
1086         mpt = ddi_get_soft_state(mptsas_state, instance);
1087 
1088         if (mpt == NULL) {
1089                 mptsas_log(NULL, CE_WARN,
1090                     "mptsas%d: cannot get soft state", instance);
1091                 goto fail;
1092         }
1093 
1094         /* Indicate that we are 'sizeof (scsi_*(9S))' clean. */
1095         scsi_size_clean(dip);
1096 
1097         mpt->m_dip = dip;
1098         mpt->m_instance = instance;
1099 
1100         /* Make a per-instance copy of the structures */
1101         mpt->m_io_dma_attr = mptsas_dma_attrs64;
1102         mpt->m_msg_dma_attr = mptsas_dma_attrs;
1103         mpt->m_reg_acc_attr = mptsas_dev_attr;
1104         mpt->m_dev_acc_attr = mptsas_dev_attr;
1105 
1106         /*
1107          * Initialize FMA
1108          */
1109         mpt->m_fm_capabilities = ddi_getprop(DDI_DEV_T_ANY, mpt->m_dip,
1110             DDI_PROP_CANSLEEP | DDI_PROP_DONTPASS, "fm-capable",
1111             DDI_FM_EREPORT_CAPABLE | DDI_FM_ACCCHK_CAPABLE |
1112             DDI_FM_DMACHK_CAPABLE | DDI_FM_ERRCB_CAPABLE);
1113 
1114         mptsas_fm_init(mpt);
1115 
1116         if (mptsas_alloc_handshake_msg(mpt,
1117             sizeof (Mpi2SCSITaskManagementRequest_t)) == DDI_FAILURE) {
1118                 mptsas_log(mpt, CE_WARN, "cannot initialize handshake msg.");
1119                 goto fail;
1120         }
1121 
1122         /*
1123          * Setup configuration space
1124          */
1125         if (mptsas_config_space_init(mpt) == FALSE) {
1126                 mptsas_log(mpt, CE_WARN, "mptsas_config_space_init failed");
1127                 goto fail;
1128         }
1129         config_setup++;
1130 
1131         if (ddi_regs_map_setup(dip, mem_bar, (caddr_t *)&mpt->m_reg,
1132             0, 0, &mpt->m_reg_acc_attr, &mpt->m_datap) != DDI_SUCCESS) {
1133                 mptsas_log(mpt, CE_WARN, "map setup failed");
1134                 goto fail;
1135         }
1136         map_setup++;
1137 
1138         /*
1139          * A taskq is created for dealing with the event handler
1140          */
1141         if ((mpt->m_event_taskq = ddi_taskq_create(dip, "mptsas_event_taskq",
1142             1, TASKQ_DEFAULTPRI, 0)) == NULL) {
1143                 mptsas_log(mpt, CE_NOTE, "ddi_taskq_create failed");
1144                 goto fail;
1145         }
1146         event_taskq_create++;
1147 
1148         /*
1149          * A taskq is created for dealing with dr events
1150          */
1151         if ((mpt->m_dr_taskq = ddi_taskq_create(dip,
1152             "mptsas_dr_taskq",
1153             1, TASKQ_DEFAULTPRI, 0)) == NULL) {
1154                 mptsas_log(mpt, CE_NOTE, "ddi_taskq_create for discovery "
1155                     "failed");
1156                 goto fail;
1157         }
1158         dr_taskq_create++;
1159 
1160         mpt->m_doneq_thread_threshold = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1161             0, "mptsas_doneq_thread_threshold_prop", 10);
1162         mpt->m_doneq_length_threshold = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1163             0, "mptsas_doneq_length_threshold_prop", 8);
1164         mpt->m_doneq_thread_n = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1165             0, "mptsas_doneq_thread_n_prop", 8);
1166 
1167         if (mpt->m_doneq_thread_n) {
1168                 cv_init(&mpt->m_doneq_thread_cv, NULL, CV_DRIVER, NULL);
1169                 mutex_init(&mpt->m_doneq_mutex, NULL, MUTEX_DRIVER, NULL);
1170 
1171                 mutex_enter(&mpt->m_doneq_mutex);
1172                 mpt->m_doneq_thread_id =
1173                     kmem_zalloc(sizeof (mptsas_doneq_thread_list_t)
1174                     * mpt->m_doneq_thread_n, KM_SLEEP);
1175 
1176                 for (j = 0; j < mpt->m_doneq_thread_n; j++) {
1177                         cv_init(&mpt->m_doneq_thread_id[j].cv, NULL,
1178                             CV_DRIVER, NULL);
1179                         mutex_init(&mpt->m_doneq_thread_id[j].mutex, NULL,
1180                             MUTEX_DRIVER, NULL);
1181                         mutex_enter(&mpt->m_doneq_thread_id[j].mutex);
1182                         mpt->m_doneq_thread_id[j].flag |=
1183                             MPTSAS_DONEQ_THREAD_ACTIVE;
1184                         mpt->m_doneq_thread_id[j].arg.mpt = mpt;
1185                         mpt->m_doneq_thread_id[j].arg.t = j;
1186                         mpt->m_doneq_thread_id[j].threadp =
1187                             thread_create(NULL, 0, mptsas_doneq_thread,
1188                             &mpt->m_doneq_thread_id[j].arg,
1189                             0, &p0, TS_RUN, minclsyspri);
1190                         mpt->m_doneq_thread_id[j].donetail =
1191                             &mpt->m_doneq_thread_id[j].doneq;
1192                         mutex_exit(&mpt->m_doneq_thread_id[j].mutex);
1193                 }
1194                 mutex_exit(&mpt->m_doneq_mutex);
1195                 doneq_thread_create++;
1196         }
1197 
1198         /* Initialize mutex used in interrupt handler */
1199         mutex_init(&mpt->m_mutex, NULL, MUTEX_DRIVER,
1200             DDI_INTR_PRI(mpt->m_intr_pri));
1201         mutex_init(&mpt->m_passthru_mutex, NULL, MUTEX_DRIVER, NULL);
1202         mutex_init(&mpt->m_intr_mutex, NULL, MUTEX_DRIVER,
1203             DDI_INTR_PRI(mpt->m_intr_pri));
1204         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
1205                 mutex_init(&mpt->m_phy_info[i].smhba_info.phy_mutex,
1206                     NULL, MUTEX_DRIVER,
1207                     DDI_INTR_PRI(mpt->m_intr_pri));
1208         }
1209 
1210         cv_init(&mpt->m_cv, NULL, CV_DRIVER, NULL);
1211         cv_init(&mpt->m_passthru_cv, NULL, CV_DRIVER, NULL);
1212         cv_init(&mpt->m_fw_cv, NULL, CV_DRIVER, NULL);
1213         cv_init(&mpt->m_config_cv, NULL, CV_DRIVER, NULL);
1214         cv_init(&mpt->m_fw_diag_cv, NULL, CV_DRIVER, NULL);
1215         mutex_init_done++;
1216 
1217         /*
1218          * Disable hardware interrupt since we're not ready to
1219          * handle it yet.
1220          */
1221         MPTSAS_DISABLE_INTR(mpt);
1222         if (mptsas_register_intrs(mpt) == FALSE)
1223                 goto fail;
1224         intr_added++;
1225 
1226         mutex_enter(&mpt->m_mutex);
1227         /*
1228          * Initialize power management component
1229          */
1230         if (mpt->m_options & MPTSAS_OPT_PM) {
1231                 if (mptsas_init_pm(mpt)) {
1232                         mutex_exit(&mpt->m_mutex);
1233                         mptsas_log(mpt, CE_WARN, "mptsas pm initialization "
1234                             "failed");
1235                         goto fail;
1236                 }
1237         }
1238 
1239         /*
1240          * Initialize chip using Message Unit Reset, if allowed
1241          */
1242         mpt->m_softstate |= MPTSAS_SS_MSG_UNIT_RESET;
1243         if (mptsas_init_chip(mpt, TRUE) == DDI_FAILURE) {
1244                 mutex_exit(&mpt->m_mutex);
1245                 mptsas_log(mpt, CE_WARN, "mptsas chip initialization failed");
1246                 goto fail;
1247         }
1248 
1249         /*
1250          * Fill in the phy_info structure and get the base WWID
1251          */
1252         if (mptsas_get_manufacture_page5(mpt) == DDI_FAILURE) {
1253                 mptsas_log(mpt, CE_WARN,
1254                     "mptsas_get_manufacture_page5 failed!");
1255                 goto fail;
1256         }
1257 
1258         if (mptsas_get_sas_io_unit_page_hndshk(mpt)) {
1259                 mptsas_log(mpt, CE_WARN,
1260                     "mptsas_get_sas_io_unit_page_hndshk failed!");
1261                 goto fail;
1262         }
1263 
1264         if (mptsas_get_manufacture_page0(mpt) == DDI_FAILURE) {
1265                 mptsas_log(mpt, CE_WARN,
1266                     "mptsas_get_manufacture_page0 failed!");
1267                 goto fail;
1268         }
1269 
1270         mutex_exit(&mpt->m_mutex);
1271 
1272         /*
1273          * Register the iport for multiple port HBA
1274          */
1275         mptsas_iport_register(mpt);
1276 
1277         /*
1278          * initialize SCSI HBA transport structure
1279          */
1280         if (mptsas_hba_setup(mpt) == FALSE)
1281                 goto fail;
1282         hba_attach_setup++;
1283 
1284         if (mptsas_smp_setup(mpt) == FALSE)
1285                 goto fail;
1286         smp_attach_setup++;
1287 
1288         if (mptsas_cache_create(mpt) == FALSE)
1289                 goto fail;
1290 
1291         mpt->m_scsi_reset_delay      = ddi_prop_get_int(DDI_DEV_T_ANY,
1292             dip, 0, "scsi-reset-delay", SCSI_DEFAULT_RESET_DELAY);
1293         if (mpt->m_scsi_reset_delay == 0) {
1294                 mptsas_log(mpt, CE_NOTE,
1295                     "scsi_reset_delay of 0 is not recommended,"
1296                     " resetting to SCSI_DEFAULT_RESET_DELAY\n");
1297                 mpt->m_scsi_reset_delay = SCSI_DEFAULT_RESET_DELAY;
1298         }
1299 
1300         /*
1301          * Initialize the wait and done FIFO queue
1302          */
1303         mpt->m_donetail = &mpt->m_doneq;
1304         mpt->m_waitqtail = &mpt->m_waitq;
1305 
1306         /*
1307          * ioc cmd queue initialize
1308          */
1309         mpt->m_ioc_event_cmdtail = &mpt->m_ioc_event_cmdq;
1310         mpt->m_dev_handle = 0xFFFF;
1311 
1312         MPTSAS_ENABLE_INTR(mpt);
1313 
1314         /*
1315          * enable event notification
1316          */
1317         mutex_enter(&mpt->m_mutex);
1318         if (mptsas_ioc_enable_event_notification(mpt)) {
1319                 mutex_exit(&mpt->m_mutex);
1320                 goto fail;
1321         }
1322         mutex_exit(&mpt->m_mutex);
1323 
1324         /*
1325          * Initialize PHY info for smhba
1326          */
1327         if (mptsas_smhba_setup(mpt)) {
1328                 mptsas_log(mpt, CE_WARN, "mptsas phy initialization "
1329                     "failed");
1330                 goto fail;
1331         }
1332 
1333         /* Check all dma handles allocated in attach */
1334         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl)
1335             != DDI_SUCCESS) ||
1336             (mptsas_check_dma_handle(mpt->m_dma_reply_frame_hdl)
1337             != DDI_SUCCESS) ||
1338             (mptsas_check_dma_handle(mpt->m_dma_free_queue_hdl)
1339             != DDI_SUCCESS) ||
1340             (mptsas_check_dma_handle(mpt->m_dma_post_queue_hdl)
1341             != DDI_SUCCESS) ||
1342             (mptsas_check_dma_handle(mpt->m_hshk_dma_hdl)
1343             != DDI_SUCCESS)) {
1344                 goto fail;
1345         }
1346 
1347         /* Check all acc handles allocated in attach */
1348         if ((mptsas_check_acc_handle(mpt->m_datap) != DDI_SUCCESS) ||
1349             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl)
1350             != DDI_SUCCESS) ||
1351             (mptsas_check_acc_handle(mpt->m_acc_reply_frame_hdl)
1352             != DDI_SUCCESS) ||
1353             (mptsas_check_acc_handle(mpt->m_acc_free_queue_hdl)
1354             != DDI_SUCCESS) ||
1355             (mptsas_check_acc_handle(mpt->m_acc_post_queue_hdl)
1356             != DDI_SUCCESS) ||
1357             (mptsas_check_acc_handle(mpt->m_hshk_acc_hdl)
1358             != DDI_SUCCESS) ||
1359             (mptsas_check_acc_handle(mpt->m_config_handle)
1360             != DDI_SUCCESS)) {
1361                 goto fail;
1362         }
1363 
1364         /*
1365          * After this point, we are not going to fail the attach.
1366          */
1367         /*
1368          * used for mptsas_watch
1369          */
1370         mptsas_list_add(mpt);
1371 
1372         mutex_enter(&mptsas_global_mutex);
1373         if (mptsas_timeouts_enabled == 0) {
1374                 mptsas_scsi_watchdog_tick = ddi_prop_get_int(DDI_DEV_T_ANY,
1375                     dip, 0, "scsi-watchdog-tick", DEFAULT_WD_TICK);
1376 
1377                 mptsas_tick = mptsas_scsi_watchdog_tick *
1378                     drv_usectohz((clock_t)1000000);
1379 
1380                 mptsas_timeout_id = timeout(mptsas_watch, NULL, mptsas_tick);
1381                 mptsas_timeouts_enabled = 1;
1382         }
1383         mutex_exit(&mptsas_global_mutex);
1384 
1385         /* Print message of HBA present */
1386         ddi_report_dev(dip);
1387 
1388         /* report idle status to pm framework */
1389         if (mpt->m_options & MPTSAS_OPT_PM) {
1390                 (void) pm_idle_component(dip, 0);
1391         }
1392 
1393         return (DDI_SUCCESS);
1394 
1395 fail:
1396         mptsas_log(mpt, CE_WARN, "attach failed");
1397         mptsas_fm_ereport(mpt, DDI_FM_DEVICE_NO_RESPONSE);
1398         ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_LOST);
1399         if (mpt) {
1400                 mutex_enter(&mptsas_global_mutex);
1401 
1402                 if (mptsas_timeout_id && (mptsas_head == NULL)) {
1403                         timeout_id_t tid = mptsas_timeout_id;
1404                         mptsas_timeouts_enabled = 0;
1405                         mptsas_timeout_id = 0;
1406                         mutex_exit(&mptsas_global_mutex);
1407                         (void) untimeout(tid);
1408                         mutex_enter(&mptsas_global_mutex);
1409                 }
1410                 mutex_exit(&mptsas_global_mutex);
1411                 /* deallocate in reverse order */
1412                 mptsas_cache_destroy(mpt);
1413 
1414                 if (smp_attach_setup) {
1415                         mptsas_smp_teardown(mpt);
1416                 }
1417                 if (hba_attach_setup) {
1418                         mptsas_hba_teardown(mpt);
1419                 }
1420 
1421                 if (mpt->m_active) {
1422                         mptsas_hash_uninit(&mpt->m_active->m_smptbl,
1423                             sizeof (mptsas_smp_t));
1424                         mptsas_hash_uninit(&mpt->m_active->m_tgttbl,
1425                             sizeof (mptsas_target_t));
1426                         mptsas_free_active_slots(mpt);
1427                 }
1428                 if (intr_added) {
1429                         mptsas_unregister_intrs(mpt);
1430                 }
1431 
1432                 if (doneq_thread_create) {
1433                         mutex_enter(&mpt->m_doneq_mutex);
1434                         doneq_thread_num = mpt->m_doneq_thread_n;
1435                         for (j = 0; j < mpt->m_doneq_thread_n; j++) {
1436                                 mutex_enter(&mpt->m_doneq_thread_id[j].mutex);
1437                                 mpt->m_doneq_thread_id[j].flag &=
1438                                     (~MPTSAS_DONEQ_THREAD_ACTIVE);
1439                                 cv_signal(&mpt->m_doneq_thread_id[j].cv);
1440                                 mutex_exit(&mpt->m_doneq_thread_id[j].mutex);
1441                         }
1442                         while (mpt->m_doneq_thread_n) {
1443                                 cv_wait(&mpt->m_doneq_thread_cv,
1444                                     &mpt->m_doneq_mutex);
1445                         }
1446                         for (j = 0; j < doneq_thread_num; j++) {
1447                                 cv_destroy(&mpt->m_doneq_thread_id[j].cv);
1448                                 mutex_destroy(&mpt->m_doneq_thread_id[j].mutex);
1449                         }
1450                         kmem_free(mpt->m_doneq_thread_id,
1451                             sizeof (mptsas_doneq_thread_list_t)
1452                             * doneq_thread_num);
1453                         mutex_exit(&mpt->m_doneq_mutex);
1454                         cv_destroy(&mpt->m_doneq_thread_cv);
1455                         mutex_destroy(&mpt->m_doneq_mutex);
1456                 }
1457                 if (event_taskq_create) {
1458                         ddi_taskq_destroy(mpt->m_event_taskq);
1459                 }
1460                 if (dr_taskq_create) {
1461                         ddi_taskq_destroy(mpt->m_dr_taskq);
1462                 }
1463                 if (mutex_init_done) {
1464                         mutex_destroy(&mpt->m_intr_mutex);
1465                         mutex_destroy(&mpt->m_passthru_mutex);
1466                         mutex_destroy(&mpt->m_mutex);
1467                         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
1468                                 mutex_destroy(
1469                                     &mpt->m_phy_info[i].smhba_info.phy_mutex);
1470                         }
1471                         cv_destroy(&mpt->m_cv);
1472                         cv_destroy(&mpt->m_passthru_cv);
1473                         cv_destroy(&mpt->m_fw_cv);
1474                         cv_destroy(&mpt->m_config_cv);
1475                         cv_destroy(&mpt->m_fw_diag_cv);
1476                 }
1477 
1478                 if (map_setup) {
1479                         mptsas_cfg_fini(mpt);
1480                 }
1481                 if (config_setup) {
1482                         mptsas_config_space_fini(mpt);
1483                 }
1484                 mptsas_free_handshake_msg(mpt);
1485                 mptsas_hba_fini(mpt);
1486 
1487                 mptsas_fm_fini(mpt);
1488                 ddi_soft_state_free(mptsas_state, instance);
1489                 ddi_prop_remove_all(dip);
1490         }
1491         return (DDI_FAILURE);
1492 }
1493 
1494 static int
1495 mptsas_suspend(dev_info_t *devi)
1496 {
1497         mptsas_t        *mpt, *g;
1498         scsi_hba_tran_t *tran;
1499 
1500         if (scsi_hba_iport_unit_address(devi)) {
1501                 return (DDI_SUCCESS);
1502         }
1503 
1504         if ((tran = ddi_get_driver_private(devi)) == NULL)
1505                 return (DDI_SUCCESS);
1506 
1507         mpt = TRAN2MPT(tran);
1508         if (!mpt) {
1509                 return (DDI_SUCCESS);
1510         }
1511 
1512         mutex_enter(&mpt->m_mutex);
1513 
1514         if (mpt->m_suspended++) {
1515                 mutex_exit(&mpt->m_mutex);
1516                 return (DDI_SUCCESS);
1517         }
1518 
1519         /*
1520          * Cancel timeout threads for this mpt
1521          */
1522         if (mpt->m_quiesce_timeid) {
1523                 timeout_id_t tid = mpt->m_quiesce_timeid;
1524                 mpt->m_quiesce_timeid = 0;
1525                 mutex_exit(&mpt->m_mutex);
1526                 (void) untimeout(tid);
1527                 mutex_enter(&mpt->m_mutex);
1528         }
1529 
1530         if (mpt->m_restart_cmd_timeid) {
1531                 timeout_id_t tid = mpt->m_restart_cmd_timeid;
1532                 mpt->m_restart_cmd_timeid = 0;
1533                 mutex_exit(&mpt->m_mutex);
1534                 (void) untimeout(tid);
1535                 mutex_enter(&mpt->m_mutex);
1536         }
1537 
1538         mutex_exit(&mpt->m_mutex);
1539 
1540         (void) pm_idle_component(mpt->m_dip, 0);
1541 
1542         /*
1543          * Cancel watch threads if all mpts suspended
1544          */
1545         rw_enter(&mptsas_global_rwlock, RW_WRITER);
1546         for (g = mptsas_head; g != NULL; g = g->m_next) {
1547                 if (!g->m_suspended)
1548                         break;
1549         }
1550         rw_exit(&mptsas_global_rwlock);
1551 
1552         mutex_enter(&mptsas_global_mutex);
1553         if (g == NULL) {
1554                 timeout_id_t tid;
1555 
1556                 mptsas_timeouts_enabled = 0;
1557                 if (mptsas_timeout_id) {
1558                         tid = mptsas_timeout_id;
1559                         mptsas_timeout_id = 0;
1560                         mutex_exit(&mptsas_global_mutex);
1561                         (void) untimeout(tid);
1562                         mutex_enter(&mptsas_global_mutex);
1563                 }
1564                 if (mptsas_reset_watch) {
1565                         tid = mptsas_reset_watch;
1566                         mptsas_reset_watch = 0;
1567                         mutex_exit(&mptsas_global_mutex);
1568                         (void) untimeout(tid);
1569                         mutex_enter(&mptsas_global_mutex);
1570                 }
1571         }
1572         mutex_exit(&mptsas_global_mutex);
1573 
1574         mutex_enter(&mpt->m_mutex);
1575 
1576         /*
1577          * If this mpt is not in full power(PM_LEVEL_D0), just return.
1578          */
1579         if ((mpt->m_options & MPTSAS_OPT_PM) &&
1580             (mpt->m_power_level != PM_LEVEL_D0)) {
1581                 mutex_exit(&mpt->m_mutex);
1582                 return (DDI_SUCCESS);
1583         }
1584 
1585         /* Disable HBA interrupts in hardware */
1586         MPTSAS_DISABLE_INTR(mpt);
1587         /*
1588          * Send RAID action system shutdown to sync IR
1589          */
1590         mptsas_raid_action_system_shutdown(mpt);
1591 
1592         mutex_exit(&mpt->m_mutex);
1593 
1594         /* drain the taskq */
1595         ddi_taskq_wait(mpt->m_event_taskq);
1596         ddi_taskq_wait(mpt->m_dr_taskq);
1597 
1598         return (DDI_SUCCESS);
1599 }
1600 
1601 #ifdef  __sparc
1602 /*ARGSUSED*/
1603 static int
1604 mptsas_reset(dev_info_t *devi, ddi_reset_cmd_t cmd)
1605 {
1606         mptsas_t        *mpt;
1607         scsi_hba_tran_t *tran;
1608 
1609         /*
1610          * If this call is for iport, just return.
1611          */
1612         if (scsi_hba_iport_unit_address(devi))
1613                 return (DDI_SUCCESS);
1614 
1615         if ((tran = ddi_get_driver_private(devi)) == NULL)
1616                 return (DDI_SUCCESS);
1617 
1618         if ((mpt = TRAN2MPT(tran)) == NULL)
1619                 return (DDI_SUCCESS);
1620 
1621         /*
1622          * Send RAID action system shutdown to sync IR.  Disable HBA
1623          * interrupts in hardware first.
1624          */
1625         MPTSAS_DISABLE_INTR(mpt);
1626         mptsas_raid_action_system_shutdown(mpt);
1627 
1628         return (DDI_SUCCESS);
1629 }
1630 #else /* __sparc */
1631 /*
1632  * quiesce(9E) entry point.
1633  *
1634  * This function is called when the system is single-threaded at high
1635  * PIL with preemption disabled. Therefore, this function must not be
1636  * blocked.
1637  *
1638  * This function returns DDI_SUCCESS on success, or DDI_FAILURE on failure.
1639  * DDI_FAILURE indicates an error condition and should almost never happen.
1640  */
1641 static int
1642 mptsas_quiesce(dev_info_t *devi)
1643 {
1644         mptsas_t        *mpt;
1645         scsi_hba_tran_t *tran;
1646 
1647         /*
1648          * If this call is for iport, just return.
1649          */
1650         if (scsi_hba_iport_unit_address(devi))
1651                 return (DDI_SUCCESS);
1652 
1653         if ((tran = ddi_get_driver_private(devi)) == NULL)
1654                 return (DDI_SUCCESS);
1655 
1656         if ((mpt = TRAN2MPT(tran)) == NULL)
1657                 return (DDI_SUCCESS);
1658 
1659         /* Disable HBA interrupts in hardware */
1660         MPTSAS_DISABLE_INTR(mpt);
1661         /* Send RAID action system shutdonw to sync IR */
1662         mptsas_raid_action_system_shutdown(mpt);
1663 
1664         return (DDI_SUCCESS);
1665 }
1666 #endif  /* __sparc */
1667 
1668 /*
1669  * detach(9E).  Remove all device allocations and system resources;
1670  * disable device interrupts.
1671  * Return DDI_SUCCESS if done; DDI_FAILURE if there's a problem.
1672  */
1673 static int
1674 mptsas_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1675 {
1676         /* CONSTCOND */
1677         ASSERT(NO_COMPETING_THREADS);
1678         NDBG0(("mptsas_detach: dip=0x%p cmd=0x%p", (void *)devi, (void *)cmd));
1679 
1680         switch (cmd) {
1681         case DDI_DETACH:
1682                 return (mptsas_do_detach(devi));
1683 
1684         case DDI_SUSPEND:
1685                 return (mptsas_suspend(devi));
1686 
1687         default:
1688                 return (DDI_FAILURE);
1689         }
1690         /* NOTREACHED */
1691 }
1692 
1693 static int
1694 mptsas_do_detach(dev_info_t *dip)
1695 {
1696         mptsas_t        *mpt;
1697         scsi_hba_tran_t *tran;
1698         int             circ = 0;
1699         int             circ1 = 0;
1700         mdi_pathinfo_t  *pip = NULL;
1701         int             i;
1702         int             doneq_thread_num = 0;
1703 
1704         NDBG0(("mptsas_do_detach: dip=0x%p", (void *)dip));
1705 
1706         if ((tran = ndi_flavorv_get(dip, SCSA_FLAVOR_SCSI_DEVICE)) == NULL)
1707                 return (DDI_FAILURE);
1708 
1709         mpt = TRAN2MPT(tran);
1710         if (!mpt) {
1711                 return (DDI_FAILURE);
1712         }
1713         /*
1714          * Still have pathinfo child, should not detach mpt driver
1715          */
1716         if (scsi_hba_iport_unit_address(dip)) {
1717                 if (mpt->m_mpxio_enable) {
1718                         /*
1719                          * MPxIO enabled for the iport
1720                          */
1721                         ndi_devi_enter(scsi_vhci_dip, &circ1);
1722                         ndi_devi_enter(dip, &circ);
1723                         while (pip = mdi_get_next_client_path(dip, NULL)) {
1724                                 if (mdi_pi_free(pip, 0) == MDI_SUCCESS) {
1725                                         continue;
1726                                 }
1727                                 ndi_devi_exit(dip, circ);
1728                                 ndi_devi_exit(scsi_vhci_dip, circ1);
1729                                 NDBG12(("detach failed because of "
1730                                     "outstanding path info"));
1731                                 return (DDI_FAILURE);
1732                         }
1733                         ndi_devi_exit(dip, circ);
1734                         ndi_devi_exit(scsi_vhci_dip, circ1);
1735                         (void) mdi_phci_unregister(dip, 0);
1736                 }
1737 
1738                 ddi_prop_remove_all(dip);
1739 
1740                 return (DDI_SUCCESS);
1741         }
1742 
1743         /* Make sure power level is D0 before accessing registers */
1744         if (mpt->m_options & MPTSAS_OPT_PM) {
1745                 (void) pm_busy_component(dip, 0);
1746                 if (mpt->m_power_level != PM_LEVEL_D0) {
1747                         if (pm_raise_power(dip, 0, PM_LEVEL_D0) !=
1748                             DDI_SUCCESS) {
1749                                 mptsas_log(mpt, CE_WARN,
1750                                     "mptsas%d: Raise power request failed.",
1751                                     mpt->m_instance);
1752                                 (void) pm_idle_component(dip, 0);
1753                                 return (DDI_FAILURE);
1754                         }
1755                 }
1756         }
1757 
1758         /*
1759          * Send RAID action system shutdown to sync IR.  After action, send a
1760          * Message Unit Reset. Since after that DMA resource will be freed,
1761          * set ioc to READY state will avoid HBA initiated DMA operation.
1762          */
1763         mutex_enter(&mpt->m_mutex);
1764         MPTSAS_DISABLE_INTR(mpt);
1765         mptsas_raid_action_system_shutdown(mpt);
1766         mpt->m_softstate |= MPTSAS_SS_MSG_UNIT_RESET;
1767         (void) mptsas_ioc_reset(mpt, FALSE);
1768         mutex_exit(&mpt->m_mutex);
1769         mptsas_rem_intrs(mpt);
1770         ddi_taskq_destroy(mpt->m_event_taskq);
1771         ddi_taskq_destroy(mpt->m_dr_taskq);
1772 
1773         if (mpt->m_doneq_thread_n) {
1774                 mutex_enter(&mpt->m_doneq_mutex);
1775                 doneq_thread_num = mpt->m_doneq_thread_n;
1776                 for (i = 0; i < mpt->m_doneq_thread_n; i++) {
1777                         mutex_enter(&mpt->m_doneq_thread_id[i].mutex);
1778                         mpt->m_doneq_thread_id[i].flag &=
1779                             (~MPTSAS_DONEQ_THREAD_ACTIVE);
1780                         cv_signal(&mpt->m_doneq_thread_id[i].cv);
1781                         mutex_exit(&mpt->m_doneq_thread_id[i].mutex);
1782                 }
1783                 while (mpt->m_doneq_thread_n) {
1784                         cv_wait(&mpt->m_doneq_thread_cv,
1785                             &mpt->m_doneq_mutex);
1786                 }
1787                 for (i = 0;  i < doneq_thread_num; i++) {
1788                         cv_destroy(&mpt->m_doneq_thread_id[i].cv);
1789                         mutex_destroy(&mpt->m_doneq_thread_id[i].mutex);
1790                 }
1791                 kmem_free(mpt->m_doneq_thread_id,
1792                     sizeof (mptsas_doneq_thread_list_t)
1793                     * doneq_thread_num);
1794                 mutex_exit(&mpt->m_doneq_mutex);
1795                 cv_destroy(&mpt->m_doneq_thread_cv);
1796                 mutex_destroy(&mpt->m_doneq_mutex);
1797         }
1798 
1799         scsi_hba_reset_notify_tear_down(mpt->m_reset_notify_listf);
1800 
1801         mptsas_list_del(mpt);
1802 
1803         /*
1804          * Cancel timeout threads for this mpt
1805          */
1806         mutex_enter(&mpt->m_mutex);
1807         if (mpt->m_quiesce_timeid) {
1808                 timeout_id_t tid = mpt->m_quiesce_timeid;
1809                 mpt->m_quiesce_timeid = 0;
1810                 mutex_exit(&mpt->m_mutex);
1811                 (void) untimeout(tid);
1812                 mutex_enter(&mpt->m_mutex);
1813         }
1814 
1815         if (mpt->m_restart_cmd_timeid) {
1816                 timeout_id_t tid = mpt->m_restart_cmd_timeid;
1817                 mpt->m_restart_cmd_timeid = 0;
1818                 mutex_exit(&mpt->m_mutex);
1819                 (void) untimeout(tid);
1820                 mutex_enter(&mpt->m_mutex);
1821         }
1822 
1823         mutex_exit(&mpt->m_mutex);
1824 
1825         /*
1826          * last mpt? ... if active, CANCEL watch threads.
1827          */
1828         mutex_enter(&mptsas_global_mutex);
1829         if (mptsas_head == NULL) {
1830                 timeout_id_t tid;
1831                 /*
1832                  * Clear mptsas_timeouts_enable so that the watch thread
1833                  * gets restarted on DDI_ATTACH
1834                  */
1835                 mptsas_timeouts_enabled = 0;
1836                 if (mptsas_timeout_id) {
1837                         tid = mptsas_timeout_id;
1838                         mptsas_timeout_id = 0;
1839                         mutex_exit(&mptsas_global_mutex);
1840                         (void) untimeout(tid);
1841                         mutex_enter(&mptsas_global_mutex);
1842                 }
1843                 if (mptsas_reset_watch) {
1844                         tid = mptsas_reset_watch;
1845                         mptsas_reset_watch = 0;
1846                         mutex_exit(&mptsas_global_mutex);
1847                         (void) untimeout(tid);
1848                         mutex_enter(&mptsas_global_mutex);
1849                 }
1850         }
1851         mutex_exit(&mptsas_global_mutex);
1852 
1853         /*
1854          * Delete Phy stats
1855          */
1856         mptsas_destroy_phy_stats(mpt);
1857 
1858         /*
1859          * Delete nt_active.
1860          */
1861         mutex_enter(&mpt->m_mutex);
1862         mptsas_hash_uninit(&mpt->m_active->m_tgttbl, sizeof (mptsas_target_t));
1863         mptsas_hash_uninit(&mpt->m_active->m_smptbl, sizeof (mptsas_smp_t));
1864         mptsas_free_active_slots(mpt);
1865         mutex_exit(&mpt->m_mutex);
1866 
1867         /* deallocate everything that was allocated in mptsas_attach */
1868         mptsas_cache_destroy(mpt);
1869 
1870         mptsas_hba_fini(mpt);
1871         mptsas_cfg_fini(mpt);
1872 
1873         /* Lower the power informing PM Framework */
1874         if (mpt->m_options & MPTSAS_OPT_PM) {
1875                 if (pm_lower_power(dip, 0, PM_LEVEL_D3) != DDI_SUCCESS)
1876                         mptsas_log(mpt, CE_WARN,
1877                             "!mptsas%d: Lower power request failed "
1878                             "during detach, ignoring.",
1879                             mpt->m_instance);
1880         }
1881 
1882         mutex_destroy(&mpt->m_intr_mutex);
1883         mutex_destroy(&mpt->m_passthru_mutex);
1884         mutex_destroy(&mpt->m_mutex);
1885         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
1886                 mutex_destroy(&mpt->m_phy_info[i].smhba_info.phy_mutex);
1887         }
1888         cv_destroy(&mpt->m_cv);
1889         cv_destroy(&mpt->m_passthru_cv);
1890         cv_destroy(&mpt->m_fw_cv);
1891         cv_destroy(&mpt->m_config_cv);
1892         cv_destroy(&mpt->m_fw_diag_cv);
1893 
1894 
1895         mptsas_smp_teardown(mpt);
1896         mptsas_hba_teardown(mpt);
1897 
1898         mptsas_config_space_fini(mpt);
1899 
1900         mptsas_free_handshake_msg(mpt);
1901 
1902         mptsas_fm_fini(mpt);
1903         ddi_soft_state_free(mptsas_state, ddi_get_instance(dip));
1904         ddi_prop_remove_all(dip);
1905 
1906         return (DDI_SUCCESS);
1907 }
1908 
1909 static void
1910 mptsas_list_add(mptsas_t *mpt)
1911 {
1912         rw_enter(&mptsas_global_rwlock, RW_WRITER);
1913 
1914         if (mptsas_head == NULL) {
1915                 mptsas_head = mpt;
1916         } else {
1917                 mptsas_tail->m_next = mpt;
1918         }
1919         mptsas_tail = mpt;
1920         rw_exit(&mptsas_global_rwlock);
1921 }
1922 
1923 static void
1924 mptsas_list_del(mptsas_t *mpt)
1925 {
1926         mptsas_t *m;
1927         /*
1928          * Remove device instance from the global linked list
1929          */
1930         rw_enter(&mptsas_global_rwlock, RW_WRITER);
1931         if (mptsas_head == mpt) {
1932                 m = mptsas_head = mpt->m_next;
1933         } else {
1934                 for (m = mptsas_head; m != NULL; m = m->m_next) {
1935                         if (m->m_next == mpt) {
1936                                 m->m_next = mpt->m_next;
1937                                 break;
1938                         }
1939                 }
1940                 if (m == NULL) {
1941                         mptsas_log(mpt, CE_PANIC, "Not in softc list!");
1942                 }
1943         }
1944 
1945         if (mptsas_tail == mpt) {
1946                 mptsas_tail = m;
1947         }
1948         rw_exit(&mptsas_global_rwlock);
1949 }
1950 
1951 static int
1952 mptsas_alloc_handshake_msg(mptsas_t *mpt, size_t alloc_size)
1953 {
1954         ddi_dma_attr_t  task_dma_attrs;
1955 
1956         task_dma_attrs = mpt->m_msg_dma_attr;
1957         task_dma_attrs.dma_attr_sgllen = 1;
1958         task_dma_attrs.dma_attr_granular = (uint32_t)(alloc_size);
1959 
1960         /* allocate Task Management ddi_dma resources */
1961         if (mptsas_dma_addr_create(mpt, task_dma_attrs,
1962             &mpt->m_hshk_dma_hdl, &mpt->m_hshk_acc_hdl, &mpt->m_hshk_memp,
1963             alloc_size, NULL) == FALSE) {
1964                 return (DDI_FAILURE);
1965         }
1966         mpt->m_hshk_dma_size = alloc_size;
1967 
1968         return (DDI_SUCCESS);
1969 }
1970 
1971 static void
1972 mptsas_free_handshake_msg(mptsas_t *mpt)
1973 {
1974         mptsas_dma_addr_destroy(&mpt->m_hshk_dma_hdl, &mpt->m_hshk_acc_hdl);
1975         mpt->m_hshk_dma_size = 0;
1976 }
1977 
1978 static int
1979 mptsas_hba_setup(mptsas_t *mpt)
1980 {
1981         scsi_hba_tran_t         *hba_tran;
1982         int                     tran_flags;
1983 
1984         /* Allocate a transport structure */
1985         hba_tran = mpt->m_tran = scsi_hba_tran_alloc(mpt->m_dip,
1986             SCSI_HBA_CANSLEEP);
1987         ASSERT(mpt->m_tran != NULL);
1988 
1989         hba_tran->tran_hba_private   = mpt;
1990         hba_tran->tran_tgt_private   = NULL;
1991 
1992         hba_tran->tran_tgt_init              = mptsas_scsi_tgt_init;
1993         hba_tran->tran_tgt_free              = mptsas_scsi_tgt_free;
1994 
1995         hba_tran->tran_start         = mptsas_scsi_start;
1996         hba_tran->tran_reset         = mptsas_scsi_reset;
1997         hba_tran->tran_abort         = mptsas_scsi_abort;
1998         hba_tran->tran_getcap                = mptsas_scsi_getcap;
1999         hba_tran->tran_setcap                = mptsas_scsi_setcap;
2000         hba_tran->tran_init_pkt              = mptsas_scsi_init_pkt;
2001         hba_tran->tran_destroy_pkt   = mptsas_scsi_destroy_pkt;
2002 
2003         hba_tran->tran_dmafree               = mptsas_scsi_dmafree;
2004         hba_tran->tran_sync_pkt              = mptsas_scsi_sync_pkt;
2005         hba_tran->tran_reset_notify  = mptsas_scsi_reset_notify;
2006 
2007         hba_tran->tran_get_bus_addr  = mptsas_get_bus_addr;
2008         hba_tran->tran_get_name              = mptsas_get_name;
2009 
2010         hba_tran->tran_quiesce               = mptsas_scsi_quiesce;
2011         hba_tran->tran_unquiesce     = mptsas_scsi_unquiesce;
2012         hba_tran->tran_bus_reset     = NULL;
2013 
2014         hba_tran->tran_add_eventcall = NULL;
2015         hba_tran->tran_get_eventcookie       = NULL;
2016         hba_tran->tran_post_event    = NULL;
2017         hba_tran->tran_remove_eventcall      = NULL;
2018 
2019         hba_tran->tran_bus_config    = mptsas_bus_config;
2020 
2021         hba_tran->tran_interconnect_type = INTERCONNECT_SAS;
2022 
2023         /*
2024          * All children of the HBA are iports. We need tran was cloned.
2025          * So we pass the flags to SCSA. SCSI_HBA_TRAN_CLONE will be
2026          * inherited to iport's tran vector.
2027          */
2028         tran_flags = (SCSI_HBA_HBA | SCSI_HBA_TRAN_CLONE);
2029 
2030         if (scsi_hba_attach_setup(mpt->m_dip, &mpt->m_msg_dma_attr,
2031             hba_tran, tran_flags) != DDI_SUCCESS) {
2032                 mptsas_log(mpt, CE_WARN, "hba attach setup failed");
2033                 scsi_hba_tran_free(hba_tran);
2034                 mpt->m_tran = NULL;
2035                 return (FALSE);
2036         }
2037         return (TRUE);
2038 }
2039 
2040 static void
2041 mptsas_hba_teardown(mptsas_t *mpt)
2042 {
2043         (void) scsi_hba_detach(mpt->m_dip);
2044         if (mpt->m_tran != NULL) {
2045                 scsi_hba_tran_free(mpt->m_tran);
2046                 mpt->m_tran = NULL;
2047         }
2048 }
2049 
2050 static void
2051 mptsas_iport_register(mptsas_t *mpt)
2052 {
2053         int i, j;
2054         mptsas_phymask_t        mask = 0x0;
2055         /*
2056          * initial value of mask is 0
2057          */
2058         mutex_enter(&mpt->m_mutex);
2059         for (i = 0; i < mpt->m_num_phys; i++) {
2060                 mptsas_phymask_t phy_mask = 0x0;
2061                 char phy_mask_name[MPTSAS_MAX_PHYS];
2062                 uint8_t current_port;
2063 
2064                 if (mpt->m_phy_info[i].attached_devhdl == 0)
2065                         continue;
2066 
2067                 bzero(phy_mask_name, sizeof (phy_mask_name));
2068 
2069                 current_port = mpt->m_phy_info[i].port_num;
2070 
2071                 if ((mask & (1 << i)) != 0)
2072                         continue;
2073 
2074                 for (j = 0; j < mpt->m_num_phys; j++) {
2075                         if (mpt->m_phy_info[j].attached_devhdl &&
2076                             (mpt->m_phy_info[j].port_num == current_port)) {
2077                                 phy_mask |= (1 << j);
2078                         }
2079                 }
2080                 mask = mask | phy_mask;
2081 
2082                 for (j = 0; j < mpt->m_num_phys; j++) {
2083                         if ((phy_mask >> j) & 0x01) {
2084                                 mpt->m_phy_info[j].phy_mask = phy_mask;
2085                         }
2086                 }
2087 
2088                 (void) sprintf(phy_mask_name, "%x", phy_mask);
2089 
2090                 mutex_exit(&mpt->m_mutex);
2091                 /*
2092                  * register a iport
2093                  */
2094                 (void) scsi_hba_iport_register(mpt->m_dip, phy_mask_name);
2095                 mutex_enter(&mpt->m_mutex);
2096         }
2097         mutex_exit(&mpt->m_mutex);
2098         /*
2099          * register a virtual port for RAID volume always
2100          */
2101         (void) scsi_hba_iport_register(mpt->m_dip, "v0");
2102 
2103 }
2104 
2105 static int
2106 mptsas_smp_setup(mptsas_t *mpt)
2107 {
2108         mpt->m_smptran = smp_hba_tran_alloc(mpt->m_dip);
2109         ASSERT(mpt->m_smptran != NULL);
2110         mpt->m_smptran->smp_tran_hba_private = mpt;
2111         mpt->m_smptran->smp_tran_start = mptsas_smp_start;
2112         if (smp_hba_attach_setup(mpt->m_dip, mpt->m_smptran) != DDI_SUCCESS) {
2113                 mptsas_log(mpt, CE_WARN, "smp attach setup failed");
2114                 smp_hba_tran_free(mpt->m_smptran);
2115                 mpt->m_smptran = NULL;
2116                 return (FALSE);
2117         }
2118         /*
2119          * Initialize smp hash table
2120          */
2121         mptsas_hash_init(&mpt->m_active->m_smptbl);
2122         mpt->m_smp_devhdl = 0xFFFF;
2123 
2124         return (TRUE);
2125 }
2126 
2127 static void
2128 mptsas_smp_teardown(mptsas_t *mpt)
2129 {
2130         (void) smp_hba_detach(mpt->m_dip);
2131         if (mpt->m_smptran != NULL) {
2132                 smp_hba_tran_free(mpt->m_smptran);
2133                 mpt->m_smptran = NULL;
2134         }
2135         mpt->m_smp_devhdl = 0;
2136 }
2137 
2138 static int
2139 mptsas_cache_create(mptsas_t *mpt)
2140 {
2141         int instance = mpt->m_instance;
2142         char buf[64];
2143 
2144         /*
2145          * create kmem cache for packets
2146          */
2147         (void) sprintf(buf, "mptsas%d_cache", instance);
2148         mpt->m_kmem_cache = kmem_cache_create(buf,
2149             sizeof (struct mptsas_cmd) + scsi_pkt_size(), 8,
2150             mptsas_kmem_cache_constructor, mptsas_kmem_cache_destructor,
2151             NULL, (void *)mpt, NULL, 0);
2152 
2153         if (mpt->m_kmem_cache == NULL) {
2154                 mptsas_log(mpt, CE_WARN, "creating kmem cache failed");
2155                 return (FALSE);
2156         }
2157 
2158         /*
2159          * create kmem cache for extra SGL frames if SGL cannot
2160          * be accomodated into main request frame.
2161          */
2162         (void) sprintf(buf, "mptsas%d_cache_frames", instance);
2163         mpt->m_cache_frames = kmem_cache_create(buf,
2164             sizeof (mptsas_cache_frames_t), 8,
2165             mptsas_cache_frames_constructor, mptsas_cache_frames_destructor,
2166             NULL, (void *)mpt, NULL, 0);
2167 
2168         if (mpt->m_cache_frames == NULL) {
2169                 mptsas_log(mpt, CE_WARN, "creating cache for frames failed");
2170                 return (FALSE);
2171         }
2172 
2173         return (TRUE);
2174 }
2175 
2176 static void
2177 mptsas_cache_destroy(mptsas_t *mpt)
2178 {
2179         /* deallocate in reverse order */
2180         if (mpt->m_cache_frames) {
2181                 kmem_cache_destroy(mpt->m_cache_frames);
2182                 mpt->m_cache_frames = NULL;
2183         }
2184         if (mpt->m_kmem_cache) {
2185                 kmem_cache_destroy(mpt->m_kmem_cache);
2186                 mpt->m_kmem_cache = NULL;
2187         }
2188 }
2189 
2190 static int
2191 mptsas_power(dev_info_t *dip, int component, int level)
2192 {
2193 #ifndef __lock_lint
2194         _NOTE(ARGUNUSED(component))
2195 #endif
2196         mptsas_t        *mpt;
2197         int             rval = DDI_SUCCESS;
2198         int             polls = 0;
2199         uint32_t        ioc_status;
2200 
2201         if (scsi_hba_iport_unit_address(dip) != 0)
2202                 return (DDI_SUCCESS);
2203 
2204         mpt = ddi_get_soft_state(mptsas_state, ddi_get_instance(dip));
2205         if (mpt == NULL) {
2206                 return (DDI_FAILURE);
2207         }
2208 
2209         mutex_enter(&mpt->m_mutex);
2210 
2211         /*
2212          * If the device is busy, don't lower its power level
2213          */
2214         if (mpt->m_busy && (mpt->m_power_level > level)) {
2215                 mutex_exit(&mpt->m_mutex);
2216                 return (DDI_FAILURE);
2217         }
2218         switch (level) {
2219         case PM_LEVEL_D0:
2220                 NDBG11(("mptsas%d: turning power ON.", mpt->m_instance));
2221                 MPTSAS_POWER_ON(mpt);
2222                 /*
2223                  * Wait up to 30 seconds for IOC to come out of reset.
2224                  */
2225                 while (((ioc_status = ddi_get32(mpt->m_datap,
2226                     &mpt->m_reg->Doorbell)) &
2227                     MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_RESET) {
2228                         if (polls++ > 3000) {
2229                                 break;
2230                         }
2231                         delay(drv_usectohz(10000));
2232                 }
2233                 /*
2234                  * If IOC is not in operational state, try to hard reset it.
2235                  */
2236                 if ((ioc_status & MPI2_IOC_STATE_MASK) !=
2237                     MPI2_IOC_STATE_OPERATIONAL) {
2238                         mpt->m_softstate &= ~MPTSAS_SS_MSG_UNIT_RESET;
2239                         if (mptsas_restart_ioc(mpt) == DDI_FAILURE) {
2240                                 mptsas_log(mpt, CE_WARN,
2241                                     "mptsas_power: hard reset failed");
2242                                 mutex_exit(&mpt->m_mutex);
2243                                 return (DDI_FAILURE);
2244                         }
2245                 }
2246                 mutex_enter(&mpt->m_intr_mutex);
2247                 mpt->m_power_level = PM_LEVEL_D0;
2248                 mutex_exit(&mpt->m_intr_mutex);
2249                 break;
2250         case PM_LEVEL_D3:
2251                 NDBG11(("mptsas%d: turning power OFF.", mpt->m_instance));
2252                 MPTSAS_POWER_OFF(mpt);
2253                 break;
2254         default:
2255                 mptsas_log(mpt, CE_WARN, "mptsas%d: unknown power level <%x>.",
2256                     mpt->m_instance, level);
2257                 rval = DDI_FAILURE;
2258                 break;
2259         }
2260         mutex_exit(&mpt->m_mutex);
2261         return (rval);
2262 }
2263 
2264 /*
2265  * Initialize configuration space and figure out which
2266  * chip and revison of the chip the mpt driver is using.
2267  */
2268 static int
2269 mptsas_config_space_init(mptsas_t *mpt)
2270 {
2271         NDBG0(("mptsas_config_space_init"));
2272 
2273         if (mpt->m_config_handle != NULL)
2274                 return (TRUE);
2275 
2276         if (pci_config_setup(mpt->m_dip,
2277             &mpt->m_config_handle) != DDI_SUCCESS) {
2278                 mptsas_log(mpt, CE_WARN, "cannot map configuration space.");
2279                 return (FALSE);
2280         }
2281 
2282         /*
2283          * This is a workaround for a XMITS ASIC bug which does not
2284          * drive the CBE upper bits.
2285          */
2286         if (pci_config_get16(mpt->m_config_handle, PCI_CONF_STAT) &
2287             PCI_STAT_PERROR) {
2288                 pci_config_put16(mpt->m_config_handle, PCI_CONF_STAT,
2289                     PCI_STAT_PERROR);
2290         }
2291 
2292         mptsas_setup_cmd_reg(mpt);
2293 
2294         /*
2295          * Get the chip device id:
2296          */
2297         mpt->m_devid = pci_config_get16(mpt->m_config_handle, PCI_CONF_DEVID);
2298 
2299         /*
2300          * Save the revision.
2301          */
2302         mpt->m_revid = pci_config_get8(mpt->m_config_handle, PCI_CONF_REVID);
2303 
2304         /*
2305          * Save the SubSystem Vendor and Device IDs
2306          */
2307         mpt->m_svid = pci_config_get16(mpt->m_config_handle, PCI_CONF_SUBVENID);
2308         mpt->m_ssid = pci_config_get16(mpt->m_config_handle, PCI_CONF_SUBSYSID);
2309 
2310         /*
2311          * Set the latency timer to 0x40 as specified by the upa -> pci
2312          * bridge chip design team.  This may be done by the sparc pci
2313          * bus nexus driver, but the driver should make sure the latency
2314          * timer is correct for performance reasons.
2315          */
2316         pci_config_put8(mpt->m_config_handle, PCI_CONF_LATENCY_TIMER,
2317             MPTSAS_LATENCY_TIMER);
2318 
2319         (void) mptsas_get_pci_cap(mpt);
2320         return (TRUE);
2321 }
2322 
2323 static void
2324 mptsas_config_space_fini(mptsas_t *mpt)
2325 {
2326         if (mpt->m_config_handle != NULL) {
2327                 mptsas_disable_bus_master(mpt);
2328                 pci_config_teardown(&mpt->m_config_handle);
2329                 mpt->m_config_handle = NULL;
2330         }
2331 }
2332 
2333 static void
2334 mptsas_setup_cmd_reg(mptsas_t *mpt)
2335 {
2336         ushort_t        cmdreg;
2337 
2338         /*
2339          * Set the command register to the needed values.
2340          */
2341         cmdreg = pci_config_get16(mpt->m_config_handle, PCI_CONF_COMM);
2342         cmdreg |= (PCI_COMM_ME | PCI_COMM_SERR_ENABLE |
2343             PCI_COMM_PARITY_DETECT | PCI_COMM_MAE);
2344         cmdreg &= ~PCI_COMM_IO;
2345         pci_config_put16(mpt->m_config_handle, PCI_CONF_COMM, cmdreg);
2346 }
2347 
2348 static void
2349 mptsas_disable_bus_master(mptsas_t *mpt)
2350 {
2351         ushort_t        cmdreg;
2352 
2353         /*
2354          * Clear the master enable bit in the PCI command register.
2355          * This prevents any bus mastering activity like DMA.
2356          */
2357         cmdreg = pci_config_get16(mpt->m_config_handle, PCI_CONF_COMM);
2358         cmdreg &= ~PCI_COMM_ME;
2359         pci_config_put16(mpt->m_config_handle, PCI_CONF_COMM, cmdreg);
2360 }
2361 
2362 int
2363 mptsas_dma_alloc(mptsas_t *mpt, mptsas_dma_alloc_state_t *dma_statep)
2364 {
2365         ddi_dma_attr_t  attrs;
2366 
2367         attrs = mpt->m_io_dma_attr;
2368         attrs.dma_attr_sgllen = 1;
2369 
2370         ASSERT(dma_statep != NULL);
2371 
2372         if (mptsas_dma_addr_create(mpt, attrs, &dma_statep->handle,
2373             &dma_statep->accessp, &dma_statep->memp, dma_statep->size,
2374             &dma_statep->cookie) == FALSE) {
2375                 return (DDI_FAILURE);
2376         }
2377 
2378         return (DDI_SUCCESS);
2379 }
2380 
2381 void
2382 mptsas_dma_free(mptsas_dma_alloc_state_t *dma_statep)
2383 {
2384         ASSERT(dma_statep != NULL);
2385         mptsas_dma_addr_destroy(&dma_statep->handle, &dma_statep->accessp);
2386         dma_statep->size = 0;
2387 }
2388 
2389 int
2390 mptsas_do_dma(mptsas_t *mpt, uint32_t size, int var, int (*callback)())
2391 {
2392         ddi_dma_attr_t          attrs;
2393         ddi_dma_handle_t        dma_handle;
2394         caddr_t                 memp;
2395         ddi_acc_handle_t        accessp;
2396         int                     rval;
2397 
2398         ASSERT(mutex_owned(&mpt->m_mutex));
2399 
2400         attrs = mpt->m_msg_dma_attr;
2401         attrs.dma_attr_sgllen = 1;
2402         attrs.dma_attr_granular = size;
2403 
2404         if (mptsas_dma_addr_create(mpt, attrs, &dma_handle,
2405             &accessp, &memp, size, NULL) == FALSE) {
2406                 return (DDI_FAILURE);
2407         }
2408 
2409         rval = (*callback) (mpt, memp, var, accessp);
2410 
2411         if ((mptsas_check_dma_handle(dma_handle) != DDI_SUCCESS) ||
2412             (mptsas_check_acc_handle(accessp) != DDI_SUCCESS)) {
2413                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
2414                 rval = DDI_FAILURE;
2415         }
2416 
2417         mptsas_dma_addr_destroy(&dma_handle, &accessp);
2418         return (rval);
2419 
2420 }
2421 
2422 static int
2423 mptsas_alloc_request_frames(mptsas_t *mpt)
2424 {
2425         ddi_dma_attr_t          frame_dma_attrs;
2426         caddr_t                 memp;
2427         ddi_dma_cookie_t        cookie;
2428         size_t                  mem_size;
2429 
2430         /*
2431          * re-alloc when it has already alloced
2432          */
2433         mptsas_dma_addr_destroy(&mpt->m_dma_req_frame_hdl,
2434             &mpt->m_acc_req_frame_hdl);
2435 
2436         /*
2437          * The size of the request frame pool is:
2438          *   Number of Request Frames * Request Frame Size
2439          */
2440         mem_size = mpt->m_max_requests * mpt->m_req_frame_size;
2441 
2442         /*
2443          * set the DMA attributes.  System Request Message Frames must be
2444          * aligned on a 16-byte boundry.
2445          */
2446         frame_dma_attrs = mpt->m_msg_dma_attr;
2447         frame_dma_attrs.dma_attr_align = 16;
2448         frame_dma_attrs.dma_attr_sgllen = 1;
2449 
2450         /*
2451          * allocate the request frame pool.
2452          */
2453         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2454             &mpt->m_dma_req_frame_hdl, &mpt->m_acc_req_frame_hdl, &memp,
2455             mem_size, &cookie) == FALSE) {
2456                 return (DDI_FAILURE);
2457         }
2458 
2459         /*
2460          * Store the request frame memory address.  This chip uses this
2461          * address to dma to and from the driver's frame.  The second
2462          * address is the address mpt uses to fill in the frame.
2463          */
2464         mpt->m_req_frame_dma_addr = cookie.dmac_laddress;
2465         mpt->m_req_frame = memp;
2466 
2467         /*
2468          * Clear the request frame pool.
2469          */
2470         bzero(mpt->m_req_frame, mem_size);
2471 
2472         return (DDI_SUCCESS);
2473 }
2474 
2475 static int
2476 mptsas_alloc_reply_frames(mptsas_t *mpt)
2477 {
2478         ddi_dma_attr_t          frame_dma_attrs;
2479         caddr_t                 memp;
2480         ddi_dma_cookie_t        cookie;
2481         size_t                  mem_size;
2482 
2483         /*
2484          * re-alloc when it has already alloced
2485          */
2486         mptsas_dma_addr_destroy(&mpt->m_dma_reply_frame_hdl,
2487             &mpt->m_acc_reply_frame_hdl);
2488 
2489         /*
2490          * The size of the reply frame pool is:
2491          *   Number of Reply Frames * Reply Frame Size
2492          */
2493         mem_size = mpt->m_max_replies * mpt->m_reply_frame_size;
2494 
2495         /*
2496          * set the DMA attributes.   System Reply Message Frames must be
2497          * aligned on a 4-byte boundry.  This is the default.
2498          */
2499         frame_dma_attrs = mpt->m_msg_dma_attr;
2500         frame_dma_attrs.dma_attr_sgllen = 1;
2501 
2502         /*
2503          * allocate the reply frame pool
2504          */
2505         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2506             &mpt->m_dma_reply_frame_hdl, &mpt->m_acc_reply_frame_hdl, &memp,
2507             mem_size, &cookie) == FALSE) {
2508                 return (DDI_FAILURE);
2509         }
2510 
2511         /*
2512          * Store the reply frame memory address.  This chip uses this
2513          * address to dma to and from the driver's frame.  The second
2514          * address is the address mpt uses to process the frame.
2515          */
2516         mpt->m_reply_frame_dma_addr = cookie.dmac_laddress;
2517         mpt->m_reply_frame = memp;
2518 
2519         /*
2520          * Clear the reply frame pool.
2521          */
2522         bzero(mpt->m_reply_frame, mem_size);
2523 
2524         return (DDI_SUCCESS);
2525 }
2526 
2527 static int
2528 mptsas_alloc_free_queue(mptsas_t *mpt)
2529 {
2530         ddi_dma_attr_t          frame_dma_attrs;
2531         caddr_t                 memp;
2532         ddi_dma_cookie_t        cookie;
2533         size_t                  mem_size;
2534 
2535         /*
2536          * re-alloc when it has already alloced
2537          */
2538         mptsas_dma_addr_destroy(&mpt->m_dma_free_queue_hdl,
2539             &mpt->m_acc_free_queue_hdl);
2540 
2541         /*
2542          * The reply free queue size is:
2543          *   Reply Free Queue Depth * 4
2544          * The "4" is the size of one 32 bit address (low part of 64-bit
2545          *   address)
2546          */
2547         mem_size = mpt->m_free_queue_depth * 4;
2548 
2549         /*
2550          * set the DMA attributes  The Reply Free Queue must be aligned on a
2551          * 16-byte boundry.
2552          */
2553         frame_dma_attrs = mpt->m_msg_dma_attr;
2554         frame_dma_attrs.dma_attr_align = 16;
2555         frame_dma_attrs.dma_attr_sgllen = 1;
2556 
2557         /*
2558          * allocate the reply free queue
2559          */
2560         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2561             &mpt->m_dma_free_queue_hdl, &mpt->m_acc_free_queue_hdl, &memp,
2562             mem_size, &cookie) == FALSE) {
2563                 return (DDI_FAILURE);
2564         }
2565 
2566         /*
2567          * Store the reply free queue memory address.  This chip uses this
2568          * address to read from the reply free queue.  The second address
2569          * is the address mpt uses to manage the queue.
2570          */
2571         mpt->m_free_queue_dma_addr = cookie.dmac_laddress;
2572         mpt->m_free_queue = memp;
2573 
2574         /*
2575          * Clear the reply free queue memory.
2576          */
2577         bzero(mpt->m_free_queue, mem_size);
2578 
2579         return (DDI_SUCCESS);
2580 }
2581 
2582 static int
2583 mptsas_alloc_post_queue(mptsas_t *mpt)
2584 {
2585         ddi_dma_attr_t          frame_dma_attrs;
2586         caddr_t                 memp;
2587         ddi_dma_cookie_t        cookie;
2588         size_t                  mem_size;
2589 
2590         /*
2591          * re-alloc when it has already alloced
2592          */
2593         mptsas_dma_addr_destroy(&mpt->m_dma_post_queue_hdl,
2594             &mpt->m_acc_post_queue_hdl);
2595 
2596         /*
2597          * The reply descriptor post queue size is:
2598          *   Reply Descriptor Post Queue Depth * 8
2599          * The "8" is the size of each descriptor (8 bytes or 64 bits).
2600          */
2601         mem_size = mpt->m_post_queue_depth * 8;
2602 
2603         /*
2604          * set the DMA attributes.  The Reply Descriptor Post Queue must be
2605          * aligned on a 16-byte boundry.
2606          */
2607         frame_dma_attrs = mpt->m_msg_dma_attr;
2608         frame_dma_attrs.dma_attr_align = 16;
2609         frame_dma_attrs.dma_attr_sgllen = 1;
2610 
2611         /*
2612          * allocate the reply post queue
2613          */
2614         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2615             &mpt->m_dma_post_queue_hdl, &mpt->m_acc_post_queue_hdl, &memp,
2616             mem_size, &cookie) == FALSE) {
2617                 return (DDI_FAILURE);
2618         }
2619 
2620         /*
2621          * Store the reply descriptor post queue memory address.  This chip
2622          * uses this address to write to the reply descriptor post queue.  The
2623          * second address is the address mpt uses to manage the queue.
2624          */
2625         mpt->m_post_queue_dma_addr = cookie.dmac_laddress;
2626         mpt->m_post_queue = memp;
2627 
2628         /*
2629          * Clear the reply post queue memory.
2630          */
2631         bzero(mpt->m_post_queue, mem_size);
2632 
2633         return (DDI_SUCCESS);
2634 }
2635 
2636 static void
2637 mptsas_alloc_reply_args(mptsas_t *mpt)
2638 {
2639         if (mpt->m_replyh_args != NULL) {
2640                 kmem_free(mpt->m_replyh_args, sizeof (m_replyh_arg_t)
2641                     * mpt->m_max_replies);
2642                 mpt->m_replyh_args = NULL;
2643         }
2644         mpt->m_replyh_args = kmem_zalloc(sizeof (m_replyh_arg_t) *
2645             mpt->m_max_replies, KM_SLEEP);
2646 }
2647 
2648 static int
2649 mptsas_alloc_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd)
2650 {
2651         mptsas_cache_frames_t   *frames = NULL;
2652         if (cmd->cmd_extra_frames == NULL) {
2653                 frames = kmem_cache_alloc(mpt->m_cache_frames, KM_NOSLEEP);
2654                 if (frames == NULL) {
2655                         return (DDI_FAILURE);
2656                 }
2657                 cmd->cmd_extra_frames = frames;
2658         }
2659         return (DDI_SUCCESS);
2660 }
2661 
2662 static void
2663 mptsas_free_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd)
2664 {
2665         if (cmd->cmd_extra_frames) {
2666                 kmem_cache_free(mpt->m_cache_frames,
2667                     (void *)cmd->cmd_extra_frames);
2668                 cmd->cmd_extra_frames = NULL;
2669         }
2670 }
2671 
2672 static void
2673 mptsas_cfg_fini(mptsas_t *mpt)
2674 {
2675         NDBG0(("mptsas_cfg_fini"));
2676         ddi_regs_map_free(&mpt->m_datap);
2677 }
2678 
2679 static void
2680 mptsas_hba_fini(mptsas_t *mpt)
2681 {
2682         NDBG0(("mptsas_hba_fini"));
2683 
2684         /*
2685          * Free up any allocated memory
2686          */
2687         mptsas_dma_addr_destroy(&mpt->m_dma_req_frame_hdl,
2688             &mpt->m_acc_req_frame_hdl);
2689 
2690         mptsas_dma_addr_destroy(&mpt->m_dma_reply_frame_hdl,
2691             &mpt->m_acc_reply_frame_hdl);
2692 
2693         mptsas_dma_addr_destroy(&mpt->m_dma_free_queue_hdl,
2694             &mpt->m_acc_free_queue_hdl);
2695 
2696         mptsas_dma_addr_destroy(&mpt->m_dma_post_queue_hdl,
2697             &mpt->m_acc_post_queue_hdl);
2698 
2699         if (mpt->m_replyh_args != NULL) {
2700                 kmem_free(mpt->m_replyh_args, sizeof (m_replyh_arg_t)
2701                     * mpt->m_max_replies);
2702         }
2703 }
2704 
2705 static int
2706 mptsas_name_child(dev_info_t *lun_dip, char *name, int len)
2707 {
2708         int             lun = 0;
2709         char            *sas_wwn = NULL;
2710         int             phynum = -1;
2711         int             reallen = 0;
2712 
2713         /* Get the target num */
2714         lun = ddi_prop_get_int(DDI_DEV_T_ANY, lun_dip, DDI_PROP_DONTPASS,
2715             LUN_PROP, 0);
2716 
2717         if ((phynum = ddi_prop_get_int(DDI_DEV_T_ANY, lun_dip,
2718             DDI_PROP_DONTPASS, "sata-phy", -1)) != -1) {
2719                 /*
2720                  * Stick in the address of form "pPHY,LUN"
2721                  */
2722                 reallen = snprintf(name, len, "p%x,%x", phynum, lun);
2723         } else if (ddi_prop_lookup_string(DDI_DEV_T_ANY, lun_dip,
2724             DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET_PORT, &sas_wwn)
2725             == DDI_PROP_SUCCESS) {
2726                 /*
2727                  * Stick in the address of the form "wWWN,LUN"
2728                  */
2729                 reallen = snprintf(name, len, "%s,%x", sas_wwn, lun);
2730                 ddi_prop_free(sas_wwn);
2731         } else {
2732                 return (DDI_FAILURE);
2733         }
2734 
2735         ASSERT(reallen < len);
2736         if (reallen >= len) {
2737                 mptsas_log(0, CE_WARN, "!mptsas_get_name: name parameter "
2738                     "length too small, it needs to be %d bytes", reallen + 1);
2739         }
2740         return (DDI_SUCCESS);
2741 }
2742 
2743 /*
2744  * tran_tgt_init(9E) - target device instance initialization
2745  */
2746 static int
2747 mptsas_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2748     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2749 {
2750 #ifndef __lock_lint
2751         _NOTE(ARGUNUSED(hba_tran))
2752 #endif
2753 
2754         /*
2755          * At this point, the scsi_device structure already exists
2756          * and has been initialized.
2757          *
2758          * Use this function to allocate target-private data structures,
2759          * if needed by this HBA.  Add revised flow-control and queue
2760          * properties for child here, if desired and if you can tell they
2761          * support tagged queueing by now.
2762          */
2763         mptsas_t                *mpt;
2764         int                     lun = sd->sd_address.a_lun;
2765         mdi_pathinfo_t          *pip = NULL;
2766         mptsas_tgt_private_t    *tgt_private = NULL;
2767         mptsas_target_t         *ptgt = NULL;
2768         char                    *psas_wwn = NULL;
2769         int                     phymask = 0;
2770         uint64_t                sas_wwn = 0;
2771         mpt = SDEV2MPT(sd);
2772 
2773         ASSERT(scsi_hba_iport_unit_address(hba_dip) != 0);
2774 
2775         NDBG0(("mptsas_scsi_tgt_init: hbadip=0x%p tgtdip=0x%p lun=%d",
2776             (void *)hba_dip, (void *)tgt_dip, lun));
2777 
2778         if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
2779                 (void) ndi_merge_node(tgt_dip, mptsas_name_child);
2780                 ddi_set_name_addr(tgt_dip, NULL);
2781                 return (DDI_FAILURE);
2782         }
2783         /*
2784          * phymask is 0 means the virtual port for RAID
2785          */
2786         phymask = ddi_prop_get_int(DDI_DEV_T_ANY, hba_dip, 0,
2787             "phymask", 0);
2788         if (mdi_component_is_client(tgt_dip, NULL) == MDI_SUCCESS) {
2789                 if ((pip = (void *)(sd->sd_private)) == NULL) {
2790                         /*
2791                          * Very bad news if this occurs. Somehow scsi_vhci has
2792                          * lost the pathinfo node for this target.
2793                          */
2794                         return (DDI_NOT_WELL_FORMED);
2795                 }
2796 
2797                 if (mdi_prop_lookup_int(pip, LUN_PROP, &lun) !=
2798                     DDI_PROP_SUCCESS) {
2799                         mptsas_log(mpt, CE_WARN, "Get lun property failed\n");
2800                         return (DDI_FAILURE);
2801                 }
2802 
2803                 if (mdi_prop_lookup_string(pip, SCSI_ADDR_PROP_TARGET_PORT,
2804                     &psas_wwn) == MDI_SUCCESS) {
2805                         if (scsi_wwnstr_to_wwn(psas_wwn, &sas_wwn)) {
2806                                 sas_wwn = 0;
2807                         }
2808                         (void) mdi_prop_free(psas_wwn);
2809                 }
2810         } else {
2811                 lun = ddi_prop_get_int(DDI_DEV_T_ANY, tgt_dip,
2812                     DDI_PROP_DONTPASS, LUN_PROP, 0);
2813                 if (ddi_prop_lookup_string(DDI_DEV_T_ANY, tgt_dip,
2814                     DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET_PORT, &psas_wwn) ==
2815                     DDI_PROP_SUCCESS) {
2816                         if (scsi_wwnstr_to_wwn(psas_wwn, &sas_wwn)) {
2817                                 sas_wwn = 0;
2818                         }
2819                         ddi_prop_free(psas_wwn);
2820                 } else {
2821                         sas_wwn = 0;
2822                 }
2823         }
2824         ASSERT((sas_wwn != 0) || (phymask != 0));
2825         mutex_enter(&mpt->m_mutex);
2826         ptgt = mptsas_hash_search(&mpt->m_active->m_tgttbl, sas_wwn, phymask);
2827         mutex_exit(&mpt->m_mutex);
2828         if (ptgt == NULL) {
2829                 mptsas_log(mpt, CE_WARN, "!tgt_init: target doesn't exist or "
2830                     "gone already! phymask:%x, saswwn %"PRIx64, phymask,
2831                     sas_wwn);
2832                 return (DDI_FAILURE);
2833         }
2834         if (hba_tran->tran_tgt_private == NULL) {
2835                 tgt_private = kmem_zalloc(sizeof (mptsas_tgt_private_t),
2836                     KM_SLEEP);
2837                 tgt_private->t_lun = lun;
2838                 tgt_private->t_private = ptgt;
2839                 hba_tran->tran_tgt_private = tgt_private;
2840         }
2841 
2842         if (mdi_component_is_client(tgt_dip, NULL) == MDI_SUCCESS) {
2843                 return (DDI_SUCCESS);
2844         }
2845         mutex_enter(&mpt->m_mutex);
2846 
2847         if (ptgt->m_deviceinfo &
2848             (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
2849             MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
2850                 uchar_t *inq89 = NULL;
2851                 int inq89_len = 0x238;
2852                 int reallen = 0;
2853                 int rval = 0;
2854                 struct sata_id *sid = NULL;
2855                 char model[SATA_ID_MODEL_LEN + 1];
2856                 char fw[SATA_ID_FW_LEN + 1];
2857                 char *vid, *pid;
2858                 int i;
2859 
2860                 mutex_exit(&mpt->m_mutex);
2861                 /*
2862                  * According SCSI/ATA Translation -2 (SAT-2) revision 01a
2863                  * chapter 12.4.2 VPD page 89h includes 512 bytes ATA IDENTIFY
2864                  * DEVICE data or ATA IDENTIFY PACKET DEVICE data.
2865                  */
2866                 inq89 = kmem_zalloc(inq89_len, KM_SLEEP);
2867                 rval = mptsas_inquiry(mpt, ptgt, 0, 0x89,
2868                     inq89, inq89_len, &reallen, 1);
2869 
2870                 if (rval != 0) {
2871                         if (inq89 != NULL) {
2872                                 kmem_free(inq89, inq89_len);
2873                         }
2874 
2875                         mptsas_log(mpt, CE_WARN, "!mptsas request inquiry page "
2876                             "0x89 for SATA target:%x failed!", ptgt->m_devhdl);
2877                         return (DDI_SUCCESS);
2878                 }
2879                 sid = (void *)(&inq89[60]);
2880 
2881                 swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
2882                 swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
2883 
2884                 model[SATA_ID_MODEL_LEN] = 0;
2885                 fw[SATA_ID_FW_LEN] = 0;
2886 
2887                 /*
2888                  * split model into into vid/pid
2889                  */
2890                 for (i = 0, pid = model; i < SATA_ID_MODEL_LEN; i++, pid++)
2891                         if ((*pid == ' ') || (*pid == '\t'))
2892                                 break;
2893                 if (i < SATA_ID_MODEL_LEN) {
2894                         vid = model;
2895                         /*
2896                          * terminate vid, establish pid
2897                          */
2898                         *pid++ = 0;
2899                 } else {
2900                         /*
2901                          * vid will stay "ATA     ", the rule is same
2902                          * as sata framework implementation.
2903                          */
2904                         vid = NULL;
2905                         /*
2906                          * model is all pid
2907                          */
2908                         pid = model;
2909                 }
2910 
2911                 /*
2912                  * override SCSA "inquiry-*" properties
2913                  */
2914                 if (vid)
2915                         (void) scsi_device_prop_update_inqstring(sd,
2916                             INQUIRY_VENDOR_ID, vid, strlen(vid));
2917                 if (pid)
2918                         (void) scsi_device_prop_update_inqstring(sd,
2919                             INQUIRY_PRODUCT_ID, pid, strlen(pid));
2920                 (void) scsi_device_prop_update_inqstring(sd,
2921                     INQUIRY_REVISION_ID, fw, strlen(fw));
2922 
2923                 if (inq89 != NULL) {
2924                         kmem_free(inq89, inq89_len);
2925                 }
2926         } else {
2927                 mutex_exit(&mpt->m_mutex);
2928         }
2929 
2930         return (DDI_SUCCESS);
2931 }
2932 /*
2933  * tran_tgt_free(9E) - target device instance deallocation
2934  */
2935 static void
2936 mptsas_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2937     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2938 {
2939 #ifndef __lock_lint
2940         _NOTE(ARGUNUSED(hba_dip, tgt_dip, hba_tran, sd))
2941 #endif
2942 
2943         mptsas_tgt_private_t    *tgt_private = hba_tran->tran_tgt_private;
2944 
2945         if (tgt_private != NULL) {
2946                 kmem_free(tgt_private, sizeof (mptsas_tgt_private_t));
2947                 hba_tran->tran_tgt_private = NULL;
2948         }
2949 }
2950 
2951 /*
2952  * scsi_pkt handling
2953  *
2954  * Visible to the external world via the transport structure.
2955  */
2956 
2957 /*
2958  * Notes:
2959  *      - transport the command to the addressed SCSI target/lun device
2960  *      - normal operation is to schedule the command to be transported,
2961  *        and return TRAN_ACCEPT if this is successful.
2962  *      - if NO_INTR, tran_start must poll device for command completion
2963  */
2964 static int
2965 mptsas_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2966 {
2967 #ifndef __lock_lint
2968         _NOTE(ARGUNUSED(ap))
2969 #endif
2970         mptsas_t        *mpt = PKT2MPT(pkt);
2971         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
2972         int             rval;
2973         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
2974 
2975         NDBG1(("mptsas_scsi_start: pkt=0x%p", (void *)pkt));
2976         ASSERT(ptgt);
2977         if (ptgt == NULL)
2978                 return (TRAN_FATAL_ERROR);
2979 
2980         /*
2981          * prepare the pkt before taking mutex.
2982          */
2983         rval = mptsas_prepare_pkt(cmd);
2984         if (rval != TRAN_ACCEPT) {
2985                 return (rval);
2986         }
2987 
2988         /*
2989          * Send the command to target/lun, however your HBA requires it.
2990          * If busy, return TRAN_BUSY; if there's some other formatting error
2991          * in the packet, return TRAN_BADPKT; otherwise, fall through to the
2992          * return of TRAN_ACCEPT.
2993          *
2994          * Remember that access to shared resources, including the mptsas_t
2995          * data structure and the HBA hardware registers, must be protected
2996          * with mutexes, here and everywhere.
2997          *
2998          * Also remember that at interrupt time, you'll get an argument
2999          * to the interrupt handler which is a pointer to your mptsas_t
3000          * structure; you'll have to remember which commands are outstanding
3001          * and which scsi_pkt is the currently-running command so the
3002          * interrupt handler can refer to the pkt to set completion
3003          * status, call the target driver back through pkt_comp, etc.
3004          */
3005 
3006         mutex_enter(&ptgt->m_tgt_intr_mutex);
3007         if (ptgt->m_dr_flag == MPTSAS_DR_INTRANSITION) {
3008                 if (cmd->cmd_pkt_flags & FLAG_NOQUEUE) {
3009                         /*
3010                          * commands should be allowed to retry by
3011                          * returning TRAN_BUSY to stall the I/O's
3012                          * which come from scsi_vhci since the device/
3013                          * path is in unstable state now.
3014                          */
3015                         mutex_exit(&ptgt->m_tgt_intr_mutex);
3016                         return (TRAN_BUSY);
3017                 } else {
3018                         /*
3019                          * The device is offline, just fail the
3020                          * command by returning TRAN_FATAL_ERROR.
3021                          */
3022                         mutex_exit(&ptgt->m_tgt_intr_mutex);
3023                         return (TRAN_FATAL_ERROR);
3024                 }
3025         }
3026         mutex_exit(&ptgt->m_tgt_intr_mutex);
3027         rval = mptsas_accept_pkt(mpt, cmd);
3028 
3029         return (rval);
3030 }
3031 
3032 static int
3033 mptsas_accept_pkt(mptsas_t *mpt, mptsas_cmd_t *cmd)
3034 {
3035         int             rval = TRAN_ACCEPT;
3036         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
3037 
3038         NDBG1(("mptsas_accept_pkt: cmd=0x%p", (void *)cmd));
3039 
3040         if ((cmd->cmd_flags & CFLAG_PREPARED) == 0) {
3041                 rval = mptsas_prepare_pkt(cmd);
3042                 if (rval != TRAN_ACCEPT) {
3043                         cmd->cmd_flags &= ~CFLAG_TRANFLAG;
3044                         return (rval);
3045                 }
3046         }
3047 
3048         /*
3049          * reset the throttle if we were draining
3050          */
3051         mutex_enter(&ptgt->m_tgt_intr_mutex);
3052         if ((ptgt->m_t_ncmds == 0) &&
3053             (ptgt->m_t_throttle == DRAIN_THROTTLE)) {
3054                 NDBG23(("reset throttle"));
3055                 ASSERT(ptgt->m_reset_delay == 0);
3056                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
3057         }
3058 
3059         /*
3060          * If device handle has already been invalidated, just
3061          * fail the command. In theory, command from scsi_vhci
3062          * client is impossible send down command with invalid
3063          * devhdl since devhdl is set after path offline, target
3064          * driver is not suppose to select a offlined path.
3065          */
3066         if (ptgt->m_devhdl == MPTSAS_INVALID_DEVHDL) {
3067                 NDBG20(("rejecting command, it might because invalid devhdl "
3068                     "request."));
3069                 mutex_exit(&ptgt->m_tgt_intr_mutex);
3070                 mutex_enter(&mpt->m_mutex);
3071                 /*
3072                  * If HBA is being reset, the DevHandles are being
3073                  * re-initialized, which means that they could be invalid
3074                  * even if the target is still attached. Check if being reset
3075                  * and if DevHandle is being re-initialized. If this is the
3076                  * case, return BUSY so the I/O can be retried later.
3077                  */
3078                 if (mpt->m_in_reset) {
3079                         mptsas_set_pkt_reason(mpt, cmd, CMD_RESET,
3080                             STAT_BUS_RESET);
3081                         if (cmd->cmd_flags & CFLAG_TXQ) {
3082                                 mptsas_doneq_add(mpt, cmd);
3083                                 mptsas_doneq_empty(mpt);
3084                                 mutex_exit(&mpt->m_mutex);
3085                                 return (rval);
3086                         } else {
3087                                 mutex_exit(&mpt->m_mutex);
3088                                 return (TRAN_BUSY);
3089                         }
3090                 }
3091                 mptsas_set_pkt_reason(mpt, cmd, CMD_DEV_GONE, STAT_TERMINATED);
3092                 if (cmd->cmd_flags & CFLAG_TXQ) {
3093                         mptsas_doneq_add(mpt, cmd);
3094                         mptsas_doneq_empty(mpt);
3095                         mutex_exit(&mpt->m_mutex);
3096                         return (rval);
3097                 } else {
3098                         mutex_exit(&mpt->m_mutex);
3099                         return (TRAN_FATAL_ERROR);
3100                 }
3101         }
3102         mutex_exit(&ptgt->m_tgt_intr_mutex);
3103         /*
3104          * The first case is the normal case.  mpt gets a command from the
3105          * target driver and starts it.
3106          * Since SMID 0 is reserved and the TM slot is reserved, the actual max
3107          * commands is m_max_requests - 2.
3108          */
3109         mutex_enter(&ptgt->m_tgt_intr_mutex);
3110         if ((ptgt->m_t_throttle > HOLD_THROTTLE) &&
3111             (ptgt->m_t_ncmds < ptgt->m_t_throttle) &&
3112             (ptgt->m_reset_delay == 0) &&
3113             (ptgt->m_t_nwait == 0) &&
3114             ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0)) {
3115                 mutex_exit(&ptgt->m_tgt_intr_mutex);
3116                 if (mptsas_save_cmd(mpt, cmd) == TRUE) {
3117                         (void) mptsas_start_cmd0(mpt, cmd);
3118                 } else {
3119                         mutex_enter(&mpt->m_mutex);
3120                         mptsas_waitq_add(mpt, cmd);
3121                         mutex_exit(&mpt->m_mutex);
3122                 }
3123         } else {
3124                 /*
3125                  * Add this pkt to the work queue
3126                  */
3127                 mutex_exit(&ptgt->m_tgt_intr_mutex);
3128                 mutex_enter(&mpt->m_mutex);
3129                 mptsas_waitq_add(mpt, cmd);
3130 
3131                 if (cmd->cmd_pkt_flags & FLAG_NOINTR) {
3132                         (void) mptsas_poll(mpt, cmd, MPTSAS_POLL_TIME);
3133 
3134                         /*
3135                          * Only flush the doneq if this is not a TM
3136                          * cmd.  For TM cmds the flushing of the
3137                          * doneq will be done in those routines.
3138                          */
3139                         if ((cmd->cmd_flags & CFLAG_TM_CMD) == 0) {
3140                                 mptsas_doneq_empty(mpt);
3141                         }
3142                 }
3143                 mutex_exit(&mpt->m_mutex);
3144         }
3145         return (rval);
3146 }
3147 
3148 int
3149 mptsas_save_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
3150 {
3151         mptsas_slots_t  *slots;
3152         int             slot;
3153         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
3154         mptsas_slot_free_e_t    *pe;
3155         int             qn, qn_first;
3156 
3157         slots = mpt->m_active;
3158 
3159         /*
3160          * Account for reserved TM request slot and reserved SMID of 0.
3161          */
3162         ASSERT(slots->m_n_slots == (mpt->m_max_requests - 2));
3163 
3164         qn = qn_first = CPU->cpu_seqid & (mpt->m_slot_freeq_pair_n - 1);
3165 
3166 qpair_retry:
3167         ASSERT(qn < mpt->m_slot_freeq_pair_n);
3168         mutex_enter(&mpt->m_slot_freeq_pairp[qn].m_slot_allocq.s.m_fq_mutex);
3169         pe = list_head(&mpt->m_slot_freeq_pairp[qn].m_slot_allocq.
3170             s.m_fq_list);
3171         if (!pe) { /* switch the allocq and releq */
3172                 mutex_enter(&mpt->m_slot_freeq_pairp[qn].m_slot_releq.
3173                     s.m_fq_mutex);
3174                 if (mpt->m_slot_freeq_pairp[qn].m_slot_releq.s.m_fq_n) {
3175                         mpt->m_slot_freeq_pairp[qn].
3176                             m_slot_allocq.s.m_fq_n =
3177                             mpt->m_slot_freeq_pairp[qn].
3178                             m_slot_releq.s.m_fq_n;
3179                         mpt->m_slot_freeq_pairp[qn].
3180                             m_slot_allocq.s.m_fq_list.list_head.list_next =
3181                             mpt->m_slot_freeq_pairp[qn].
3182                             m_slot_releq.s.m_fq_list.list_head.list_next;
3183                         mpt->m_slot_freeq_pairp[qn].
3184                             m_slot_allocq.s.m_fq_list.list_head.list_prev =
3185                             mpt->m_slot_freeq_pairp[qn].
3186                             m_slot_releq.s.m_fq_list.list_head.list_prev;
3187                         mpt->m_slot_freeq_pairp[qn].
3188                             m_slot_releq.s.m_fq_list.list_head.list_prev->
3189                             list_next =
3190                             &mpt->m_slot_freeq_pairp[qn].
3191                             m_slot_allocq.s.m_fq_list.list_head;
3192                         mpt->m_slot_freeq_pairp[qn].
3193                             m_slot_releq.s.m_fq_list.list_head.list_next->
3194                             list_prev =
3195                             &mpt->m_slot_freeq_pairp[qn].
3196                             m_slot_allocq.s.m_fq_list.list_head;
3197 
3198                         mpt->m_slot_freeq_pairp[qn].
3199                             m_slot_releq.s.m_fq_list.list_head.list_next =
3200                             mpt->m_slot_freeq_pairp[qn].
3201                             m_slot_releq.s.m_fq_list.list_head.list_prev =
3202                             &mpt->m_slot_freeq_pairp[qn].
3203                             m_slot_releq.s.m_fq_list.list_head;
3204                         mpt->m_slot_freeq_pairp[qn].
3205                             m_slot_releq.s.m_fq_n = 0;
3206                 } else {
3207                         mutex_exit(&mpt->m_slot_freeq_pairp[qn].
3208                             m_slot_releq.s.m_fq_mutex);
3209                         mutex_exit(&mpt->m_slot_freeq_pairp[qn].
3210                             m_slot_allocq.s.m_fq_mutex);
3211                         qn = (qn + 1) & (mpt->m_slot_freeq_pair_n - 1);
3212                         if (qn == qn_first)
3213                                 return (FALSE);
3214                         else
3215                                 goto qpair_retry;
3216                 }
3217                 mutex_exit(&mpt->m_slot_freeq_pairp[qn].
3218                     m_slot_releq.s.m_fq_mutex);
3219                 pe = list_head(&mpt->m_slot_freeq_pairp[qn].
3220                     m_slot_allocq.s.m_fq_list);
3221                 ASSERT(pe);
3222         }
3223         list_remove(&mpt->m_slot_freeq_pairp[qn].
3224             m_slot_allocq.s.m_fq_list, pe);
3225         slot = pe->slot;
3226         /*
3227          * Make sure SMID is not using reserved value of 0
3228          * and the TM request slot.
3229          */
3230         ASSERT((slot > 0) && (slot <= slots->m_n_slots) &&
3231             mpt->m_slot_freeq_pairp[qn].m_slot_allocq.s.m_fq_n > 0);
3232         cmd->cmd_slot = slot;
3233         mpt->m_slot_freeq_pairp[qn].m_slot_allocq.s.m_fq_n--;
3234         ASSERT(mpt->m_slot_freeq_pairp[qn].m_slot_allocq.s.m_fq_n >= 0);
3235 
3236         mutex_exit(&mpt->m_slot_freeq_pairp[qn].m_slot_allocq.s.m_fq_mutex);
3237         /*
3238          * only increment per target ncmds if this is not a
3239          * command that has no target associated with it (i.e. a
3240          * event acknoledgment)
3241          */
3242         if ((cmd->cmd_flags & CFLAG_CMDIOC) == 0) {
3243                 mutex_enter(&ptgt->m_tgt_intr_mutex);
3244                 ptgt->m_t_ncmds++;
3245                 mutex_exit(&ptgt->m_tgt_intr_mutex);
3246         }
3247         cmd->cmd_active_timeout = cmd->cmd_pkt->pkt_time;
3248 
3249         /*
3250          * If initial timout is less than or equal to one tick, bump
3251          * the timeout by a tick so that command doesn't timeout before
3252          * its allotted time.
3253          */
3254         if (cmd->cmd_active_timeout <= mptsas_scsi_watchdog_tick) {
3255                 cmd->cmd_active_timeout += mptsas_scsi_watchdog_tick;
3256         }
3257         return (TRUE);
3258 }
3259 
3260 /*
3261  * prepare the pkt:
3262  * the pkt may have been resubmitted or just reused so
3263  * initialize some fields and do some checks.
3264  */
3265 static int
3266 mptsas_prepare_pkt(mptsas_cmd_t *cmd)
3267 {
3268         struct scsi_pkt *pkt = CMD2PKT(cmd);
3269 
3270         NDBG1(("mptsas_prepare_pkt: cmd=0x%p", (void *)cmd));
3271 
3272         /*
3273          * Reinitialize some fields that need it; the packet may
3274          * have been resubmitted
3275          */
3276         pkt->pkt_reason = CMD_CMPLT;
3277         pkt->pkt_state = 0;
3278         pkt->pkt_statistics = 0;
3279         pkt->pkt_resid = 0;
3280         cmd->cmd_age = 0;
3281         cmd->cmd_pkt_flags = pkt->pkt_flags;
3282 
3283         /*
3284          * zero status byte.
3285          */
3286         *(pkt->pkt_scbp) = 0;
3287 
3288         if (cmd->cmd_flags & CFLAG_DMAVALID) {
3289                 pkt->pkt_resid = cmd->cmd_dmacount;
3290 
3291                 /*
3292                  * consistent packets need to be sync'ed first
3293                  * (only for data going out)
3294                  */
3295                 if ((cmd->cmd_flags & CFLAG_CMDIOPB) &&
3296                     (cmd->cmd_flags & CFLAG_DMASEND)) {
3297                         (void) ddi_dma_sync(cmd->cmd_dmahandle, 0, 0,
3298                             DDI_DMA_SYNC_FORDEV);
3299                 }
3300         }
3301 
3302         cmd->cmd_flags =
3303             (cmd->cmd_flags & ~(CFLAG_TRANFLAG)) |
3304             CFLAG_PREPARED | CFLAG_IN_TRANSPORT;
3305 
3306         return (TRAN_ACCEPT);
3307 }
3308 
3309 /*
3310  * tran_init_pkt(9E) - allocate scsi_pkt(9S) for command
3311  *
3312  * One of three possibilities:
3313  *      - allocate scsi_pkt
3314  *      - allocate scsi_pkt and DMA resources
3315  *      - allocate DMA resources to an already-allocated pkt
3316  */
3317 static struct scsi_pkt *
3318 mptsas_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
3319     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
3320     int (*callback)(), caddr_t arg)
3321 {
3322         mptsas_cmd_t            *cmd, *new_cmd;
3323         mptsas_t                *mpt = ADDR2MPT(ap);
3324         int                     failure = 1;
3325 #ifndef __sparc
3326         uint_t                  oldcookiec;
3327 #endif  /* __sparc */
3328         mptsas_target_t         *ptgt = NULL;
3329         int                     rval;
3330         mptsas_tgt_private_t    *tgt_private;
3331         int                     kf;
3332 
3333         kf = (callback == SLEEP_FUNC)? KM_SLEEP: KM_NOSLEEP;
3334 
3335         tgt_private = (mptsas_tgt_private_t *)ap->a_hba_tran->
3336             tran_tgt_private;
3337         ASSERT(tgt_private != NULL);
3338         if (tgt_private == NULL) {
3339                 return (NULL);
3340         }
3341         ptgt = tgt_private->t_private;
3342         ASSERT(ptgt != NULL);
3343         if (ptgt == NULL)
3344                 return (NULL);
3345         ap->a_target = ptgt->m_devhdl;
3346         ap->a_lun = tgt_private->t_lun;
3347 
3348         ASSERT(callback == NULL_FUNC || callback == SLEEP_FUNC);
3349 #ifdef MPTSAS_TEST_EXTRN_ALLOC
3350         statuslen *= 100; tgtlen *= 4;
3351 #endif
3352         NDBG3(("mptsas_scsi_init_pkt:\n"
3353             "\ttgt=%d in=0x%p bp=0x%p clen=%d slen=%d tlen=%d flags=%x",
3354             ap->a_target, (void *)pkt, (void *)bp,
3355             cmdlen, statuslen, tgtlen, flags));
3356 
3357         /*
3358          * Allocate the new packet.
3359          */
3360         if (pkt == NULL) {
3361                 ddi_dma_handle_t        save_dma_handle;
3362                 ddi_dma_handle_t        save_arq_dma_handle;
3363                 struct buf              *save_arq_bp;
3364                 ddi_dma_cookie_t        save_arqcookie;
3365 #ifdef  __sparc
3366                 mptti_t                 *save_sg;
3367 #endif  /* __sparc */
3368 
3369                 cmd = kmem_cache_alloc(mpt->m_kmem_cache, kf);
3370 
3371                 if (cmd) {
3372                         save_dma_handle = cmd->cmd_dmahandle;
3373                         save_arq_dma_handle = cmd->cmd_arqhandle;
3374                         save_arq_bp = cmd->cmd_arq_buf;
3375                         save_arqcookie = cmd->cmd_arqcookie;
3376 #ifdef  __sparc
3377                         save_sg = cmd->cmd_sg;
3378 #endif  /* __sparc */
3379                         bzero(cmd, sizeof (*cmd) + scsi_pkt_size());
3380                         cmd->cmd_dmahandle = save_dma_handle;
3381                         cmd->cmd_arqhandle = save_arq_dma_handle;
3382                         cmd->cmd_arq_buf = save_arq_bp;
3383                         cmd->cmd_arqcookie = save_arqcookie;
3384 #ifdef  __sparc
3385                         cmd->cmd_sg = save_sg;
3386 #endif  /* __sparc */
3387                         pkt = (void *)((uchar_t *)cmd +
3388                             sizeof (struct mptsas_cmd));
3389                         pkt->pkt_ha_private = (opaque_t)cmd;
3390                         pkt->pkt_address = *ap;
3391                         pkt->pkt_private = (opaque_t)cmd->cmd_pkt_private;
3392                         pkt->pkt_scbp = (opaque_t)&cmd->cmd_scb;
3393                         pkt->pkt_cdbp = (opaque_t)&cmd->cmd_cdb;
3394                         cmd->cmd_pkt = (struct scsi_pkt *)pkt;
3395                         cmd->cmd_cdblen = (uchar_t)cmdlen;
3396                         cmd->cmd_scblen = statuslen;
3397                         cmd->cmd_rqslen = SENSE_LENGTH;
3398                         cmd->cmd_tgt_addr = ptgt;
3399                         failure = 0;
3400                 }
3401 
3402                 if (failure || (cmdlen > sizeof (cmd->cmd_cdb)) ||
3403                     (tgtlen > PKT_PRIV_LEN) ||
3404                     (statuslen > EXTCMDS_STATUS_SIZE)) {
3405                         if (failure == 0) {
3406                                 /*
3407                                  * if extern alloc fails, all will be
3408                                  * deallocated, including cmd
3409                                  */
3410                                 failure = mptsas_pkt_alloc_extern(mpt, cmd,
3411                                     cmdlen, tgtlen, statuslen, kf);
3412                         }
3413                         if (failure) {
3414                                 /*
3415                                  * if extern allocation fails, it will
3416                                  * deallocate the new pkt as well
3417                                  */
3418                                 return (NULL);
3419                         }
3420                 }
3421                 new_cmd = cmd;
3422 
3423         } else {
3424                 cmd = PKT2CMD(pkt);
3425                 new_cmd = NULL;
3426         }
3427 
3428 
3429 #ifndef __sparc
3430         /* grab cmd->cmd_cookiec here as oldcookiec */
3431 
3432         oldcookiec = cmd->cmd_cookiec;
3433 #endif  /* __sparc */
3434 
3435         /*
3436          * If the dma was broken up into PARTIAL transfers cmd_nwin will be
3437          * greater than 0 and we'll need to grab the next dma window
3438          */
3439         /*
3440          * SLM-not doing extra command frame right now; may add later
3441          */
3442 
3443         if (cmd->cmd_nwin > 0) {
3444 
3445                 /*
3446                  * Make sure we havn't gone past the the total number
3447                  * of windows
3448                  */
3449                 if (++cmd->cmd_winindex >= cmd->cmd_nwin) {
3450                         return (NULL);
3451                 }
3452                 if (ddi_dma_getwin(cmd->cmd_dmahandle, cmd->cmd_winindex,
3453                     &cmd->cmd_dma_offset, &cmd->cmd_dma_len,
3454                     &cmd->cmd_cookie, &cmd->cmd_cookiec) == DDI_FAILURE) {
3455                         return (NULL);
3456                 }
3457                 goto get_dma_cookies;
3458         }
3459 
3460 
3461         if (flags & PKT_XARQ) {
3462                 cmd->cmd_flags |= CFLAG_XARQ;
3463         }
3464 
3465         /*
3466          * DMA resource allocation.  This version assumes your
3467          * HBA has some sort of bus-mastering or onboard DMA capability, with a
3468          * scatter-gather list of length MPTSAS_MAX_DMA_SEGS, as given in the
3469          * ddi_dma_attr_t structure and passed to scsi_impl_dmaget.
3470          */
3471         if (bp && (bp->b_bcount != 0) &&
3472             (cmd->cmd_flags & CFLAG_DMAVALID) == 0) {
3473 
3474                 int     cnt, dma_flags;
3475                 mptti_t *dmap;          /* ptr to the S/G list */
3476 
3477                 /*
3478                  * Set up DMA memory and position to the next DMA segment.
3479                  */
3480                 ASSERT(cmd->cmd_dmahandle != NULL);
3481 
3482                 if (bp->b_flags & B_READ) {
3483                         dma_flags = DDI_DMA_READ;
3484                         cmd->cmd_flags &= ~CFLAG_DMASEND;
3485                 } else {
3486                         dma_flags = DDI_DMA_WRITE;
3487                         cmd->cmd_flags |= CFLAG_DMASEND;
3488                 }
3489                 if (flags & PKT_CONSISTENT) {
3490                         cmd->cmd_flags |= CFLAG_CMDIOPB;
3491                         dma_flags |= DDI_DMA_CONSISTENT;
3492                 }
3493 
3494                 if (flags & PKT_DMA_PARTIAL) {
3495                         dma_flags |= DDI_DMA_PARTIAL;
3496                 }
3497 
3498                 /*
3499                  * workaround for byte hole issue on psycho and
3500                  * schizo pre 2.1
3501                  */
3502                 if ((bp->b_flags & B_READ) && ((bp->b_flags &
3503                     (B_PAGEIO|B_REMAPPED)) != B_PAGEIO) &&
3504                     ((uintptr_t)bp->b_un.b_addr & 0x7)) {
3505                         dma_flags |= DDI_DMA_CONSISTENT;
3506                 }
3507 
3508                 rval = ddi_dma_buf_bind_handle(cmd->cmd_dmahandle, bp,
3509                     dma_flags, callback, arg,
3510                     &cmd->cmd_cookie, &cmd->cmd_cookiec);
3511                 if (rval == DDI_DMA_PARTIAL_MAP) {
3512                         (void) ddi_dma_numwin(cmd->cmd_dmahandle,
3513                             &cmd->cmd_nwin);
3514                         cmd->cmd_winindex = 0;
3515                         (void) ddi_dma_getwin(cmd->cmd_dmahandle,
3516                             cmd->cmd_winindex, &cmd->cmd_dma_offset,
3517                             &cmd->cmd_dma_len, &cmd->cmd_cookie,
3518                             &cmd->cmd_cookiec);
3519                 } else if (rval && (rval != DDI_DMA_MAPPED)) {
3520                         switch (rval) {
3521                         case DDI_DMA_NORESOURCES:
3522                                 bioerror(bp, 0);
3523                                 break;
3524                         case DDI_DMA_BADATTR:
3525                         case DDI_DMA_NOMAPPING:
3526                                 bioerror(bp, EFAULT);
3527                                 break;
3528                         case DDI_DMA_TOOBIG:
3529                         default:
3530                                 bioerror(bp, EINVAL);
3531                                 break;
3532                         }
3533                         cmd->cmd_flags &= ~CFLAG_DMAVALID;
3534                         if (new_cmd) {
3535                                 mptsas_scsi_destroy_pkt(ap, pkt);
3536                         }
3537                         return ((struct scsi_pkt *)NULL);
3538                 }
3539 
3540 get_dma_cookies:
3541                 cmd->cmd_flags |= CFLAG_DMAVALID;
3542                 ASSERT(cmd->cmd_cookiec > 0);
3543 
3544                 if (cmd->cmd_cookiec > MPTSAS_MAX_CMD_SEGS) {
3545                         mptsas_log(mpt, CE_NOTE, "large cookiec received %d\n",
3546                             cmd->cmd_cookiec);
3547                         bioerror(bp, EINVAL);
3548                         if (new_cmd) {
3549                                 mptsas_scsi_destroy_pkt(ap, pkt);
3550                         }
3551                         return ((struct scsi_pkt *)NULL);
3552                 }
3553 
3554                 /*
3555                  * Allocate extra SGL buffer if needed.
3556                  */
3557                 if ((cmd->cmd_cookiec > MPTSAS_MAX_FRAME_SGES64(mpt)) &&
3558                     (cmd->cmd_extra_frames == NULL)) {
3559                         if (mptsas_alloc_extra_sgl_frame(mpt, cmd) ==
3560                             DDI_FAILURE) {
3561                                 mptsas_log(mpt, CE_WARN, "MPT SGL mem alloc "
3562                                     "failed");
3563                                 bioerror(bp, ENOMEM);
3564                                 if (new_cmd) {
3565                                         mptsas_scsi_destroy_pkt(ap, pkt);
3566                                 }
3567                                 return ((struct scsi_pkt *)NULL);
3568                         }
3569                 }
3570 
3571                 /*
3572                  * Always use scatter-gather transfer
3573                  * Use the loop below to store physical addresses of
3574                  * DMA segments, from the DMA cookies, into your HBA's
3575                  * scatter-gather list.
3576                  * We need to ensure we have enough kmem alloc'd
3577                  * for the sg entries since we are no longer using an
3578                  * array inside mptsas_cmd_t.
3579                  *
3580                  * We check cmd->cmd_cookiec against oldcookiec so
3581                  * the scatter-gather list is correctly allocated
3582                  */
3583 #ifndef __sparc
3584                 if (oldcookiec != cmd->cmd_cookiec) {
3585                         if (cmd->cmd_sg != (mptti_t *)NULL) {
3586                                 kmem_free(cmd->cmd_sg, sizeof (mptti_t) *
3587                                     oldcookiec);
3588                                 cmd->cmd_sg = NULL;
3589                         }
3590                 }
3591 
3592                 if (cmd->cmd_sg == (mptti_t *)NULL) {
3593                         cmd->cmd_sg = kmem_alloc((size_t)(sizeof (mptti_t)*
3594                             cmd->cmd_cookiec), kf);
3595 
3596                         if (cmd->cmd_sg == (mptti_t *)NULL) {
3597                                 mptsas_log(mpt, CE_WARN,
3598                                     "unable to kmem_alloc enough memory "
3599                                     "for scatter/gather list");
3600                 /*
3601                  * if we have an ENOMEM condition we need to behave
3602                  * the same way as the rest of this routine
3603                  */
3604 
3605                                 bioerror(bp, ENOMEM);
3606                                 if (new_cmd) {
3607                                         mptsas_scsi_destroy_pkt(ap, pkt);
3608                                 }
3609                                 return ((struct scsi_pkt *)NULL);
3610                         }
3611                 }
3612 #endif  /* __sparc */
3613                 dmap = cmd->cmd_sg;
3614 
3615                 ASSERT(cmd->cmd_cookie.dmac_size != 0);
3616 
3617                 /*
3618                  * store the first segment into the S/G list
3619                  */
3620                 dmap->count = cmd->cmd_cookie.dmac_size;
3621                 dmap->addr.address64.Low = (uint32_t)
3622                     (cmd->cmd_cookie.dmac_laddress & 0xffffffffull);
3623                 dmap->addr.address64.High = (uint32_t)
3624                     (cmd->cmd_cookie.dmac_laddress >> 32);
3625 
3626                 /*
3627                  * dmacount counts the size of the dma for this window
3628                  * (if partial dma is being used).  totaldmacount
3629                  * keeps track of the total amount of dma we have
3630                  * transferred for all the windows (needed to calculate
3631                  * the resid value below).
3632                  */
3633                 cmd->cmd_dmacount = cmd->cmd_cookie.dmac_size;
3634                 cmd->cmd_totaldmacount += cmd->cmd_cookie.dmac_size;
3635 
3636                 /*
3637                  * We already stored the first DMA scatter gather segment,
3638                  * start at 1 if we need to store more.
3639                  */
3640                 for (cnt = 1; cnt < cmd->cmd_cookiec; cnt++) {
3641                         /*
3642                          * Get next DMA cookie
3643                          */
3644                         ddi_dma_nextcookie(cmd->cmd_dmahandle,
3645                             &cmd->cmd_cookie);
3646                         dmap++;
3647 
3648                         cmd->cmd_dmacount += cmd->cmd_cookie.dmac_size;
3649                         cmd->cmd_totaldmacount += cmd->cmd_cookie.dmac_size;
3650 
3651                         /*
3652                          * store the segment parms into the S/G list
3653                          */
3654                         dmap->count = cmd->cmd_cookie.dmac_size;
3655                         dmap->addr.address64.Low = (uint32_t)
3656                             (cmd->cmd_cookie.dmac_laddress & 0xffffffffull);
3657                         dmap->addr.address64.High = (uint32_t)
3658                             (cmd->cmd_cookie.dmac_laddress >> 32);
3659                 }
3660 
3661                 /*
3662                  * If this was partially allocated we set the resid
3663                  * the amount of data NOT transferred in this window
3664                  * If there is only one window, the resid will be 0
3665                  */
3666                 pkt->pkt_resid = (bp->b_bcount - cmd->cmd_totaldmacount);
3667                 NDBG16(("mptsas_dmaget: cmd_dmacount=%d.", cmd->cmd_dmacount));
3668         }
3669         return (pkt);
3670 }
3671 
3672 /*
3673  * tran_destroy_pkt(9E) - scsi_pkt(9s) deallocation
3674  *
3675  * Notes:
3676  *      - also frees DMA resources if allocated
3677  *      - implicit DMA synchonization
3678  */
3679 static void
3680 mptsas_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3681 {
3682         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
3683         mptsas_t        *mpt = ADDR2MPT(ap);
3684 
3685         NDBG3(("mptsas_scsi_destroy_pkt: target=%d pkt=0x%p",
3686             ap->a_target, (void *)pkt));
3687 
3688         if (cmd->cmd_flags & CFLAG_DMAVALID) {
3689                 (void) ddi_dma_unbind_handle(cmd->cmd_dmahandle);
3690                 cmd->cmd_flags &= ~CFLAG_DMAVALID;
3691         }
3692 #ifndef __sparc
3693         if (cmd->cmd_sg) {
3694                 kmem_free(cmd->cmd_sg, sizeof (mptti_t) * cmd->cmd_cookiec);
3695                 cmd->cmd_sg = NULL;
3696         }
3697 #endif  /* __sparc */
3698         mptsas_free_extra_sgl_frame(mpt, cmd);
3699 
3700         if ((cmd->cmd_flags &
3701             (CFLAG_FREE | CFLAG_CDBEXTERN | CFLAG_PRIVEXTERN |
3702             CFLAG_SCBEXTERN)) == 0) {
3703                 cmd->cmd_flags = CFLAG_FREE;
3704                 kmem_cache_free(mpt->m_kmem_cache, (void *)cmd);
3705         } else {
3706                 mptsas_pkt_destroy_extern(mpt, cmd);
3707         }
3708 }
3709 
3710 /*
3711  * kmem cache constructor and destructor:
3712  * When constructing, we bzero the cmd and allocate the dma handle
3713  * When destructing, just free the dma handle
3714  */
3715 static int
3716 mptsas_kmem_cache_constructor(void *buf, void *cdrarg, int kmflags)
3717 {
3718         mptsas_cmd_t            *cmd = buf;
3719         mptsas_t                *mpt  = cdrarg;
3720         struct scsi_address     ap;
3721         uint_t                  cookiec;
3722         ddi_dma_attr_t          arq_dma_attr;
3723         int                     (*callback)(caddr_t);
3724 
3725         callback = (kmflags == KM_SLEEP)? DDI_DMA_SLEEP: DDI_DMA_DONTWAIT;
3726 
3727         NDBG4(("mptsas_kmem_cache_constructor"));
3728 
3729         ap.a_hba_tran = mpt->m_tran;
3730         ap.a_target = 0;
3731         ap.a_lun = 0;
3732 
3733         /*
3734          * allocate a dma handle
3735          */
3736         if ((ddi_dma_alloc_handle(mpt->m_dip, &mpt->m_io_dma_attr, callback,
3737             NULL, &cmd->cmd_dmahandle)) != DDI_SUCCESS) {
3738                 cmd->cmd_dmahandle = NULL;
3739                 return (-1);
3740         }
3741 
3742         cmd->cmd_arq_buf = scsi_alloc_consistent_buf(&ap, (struct buf *)NULL,
3743             SENSE_LENGTH, B_READ, callback, NULL);
3744         if (cmd->cmd_arq_buf == NULL) {
3745                 ddi_dma_free_handle(&cmd->cmd_dmahandle);
3746                 cmd->cmd_dmahandle = NULL;
3747                 return (-1);
3748         }
3749 
3750         /*
3751          * allocate a arq handle
3752          */
3753         arq_dma_attr = mpt->m_msg_dma_attr;
3754         arq_dma_attr.dma_attr_sgllen = 1;
3755         if ((ddi_dma_alloc_handle(mpt->m_dip, &arq_dma_attr, callback,
3756             NULL, &cmd->cmd_arqhandle)) != DDI_SUCCESS) {
3757                 ddi_dma_free_handle(&cmd->cmd_dmahandle);
3758                 scsi_free_consistent_buf(cmd->cmd_arq_buf);
3759                 cmd->cmd_dmahandle = NULL;
3760                 cmd->cmd_arqhandle = NULL;
3761                 return (-1);
3762         }
3763 
3764         if (ddi_dma_buf_bind_handle(cmd->cmd_arqhandle,
3765             cmd->cmd_arq_buf, (DDI_DMA_READ | DDI_DMA_CONSISTENT),
3766             callback, NULL, &cmd->cmd_arqcookie, &cookiec) != DDI_SUCCESS) {
3767                 ddi_dma_free_handle(&cmd->cmd_dmahandle);
3768                 ddi_dma_free_handle(&cmd->cmd_arqhandle);
3769                 scsi_free_consistent_buf(cmd->cmd_arq_buf);
3770                 cmd->cmd_dmahandle = NULL;
3771                 cmd->cmd_arqhandle = NULL;
3772                 cmd->cmd_arq_buf = NULL;
3773                 return (-1);
3774         }
3775         /*
3776          * In sparc, the sgl length in most of the cases would be 1, so we
3777          * pre-allocate it in cache. On x86, the max number would be 256,
3778          * pre-allocate a maximum would waste a lot of memory especially
3779          * when many cmds are put onto waitq.
3780          */
3781 #ifdef  __sparc
3782         cmd->cmd_sg = kmem_alloc((size_t)(sizeof (mptti_t)*
3783             MPTSAS_MAX_CMD_SEGS), KM_SLEEP);
3784 #endif  /* __sparc */
3785 
3786         return (0);
3787 }
3788 
3789 static void
3790 mptsas_kmem_cache_destructor(void *buf, void *cdrarg)
3791 {
3792 #ifndef __lock_lint
3793         _NOTE(ARGUNUSED(cdrarg))
3794 #endif
3795         mptsas_cmd_t    *cmd = buf;
3796 
3797         NDBG4(("mptsas_kmem_cache_destructor"));
3798 
3799         if (cmd->cmd_arqhandle) {
3800                 (void) ddi_dma_unbind_handle(cmd->cmd_arqhandle);
3801                 ddi_dma_free_handle(&cmd->cmd_arqhandle);
3802                 cmd->cmd_arqhandle = NULL;
3803         }
3804         if (cmd->cmd_arq_buf) {
3805                 scsi_free_consistent_buf(cmd->cmd_arq_buf);
3806                 cmd->cmd_arq_buf = NULL;
3807         }
3808         if (cmd->cmd_dmahandle) {
3809                 ddi_dma_free_handle(&cmd->cmd_dmahandle);
3810                 cmd->cmd_dmahandle = NULL;
3811         }
3812 #ifdef  __sparc
3813         if (cmd->cmd_sg) {
3814                 kmem_free(cmd->cmd_sg, sizeof (mptti_t)* MPTSAS_MAX_CMD_SEGS);
3815                 cmd->cmd_sg = NULL;
3816         }
3817 #endif  /* __sparc */
3818 }
3819 
3820 static int
3821 mptsas_cache_frames_constructor(void *buf, void *cdrarg, int kmflags)
3822 {
3823         mptsas_cache_frames_t   *p = buf;
3824         mptsas_t                *mpt = cdrarg;
3825         ddi_dma_attr_t          frame_dma_attr;
3826         size_t                  mem_size, alloc_len;
3827         ddi_dma_cookie_t        cookie;
3828         uint_t                  ncookie;
3829         int (*callback)(caddr_t) = (kmflags == KM_SLEEP)
3830             ? DDI_DMA_SLEEP: DDI_DMA_DONTWAIT;
3831 
3832         frame_dma_attr = mpt->m_msg_dma_attr;
3833         frame_dma_attr.dma_attr_align = 0x10;
3834         frame_dma_attr.dma_attr_sgllen = 1;
3835 
3836         if (ddi_dma_alloc_handle(mpt->m_dip, &frame_dma_attr, callback, NULL,
3837             &p->m_dma_hdl) != DDI_SUCCESS) {
3838                 mptsas_log(mpt, CE_WARN, "Unable to allocate dma handle for"
3839                     " extra SGL.");
3840                 return (DDI_FAILURE);
3841         }
3842 
3843         mem_size = (mpt->m_max_request_frames - 1) * mpt->m_req_frame_size;
3844 
3845         if (ddi_dma_mem_alloc(p->m_dma_hdl, mem_size, &mpt->m_dev_acc_attr,
3846             DDI_DMA_CONSISTENT, callback, NULL, (caddr_t *)&p->m_frames_addr,
3847             &alloc_len, &p->m_acc_hdl) != DDI_SUCCESS) {
3848                 ddi_dma_free_handle(&p->m_dma_hdl);
3849                 p->m_dma_hdl = NULL;
3850                 mptsas_log(mpt, CE_WARN, "Unable to allocate dma memory for"
3851                     " extra SGL.");
3852                 return (DDI_FAILURE);
3853         }
3854 
3855         if (ddi_dma_addr_bind_handle(p->m_dma_hdl, NULL, p->m_frames_addr,
3856             alloc_len, DDI_DMA_RDWR | DDI_DMA_CONSISTENT, callback, NULL,
3857             &cookie, &ncookie) != DDI_DMA_MAPPED) {
3858                 (void) ddi_dma_mem_free(&p->m_acc_hdl);
3859                 ddi_dma_free_handle(&p->m_dma_hdl);
3860                 p->m_dma_hdl = NULL;
3861                 mptsas_log(mpt, CE_WARN, "Unable to bind DMA resources for"
3862                     " extra SGL");
3863                 return (DDI_FAILURE);
3864         }
3865 
3866         /*
3867          * Store the SGL memory address.  This chip uses this
3868          * address to dma to and from the driver.  The second
3869          * address is the address mpt uses to fill in the SGL.
3870          */
3871         p->m_phys_addr = cookie.dmac_address;
3872 
3873         return (DDI_SUCCESS);
3874 }
3875 
3876 static void
3877 mptsas_cache_frames_destructor(void *buf, void *cdrarg)
3878 {
3879 #ifndef __lock_lint
3880         _NOTE(ARGUNUSED(cdrarg))
3881 #endif
3882         mptsas_cache_frames_t   *p = buf;
3883         if (p->m_dma_hdl != NULL) {
3884                 (void) ddi_dma_unbind_handle(p->m_dma_hdl);
3885                 (void) ddi_dma_mem_free(&p->m_acc_hdl);
3886                 ddi_dma_free_handle(&p->m_dma_hdl);
3887                 p->m_phys_addr = NULL;
3888                 p->m_frames_addr = NULL;
3889                 p->m_dma_hdl = NULL;
3890                 p->m_acc_hdl = NULL;
3891         }
3892 
3893 }
3894 
3895 /*
3896  * allocate and deallocate external pkt space (ie. not part of mptsas_cmd)
3897  * for non-standard length cdb, pkt_private, status areas
3898  * if allocation fails, then deallocate all external space and the pkt
3899  */
3900 /* ARGSUSED */
3901 static int
3902 mptsas_pkt_alloc_extern(mptsas_t *mpt, mptsas_cmd_t *cmd,
3903     int cmdlen, int tgtlen, int statuslen, int kf)
3904 {
3905         caddr_t                 cdbp, scbp, tgt;
3906         int                     (*callback)(caddr_t) = (kf == KM_SLEEP) ?
3907             DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
3908         struct scsi_address     ap;
3909         size_t                  senselength;
3910         ddi_dma_attr_t          ext_arq_dma_attr;
3911         uint_t                  cookiec;
3912 
3913         NDBG3(("mptsas_pkt_alloc_extern: "
3914             "cmd=0x%p cmdlen=%d tgtlen=%d statuslen=%d kf=%x",
3915             (void *)cmd, cmdlen, tgtlen, statuslen, kf));
3916 
3917         tgt = cdbp = scbp = NULL;
3918         cmd->cmd_scblen              = statuslen;
3919         cmd->cmd_privlen     = (uchar_t)tgtlen;
3920 
3921         if (cmdlen > sizeof (cmd->cmd_cdb)) {
3922                 if ((cdbp = kmem_zalloc((size_t)cmdlen, kf)) == NULL) {
3923                         goto fail;
3924                 }
3925                 cmd->cmd_pkt->pkt_cdbp = (opaque_t)cdbp;
3926                 cmd->cmd_flags |= CFLAG_CDBEXTERN;
3927         }
3928         if (tgtlen > PKT_PRIV_LEN) {
3929                 if ((tgt = kmem_zalloc((size_t)tgtlen, kf)) == NULL) {
3930                         goto fail;
3931                 }
3932                 cmd->cmd_flags |= CFLAG_PRIVEXTERN;
3933                 cmd->cmd_pkt->pkt_private = tgt;
3934         }
3935         if (statuslen > EXTCMDS_STATUS_SIZE) {
3936                 if ((scbp = kmem_zalloc((size_t)statuslen, kf)) == NULL) {
3937                         goto fail;
3938                 }
3939                 cmd->cmd_flags |= CFLAG_SCBEXTERN;
3940                 cmd->cmd_pkt->pkt_scbp = (opaque_t)scbp;
3941 
3942                 /* allocate sense data buf for DMA */
3943 
3944                 senselength = statuslen - MPTSAS_GET_ITEM_OFF(
3945                     struct scsi_arq_status, sts_sensedata);
3946                 cmd->cmd_rqslen = (uchar_t)senselength;
3947 
3948                 ap.a_hba_tran = mpt->m_tran;
3949                 ap.a_target = 0;
3950                 ap.a_lun = 0;
3951 
3952                 cmd->cmd_ext_arq_buf = scsi_alloc_consistent_buf(&ap,
3953                     (struct buf *)NULL, senselength, B_READ,
3954                     callback, NULL);
3955 
3956                 if (cmd->cmd_ext_arq_buf == NULL) {
3957                         goto fail;
3958                 }
3959                 /*
3960                  * allocate a extern arq handle and bind the buf
3961                  */
3962                 ext_arq_dma_attr = mpt->m_msg_dma_attr;
3963                 ext_arq_dma_attr.dma_attr_sgllen = 1;
3964                 if ((ddi_dma_alloc_handle(mpt->m_dip,
3965                     &ext_arq_dma_attr, callback,
3966                     NULL, &cmd->cmd_ext_arqhandle)) != DDI_SUCCESS) {
3967                         goto fail;
3968                 }
3969 
3970                 if (ddi_dma_buf_bind_handle(cmd->cmd_ext_arqhandle,
3971                     cmd->cmd_ext_arq_buf, (DDI_DMA_READ | DDI_DMA_CONSISTENT),
3972                     callback, NULL, &cmd->cmd_ext_arqcookie,
3973                     &cookiec)
3974                     != DDI_SUCCESS) {
3975                         goto fail;
3976                 }
3977                 cmd->cmd_flags |= CFLAG_EXTARQBUFVALID;
3978         }
3979         return (0);
3980 fail:
3981         mptsas_pkt_destroy_extern(mpt, cmd);
3982         return (1);
3983 }
3984 
3985 /*
3986  * deallocate external pkt space and deallocate the pkt
3987  */
3988 static void
3989 mptsas_pkt_destroy_extern(mptsas_t *mpt, mptsas_cmd_t *cmd)
3990 {
3991         NDBG3(("mptsas_pkt_destroy_extern: cmd=0x%p", (void *)cmd));
3992 
3993         if (cmd->cmd_flags & CFLAG_FREE) {
3994                 mptsas_log(mpt, CE_PANIC,
3995                     "mptsas_pkt_destroy_extern: freeing free packet");
3996                 _NOTE(NOT_REACHED)
3997                 /* NOTREACHED */
3998         }
3999         if (cmd->cmd_flags & CFLAG_CDBEXTERN) {
4000                 kmem_free(cmd->cmd_pkt->pkt_cdbp, (size_t)cmd->cmd_cdblen);
4001         }
4002         if (cmd->cmd_flags & CFLAG_SCBEXTERN) {
4003                 kmem_free(cmd->cmd_pkt->pkt_scbp, (size_t)cmd->cmd_scblen);
4004                 if (cmd->cmd_flags & CFLAG_EXTARQBUFVALID) {
4005                         (void) ddi_dma_unbind_handle(cmd->cmd_ext_arqhandle);
4006                 }
4007                 if (cmd->cmd_ext_arqhandle) {
4008                         ddi_dma_free_handle(&cmd->cmd_ext_arqhandle);
4009                         cmd->cmd_ext_arqhandle = NULL;
4010                 }
4011                 if (cmd->cmd_ext_arq_buf)
4012                         scsi_free_consistent_buf(cmd->cmd_ext_arq_buf);
4013         }
4014         if (cmd->cmd_flags & CFLAG_PRIVEXTERN) {
4015                 kmem_free(cmd->cmd_pkt->pkt_private, (size_t)cmd->cmd_privlen);
4016         }
4017         cmd->cmd_flags = CFLAG_FREE;
4018         kmem_cache_free(mpt->m_kmem_cache, (void *)cmd);
4019 }
4020 
4021 /*
4022  * tran_sync_pkt(9E) - explicit DMA synchronization
4023  */
4024 /*ARGSUSED*/
4025 static void
4026 mptsas_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
4027 {
4028         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
4029 
4030         NDBG3(("mptsas_scsi_sync_pkt: target=%d, pkt=0x%p",
4031             ap->a_target, (void *)pkt));
4032 
4033         if (cmd->cmd_dmahandle) {
4034                 (void) ddi_dma_sync(cmd->cmd_dmahandle, 0, 0,
4035                     (cmd->cmd_flags & CFLAG_DMASEND) ?
4036                     DDI_DMA_SYNC_FORDEV : DDI_DMA_SYNC_FORCPU);
4037         }
4038 }
4039 
4040 /*
4041  * tran_dmafree(9E) - deallocate DMA resources allocated for command
4042  */
4043 /*ARGSUSED*/
4044 static void
4045 mptsas_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
4046 {
4047         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
4048         mptsas_t        *mpt = ADDR2MPT(ap);
4049 
4050         NDBG3(("mptsas_scsi_dmafree: target=%d pkt=0x%p",
4051             ap->a_target, (void *)pkt));
4052 
4053         if (cmd->cmd_flags & CFLAG_DMAVALID) {
4054                 (void) ddi_dma_unbind_handle(cmd->cmd_dmahandle);
4055                 cmd->cmd_flags &= ~CFLAG_DMAVALID;
4056         }
4057 
4058         if (cmd->cmd_flags & CFLAG_EXTARQBUFVALID) {
4059                 (void) ddi_dma_unbind_handle(cmd->cmd_ext_arqhandle);
4060                 cmd->cmd_flags &= ~CFLAG_EXTARQBUFVALID;
4061         }
4062 
4063         mptsas_free_extra_sgl_frame(mpt, cmd);
4064 }
4065 
4066 static void
4067 mptsas_pkt_comp(struct scsi_pkt *pkt, mptsas_cmd_t *cmd)
4068 {
4069         if ((cmd->cmd_flags & CFLAG_CMDIOPB) &&
4070             (!(cmd->cmd_flags & CFLAG_DMASEND))) {
4071                 (void) ddi_dma_sync(cmd->cmd_dmahandle, 0, 0,
4072                     DDI_DMA_SYNC_FORCPU);
4073         }
4074         (*pkt->pkt_comp)(pkt);
4075 }
4076 
4077 static void
4078 mptsas_sge_setup(mptsas_t *mpt, mptsas_cmd_t *cmd, uint32_t *control,
4079         pMpi2SCSIIORequest_t frame, ddi_acc_handle_t acc_hdl)
4080 {
4081         uint_t                  cookiec;
4082         mptti_t                 *dmap;
4083         uint32_t                flags;
4084         pMpi2SGESimple64_t      sge;
4085         pMpi2SGEChain64_t       sgechain;
4086         ASSERT(cmd->cmd_flags & CFLAG_DMAVALID);
4087 
4088         /*
4089          * Save the number of entries in the DMA
4090          * Scatter/Gather list
4091          */
4092         cookiec = cmd->cmd_cookiec;
4093 
4094         NDBG1(("mptsas_sge_setup: cookiec=%d", cookiec));
4095 
4096         /*
4097          * Set read/write bit in control.
4098          */
4099         if (cmd->cmd_flags & CFLAG_DMASEND) {
4100                 *control |= MPI2_SCSIIO_CONTROL_WRITE;
4101         } else {
4102                 *control |= MPI2_SCSIIO_CONTROL_READ;
4103         }
4104 
4105         ddi_put32(acc_hdl, &frame->DataLength, cmd->cmd_dmacount);
4106 
4107         /*
4108          * We have 2 cases here.  First where we can fit all the
4109          * SG elements into the main frame, and the case
4110          * where we can't.
4111          * If we have more cookies than we can attach to a frame
4112          * we will need to use a chain element to point
4113          * a location of memory where the rest of the S/G
4114          * elements reside.
4115          */
4116         if (cookiec <= MPTSAS_MAX_FRAME_SGES64(mpt)) {
4117                 dmap = cmd->cmd_sg;
4118                 sge = (pMpi2SGESimple64_t)(&frame->SGL);
4119                 while (cookiec--) {
4120                         ddi_put32(acc_hdl,
4121                             &sge->Address.Low, dmap->addr.address64.Low);
4122                         ddi_put32(acc_hdl,
4123                             &sge->Address.High, dmap->addr.address64.High);
4124                         ddi_put32(acc_hdl, &sge->FlagsLength,
4125                             dmap->count);
4126                         flags = ddi_get32(acc_hdl, &sge->FlagsLength);
4127                         flags |= ((uint32_t)
4128                             (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
4129                             MPI2_SGE_FLAGS_SYSTEM_ADDRESS |
4130                             MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
4131                             MPI2_SGE_FLAGS_SHIFT);
4132 
4133                         /*
4134                          * If this is the last cookie, we set the flags
4135                          * to indicate so
4136                          */
4137                         if (cookiec == 0) {
4138                                 flags |=
4139                                     ((uint32_t)(MPI2_SGE_FLAGS_LAST_ELEMENT
4140                                     | MPI2_SGE_FLAGS_END_OF_BUFFER
4141                                     | MPI2_SGE_FLAGS_END_OF_LIST) <<
4142                                     MPI2_SGE_FLAGS_SHIFT);
4143                         }
4144                         if (cmd->cmd_flags & CFLAG_DMASEND) {
4145                                 flags |= (MPI2_SGE_FLAGS_HOST_TO_IOC <<
4146                                     MPI2_SGE_FLAGS_SHIFT);
4147                         } else {
4148                                 flags |= (MPI2_SGE_FLAGS_IOC_TO_HOST <<
4149                                     MPI2_SGE_FLAGS_SHIFT);
4150                         }
4151                         ddi_put32(acc_hdl, &sge->FlagsLength, flags);
4152                         dmap++;
4153                         sge++;
4154                 }
4155         } else {
4156                 /*
4157                  * Hereby we start to deal with multiple frames.
4158                  * The process is as follows:
4159                  * 1. Determine how many frames are needed for SGL element
4160                  *    storage; Note that all frames are stored in contiguous
4161                  *    memory space and in 64-bit DMA mode each element is
4162                  *    3 double-words (12 bytes) long.
4163                  * 2. Fill up the main frame. We need to do this separately
4164                  *    since it contains the SCSI IO request header and needs
4165                  *    dedicated processing. Note that the last 4 double-words
4166                  *    of the SCSI IO header is for SGL element storage
4167                  *    (MPI2_SGE_IO_UNION).
4168                  * 3. Fill the chain element in the main frame, so the DMA
4169                  *    engine can use the following frames.
4170                  * 4. Enter a loop to fill the remaining frames. Note that the
4171                  *    last frame contains no chain element.  The remaining
4172                  *    frames go into the mpt SGL buffer allocated on the fly,
4173                  *    not immediately following the main message frame, as in
4174                  *    Gen1.
4175                  * Some restrictions:
4176                  * 1. For 64-bit DMA, the simple element and chain element
4177                  *    are both of 3 double-words (12 bytes) in size, even
4178                  *    though all frames are stored in the first 4G of mem
4179                  *    range and the higher 32-bits of the address are always 0.
4180                  * 2. On some controllers (like the 1064/1068), a frame can
4181                  *    hold SGL elements with the last 1 or 2 double-words
4182                  *    (4 or 8 bytes) un-used. On these controllers, we should
4183                  *    recognize that there's not enough room for another SGL
4184                  *    element and move the sge pointer to the next frame.
4185                  */
4186                 int             i, j, k, l, frames, sgemax;
4187                 int             temp;
4188                 uint8_t         chainflags;
4189                 uint16_t        chainlength;
4190                 mptsas_cache_frames_t *p;
4191 
4192                 /*
4193                  * Sgemax is the number of SGE's that will fit
4194                  * each extra frame and frames is total
4195                  * number of frames we'll need.  1 sge entry per
4196                  * frame is reseverd for the chain element thus the -1 below.
4197                  */
4198                 sgemax = ((mpt->m_req_frame_size / sizeof (MPI2_SGE_SIMPLE64))
4199                     - 1);
4200                 temp = (cookiec - (MPTSAS_MAX_FRAME_SGES64(mpt) - 1)) / sgemax;
4201 
4202                 /*
4203                  * A little check to see if we need to round up the number
4204                  * of frames we need
4205                  */
4206                 if ((cookiec - (MPTSAS_MAX_FRAME_SGES64(mpt) - 1)) - (temp *
4207                     sgemax) > 1) {
4208                         frames = (temp + 1);
4209                 } else {
4210                         frames = temp;
4211                 }
4212                 dmap = cmd->cmd_sg;
4213                 sge = (pMpi2SGESimple64_t)(&frame->SGL);
4214 
4215                 /*
4216                  * First fill in the main frame
4217                  */
4218                 for (j = 1; j < MPTSAS_MAX_FRAME_SGES64(mpt); j++) {
4219                         ddi_put32(acc_hdl, &sge->Address.Low,
4220                             dmap->addr.address64.Low);
4221                         ddi_put32(acc_hdl, &sge->Address.High,
4222                             dmap->addr.address64.High);
4223                         ddi_put32(acc_hdl, &sge->FlagsLength, dmap->count);
4224                         flags = ddi_get32(acc_hdl, &sge->FlagsLength);
4225                         flags |= ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
4226                             MPI2_SGE_FLAGS_SYSTEM_ADDRESS |
4227                             MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
4228                             MPI2_SGE_FLAGS_SHIFT);
4229 
4230                         /*
4231                          * If this is the last SGE of this frame
4232                          * we set the end of list flag
4233                          */
4234                         if (j == (MPTSAS_MAX_FRAME_SGES64(mpt) - 1)) {
4235                                 flags |= ((uint32_t)
4236                                     (MPI2_SGE_FLAGS_LAST_ELEMENT) <<
4237                                     MPI2_SGE_FLAGS_SHIFT);
4238                         }
4239                         if (cmd->cmd_flags & CFLAG_DMASEND) {
4240                                 flags |=
4241                                     (MPI2_SGE_FLAGS_HOST_TO_IOC <<
4242                                     MPI2_SGE_FLAGS_SHIFT);
4243                         } else {
4244                                 flags |=
4245                                     (MPI2_SGE_FLAGS_IOC_TO_HOST <<
4246                                     MPI2_SGE_FLAGS_SHIFT);
4247                         }
4248                         ddi_put32(acc_hdl, &sge->FlagsLength, flags);
4249                         dmap++;
4250                         sge++;
4251                 }
4252 
4253                 /*
4254                  * Fill in the chain element in the main frame.
4255                  * About calculation on ChainOffset:
4256                  * 1. Struct msg_scsi_io_request has 4 double-words (16 bytes)
4257                  *    in the end reserved for SGL element storage
4258                  *    (MPI2_SGE_IO_UNION); we should count it in our
4259                  *    calculation.  See its definition in the header file.
4260                  * 2. Constant j is the counter of the current SGL element
4261                  *    that will be processed, and (j - 1) is the number of
4262                  *    SGL elements that have been processed (stored in the
4263                  *    main frame).
4264                  * 3. ChainOffset value should be in units of double-words (4
4265                  *    bytes) so the last value should be divided by 4.
4266                  */
4267                 ddi_put8(acc_hdl, &frame->ChainOffset,
4268                     (sizeof (MPI2_SCSI_IO_REQUEST) -
4269                     sizeof (MPI2_SGE_IO_UNION) +
4270                     (j - 1) * sizeof (MPI2_SGE_SIMPLE64)) >> 2);
4271                 sgechain = (pMpi2SGEChain64_t)sge;
4272                 chainflags = (MPI2_SGE_FLAGS_CHAIN_ELEMENT |
4273                     MPI2_SGE_FLAGS_SYSTEM_ADDRESS |
4274                     MPI2_SGE_FLAGS_64_BIT_ADDRESSING);
4275                 ddi_put8(acc_hdl, &sgechain->Flags, chainflags);
4276 
4277                 /*
4278                  * The size of the next frame is the accurate size of space
4279                  * (in bytes) used to store the SGL elements. j is the counter
4280                  * of SGL elements. (j - 1) is the number of SGL elements that
4281                  * have been processed (stored in frames).
4282                  */
4283                 if (frames >= 2) {
4284                         chainlength = mpt->m_req_frame_size /
4285                             sizeof (MPI2_SGE_SIMPLE64) *
4286                             sizeof (MPI2_SGE_SIMPLE64);
4287                 } else {
4288                         chainlength = ((cookiec - (j - 1)) *
4289                             sizeof (MPI2_SGE_SIMPLE64));
4290                 }
4291 
4292                 p = cmd->cmd_extra_frames;
4293 
4294                 ddi_put16(acc_hdl, &sgechain->Length, chainlength);
4295                 ddi_put32(acc_hdl, &sgechain->Address.Low,
4296                     p->m_phys_addr);
4297                 /* SGL is allocated in the first 4G mem range */
4298                 ddi_put32(acc_hdl, &sgechain->Address.High, 0);
4299 
4300                 /*
4301                  * If there are more than 2 frames left we have to
4302                  * fill in the next chain offset to the location of
4303                  * the chain element in the next frame.
4304                  * sgemax is the number of simple elements in an extra
4305                  * frame. Note that the value NextChainOffset should be
4306                  * in double-words (4 bytes).
4307                  */
4308                 if (frames >= 2) {
4309                         ddi_put8(acc_hdl, &sgechain->NextChainOffset,
4310                             (sgemax * sizeof (MPI2_SGE_SIMPLE64)) >> 2);
4311                 } else {
4312                         ddi_put8(acc_hdl, &sgechain->NextChainOffset, 0);
4313                 }
4314 
4315                 /*
4316                  * Jump to next frame;
4317                  * Starting here, chain buffers go into the per command SGL.
4318                  * This buffer is allocated when chain buffers are needed.
4319                  */
4320                 sge = (pMpi2SGESimple64_t)p->m_frames_addr;
4321                 i = cookiec;
4322 
4323                 /*
4324                  * Start filling in frames with SGE's.  If we
4325                  * reach the end of frame and still have SGE's
4326                  * to fill we need to add a chain element and
4327                  * use another frame.  j will be our counter
4328                  * for what cookie we are at and i will be
4329                  * the total cookiec. k is the current frame
4330                  */
4331                 for (k = 1; k <= frames; k++) {
4332                         for (l = 1; (l <= (sgemax + 1)) && (j <= i); j++, l++) {
4333 
4334                                 /*
4335                                  * If we have reached the end of frame
4336                                  * and we have more SGE's to fill in
4337                                  * we have to fill the final entry
4338                                  * with a chain element and then
4339                                  * continue to the next frame
4340                                  */
4341                                 if ((l == (sgemax + 1)) && (k != frames)) {
4342                                         sgechain = (pMpi2SGEChain64_t)sge;
4343                                         j--;
4344                                         chainflags = (
4345                                             MPI2_SGE_FLAGS_CHAIN_ELEMENT |
4346                                             MPI2_SGE_FLAGS_SYSTEM_ADDRESS |
4347                                             MPI2_SGE_FLAGS_64_BIT_ADDRESSING);
4348                                         ddi_put8(p->m_acc_hdl,
4349                                             &sgechain->Flags, chainflags);
4350                                         /*
4351                                          * k is the frame counter and (k + 1)
4352                                          * is the number of the next frame.
4353                                          * Note that frames are in contiguous
4354                                          * memory space.
4355                                          */
4356                                         ddi_put32(p->m_acc_hdl,
4357                                             &sgechain->Address.Low,
4358                                             (p->m_phys_addr +
4359                                             (mpt->m_req_frame_size * k)));
4360                                         ddi_put32(p->m_acc_hdl,
4361                                             &sgechain->Address.High, 0);
4362 
4363                                         /*
4364                                          * If there are more than 2 frames left
4365                                          * we have to next chain offset to
4366                                          * the location of the chain element
4367                                          * in the next frame and fill in the
4368                                          * length of the next chain
4369                                          */
4370                                         if ((frames - k) >= 2) {
4371                                                 ddi_put8(p->m_acc_hdl,
4372                                                     &sgechain->NextChainOffset,
4373                                                     (sgemax *
4374                                                     sizeof (MPI2_SGE_SIMPLE64))
4375                                                     >> 2);
4376                                                 ddi_put16(p->m_acc_hdl,
4377                                                     &sgechain->Length,
4378                                                     mpt->m_req_frame_size /
4379                                                     sizeof (MPI2_SGE_SIMPLE64) *
4380                                                     sizeof (MPI2_SGE_SIMPLE64));
4381                                         } else {
4382                                                 /*
4383                                                  * This is the last frame. Set
4384                                                  * the NextChainOffset to 0 and
4385                                                  * Length is the total size of
4386                                                  * all remaining simple elements
4387                                                  */
4388                                                 ddi_put8(p->m_acc_hdl,
4389                                                     &sgechain->NextChainOffset,
4390                                                     0);
4391                                                 ddi_put16(p->m_acc_hdl,
4392                                                     &sgechain->Length,
4393                                                     (cookiec - j) *
4394                                                     sizeof (MPI2_SGE_SIMPLE64));
4395                                         }
4396 
4397                                         /* Jump to the next frame */
4398                                         sge = (pMpi2SGESimple64_t)
4399                                             ((char *)p->m_frames_addr +
4400                                             (int)mpt->m_req_frame_size * k);
4401 
4402                                         continue;
4403                                 }
4404 
4405                                 ddi_put32(p->m_acc_hdl,
4406                                     &sge->Address.Low,
4407                                     dmap->addr.address64.Low);
4408                                 ddi_put32(p->m_acc_hdl,
4409                                     &sge->Address.High,
4410                                     dmap->addr.address64.High);
4411                                 ddi_put32(p->m_acc_hdl,
4412                                     &sge->FlagsLength, dmap->count);
4413                                 flags = ddi_get32(p->m_acc_hdl,
4414                                     &sge->FlagsLength);
4415                                 flags |= ((uint32_t)(
4416                                     MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
4417                                     MPI2_SGE_FLAGS_SYSTEM_ADDRESS |
4418                                     MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
4419                                     MPI2_SGE_FLAGS_SHIFT);
4420 
4421                                 /*
4422                                  * If we are at the end of the frame and
4423                                  * there is another frame to fill in
4424                                  * we set the last simple element as last
4425                                  * element
4426                                  */
4427                                 if ((l == sgemax) && (k != frames)) {
4428                                         flags |= ((uint32_t)
4429                                             (MPI2_SGE_FLAGS_LAST_ELEMENT) <<
4430                                             MPI2_SGE_FLAGS_SHIFT);
4431                                 }
4432 
4433                                 /*
4434                                  * If this is the final cookie we
4435                                  * indicate it by setting the flags
4436                                  */
4437                                 if (j == i) {
4438                                         flags |= ((uint32_t)
4439                                             (MPI2_SGE_FLAGS_LAST_ELEMENT |
4440                                             MPI2_SGE_FLAGS_END_OF_BUFFER |
4441                                             MPI2_SGE_FLAGS_END_OF_LIST) <<
4442                                             MPI2_SGE_FLAGS_SHIFT);
4443                                 }
4444                                 if (cmd->cmd_flags & CFLAG_DMASEND) {
4445                                         flags |=
4446                                             (MPI2_SGE_FLAGS_HOST_TO_IOC <<
4447                                             MPI2_SGE_FLAGS_SHIFT);
4448                                 } else {
4449                                         flags |=
4450                                             (MPI2_SGE_FLAGS_IOC_TO_HOST <<
4451                                             MPI2_SGE_FLAGS_SHIFT);
4452                                 }
4453                                 ddi_put32(p->m_acc_hdl,
4454                                     &sge->FlagsLength, flags);
4455                                 dmap++;
4456                                 sge++;
4457                         }
4458                 }
4459 
4460                 /*
4461                  * Sync DMA with the chain buffers that were just created
4462                  */
4463                 (void) ddi_dma_sync(p->m_dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);
4464         }
4465 }
4466 
4467 /*
4468  * Interrupt handling
4469  * Utility routine.  Poll for status of a command sent to HBA
4470  * without interrupts (a FLAG_NOINTR command).
4471  */
4472 int
4473 mptsas_poll(mptsas_t *mpt, mptsas_cmd_t *poll_cmd, int polltime)
4474 {
4475         int     rval = TRUE;
4476 
4477         NDBG5(("mptsas_poll: cmd=0x%p", (void *)poll_cmd));
4478 
4479         /*
4480          * In order to avoid using m_mutex in ISR(a new separate mutex
4481          * m_intr_mutex is introduced) and keep the same lock logic,
4482          * the m_intr_mutex should be used to protect the getting and
4483          * setting of the ReplyDescriptorIndex.
4484          *
4485          * Since the m_intr_mutex would be released during processing the poll
4486          * cmd, so we should set the poll flag earlier here to make sure the
4487          * polled cmd be handled in this thread/context. A side effect is other
4488          * cmds during the period between the flag set and reset are also
4489          * handled in this thread and not the ISR. Since the poll cmd is not
4490          * so common, so the performance degradation in this case is not a big
4491          * issue.
4492          */
4493         mutex_enter(&mpt->m_intr_mutex);
4494         mpt->m_polled_intr = 1;
4495         mutex_exit(&mpt->m_intr_mutex);
4496 
4497         if ((poll_cmd->cmd_flags & CFLAG_TM_CMD) == 0) {
4498                 mptsas_restart_hba(mpt);
4499         }
4500 
4501         /*
4502          * Wait, using drv_usecwait(), long enough for the command to
4503          * reasonably return from the target if the target isn't
4504          * "dead".  A polled command may well be sent from scsi_poll, and
4505          * there are retries built in to scsi_poll if the transport
4506          * accepted the packet (TRAN_ACCEPT).  scsi_poll waits 1 second
4507          * and retries the transport up to scsi_poll_busycnt times
4508          * (currently 60) if
4509          * 1. pkt_reason is CMD_INCOMPLETE and pkt_state is 0, or
4510          * 2. pkt_reason is CMD_CMPLT and *pkt_scbp has STATUS_BUSY
4511          *
4512          * limit the waiting to avoid a hang in the event that the
4513          * cmd never gets started but we are still receiving interrupts
4514          */
4515         while (!(poll_cmd->cmd_flags & CFLAG_FINISHED)) {
4516                 if (mptsas_wait_intr(mpt, polltime) == FALSE) {
4517                         NDBG5(("mptsas_poll: command incomplete"));
4518                         rval = FALSE;
4519                         break;
4520                 }
4521         }
4522 
4523         mutex_enter(&mpt->m_intr_mutex);
4524         mpt->m_polled_intr = 0;
4525         mutex_exit(&mpt->m_intr_mutex);
4526 
4527         if (rval == FALSE) {
4528 
4529                 /*
4530                  * this isn't supposed to happen, the hba must be wedged
4531                  * Mark this cmd as a timeout.
4532                  */
4533                 mptsas_set_pkt_reason(mpt, poll_cmd, CMD_TIMEOUT,
4534                     (STAT_TIMEOUT|STAT_ABORTED));
4535 
4536                 if (poll_cmd->cmd_queued == FALSE) {
4537 
4538                         NDBG5(("mptsas_poll: not on waitq"));
4539 
4540                         poll_cmd->cmd_pkt->pkt_state |=
4541                             (STATE_GOT_BUS|STATE_GOT_TARGET|STATE_SENT_CMD);
4542                 } else {
4543 
4544                         /* find and remove it from the waitq */
4545                         NDBG5(("mptsas_poll: delete from waitq"));
4546                         mptsas_waitq_delete(mpt, poll_cmd);
4547                 }
4548 
4549         }
4550         mptsas_fma_check(mpt, poll_cmd);
4551         NDBG5(("mptsas_poll: done"));
4552         return (rval);
4553 }
4554 
4555 /*
4556  * Used for polling cmds and TM function
4557  */
4558 static int
4559 mptsas_wait_intr(mptsas_t *mpt, int polltime)
4560 {
4561         int                             cnt;
4562         pMpi2ReplyDescriptorsUnion_t    reply_desc_union;
4563         Mpi2ReplyDescriptorsUnion_t     reply_desc_union_v;
4564         uint32_t                        int_mask;
4565         uint8_t reply_type;
4566 
4567         NDBG5(("mptsas_wait_intr"));
4568 
4569 
4570         /*
4571          * Get the current interrupt mask and disable interrupts.  When
4572          * re-enabling ints, set mask to saved value.
4573          */
4574         int_mask = ddi_get32(mpt->m_datap, &mpt->m_reg->HostInterruptMask);
4575         MPTSAS_DISABLE_INTR(mpt);
4576 
4577         /*
4578          * Keep polling for at least (polltime * 1000) seconds
4579          */
4580         for (cnt = 0; cnt < polltime; cnt++) {
4581                 mutex_enter(&mpt->m_intr_mutex);
4582                 (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
4583                     DDI_DMA_SYNC_FORCPU);
4584 
4585                 reply_desc_union = (pMpi2ReplyDescriptorsUnion_t)
4586                     MPTSAS_GET_NEXT_REPLY(mpt, mpt->m_post_index);
4587 
4588                 if (ddi_get32(mpt->m_acc_post_queue_hdl,
4589                     &reply_desc_union->Words.Low) == 0xFFFFFFFF ||
4590                     ddi_get32(mpt->m_acc_post_queue_hdl,
4591                     &reply_desc_union->Words.High) == 0xFFFFFFFF) {
4592                         mutex_exit(&mpt->m_intr_mutex);
4593                         drv_usecwait(1000);
4594                         continue;
4595                 }
4596 
4597                 reply_type = ddi_get8(mpt->m_acc_post_queue_hdl,
4598                     &reply_desc_union->Default.ReplyFlags);
4599                 reply_type &= MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
4600                 reply_desc_union_v.Default.ReplyFlags = reply_type;
4601                 if (reply_type == MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS) {
4602                         reply_desc_union_v.SCSIIOSuccess.SMID =
4603                             ddi_get16(mpt->m_acc_post_queue_hdl,
4604                             &reply_desc_union->SCSIIOSuccess.SMID);
4605                 } else if (reply_type ==
4606                     MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {
4607                         reply_desc_union_v.AddressReply.ReplyFrameAddress =
4608                             ddi_get32(mpt->m_acc_post_queue_hdl,
4609                             &reply_desc_union->AddressReply.ReplyFrameAddress);
4610                         reply_desc_union_v.AddressReply.SMID =
4611                             ddi_get16(mpt->m_acc_post_queue_hdl,
4612                             &reply_desc_union->AddressReply.SMID);
4613                 }
4614                 /*
4615                  * Clear the reply descriptor for re-use and increment
4616                  * index.
4617                  */
4618                 ddi_put64(mpt->m_acc_post_queue_hdl,
4619                     &((uint64_t *)(void *)mpt->m_post_queue)[mpt->m_post_index],
4620                     0xFFFFFFFFFFFFFFFF);
4621                 (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
4622                     DDI_DMA_SYNC_FORDEV);
4623 
4624                 if (++mpt->m_post_index == mpt->m_post_queue_depth) {
4625                         mpt->m_post_index = 0;
4626                 }
4627 
4628                 /*
4629                  * Update the global reply index
4630                  */
4631                 ddi_put32(mpt->m_datap,
4632                     &mpt->m_reg->ReplyPostHostIndex, mpt->m_post_index);
4633                 mutex_exit(&mpt->m_intr_mutex);
4634 
4635                 /*
4636                  * The reply is valid, process it according to its
4637                  * type.
4638                  */
4639                 mptsas_process_intr(mpt, &reply_desc_union_v);
4640 
4641 
4642                 /*
4643                  * Re-enable interrupts and quit.
4644                  */
4645                 ddi_put32(mpt->m_datap, &mpt->m_reg->HostInterruptMask,
4646                     int_mask);
4647                 return (TRUE);
4648 
4649         }
4650 
4651         /*
4652          * Clear polling flag, re-enable interrupts and quit.
4653          */
4654         ddi_put32(mpt->m_datap, &mpt->m_reg->HostInterruptMask, int_mask);
4655         return (FALSE);
4656 }
4657 
4658 /*
4659  * For fastpath, the m_intr_mutex should be held from the begining to the end,
4660  * so we only treat those cmds that need not release m_intr_mutex(even just for
4661  * a moment) as candidate for fast processing. otherwise, we don't handle them
4662  * and just return, then in ISR, those cmds would be handled later with m_mutex
4663  * held and m_intr_mutex not held.
4664  */
4665 static int
4666 mptsas_handle_io_fastpath(mptsas_t *mpt,
4667     uint16_t SMID)
4668 {
4669         mptsas_slots_t                          *slots = mpt->m_active;
4670         mptsas_cmd_t                            *cmd = NULL;
4671         struct scsi_pkt                         *pkt;
4672 
4673         /*
4674          * This is a success reply so just complete the IO.  First, do a sanity
4675          * check on the SMID.  The final slot is used for TM requests, which
4676          * would not come into this reply handler.
4677          */
4678         if ((SMID == 0) || (SMID > slots->m_n_slots)) {
4679                 mptsas_log(mpt, CE_WARN, "?Received invalid SMID of %d\n",
4680                     SMID);
4681                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
4682                 return (TRUE);
4683         }
4684 
4685         cmd = slots->m_slot[SMID];
4686 
4687         /*
4688          * print warning and return if the slot is empty
4689          */
4690         if (cmd == NULL) {
4691                 mptsas_log(mpt, CE_WARN, "?NULL command for successful SCSI IO "
4692                     "in slot %d", SMID);
4693                 return (TRUE);
4694         }
4695 
4696         pkt = CMD2PKT(cmd);
4697         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
4698             STATE_GOT_STATUS);
4699         if (cmd->cmd_flags & CFLAG_DMAVALID) {
4700                 pkt->pkt_state |= STATE_XFERRED_DATA;
4701         }
4702         pkt->pkt_resid = 0;
4703 
4704         /*
4705          * If the cmd is a IOC, or a passthrough, then we don't process it in
4706          * fastpath, and later it would be handled by mptsas_process_intr()
4707          * with m_mutex protected.
4708          */
4709         if (cmd->cmd_flags & (CFLAG_PASSTHRU | CFLAG_CMDIOC)) {
4710                 return (FALSE);
4711         } else {
4712                 mptsas_remove_cmd0(mpt, cmd);
4713         }
4714 
4715         if (cmd->cmd_flags & CFLAG_RETRY) {
4716                 /*
4717                  * The target returned QFULL or busy, do not add tihs
4718                  * pkt to the doneq since the hba will retry
4719                  * this cmd.
4720                  *
4721                  * The pkt has already been resubmitted in
4722                  * mptsas_handle_qfull() or in mptsas_check_scsi_io_error().
4723                  * Remove this cmd_flag here.
4724                  */
4725                 cmd->cmd_flags &= ~CFLAG_RETRY;
4726         } else {
4727                 mptsas_doneq_add0(mpt, cmd);
4728         }
4729 
4730         /*
4731          * In fastpath, the cmd should only be a context reply, so just check
4732          * the post queue of the reply descriptor and the dmahandle of the cmd
4733          * is enough. No sense data in this case and no need to check the dma
4734          * handle where sense data dma info is saved, the dma handle of the
4735          * reply frame, and the dma handle of the reply free queue.
4736          * For the dma handle of the request queue. Check fma here since we
4737          * are sure the request must have already been sent/DMAed correctly.
4738          * otherwise checking in mptsas_scsi_start() is not correct since
4739          * at that time the dma may not start.
4740          */
4741         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl) !=
4742             DDI_SUCCESS) ||
4743             (mptsas_check_dma_handle(mpt->m_dma_post_queue_hdl) !=
4744             DDI_SUCCESS)) {
4745                 ddi_fm_service_impact(mpt->m_dip,
4746                     DDI_SERVICE_UNAFFECTED);
4747                 pkt->pkt_reason = CMD_TRAN_ERR;
4748                 pkt->pkt_statistics = 0;
4749         }
4750         if (cmd->cmd_dmahandle &&
4751             (mptsas_check_dma_handle(cmd->cmd_dmahandle) != DDI_SUCCESS)) {
4752                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
4753                 pkt->pkt_reason = CMD_TRAN_ERR;
4754                 pkt->pkt_statistics = 0;
4755         }
4756         if ((cmd->cmd_extra_frames &&
4757             ((mptsas_check_dma_handle(cmd->cmd_extra_frames->m_dma_hdl) !=
4758             DDI_SUCCESS) ||
4759             (mptsas_check_acc_handle(cmd->cmd_extra_frames->m_acc_hdl) !=
4760             DDI_SUCCESS)))) {
4761                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
4762                 pkt->pkt_reason = CMD_TRAN_ERR;
4763                 pkt->pkt_statistics = 0;
4764         }
4765 
4766         return (TRUE);
4767 }
4768 
4769 static void
4770 mptsas_handle_scsi_io_success(mptsas_t *mpt,
4771     pMpi2ReplyDescriptorsUnion_t reply_desc)
4772 {
4773         pMpi2SCSIIOSuccessReplyDescriptor_t     scsi_io_success;
4774         uint16_t                                SMID;
4775         mptsas_slots_t                          *slots = mpt->m_active;
4776         mptsas_cmd_t                            *cmd = NULL;
4777         struct scsi_pkt                         *pkt;
4778 
4779         scsi_io_success = (pMpi2SCSIIOSuccessReplyDescriptor_t)reply_desc;
4780         SMID = scsi_io_success->SMID;
4781 
4782         /*
4783          * This is a success reply so just complete the IO.  First, do a sanity
4784          * check on the SMID.  The final slot is used for TM requests, which
4785          * would not come into this reply handler.
4786          */
4787         if ((SMID == 0) || (SMID > slots->m_n_slots)) {
4788                 mptsas_log(mpt, CE_WARN, "?Received invalid SMID of %d\n",
4789                     SMID);
4790                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
4791                 return;
4792         }
4793 
4794         cmd = slots->m_slot[SMID];
4795 
4796         /*
4797          * print warning and return if the slot is empty
4798          */
4799         if (cmd == NULL) {
4800                 mptsas_log(mpt, CE_WARN, "?NULL command for successful SCSI IO "
4801                     "in slot %d", SMID);
4802                 return;
4803         }
4804 
4805         pkt = CMD2PKT(cmd);
4806         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
4807             STATE_GOT_STATUS);
4808         if (cmd->cmd_flags & CFLAG_DMAVALID) {
4809                 pkt->pkt_state |= STATE_XFERRED_DATA;
4810         }
4811         pkt->pkt_resid = 0;
4812 
4813         if (cmd->cmd_flags & CFLAG_PASSTHRU) {
4814                 cmd->cmd_flags |= CFLAG_FINISHED;
4815                 cv_broadcast(&mpt->m_passthru_cv);
4816                 return;
4817         } else {
4818                 mptsas_remove_cmd(mpt, cmd);
4819         }
4820 
4821         if (cmd->cmd_flags & CFLAG_RETRY) {
4822                 /*
4823                  * The target returned QFULL or busy, do not add tihs
4824                  * pkt to the doneq since the hba will retry
4825                  * this cmd.
4826                  *
4827                  * The pkt has already been resubmitted in
4828                  * mptsas_handle_qfull() or in mptsas_check_scsi_io_error().
4829                  * Remove this cmd_flag here.
4830                  */
4831                 cmd->cmd_flags &= ~CFLAG_RETRY;
4832         } else {
4833                 mptsas_doneq_add(mpt, cmd);
4834         }
4835 }
4836 
4837 static void
4838 mptsas_handle_address_reply(mptsas_t *mpt,
4839     pMpi2ReplyDescriptorsUnion_t reply_desc)
4840 {
4841         pMpi2AddressReplyDescriptor_t   address_reply;
4842         pMPI2DefaultReply_t             reply;
4843         mptsas_fw_diagnostic_buffer_t   *pBuffer;
4844         uint32_t                        reply_addr;
4845         uint16_t                        SMID, iocstatus;
4846         mptsas_slots_t                  *slots = mpt->m_active;
4847         mptsas_cmd_t                    *cmd = NULL;
4848         uint8_t                         function, buffer_type;
4849         m_replyh_arg_t                  *args;
4850         int                             reply_frame_no;
4851 
4852         ASSERT(mutex_owned(&mpt->m_mutex));
4853 
4854         address_reply = (pMpi2AddressReplyDescriptor_t)reply_desc;
4855 
4856         reply_addr = address_reply->ReplyFrameAddress;
4857         SMID = address_reply->SMID;
4858         /*
4859          * If reply frame is not in the proper range we should ignore this
4860          * message and exit the interrupt handler.
4861          */
4862         if ((reply_addr < mpt->m_reply_frame_dma_addr) ||
4863             (reply_addr >= (mpt->m_reply_frame_dma_addr +
4864             (mpt->m_reply_frame_size * mpt->m_max_replies))) ||
4865             ((reply_addr - mpt->m_reply_frame_dma_addr) %
4866             mpt->m_reply_frame_size != 0)) {
4867                 mptsas_log(mpt, CE_WARN, "?Received invalid reply frame "
4868                     "address 0x%x\n", reply_addr);
4869                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
4870                 return;
4871         }
4872 
4873         (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
4874             DDI_DMA_SYNC_FORCPU);
4875         reply = (pMPI2DefaultReply_t)(mpt->m_reply_frame + (reply_addr -
4876             mpt->m_reply_frame_dma_addr));
4877         function = ddi_get8(mpt->m_acc_reply_frame_hdl, &reply->Function);
4878 
4879         /*
4880          * don't get slot information and command for events since these values
4881          * don't exist
4882          */
4883         if ((function != MPI2_FUNCTION_EVENT_NOTIFICATION) &&
4884             (function != MPI2_FUNCTION_DIAG_BUFFER_POST)) {
4885                 /*
4886                  * This could be a TM reply, which use the last allocated SMID,
4887                  * so allow for that.
4888                  */
4889                 if ((SMID == 0) || (SMID > (slots->m_n_slots + 1))) {
4890                         mptsas_log(mpt, CE_WARN, "?Received invalid SMID of "
4891                             "%d\n", SMID);
4892                         ddi_fm_service_impact(mpt->m_dip,
4893                             DDI_SERVICE_UNAFFECTED);
4894                         return;
4895                 }
4896 
4897                 cmd = slots->m_slot[SMID];
4898 
4899                 /*
4900                  * print warning and return if the slot is empty
4901                  */
4902                 if (cmd == NULL) {
4903                         mptsas_log(mpt, CE_WARN, "?NULL command for address "
4904                             "reply in slot %d", SMID);
4905                         return;
4906                 }
4907                 if ((cmd->cmd_flags & CFLAG_PASSTHRU) ||
4908                     (cmd->cmd_flags & CFLAG_CONFIG) ||
4909                     (cmd->cmd_flags & CFLAG_FW_DIAG)) {
4910                         cmd->cmd_rfm = reply_addr;
4911                         cmd->cmd_flags |= CFLAG_FINISHED;
4912                         cv_broadcast(&mpt->m_passthru_cv);
4913                         cv_broadcast(&mpt->m_config_cv);
4914                         cv_broadcast(&mpt->m_fw_diag_cv);
4915                         return;
4916                 } else if (!(cmd->cmd_flags & CFLAG_FW_CMD)) {
4917                         mptsas_remove_cmd(mpt, cmd);
4918                 }
4919                 NDBG31(("\t\tmptsas_process_intr: slot=%d", SMID));
4920         }
4921         /*
4922          * Depending on the function, we need to handle
4923          * the reply frame (and cmd) differently.
4924          */
4925         switch (function) {
4926         case MPI2_FUNCTION_SCSI_IO_REQUEST:
4927                 mptsas_check_scsi_io_error(mpt, (pMpi2SCSIIOReply_t)reply, cmd);
4928                 break;
4929         case MPI2_FUNCTION_SCSI_TASK_MGMT:
4930                 cmd->cmd_rfm = reply_addr;
4931                 mptsas_check_task_mgt(mpt, (pMpi2SCSIManagementReply_t)reply,
4932                     cmd);
4933                 break;
4934         case MPI2_FUNCTION_FW_DOWNLOAD:
4935                 cmd->cmd_flags |= CFLAG_FINISHED;
4936                 cv_signal(&mpt->m_fw_cv);
4937                 break;
4938         case MPI2_FUNCTION_EVENT_NOTIFICATION:
4939                 reply_frame_no = (reply_addr - mpt->m_reply_frame_dma_addr) /
4940                     mpt->m_reply_frame_size;
4941                 args = &mpt->m_replyh_args[reply_frame_no];
4942                 args->mpt = (void *)mpt;
4943                 args->rfm = reply_addr;
4944 
4945                 /*
4946                  * Record the event if its type is enabled in
4947                  * this mpt instance by ioctl.
4948                  */
4949                 mptsas_record_event(args);
4950 
4951                 /*
4952                  * Handle time critical events
4953                  * NOT_RESPONDING/ADDED only now
4954                  */
4955                 if (mptsas_handle_event_sync(args) == DDI_SUCCESS) {
4956                         /*
4957                          * Would not return main process,
4958                          * just let taskq resolve ack action
4959                          * and ack would be sent in taskq thread
4960                          */
4961                         NDBG20(("send mptsas_handle_event_sync success"));
4962                 }
4963                 if ((ddi_taskq_dispatch(mpt->m_event_taskq, mptsas_handle_event,
4964                     (void *)args, DDI_NOSLEEP)) != DDI_SUCCESS) {
4965                         mptsas_log(mpt, CE_WARN, "No memory available"
4966                         "for dispatch taskq");
4967                         /*
4968                          * Return the reply frame to the free queue.
4969                          */
4970                         ddi_put32(mpt->m_acc_free_queue_hdl,
4971                             &((uint32_t *)(void *)
4972                             mpt->m_free_queue)[mpt->m_free_index], reply_addr);
4973                         (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
4974                             DDI_DMA_SYNC_FORDEV);
4975                         if (++mpt->m_free_index == mpt->m_free_queue_depth) {
4976                                 mpt->m_free_index = 0;
4977                         }
4978 
4979                         ddi_put32(mpt->m_datap,
4980                             &mpt->m_reg->ReplyFreeHostIndex, mpt->m_free_index);
4981                 }
4982                 return;
4983         case MPI2_FUNCTION_DIAG_BUFFER_POST:
4984                 /*
4985                  * If SMID is 0, this implies that the reply is due to a
4986                  * release function with a status that the buffer has been
4987                  * released.  Set the buffer flags accordingly.
4988                  */
4989                 if (SMID == 0) {
4990                         iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
4991                             &reply->IOCStatus);
4992                         buffer_type = ddi_get8(mpt->m_acc_reply_frame_hdl,
4993                             &(((pMpi2DiagBufferPostReply_t)reply)->BufferType));
4994                         if (iocstatus == MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED) {
4995                                 pBuffer =
4996                                     &mpt->m_fw_diag_buffer_list[buffer_type];
4997                                 pBuffer->valid_data = TRUE;
4998                                 pBuffer->owned_by_firmware = FALSE;
4999                                 pBuffer->immediate = FALSE;
5000                         }
5001                 } else {
5002                         /*
5003                          * Normal handling of diag post reply with SMID.
5004                          */
5005                         cmd = slots->m_slot[SMID];
5006 
5007                         /*
5008                          * print warning and return if the slot is empty
5009                          */
5010                         if (cmd == NULL) {
5011                                 mptsas_log(mpt, CE_WARN, "?NULL command for "
5012                                     "address reply in slot %d", SMID);
5013                                 return;
5014                         }
5015                         cmd->cmd_rfm = reply_addr;
5016                         cmd->cmd_flags |= CFLAG_FINISHED;
5017                         cv_broadcast(&mpt->m_fw_diag_cv);
5018                 }
5019                 return;
5020         default:
5021                 mptsas_log(mpt, CE_WARN, "Unknown function 0x%x ", function);
5022                 break;
5023         }
5024 
5025         /*
5026          * Return the reply frame to the free queue.
5027          */
5028         ddi_put32(mpt->m_acc_free_queue_hdl,
5029             &((uint32_t *)(void *)mpt->m_free_queue)[mpt->m_free_index],
5030             reply_addr);
5031         (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
5032             DDI_DMA_SYNC_FORDEV);
5033         if (++mpt->m_free_index == mpt->m_free_queue_depth) {
5034                 mpt->m_free_index = 0;
5035         }
5036         ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex,
5037             mpt->m_free_index);
5038 
5039         if (cmd->cmd_flags & CFLAG_FW_CMD)
5040                 return;
5041 
5042         if (cmd->cmd_flags & CFLAG_RETRY) {
5043                 /*
5044                  * The target returned QFULL or busy, do not add tihs
5045                  * pkt to the doneq since the hba will retry
5046                  * this cmd.
5047                  *
5048                  * The pkt has already been resubmitted in
5049                  * mptsas_handle_qfull() or in mptsas_check_scsi_io_error().
5050                  * Remove this cmd_flag here.
5051                  */
5052                 cmd->cmd_flags &= ~CFLAG_RETRY;
5053         } else {
5054                 mptsas_doneq_add(mpt, cmd);
5055         }
5056 }
5057 
5058 static void
5059 mptsas_check_scsi_io_error(mptsas_t *mpt, pMpi2SCSIIOReply_t reply,
5060     mptsas_cmd_t *cmd)
5061 {
5062         uint8_t                 scsi_status, scsi_state;
5063         uint16_t                ioc_status;
5064         uint32_t                xferred, sensecount, responsedata, loginfo = 0;
5065         struct scsi_pkt         *pkt;
5066         struct scsi_arq_status  *arqstat;
5067         struct buf              *bp;
5068         mptsas_target_t         *ptgt = cmd->cmd_tgt_addr;
5069         uint8_t                 *sensedata = NULL;
5070 
5071         if ((cmd->cmd_flags & (CFLAG_SCBEXTERN | CFLAG_EXTARQBUFVALID)) ==
5072             (CFLAG_SCBEXTERN | CFLAG_EXTARQBUFVALID)) {
5073                 bp = cmd->cmd_ext_arq_buf;
5074         } else {
5075                 bp = cmd->cmd_arq_buf;
5076         }
5077 
5078         scsi_status = ddi_get8(mpt->m_acc_reply_frame_hdl, &reply->SCSIStatus);
5079         ioc_status = ddi_get16(mpt->m_acc_reply_frame_hdl, &reply->IOCStatus);
5080         scsi_state = ddi_get8(mpt->m_acc_reply_frame_hdl, &reply->SCSIState);
5081         xferred = ddi_get32(mpt->m_acc_reply_frame_hdl, &reply->TransferCount);
5082         sensecount = ddi_get32(mpt->m_acc_reply_frame_hdl, &reply->SenseCount);
5083         responsedata = ddi_get32(mpt->m_acc_reply_frame_hdl,
5084             &reply->ResponseInfo);
5085 
5086         if (ioc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
5087                 loginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
5088                     &reply->IOCLogInfo);
5089                 mptsas_log(mpt, CE_NOTE,
5090                     "?Log info 0x%x received for target %d.\n"
5091                     "\tscsi_status=0x%x, ioc_status=0x%x, scsi_state=0x%x",
5092                     loginfo, Tgt(cmd), scsi_status, ioc_status,
5093                     scsi_state);
5094         }
5095 
5096         NDBG31(("\t\tscsi_status=0x%x, ioc_status=0x%x, scsi_state=0x%x",
5097             scsi_status, ioc_status, scsi_state));
5098 
5099         pkt = CMD2PKT(cmd);
5100         *(pkt->pkt_scbp) = scsi_status;
5101 
5102         if (loginfo == 0x31170000) {
5103                 /*
5104                  * if loginfo PL_LOGINFO_CODE_IO_DEVICE_MISSING_DELAY_RETRY
5105                  * 0x31170000 comes, that means the device missing delay
5106                  * is in progressing, the command need retry later.
5107                  */
5108                 *(pkt->pkt_scbp) = STATUS_BUSY;
5109                 return;
5110         }
5111 
5112         if ((scsi_state & MPI2_SCSI_STATE_NO_SCSI_STATUS) &&
5113             ((ioc_status & MPI2_IOCSTATUS_MASK) ==
5114             MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE)) {
5115                 pkt->pkt_reason = CMD_INCOMPLETE;
5116                 pkt->pkt_state |= STATE_GOT_BUS;
5117                 mutex_enter(&ptgt->m_tgt_intr_mutex);
5118                 if (ptgt->m_reset_delay == 0) {
5119                         mptsas_set_throttle(mpt, ptgt,
5120                             DRAIN_THROTTLE);
5121                 }
5122                 mutex_exit(&ptgt->m_tgt_intr_mutex);
5123                 return;
5124         }
5125 
5126         if (scsi_state & MPI2_SCSI_STATE_RESPONSE_INFO_VALID) {
5127                 responsedata &= 0x000000FF;
5128                 if (responsedata & MPTSAS_SCSI_RESPONSE_CODE_TLR_OFF) {
5129                         mptsas_log(mpt, CE_NOTE, "Do not support the TLR\n");
5130                         pkt->pkt_reason = CMD_TLR_OFF;
5131                         return;
5132                 }
5133         }
5134 
5135 
5136         switch (scsi_status) {
5137         case MPI2_SCSI_STATUS_CHECK_CONDITION:
5138                 pkt->pkt_resid = (cmd->cmd_dmacount - xferred);
5139                 arqstat = (void*)(pkt->pkt_scbp);
5140                 arqstat->sts_rqpkt_status = *((struct scsi_status *)
5141                     (pkt->pkt_scbp));
5142                 pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET |
5143                     STATE_SENT_CMD | STATE_GOT_STATUS | STATE_ARQ_DONE);
5144                 if (cmd->cmd_flags & CFLAG_XARQ) {
5145                         pkt->pkt_state |= STATE_XARQ_DONE;
5146                 }
5147                 if (pkt->pkt_resid != cmd->cmd_dmacount) {
5148                         pkt->pkt_state |= STATE_XFERRED_DATA;
5149                 }
5150                 arqstat->sts_rqpkt_reason = pkt->pkt_reason;
5151                 arqstat->sts_rqpkt_state  = pkt->pkt_state;
5152                 arqstat->sts_rqpkt_state |= STATE_XFERRED_DATA;
5153                 arqstat->sts_rqpkt_statistics = pkt->pkt_statistics;
5154                 sensedata = (uint8_t *)&arqstat->sts_sensedata;
5155 
5156                 bcopy((uchar_t *)bp->b_un.b_addr, sensedata,
5157                     ((cmd->cmd_rqslen >= sensecount) ? sensecount :
5158                     cmd->cmd_rqslen));
5159                 arqstat->sts_rqpkt_resid = (cmd->cmd_rqslen - sensecount);
5160                 cmd->cmd_flags |= CFLAG_CMDARQ;
5161                 /*
5162                  * Set proper status for pkt if autosense was valid
5163                  */
5164                 if (scsi_state & MPI2_SCSI_STATE_AUTOSENSE_VALID) {
5165                         struct scsi_status zero_status = { 0 };
5166                         arqstat->sts_rqpkt_status = zero_status;
5167                 }
5168 
5169                 /*
5170                  * ASC=0x47 is parity error
5171                  * ASC=0x48 is initiator detected error received
5172                  */
5173                 if ((scsi_sense_key(sensedata) == KEY_ABORTED_COMMAND) &&
5174                     ((scsi_sense_asc(sensedata) == 0x47) ||
5175                     (scsi_sense_asc(sensedata) == 0x48))) {
5176                         mptsas_log(mpt, CE_NOTE, "Aborted_command!");
5177                 }
5178 
5179                 /*
5180                  * ASC/ASCQ=0x3F/0x0E means report_luns data changed
5181                  * ASC/ASCQ=0x25/0x00 means invalid lun
5182                  */
5183                 if (((scsi_sense_key(sensedata) == KEY_UNIT_ATTENTION) &&
5184                     (scsi_sense_asc(sensedata) == 0x3F) &&
5185                     (scsi_sense_ascq(sensedata) == 0x0E)) ||
5186                     ((scsi_sense_key(sensedata) == KEY_ILLEGAL_REQUEST) &&
5187                     (scsi_sense_asc(sensedata) == 0x25) &&
5188                     (scsi_sense_ascq(sensedata) == 0x00))) {
5189                         mptsas_topo_change_list_t *topo_node = NULL;
5190 
5191                         topo_node = kmem_zalloc(
5192                             sizeof (mptsas_topo_change_list_t),
5193                             KM_NOSLEEP);
5194                         if (topo_node == NULL) {
5195                                 mptsas_log(mpt, CE_NOTE, "No memory"
5196                                     "resource for handle SAS dynamic"
5197                                     "reconfigure.\n");
5198                                 break;
5199                         }
5200                         topo_node->mpt = mpt;
5201                         topo_node->event = MPTSAS_DR_EVENT_RECONFIG_TARGET;
5202                         topo_node->un.phymask = ptgt->m_phymask;
5203                         topo_node->devhdl = ptgt->m_devhdl;
5204                         topo_node->object = (void *)ptgt;
5205                         topo_node->flags = MPTSAS_TOPO_FLAG_LUN_ASSOCIATED;
5206 
5207                         if ((ddi_taskq_dispatch(mpt->m_dr_taskq,
5208                             mptsas_handle_dr,
5209                             (void *)topo_node,
5210                             DDI_NOSLEEP)) != DDI_SUCCESS) {
5211                                 mptsas_log(mpt, CE_NOTE, "mptsas start taskq"
5212                                     "for handle SAS dynamic reconfigure"
5213                                     "failed. \n");
5214                         }
5215                 }
5216                 break;
5217         case MPI2_SCSI_STATUS_GOOD:
5218                 switch (ioc_status & MPI2_IOCSTATUS_MASK) {
5219                 case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
5220                         pkt->pkt_reason = CMD_DEV_GONE;
5221                         pkt->pkt_state |= STATE_GOT_BUS;
5222                         mutex_enter(&ptgt->m_tgt_intr_mutex);
5223                         if (ptgt->m_reset_delay == 0) {
5224                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
5225                         }
5226                         mutex_exit(&ptgt->m_tgt_intr_mutex);
5227                         NDBG31(("lost disk for target%d, command:%x",
5228                             Tgt(cmd), pkt->pkt_cdbp[0]));
5229                         break;
5230                 case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
5231                         NDBG31(("data overrun: xferred=%d", xferred));
5232                         NDBG31(("dmacount=%d", cmd->cmd_dmacount));
5233                         pkt->pkt_reason = CMD_DATA_OVR;
5234                         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET
5235                             | STATE_SENT_CMD | STATE_GOT_STATUS
5236                             | STATE_XFERRED_DATA);
5237                         pkt->pkt_resid = 0;
5238                         break;
5239                 case MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
5240                 case MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN:
5241                         NDBG31(("data underrun: xferred=%d", xferred));
5242                         NDBG31(("dmacount=%d", cmd->cmd_dmacount));
5243                         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET
5244                             | STATE_SENT_CMD | STATE_GOT_STATUS);
5245                         pkt->pkt_resid = (cmd->cmd_dmacount - xferred);
5246                         if (pkt->pkt_resid != cmd->cmd_dmacount) {
5247                                 pkt->pkt_state |= STATE_XFERRED_DATA;
5248                         }
5249                         break;
5250                 case MPI2_IOCSTATUS_SCSI_TASK_TERMINATED:
5251                         mptsas_set_pkt_reason(mpt,
5252                             cmd, CMD_RESET, STAT_BUS_RESET);
5253                         break;
5254                 case MPI2_IOCSTATUS_SCSI_IOC_TERMINATED:
5255                 case MPI2_IOCSTATUS_SCSI_EXT_TERMINATED:
5256                         mptsas_set_pkt_reason(mpt,
5257                             cmd, CMD_RESET, STAT_DEV_RESET);
5258                         break;
5259                 case MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR:
5260                 case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
5261                         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET);
5262                         mptsas_set_pkt_reason(mpt,
5263                             cmd, CMD_TERMINATED, STAT_TERMINATED);
5264                         break;
5265                 case MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES:
5266                 case MPI2_IOCSTATUS_BUSY:
5267                         /*
5268                          * set throttles to drain
5269                          */
5270                         ptgt = (mptsas_target_t *)mptsas_hash_traverse(
5271                             &mpt->m_active->m_tgttbl, MPTSAS_HASH_FIRST);
5272                         while (ptgt != NULL) {
5273                                 mutex_enter(&ptgt->m_tgt_intr_mutex);
5274                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
5275                                 mutex_exit(&ptgt->m_tgt_intr_mutex);
5276 
5277                                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
5278                                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
5279                         }
5280 
5281                         /*
5282                          * retry command
5283                          */
5284                         cmd->cmd_flags |= CFLAG_RETRY;
5285                         cmd->cmd_pkt_flags |= FLAG_HEAD;
5286 
5287                         mutex_exit(&mpt->m_mutex);
5288                         (void) mptsas_accept_pkt(mpt, cmd);
5289                         mutex_enter(&mpt->m_mutex);
5290                         break;
5291                 default:
5292                         mptsas_log(mpt, CE_WARN,
5293                             "unknown ioc_status = %x\n", ioc_status);
5294                         mptsas_log(mpt, CE_CONT, "scsi_state = %x, transfer "
5295                             "count = %x, scsi_status = %x", scsi_state,
5296                             xferred, scsi_status);
5297                         break;
5298                 }
5299                 break;
5300         case MPI2_SCSI_STATUS_TASK_SET_FULL:
5301                 mptsas_handle_qfull(mpt, cmd);
5302                 break;
5303         case MPI2_SCSI_STATUS_BUSY:
5304                 NDBG31(("scsi_status busy received"));
5305                 break;
5306         case MPI2_SCSI_STATUS_RESERVATION_CONFLICT:
5307                 NDBG31(("scsi_status reservation conflict received"));
5308                 break;
5309         default:
5310                 mptsas_log(mpt, CE_WARN, "scsi_status=%x, ioc_status=%x\n",
5311                     scsi_status, ioc_status);
5312                 mptsas_log(mpt, CE_WARN,
5313                     "mptsas_process_intr: invalid scsi status\n");
5314                 break;
5315         }
5316 }
5317 
5318 static void
5319 mptsas_check_task_mgt(mptsas_t *mpt, pMpi2SCSIManagementReply_t reply,
5320         mptsas_cmd_t *cmd)
5321 {
5322         uint8_t         task_type;
5323         uint16_t        ioc_status;
5324         uint32_t        log_info;
5325         uint16_t        dev_handle;
5326         struct scsi_pkt *pkt = CMD2PKT(cmd);
5327 
5328         task_type = ddi_get8(mpt->m_acc_reply_frame_hdl, &reply->TaskType);
5329         ioc_status = ddi_get16(mpt->m_acc_reply_frame_hdl, &reply->IOCStatus);
5330         log_info = ddi_get32(mpt->m_acc_reply_frame_hdl, &reply->IOCLogInfo);
5331         dev_handle = ddi_get16(mpt->m_acc_reply_frame_hdl, &reply->DevHandle);
5332 
5333         if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
5334                 mptsas_log(mpt, CE_WARN, "mptsas_check_task_mgt: Task 0x%x "
5335                     "failed. IOCStatus=0x%x IOCLogInfo=0x%x target=%d\n",
5336                     task_type, ioc_status, log_info, dev_handle);
5337                 pkt->pkt_reason = CMD_INCOMPLETE;
5338                 return;
5339         }
5340 
5341         switch (task_type) {
5342         case MPI2_SCSITASKMGMT_TASKTYPE_ABORT_TASK:
5343         case MPI2_SCSITASKMGMT_TASKTYPE_CLEAR_TASK_SET:
5344         case MPI2_SCSITASKMGMT_TASKTYPE_QUERY_TASK:
5345         case MPI2_SCSITASKMGMT_TASKTYPE_CLR_ACA:
5346         case MPI2_SCSITASKMGMT_TASKTYPE_QRY_TASK_SET:
5347         case MPI2_SCSITASKMGMT_TASKTYPE_QRY_UNIT_ATTENTION:
5348                 break;
5349         case MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET:
5350         case MPI2_SCSITASKMGMT_TASKTYPE_LOGICAL_UNIT_RESET:
5351         case MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET:
5352                 /*
5353                  * Check for invalid DevHandle of 0 in case application
5354                  * sends bad command.  DevHandle of 0 could cause problems.
5355                  */
5356                 if (dev_handle == 0) {
5357                         mptsas_log(mpt, CE_WARN, "!Can't flush target with"
5358                             " DevHandle of 0.");
5359                 } else {
5360                         mptsas_flush_target(mpt, dev_handle, Lun(cmd),
5361                             task_type);
5362                 }
5363                 break;
5364         default:
5365                 mptsas_log(mpt, CE_WARN, "Unknown task management type %d.",
5366                     task_type);
5367                 mptsas_log(mpt, CE_WARN, "ioc status = %x", ioc_status);
5368                 break;
5369         }
5370 }
5371 
5372 static void
5373 mptsas_doneq_thread(mptsas_doneq_thread_arg_t *arg)
5374 {
5375         mptsas_t                        *mpt = arg->mpt;
5376         uint64_t                        t = arg->t;
5377         mptsas_cmd_t                    *cmd;
5378         struct scsi_pkt                 *pkt;
5379         mptsas_doneq_thread_list_t      *item = &mpt->m_doneq_thread_id[t];
5380 
5381         mutex_enter(&item->mutex);
5382         while (item->flag & MPTSAS_DONEQ_THREAD_ACTIVE) {
5383                 if (!item->doneq) {
5384                         cv_wait(&item->cv, &item->mutex);
5385                 }
5386                 pkt = NULL;
5387                 if ((cmd = mptsas_doneq_thread_rm(mpt, t)) != NULL) {
5388                         cmd->cmd_flags |= CFLAG_COMPLETED;
5389                         pkt = CMD2PKT(cmd);
5390                 }
5391                 mutex_exit(&item->mutex);
5392                 if (pkt) {
5393                         mptsas_pkt_comp(pkt, cmd);
5394                 }
5395                 mutex_enter(&item->mutex);
5396         }
5397         mutex_exit(&item->mutex);
5398         mutex_enter(&mpt->m_doneq_mutex);
5399         mpt->m_doneq_thread_n--;
5400         cv_broadcast(&mpt->m_doneq_thread_cv);
5401         mutex_exit(&mpt->m_doneq_mutex);
5402 }
5403 
5404 /*
5405  * mpt interrupt handler.
5406  */
5407 static uint_t
5408 mptsas_intr(caddr_t arg1, caddr_t arg2)
5409 {
5410         mptsas_t                        *mpt = (void *)arg1;
5411         pMpi2ReplyDescriptorsUnion_t    reply_desc_union;
5412         uchar_t                         did_reply = FALSE;
5413         int                             i = 0, j;
5414         uint8_t                         reply_type;
5415         uint16_t                        SMID;
5416 
5417         NDBG1(("mptsas_intr: arg1 0x%p arg2 0x%p", (void *)arg1, (void *)arg2));
5418 
5419         /*
5420          * 1.
5421          * To avoid using m_mutex in the ISR(ISR referes not only mptsas_intr,
5422          * but all of the recursive called functions in it. the same below),
5423          * separate mutexs are introduced to protect the elements shown in ISR.
5424          * 3 type of mutex are involved here:
5425          *      a)per instance mutex m_intr_mutex.
5426          *      b)per target mutex m_tgt_intr_mutex.
5427          *      c)mutex that protect the free slot.
5428          *
5429          * a)per instance mutex m_intr_mutex:
5430          * used to protect m_options, m_power, m_waitq, etc that would be
5431          * checked/modified in ISR; protect the getting and setting the reply
5432          * descriptor index; protect the m_slots[];
5433          *
5434          * b)per target mutex m_tgt_intr_mutex:
5435          * used to protect per target element which has relationship to ISR.
5436          * contention for the new per target mutex is just as high as it in
5437          * sd(7d) driver.
5438          *
5439          * c)mutexs that protect the free slots:
5440          * those mutexs are introduced to minimize the mutex contentions
5441          * between the IO request threads where free slots are allocated
5442          * for sending cmds and ISR where slots holding outstanding cmds
5443          * are returned to the free pool.
5444          * the idea is like this:
5445          * 1) Partition all of the free slot into NCPU groups. For example,
5446          * In system where we have 15 slots, and 4 CPU, then slot s1,s5,s9,s13
5447          * are marked belonging to CPU1, s2,s6,s10,s14 to CPU2, s3,s7,s11,s15
5448          * to CPU3, and s4,s8,s12 to CPU4.
5449          * 2) In each of the group, an alloc/release queue pair is created,
5450          * and both the allocq and the releaseq have a dedicated mutex.
5451          * 3) When init, all of the slots in a CPU group are inserted into the
5452          * allocq of its CPU's pair.
5453          * 4) When doing IO,
5454          * mptsas_scsi_start()
5455          * {
5456          *      cpuid = the cpu NO of the cpu where this thread is running on
5457          * retry:
5458          *      mutex_enter(&allocq[cpuid]);
5459          *      if (get free slot = success) {
5460          *              remove the slot from the allocq
5461          *              mutex_exit(&allocq[cpuid]);
5462          *              return(success);
5463          *      } else { // exchange allocq and releaseq and try again
5464          *              mutex_enter(&releq[cpuid]);
5465          *              exchange the allocq and releaseq of this pair;
5466          *              mutex_exit(&releq[cpuid]);
5467          *              if (try to get free slot again = success) {
5468          *                      remove the slot from the allocq
5469          *                      mutex_exit(&allocq[cpuid]);
5470          *                      return(success);
5471          *              } else {
5472          *                      MOD(cpuid)++;
5473          *                      goto retry;
5474          *                      if (all CPU groups tried)
5475          *                              mutex_exit(&allocq[cpuid]);
5476          *                              return(failure);
5477          *              }
5478          *      }
5479          * }
5480          * ISR()
5481          * {
5482          *              cpuid = the CPU group id where the slot sending the
5483          *              cmd belongs;
5484          *              mutex_enter(&releq[cpuid]);
5485          *              remove the slot from the releaseq
5486          *              mutex_exit(&releq[cpuid]);
5487          * }
5488          * This way, only when the queue pair doing exchange have mutex
5489          * contentions.
5490          *
5491          * For mutex m_intr_mutex and m_tgt_intr_mutex, there are 2 scenarios:
5492          *
5493          * a)If the elements are only checked but not modified in the ISR, then
5494          * only the places where those elements are modifed(outside of ISR)
5495          * need to be protected by the new introduced mutex.
5496          * For example, data A is only read/checked in ISR, then we need do
5497          * like this:
5498          * In ISR:
5499          * {
5500          *      mutex_enter(&new_mutex);
5501          *      read(A);
5502          *      mutex_exit(&new_mutex);
5503          *      //the new_mutex here is either the m_tgt_intr_mutex or
5504          *      //the m_intr_mutex.
5505          * }
5506          * In non-ISR
5507          * {
5508          *      mutex_enter(&m_mutex); //the stock driver already did this
5509          *      mutex_enter(&new_mutex);
5510          *      write(A);
5511          *      mutex_exit(&new_mutex);
5512          *      mutex_exit(&m_mutex); //the stock driver already did this
5513          *
5514          *      read(A);
5515          *      // read(A) in non-ISR is not required to be protected by new
5516          *      // mutex since 'A' has already been protected by m_mutex
5517          *      // outside of the ISR
5518          * }
5519          *
5520          * Those fields in mptsas_target_t/ptgt which are only read in ISR
5521          * fall into this catergory. So they, together with the fields which
5522          * are never read in ISR, are not necessary to be protected by
5523          * m_tgt_intr_mutex, don't bother.
5524          * checking of m_waitq also falls into this catergory. so all of the
5525          * place outside of ISR where the m_waitq is modified, such as in
5526          * mptsas_waitq_add(), mptsas_waitq_delete(), mptsas_waitq_rm(),
5527          * m_intr_mutex should be used.
5528          *
5529          * b)If the elements are modified in the ISR, then each place where
5530          * those elements are referred(outside of ISR) need to be protected
5531          * by the new introduced mutex. Of course, if those elements only
5532          * appear in the non-key code path, that is, they don't affect
5533          * performance, then the m_mutex can still be used as before.
5534          * For example, data B is modified in key code path in ISR, and data C
5535          * is modified in non-key code path in ISR, then we can do like this:
5536          * In ISR:
5537          * {
5538          *      mutex_enter(&new_mutex);
5539          *      wirte(B);
5540          *      mutex_exit(&new_mutex);
5541          *      if (seldom happen) {
5542          *              mutex_enter(&m_mutex);
5543          *              write(C);
5544          *              mutex_exit(&m_mutex);
5545          *      }
5546          *      //the new_mutex here is either the m_tgt_intr_mutex or
5547          *      //the m_intr_mutex.
5548          * }
5549          * In non-ISR
5550          * {
5551          *      mutex_enter(&new_mutex);
5552          *      write(B);
5553          *      mutex_exit(&new_mutex);
5554          *
5555          *      mutex_enter(&new_mutex);
5556          *      read(B);
5557          *      mutex_exit(&new_mutex);
5558          *      // both write(B) and read(B) in non-ISR is required to be
5559          *      // protected by new mutex outside of the ISR
5560          *
5561          *      mutex_enter(&m_mutex); //the stock driver already did this
5562          *      read(C);
5563          *      write(C);
5564          *      mutex_exit(&m_mutex); //the stock driver already did this
5565          *      // both write(C) and read(C) in non-ISR have been already
5566          *      // been protected by m_mutex outside of the ISR
5567          * }
5568          *
5569          * For example, ptgt->m_t_ncmds fall into 'B' of this catergory, and
5570          * elements shown in address reply, restart_hba, passthrough, IOC
5571          * fall into 'C' of  this catergory.
5572          *
5573          * In any case where mutexs are nested, make sure in the following
5574          * order:
5575          *      m_mutex -> m_intr_mutex -> m_tgt_intr_mutex
5576          *      m_intr_mutex -> m_tgt_intr_mutex
5577          *      m_mutex -> m_intr_mutex
5578          *      m_mutex -> m_tgt_intr_mutex
5579          *
5580          * 2.
5581          * Make sure at any time, getting the ReplyDescriptor by m_post_index
5582          * and setting m_post_index to the ReplyDescriptorIndex register are
5583          * atomic. Since m_mutex is not used for this purpose in ISR, the new
5584          * mutex m_intr_mutex must play this role. So mptsas_poll(), where this
5585          * kind of getting/setting is also performed, must use m_intr_mutex.
5586          * Note, since context reply in ISR/process_intr is the only code path
5587          * which affect performance, a fast path is introduced to only handle
5588          * the read/write IO having context reply. For other IOs such as
5589          * passthrough and IOC with context reply and all address reply, we
5590          * use the as-is process_intr() to handle them. In order to keep the
5591          * same semantics in process_intr(), make sure any new mutex is not held
5592          * before enterring it.
5593          */
5594 
5595         mutex_enter(&mpt->m_intr_mutex);
5596 
5597         /*
5598          * If interrupts are shared by two channels then check whether this
5599          * interrupt is genuinely for this channel by making sure first the
5600          * chip is in high power state.
5601          */
5602         if ((mpt->m_options & MPTSAS_OPT_PM) &&
5603             (mpt->m_power_level != PM_LEVEL_D0)) {
5604                 mutex_exit(&mpt->m_intr_mutex);
5605                 return (DDI_INTR_UNCLAIMED);
5606         }
5607 
5608         /*
5609          * If polling, interrupt was triggered by some shared interrupt because
5610          * IOC interrupts are disabled during polling, so polling routine will
5611          * handle any replies.  Considering this, if polling is happening,
5612          * return with interrupt unclaimed.
5613          */
5614         if (mpt->m_polled_intr) {
5615                 mutex_exit(&mpt->m_intr_mutex);
5616                 mptsas_log(mpt, CE_WARN, "mpt_sas: Unclaimed interrupt");
5617                 return (DDI_INTR_UNCLAIMED);
5618         }
5619 
5620         /*
5621          * Read the istat register.
5622          */
5623         if ((INTPENDING(mpt)) != 0) {
5624                 /*
5625                  * read fifo until empty.
5626                  */
5627 #ifndef __lock_lint
5628                 _NOTE(CONSTCOND)
5629 #endif
5630                 while (TRUE) {
5631                         (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
5632                             DDI_DMA_SYNC_FORCPU);
5633                         reply_desc_union = (pMpi2ReplyDescriptorsUnion_t)
5634                             MPTSAS_GET_NEXT_REPLY(mpt, mpt->m_post_index);
5635 
5636                         if (ddi_get32(mpt->m_acc_post_queue_hdl,
5637                             &reply_desc_union->Words.Low) == 0xFFFFFFFF ||
5638                             ddi_get32(mpt->m_acc_post_queue_hdl,
5639                             &reply_desc_union->Words.High) == 0xFFFFFFFF) {
5640                                 break;
5641                         }
5642 
5643                         /*
5644                          * The reply is valid, process it according to its
5645                          * type.  Also, set a flag for updating the reply index
5646                          * after they've all been processed.
5647                          */
5648                         did_reply = TRUE;
5649 
5650                         reply_type = ddi_get8(mpt->m_acc_post_queue_hdl,
5651                             &reply_desc_union->Default.ReplyFlags);
5652                         reply_type &= MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
5653                         mpt->m_reply[i].Default.ReplyFlags = reply_type;
5654                         if (reply_type ==
5655                             MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS) {
5656                                 SMID = ddi_get16(mpt->m_acc_post_queue_hdl,
5657                                     &reply_desc_union->SCSIIOSuccess.SMID);
5658                                 if (mptsas_handle_io_fastpath(mpt, SMID) !=
5659                                     TRUE) {
5660                                         mpt->m_reply[i].SCSIIOSuccess.SMID =
5661                                             SMID;
5662                                         i++;
5663                                 }
5664                         } else if (reply_type ==
5665                             MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {
5666                                 mpt->m_reply[i].AddressReply.ReplyFrameAddress =
5667                                     ddi_get32(mpt->m_acc_post_queue_hdl,
5668                                     &reply_desc_union->AddressReply.
5669                                     ReplyFrameAddress);
5670                                 mpt->m_reply[i].AddressReply.SMID =
5671                                     ddi_get16(mpt->m_acc_post_queue_hdl,
5672                                     &reply_desc_union->AddressReply.SMID);
5673                                 i++;
5674                         }
5675                         /*
5676                          * Clear the reply descriptor for re-use and increment
5677                          * index.
5678                          */
5679                         ddi_put64(mpt->m_acc_post_queue_hdl,
5680                             &((uint64_t *)(void *)mpt->m_post_queue)
5681                             [mpt->m_post_index], 0xFFFFFFFFFFFFFFFF);
5682                         (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
5683                             DDI_DMA_SYNC_FORDEV);
5684 
5685                         /*
5686                          * Increment post index and roll over if needed.
5687                          */
5688                         if (++mpt->m_post_index == mpt->m_post_queue_depth) {
5689                                 mpt->m_post_index = 0;
5690                         }
5691                         if (i >= MPI_ADDRESS_COALSCE_MAX)
5692                                 break;
5693                 }
5694 
5695                 /*
5696                  * Update the global reply index if at least one reply was
5697                  * processed.
5698                  */
5699                 if (did_reply) {
5700                         ddi_put32(mpt->m_datap,
5701                             &mpt->m_reg->ReplyPostHostIndex, mpt->m_post_index);
5702 
5703                         /*
5704                          * For fma, only check the PIO is required and enough
5705                          * here. Those cases where fastpath is not hit, the
5706                          * mptsas_fma_check() check all of the types of
5707                          * fma. That is not necessary and sometimes not
5708                          * correct. fma check should only be done after
5709                          * the PIO and/or dma is performed.
5710                          */
5711                         if ((mptsas_check_acc_handle(mpt->m_datap) !=
5712                             DDI_SUCCESS)) {
5713                                 ddi_fm_service_impact(mpt->m_dip,
5714                                     DDI_SERVICE_UNAFFECTED);
5715                         }
5716 
5717                 }
5718         } else {
5719                 mutex_exit(&mpt->m_intr_mutex);
5720                 return (DDI_INTR_UNCLAIMED);
5721         }
5722         NDBG1(("mptsas_intr complete"));
5723         mutex_exit(&mpt->m_intr_mutex);
5724 
5725         /*
5726          * Since most of the cmds(read and write IO with success return.)
5727          * have already been processed in fast path in which the m_mutex
5728          * is not held, handling here the address reply and other context reply
5729          * such as passthrough and IOC cmd with m_mutex held should be a big
5730          * issue for performance.
5731          * If holding m_mutex to process these cmds was still an obvious issue,
5732          * we can process them in a taskq.
5733          */
5734         for (j = 0; j < i; j++) {
5735                 mutex_enter(&mpt->m_mutex);
5736                 mptsas_process_intr(mpt, &mpt->m_reply[j]);
5737                 mutex_exit(&mpt->m_mutex);
5738         }
5739 
5740         /*
5741          * If no helper threads are created, process the doneq in ISR. If
5742          * helpers are created, use the doneq length as a metric to measure the
5743          * load on the interrupt CPU. If it is long enough, which indicates the
5744          * load is heavy, then we deliver the IO completions to the helpers.
5745          * This measurement has some limitations, although it is simple and
5746          * straightforward and works well for most of the cases at present.
5747          */
5748         if (!mpt->m_doneq_thread_n) {
5749                 mptsas_doneq_empty(mpt);
5750         } else {
5751                 int helper = 1;
5752                 mutex_enter(&mpt->m_intr_mutex);
5753                 if (mpt->m_doneq_len <= mpt->m_doneq_length_threshold)
5754                         helper = 0;
5755                 mutex_exit(&mpt->m_intr_mutex);
5756                 if (helper) {
5757                         mptsas_deliver_doneq_thread(mpt);
5758                 } else {
5759                         mptsas_doneq_empty(mpt);
5760                 }
5761         }
5762 
5763         /*
5764          * If there are queued cmd, start them now.
5765          */
5766         mutex_enter(&mpt->m_intr_mutex);
5767         if (mpt->m_waitq != NULL) {
5768                 mutex_exit(&mpt->m_intr_mutex);
5769                 mutex_enter(&mpt->m_mutex);
5770                 mptsas_restart_hba(mpt);
5771                 mutex_exit(&mpt->m_mutex);
5772                 return (DDI_INTR_CLAIMED);
5773         }
5774         mutex_exit(&mpt->m_intr_mutex);
5775         return (DDI_INTR_CLAIMED);
5776 }
5777 
5778 /*
5779  * In ISR, the successfully completed read and write IO are processed in a
5780  * fast path. This function is only used to handle non-fastpath IO, including
5781  * all of the address reply, and the context reply for IOC cmd, passthrough,
5782  * etc.
5783  * This function is also used to process polled cmd.
5784  */
5785 static void
5786 mptsas_process_intr(mptsas_t *mpt,
5787     pMpi2ReplyDescriptorsUnion_t reply_desc_union)
5788 {
5789         uint8_t reply_type;
5790 
5791         /*
5792          * The reply is valid, process it according to its
5793          * type.  Also, set a flag for updated the reply index
5794          * after they've all been processed.
5795          */
5796         reply_type = reply_desc_union->Default.ReplyFlags;
5797         if (reply_type == MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS) {
5798                 mptsas_handle_scsi_io_success(mpt, reply_desc_union);
5799         } else if (reply_type == MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {
5800                 mptsas_handle_address_reply(mpt, reply_desc_union);
5801         } else {
5802                 mptsas_log(mpt, CE_WARN, "?Bad reply type %x", reply_type);
5803                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
5804         }
5805 }
5806 
5807 /*
5808  * handle qfull condition
5809  */
5810 static void
5811 mptsas_handle_qfull(mptsas_t *mpt, mptsas_cmd_t *cmd)
5812 {
5813         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
5814 
5815         if ((++cmd->cmd_qfull_retries > ptgt->m_qfull_retries) ||
5816             (ptgt->m_qfull_retries == 0)) {
5817                 /*
5818                  * We have exhausted the retries on QFULL, or,
5819                  * the target driver has indicated that it
5820                  * wants to handle QFULL itself by setting
5821                  * qfull-retries capability to 0. In either case
5822                  * we want the target driver's QFULL handling
5823                  * to kick in. We do this by having pkt_reason
5824                  * as CMD_CMPLT and pkt_scbp as STATUS_QFULL.
5825                  */
5826                 mutex_enter(&ptgt->m_tgt_intr_mutex);
5827                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
5828                 mutex_exit(&ptgt->m_tgt_intr_mutex);
5829         } else {
5830                 mutex_enter(&ptgt->m_tgt_intr_mutex);
5831                 if (ptgt->m_reset_delay == 0) {
5832                         ptgt->m_t_throttle =
5833                             max((ptgt->m_t_ncmds - 2), 0);
5834                 }
5835                 mutex_exit(&ptgt->m_tgt_intr_mutex);
5836 
5837                 cmd->cmd_pkt_flags |= FLAG_HEAD;
5838                 cmd->cmd_flags &= ~(CFLAG_TRANFLAG);
5839                 cmd->cmd_flags |= CFLAG_RETRY;
5840 
5841                 mutex_exit(&mpt->m_mutex);
5842                 (void) mptsas_accept_pkt(mpt, cmd);
5843                 mutex_enter(&mpt->m_mutex);
5844 
5845                 /*
5846                  * when target gives queue full status with no commands
5847                  * outstanding (m_t_ncmds == 0), throttle is set to 0
5848                  * (HOLD_THROTTLE), and the queue full handling start
5849                  * (see psarc/1994/313); if there are commands outstanding,
5850                  * throttle is set to (m_t_ncmds - 2)
5851                  */
5852                 mutex_enter(&ptgt->m_tgt_intr_mutex);
5853                 if (ptgt->m_t_throttle == HOLD_THROTTLE) {
5854                         /*
5855                          * By setting throttle to QFULL_THROTTLE, we
5856                          * avoid submitting new commands and in
5857                          * mptsas_restart_cmd find out slots which need
5858                          * their throttles to be cleared.
5859                          */
5860                         mptsas_set_throttle(mpt, ptgt, QFULL_THROTTLE);
5861                         if (mpt->m_restart_cmd_timeid == 0) {
5862                                 mpt->m_restart_cmd_timeid =
5863                                     timeout(mptsas_restart_cmd, mpt,
5864                                     ptgt->m_qfull_retry_interval);
5865                         }
5866                 }
5867                 mutex_exit(&ptgt->m_tgt_intr_mutex);
5868         }
5869 }
5870 
5871 mptsas_phymask_t
5872 mptsas_physport_to_phymask(mptsas_t *mpt, uint8_t physport)
5873 {
5874         mptsas_phymask_t        phy_mask = 0;
5875         uint8_t                 i = 0;
5876 
5877         NDBG20(("mptsas%d physport_to_phymask enter", mpt->m_instance));
5878 
5879         ASSERT(mutex_owned(&mpt->m_mutex));
5880 
5881         /*
5882          * If physport is 0xFF, this is a RAID volume.  Use phymask of 0.
5883          */
5884         if (physport == 0xFF) {
5885                 return (0);
5886         }
5887 
5888         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
5889                 if (mpt->m_phy_info[i].attached_devhdl &&
5890                     (mpt->m_phy_info[i].phy_mask != 0) &&
5891                     (mpt->m_phy_info[i].port_num == physport)) {
5892                         phy_mask = mpt->m_phy_info[i].phy_mask;
5893                         break;
5894                 }
5895         }
5896         NDBG20(("mptsas%d physport_to_phymask:physport :%x phymask :%x, ",
5897             mpt->m_instance, physport, phy_mask));
5898         return (phy_mask);
5899 }
5900 
5901 /*
5902  * mpt free device handle after device gone, by use of passthrough
5903  */
5904 static int
5905 mptsas_free_devhdl(mptsas_t *mpt, uint16_t devhdl)
5906 {
5907         Mpi2SasIoUnitControlRequest_t   req;
5908         Mpi2SasIoUnitControlReply_t     rep;
5909         int                             ret;
5910 
5911         ASSERT(mutex_owned(&mpt->m_mutex));
5912 
5913         /*
5914          * Need to compose a SAS IO Unit Control request message
5915          * and call mptsas_do_passthru() function
5916          */
5917         bzero(&req, sizeof (req));
5918         bzero(&rep, sizeof (rep));
5919 
5920         req.Function = MPI2_FUNCTION_SAS_IO_UNIT_CONTROL;
5921         req.Operation = MPI2_SAS_OP_REMOVE_DEVICE;
5922         req.DevHandle = LE_16(devhdl);
5923 
5924         ret = mptsas_do_passthru(mpt, (uint8_t *)&req, (uint8_t *)&rep, NULL,
5925             sizeof (req), sizeof (rep), NULL, 0, NULL, 0, 60, FKIOCTL);
5926         if (ret != 0) {
5927                 cmn_err(CE_WARN, "mptsas_free_devhdl: passthru SAS IO Unit "
5928                     "Control error %d", ret);
5929                 return (DDI_FAILURE);
5930         }
5931 
5932         /* do passthrough success, check the ioc status */
5933         if (LE_16(rep.IOCStatus) != MPI2_IOCSTATUS_SUCCESS) {
5934                 cmn_err(CE_WARN, "mptsas_free_devhdl: passthru SAS IO Unit "
5935                     "Control IOCStatus %d", LE_16(rep.IOCStatus));
5936                 return (DDI_FAILURE);
5937         }
5938 
5939         return (DDI_SUCCESS);
5940 }
5941 
5942 static void
5943 mptsas_update_phymask(mptsas_t *mpt)
5944 {
5945         mptsas_phymask_t mask = 0, phy_mask;
5946         char            *phy_mask_name;
5947         uint8_t         current_port;
5948         int             i, j;
5949 
5950         NDBG20(("mptsas%d update phymask ", mpt->m_instance));
5951 
5952         ASSERT(mutex_owned(&mpt->m_mutex));
5953 
5954         (void) mptsas_get_sas_io_unit_page(mpt);
5955 
5956         phy_mask_name = kmem_zalloc(MPTSAS_MAX_PHYS, KM_SLEEP);
5957 
5958         for (i = 0; i < mpt->m_num_phys; i++) {
5959                 phy_mask = 0x00;
5960 
5961                 if (mpt->m_phy_info[i].attached_devhdl == 0)
5962                         continue;
5963 
5964                 bzero(phy_mask_name, sizeof (phy_mask_name));
5965 
5966                 current_port = mpt->m_phy_info[i].port_num;
5967 
5968                 if ((mask & (1 << i)) != 0)
5969                         continue;
5970 
5971                 for (j = 0; j < mpt->m_num_phys; j++) {
5972                         if (mpt->m_phy_info[j].attached_devhdl &&
5973                             (mpt->m_phy_info[j].port_num == current_port)) {
5974                                 phy_mask |= (1 << j);
5975                         }
5976                 }
5977                 mask = mask | phy_mask;
5978 
5979                 for (j = 0; j < mpt->m_num_phys; j++) {
5980                         if ((phy_mask >> j) & 0x01) {
5981                                 mpt->m_phy_info[j].phy_mask = phy_mask;
5982                         }
5983                 }
5984 
5985                 (void) sprintf(phy_mask_name, "%x", phy_mask);
5986 
5987                 mutex_exit(&mpt->m_mutex);
5988                 /*
5989                  * register a iport, if the port has already been existed
5990                  * SCSA will do nothing and just return.
5991                  */
5992                 (void) scsi_hba_iport_register(mpt->m_dip, phy_mask_name);
5993                 mutex_enter(&mpt->m_mutex);
5994         }
5995         kmem_free(phy_mask_name, MPTSAS_MAX_PHYS);
5996         NDBG20(("mptsas%d update phymask return", mpt->m_instance));
5997 }
5998 
5999 /*
6000  * mptsas_handle_dr is a task handler for DR, the DR action includes:
6001  * 1. Directly attched Device Added/Removed.
6002  * 2. Expander Device Added/Removed.
6003  * 3. Indirectly Attached Device Added/Expander.
6004  * 4. LUNs of a existing device status change.
6005  * 5. RAID volume created/deleted.
6006  * 6. Member of RAID volume is released because of RAID deletion.
6007  * 7. Physical disks are removed because of RAID creation.
6008  */
6009 static void
6010 mptsas_handle_dr(void *args) {
6011         mptsas_topo_change_list_t       *topo_node = NULL;
6012         mptsas_topo_change_list_t       *save_node = NULL;
6013         mptsas_t                        *mpt;
6014         dev_info_t                      *parent = NULL;
6015         mptsas_phymask_t                phymask = 0;
6016         char                            *phy_mask_name;
6017         uint8_t                         flags = 0, physport = 0xff;
6018         uint8_t                         port_update = 0;
6019         uint_t                          event;
6020 
6021         topo_node = (mptsas_topo_change_list_t *)args;
6022 
6023         mpt = topo_node->mpt;
6024         event = topo_node->event;
6025         flags = topo_node->flags;
6026 
6027         phy_mask_name = kmem_zalloc(MPTSAS_MAX_PHYS, KM_SLEEP);
6028 
6029         NDBG20(("mptsas%d handle_dr enter", mpt->m_instance));
6030 
6031         switch (event) {
6032         case MPTSAS_DR_EVENT_RECONFIG_TARGET:
6033                 if ((flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) ||
6034                     (flags == MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE) ||
6035                     (flags == MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED)) {
6036                         /*
6037                          * Direct attached or expander attached device added
6038                          * into system or a Phys Disk that is being unhidden.
6039                          */
6040                         port_update = 1;
6041                 }
6042                 break;
6043         case MPTSAS_DR_EVENT_RECONFIG_SMP:
6044                 /*
6045                  * New expander added into system, it must be the head
6046                  * of topo_change_list_t
6047                  */
6048                 port_update = 1;
6049                 break;
6050         default:
6051                 port_update = 0;
6052                 break;
6053         }
6054         /*
6055          * All cases port_update == 1 may cause initiator port form change
6056          */
6057         mutex_enter(&mpt->m_mutex);
6058         if (mpt->m_port_chng && port_update) {
6059                 /*
6060                  * mpt->m_port_chng flag indicates some PHYs of initiator
6061                  * port have changed to online. So when expander added or
6062                  * directly attached device online event come, we force to
6063                  * update port information by issueing SAS IO Unit Page and
6064                  * update PHYMASKs.
6065                  */
6066                 (void) mptsas_update_phymask(mpt);
6067                 mpt->m_port_chng = 0;
6068 
6069         }
6070         mutex_exit(&mpt->m_mutex);
6071         while (topo_node) {
6072                 phymask = 0;
6073                 if (parent == NULL) {
6074                         physport = topo_node->un.physport;
6075                         event = topo_node->event;
6076                         flags = topo_node->flags;
6077                         if (event & (MPTSAS_DR_EVENT_OFFLINE_TARGET |
6078                             MPTSAS_DR_EVENT_OFFLINE_SMP)) {
6079                                 /*
6080                                  * For all offline events, phymask is known
6081                                  */
6082                                 phymask = topo_node->un.phymask;
6083                                 goto find_parent;
6084                         }
6085                         if (event & MPTSAS_TOPO_FLAG_REMOVE_HANDLE) {
6086                                 goto handle_topo_change;
6087                         }
6088                         if (flags & MPTSAS_TOPO_FLAG_LUN_ASSOCIATED) {
6089                                 phymask = topo_node->un.phymask;
6090                                 goto find_parent;
6091                         }
6092 
6093                         if ((flags ==
6094                             MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED) &&
6095                             (event == MPTSAS_DR_EVENT_RECONFIG_TARGET)) {
6096                                 /*
6097                                  * There is no any field in IR_CONFIG_CHANGE
6098                                  * event indicate physport/phynum, let's get
6099                                  * parent after SAS Device Page0 request.
6100                                  */
6101                                 goto handle_topo_change;
6102                         }
6103 
6104                         mutex_enter(&mpt->m_mutex);
6105                         if (flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) {
6106                                 /*
6107                                  * If the direct attached device added or a
6108                                  * phys disk is being unhidden, argument
6109                                  * physport actually is PHY#, so we have to get
6110                                  * phymask according PHY#.
6111                                  */
6112                                 physport = mpt->m_phy_info[physport].port_num;
6113                         }
6114 
6115                         /*
6116                          * Translate physport to phymask so that we can search
6117                          * parent dip.
6118                          */
6119                         phymask = mptsas_physport_to_phymask(mpt,
6120                             physport);
6121                         mutex_exit(&mpt->m_mutex);
6122 
6123 find_parent:
6124                         bzero(phy_mask_name, MPTSAS_MAX_PHYS);
6125                         /*
6126                          * For RAID topology change node, write the iport name
6127                          * as v0.
6128                          */
6129                         if (flags & MPTSAS_TOPO_FLAG_RAID_ASSOCIATED) {
6130                                 (void) sprintf(phy_mask_name, "v0");
6131                         } else {
6132                                 /*
6133                                  * phymask can bo 0 if the drive has been
6134                                  * pulled by the time an add event is
6135                                  * processed.  If phymask is 0, just skip this
6136                                  * event and continue.
6137                                  */
6138                                 if (phymask == 0) {
6139                                         mutex_enter(&mpt->m_mutex);
6140                                         save_node = topo_node;
6141                                         topo_node = topo_node->next;
6142                                         ASSERT(save_node);
6143                                         kmem_free(save_node,
6144                                             sizeof (mptsas_topo_change_list_t));
6145                                         mutex_exit(&mpt->m_mutex);
6146 
6147                                         parent = NULL;
6148                                         continue;
6149                                 }
6150                                 (void) sprintf(phy_mask_name, "%x", phymask);
6151                         }
6152                         parent = scsi_hba_iport_find(mpt->m_dip,
6153                             phy_mask_name);
6154                         if (parent == NULL) {
6155                                 mptsas_log(mpt, CE_WARN, "Failed to find an "
6156                                     "iport, should not happen!");
6157                                 goto out;
6158                         }
6159 
6160                 }
6161                 ASSERT(parent);
6162 handle_topo_change:
6163 
6164                 mutex_enter(&mpt->m_mutex);
6165 
6166                 mptsas_handle_topo_change(topo_node, parent);
6167                 save_node = topo_node;
6168                 topo_node = topo_node->next;
6169                 ASSERT(save_node);
6170                 kmem_free(save_node, sizeof (mptsas_topo_change_list_t));
6171                 mutex_exit(&mpt->m_mutex);
6172 
6173                 if ((flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) ||
6174                     (flags == MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED) ||
6175                     (flags == MPTSAS_TOPO_FLAG_RAID_ASSOCIATED)) {
6176                         /*
6177                          * If direct attached device associated, make sure
6178                          * reset the parent before start the next one. But
6179                          * all devices associated with expander shares the
6180                          * parent.  Also, reset parent if this is for RAID.
6181                          */
6182                         parent = NULL;
6183                 }
6184         }
6185 out:
6186         kmem_free(phy_mask_name, MPTSAS_MAX_PHYS);
6187 }
6188 
6189 static void
6190 mptsas_handle_topo_change(mptsas_topo_change_list_t *topo_node,
6191     dev_info_t *parent)
6192 {
6193         mptsas_target_t *ptgt = NULL;
6194         mptsas_smp_t    *psmp = NULL;
6195         mptsas_t        *mpt = (void *)topo_node->mpt;
6196         uint16_t        devhdl;
6197         uint16_t        attached_devhdl;
6198         uint64_t        sas_wwn = 0;
6199         int             rval = 0;
6200         uint32_t        page_address;
6201         uint8_t         phy, flags;
6202         char            *addr = NULL;
6203         dev_info_t      *lundip;
6204         int             circ = 0, circ1 = 0;
6205         char            attached_wwnstr[MPTSAS_WWN_STRLEN];
6206 
6207         NDBG20(("mptsas%d handle_topo_change enter", mpt->m_instance));
6208 
6209         ASSERT(mutex_owned(&mpt->m_mutex));
6210 
6211         switch (topo_node->event) {
6212         case MPTSAS_DR_EVENT_RECONFIG_TARGET:
6213         {
6214                 char *phy_mask_name;
6215                 mptsas_phymask_t phymask = 0;
6216 
6217                 if (topo_node->flags == MPTSAS_TOPO_FLAG_RAID_ASSOCIATED) {
6218                         /*
6219                          * Get latest RAID info.
6220                          */
6221                         (void) mptsas_get_raid_info(mpt);
6222                         ptgt = mptsas_search_by_devhdl(
6223                             &mpt->m_active->m_tgttbl, topo_node->devhdl);
6224                         if (ptgt == NULL)
6225                                 break;
6226                 } else {
6227                         ptgt = (void *)topo_node->object;
6228                 }
6229 
6230                 if (ptgt == NULL) {
6231                         /*
6232                          * If a Phys Disk was deleted, RAID info needs to be
6233                          * updated to reflect the new topology.
6234                          */
6235                         (void) mptsas_get_raid_info(mpt);
6236 
6237                         /*
6238                          * Get sas device page 0 by DevHandle to make sure if
6239                          * SSP/SATA end device exist.
6240                          */
6241                         page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
6242                             MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
6243                             topo_node->devhdl;
6244 
6245                         rval = mptsas_get_target_device_info(mpt, page_address,
6246                             &devhdl, &ptgt);
6247                         if (rval == DEV_INFO_WRONG_DEVICE_TYPE) {
6248                                 mptsas_log(mpt, CE_NOTE,
6249                                     "mptsas_handle_topo_change: target %d is "
6250                                     "not a SAS/SATA device. \n",
6251                                     topo_node->devhdl);
6252                         } else if (rval == DEV_INFO_FAIL_ALLOC) {
6253                                 mptsas_log(mpt, CE_NOTE,
6254                                     "mptsas_handle_topo_change: could not "
6255                                     "allocate memory. \n");
6256                         }
6257                         /*
6258                          * If rval is DEV_INFO_PHYS_DISK than there is nothing
6259                          * else to do, just leave.
6260                          */
6261                         if (rval != DEV_INFO_SUCCESS) {
6262                                 return;
6263                         }
6264                 }
6265 
6266                 ASSERT(ptgt->m_devhdl == topo_node->devhdl);
6267 
6268                 mutex_exit(&mpt->m_mutex);
6269                 flags = topo_node->flags;
6270 
6271                 if (flags == MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED) {
6272                         phymask = ptgt->m_phymask;
6273                         phy_mask_name = kmem_zalloc(MPTSAS_MAX_PHYS, KM_SLEEP);
6274                         (void) sprintf(phy_mask_name, "%x", phymask);
6275                         parent = scsi_hba_iport_find(mpt->m_dip,
6276                             phy_mask_name);
6277                         kmem_free(phy_mask_name, MPTSAS_MAX_PHYS);
6278                         if (parent == NULL) {
6279                                 mptsas_log(mpt, CE_WARN, "Failed to find a "
6280                                     "iport for PD, should not happen!");
6281                                 mutex_enter(&mpt->m_mutex);
6282                                 break;
6283                         }
6284                 }
6285 
6286                 if (flags == MPTSAS_TOPO_FLAG_RAID_ASSOCIATED) {
6287                         ndi_devi_enter(parent, &circ1);
6288                         (void) mptsas_config_raid(parent, topo_node->devhdl,
6289                             &lundip);
6290                         ndi_devi_exit(parent, circ1);
6291                 } else {
6292                         /*
6293                          * hold nexus for bus configure
6294                          */
6295                         ndi_devi_enter(scsi_vhci_dip, &circ);
6296                         ndi_devi_enter(parent, &circ1);
6297                         rval = mptsas_config_target(parent, ptgt);
6298                         /*
6299                          * release nexus for bus configure
6300                          */
6301                         ndi_devi_exit(parent, circ1);
6302                         ndi_devi_exit(scsi_vhci_dip, circ);
6303 
6304                         /*
6305                          * Add parent's props for SMHBA support
6306                          */
6307                         if (flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) {
6308                                 bzero(attached_wwnstr,
6309                                     sizeof (attached_wwnstr));
6310                                 (void) sprintf(attached_wwnstr, "w%016"PRIx64,
6311                                     ptgt->m_sas_wwn);
6312                                 if (ddi_prop_update_string(DDI_DEV_T_NONE,
6313                                     parent,
6314                                     SCSI_ADDR_PROP_ATTACHED_PORT,
6315                                     attached_wwnstr)
6316                                     != DDI_PROP_SUCCESS) {
6317                                         (void) ddi_prop_remove(DDI_DEV_T_NONE,
6318                                             parent,
6319                                             SCSI_ADDR_PROP_ATTACHED_PORT);
6320                                         mptsas_log(mpt, CE_WARN, "Failed to"
6321                                             "attached-port props");
6322                                         return;
6323                                 }
6324                                 if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6325                                     MPTSAS_NUM_PHYS, 1) !=
6326                                     DDI_PROP_SUCCESS) {
6327                                         (void) ddi_prop_remove(DDI_DEV_T_NONE,
6328                                             parent, MPTSAS_NUM_PHYS);
6329                                         mptsas_log(mpt, CE_WARN, "Failed to"
6330                                             " create num-phys props");
6331                                         return;
6332                                 }
6333 
6334                                 /*
6335                                  * Update PHY info for smhba
6336                                  */
6337                                 mutex_enter(&mpt->m_mutex);
6338                                 if (mptsas_smhba_phy_init(mpt)) {
6339                                         mutex_exit(&mpt->m_mutex);
6340                                         mptsas_log(mpt, CE_WARN, "mptsas phy"
6341                                             " update failed");
6342                                         return;
6343                                 }
6344                                 mutex_exit(&mpt->m_mutex);
6345                                 mptsas_smhba_set_phy_props(mpt,
6346                                     ddi_get_name_addr(parent), parent,
6347                                     1, &attached_devhdl);
6348                                 if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6349                                     MPTSAS_VIRTUAL_PORT, 0) !=
6350                                     DDI_PROP_SUCCESS) {
6351                                         (void) ddi_prop_remove(DDI_DEV_T_NONE,
6352                                             parent, MPTSAS_VIRTUAL_PORT);
6353                                         mptsas_log(mpt, CE_WARN,
6354                                             "mptsas virtual-port"
6355                                             "port prop update failed");
6356                                         return;
6357                                 }
6358                         }
6359                 }
6360                 mutex_enter(&mpt->m_mutex);
6361 
6362                 NDBG20(("mptsas%d handle_topo_change to online devhdl:%x, "
6363                     "phymask:%x.", mpt->m_instance, ptgt->m_devhdl,
6364                     ptgt->m_phymask));
6365                 break;
6366         }
6367         case MPTSAS_DR_EVENT_OFFLINE_TARGET:
6368         {
6369                 mptsas_hash_table_t *tgttbl = &mpt->m_active->m_tgttbl;
6370                 devhdl = topo_node->devhdl;
6371                 ptgt = mptsas_search_by_devhdl(tgttbl, devhdl);
6372                 if (ptgt == NULL)
6373                         break;
6374 
6375                 sas_wwn = ptgt->m_sas_wwn;
6376                 phy = ptgt->m_phynum;
6377 
6378                 addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
6379 
6380                 if (sas_wwn) {
6381                         (void) sprintf(addr, "w%016"PRIx64, sas_wwn);
6382                 } else {
6383                         (void) sprintf(addr, "p%x", phy);
6384                 }
6385                 ASSERT(ptgt->m_devhdl == devhdl);
6386 
6387                 if ((topo_node->flags == MPTSAS_TOPO_FLAG_RAID_ASSOCIATED) ||
6388                     (topo_node->flags ==
6389                     MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED)) {
6390                         /*
6391                          * Get latest RAID info if RAID volume status changes
6392                          * or Phys Disk status changes
6393                          */
6394                         (void) mptsas_get_raid_info(mpt);
6395                 }
6396                 /*
6397                  * Abort all outstanding command on the device
6398                  */
6399                 rval = mptsas_do_scsi_reset(mpt, devhdl);
6400                 if (rval) {
6401                         NDBG20(("mptsas%d handle_topo_change to reset target "
6402                             "before offline devhdl:%x, phymask:%x, rval:%x",
6403                             mpt->m_instance, ptgt->m_devhdl, ptgt->m_phymask,
6404                             rval));
6405                 }
6406 
6407                 mutex_exit(&mpt->m_mutex);
6408 
6409                 ndi_devi_enter(scsi_vhci_dip, &circ);
6410                 ndi_devi_enter(parent, &circ1);
6411                 rval = mptsas_offline_target(parent, addr);
6412                 ndi_devi_exit(parent, circ1);
6413                 ndi_devi_exit(scsi_vhci_dip, circ);
6414                 NDBG20(("mptsas%d handle_topo_change to offline devhdl:%x, "
6415                     "phymask:%x, rval:%x", mpt->m_instance,
6416                     ptgt->m_devhdl, ptgt->m_phymask, rval));
6417 
6418                 kmem_free(addr, SCSI_MAXNAMELEN);
6419 
6420                 /*
6421                  * Clear parent's props for SMHBA support
6422                  */
6423                 flags = topo_node->flags;
6424                 if (flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) {
6425                         bzero(attached_wwnstr, sizeof (attached_wwnstr));
6426                         if (ddi_prop_update_string(DDI_DEV_T_NONE, parent,
6427                             SCSI_ADDR_PROP_ATTACHED_PORT, attached_wwnstr) !=
6428                             DDI_PROP_SUCCESS) {
6429                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6430                                     SCSI_ADDR_PROP_ATTACHED_PORT);
6431                                 mptsas_log(mpt, CE_WARN, "mptsas attached port "
6432                                     "prop update failed");
6433                                 break;
6434                         }
6435                         if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6436                             MPTSAS_NUM_PHYS, 0) !=
6437                             DDI_PROP_SUCCESS) {
6438                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6439                                     MPTSAS_NUM_PHYS);
6440                                 mptsas_log(mpt, CE_WARN, "mptsas num phys "
6441                                     "prop update failed");
6442                                 break;
6443                         }
6444                         if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6445                             MPTSAS_VIRTUAL_PORT, 1) !=
6446                             DDI_PROP_SUCCESS) {
6447                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6448                                     MPTSAS_VIRTUAL_PORT);
6449                                 mptsas_log(mpt, CE_WARN, "mptsas virtual port "
6450                                     "prop update failed");
6451                                 break;
6452                         }
6453                 }
6454 
6455                 mutex_enter(&mpt->m_mutex);
6456                 if (mptsas_set_led_status(mpt, ptgt, 0) != DDI_SUCCESS) {
6457                         NDBG14(("mptsas: clear LED for tgt %x failed",
6458                             ptgt->m_slot_num));
6459                 }
6460                 if (rval == DDI_SUCCESS) {
6461                         mptsas_tgt_free(&mpt->m_active->m_tgttbl,
6462                             ptgt->m_sas_wwn, ptgt->m_phymask);
6463                         ptgt = NULL;
6464                 } else {
6465                         /*
6466                          * clean DR_INTRANSITION flag to allow I/O down to
6467                          * PHCI driver since failover finished.
6468                          * Invalidate the devhdl
6469                          */
6470                         mutex_enter(&ptgt->m_tgt_intr_mutex);
6471                         ptgt->m_devhdl = MPTSAS_INVALID_DEVHDL;
6472                         ptgt->m_tgt_unconfigured = 0;
6473                         ptgt->m_dr_flag = MPTSAS_DR_INACTIVE;
6474                         mutex_exit(&ptgt->m_tgt_intr_mutex);
6475                 }
6476 
6477                 /*
6478                  * Send SAS IO Unit Control to free the dev handle
6479                  */
6480                 if ((flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) ||
6481                     (flags == MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE)) {
6482                         rval = mptsas_free_devhdl(mpt, devhdl);
6483 
6484                         NDBG20(("mptsas%d handle_topo_change to remove "
6485                             "devhdl:%x, rval:%x", mpt->m_instance, devhdl,
6486                             rval));
6487                 }
6488 
6489                 break;
6490         }
6491         case MPTSAS_TOPO_FLAG_REMOVE_HANDLE:
6492         {
6493                 devhdl = topo_node->devhdl;
6494                 /*
6495                  * If this is the remove handle event, do a reset first.
6496                  */
6497                 if (topo_node->event == MPTSAS_TOPO_FLAG_REMOVE_HANDLE) {
6498                         rval = mptsas_do_scsi_reset(mpt, devhdl);
6499                         if (rval) {
6500                                 NDBG20(("mpt%d reset target before remove "
6501                                     "devhdl:%x, rval:%x", mpt->m_instance,
6502                                     devhdl, rval));
6503                         }
6504                 }
6505 
6506                 /*
6507                  * Send SAS IO Unit Control to free the dev handle
6508                  */
6509                 rval = mptsas_free_devhdl(mpt, devhdl);
6510                 NDBG20(("mptsas%d handle_topo_change to remove "
6511                     "devhdl:%x, rval:%x", mpt->m_instance, devhdl,
6512                     rval));
6513                 break;
6514         }
6515         case MPTSAS_DR_EVENT_RECONFIG_SMP:
6516         {
6517                 mptsas_smp_t smp;
6518                 dev_info_t *smpdip;
6519                 mptsas_hash_table_t *smptbl = &mpt->m_active->m_smptbl;
6520 
6521                 devhdl = topo_node->devhdl;
6522 
6523                 page_address = (MPI2_SAS_EXPAND_PGAD_FORM_HNDL &
6524                     MPI2_SAS_EXPAND_PGAD_FORM_MASK) | (uint32_t)devhdl;
6525                 rval = mptsas_get_sas_expander_page0(mpt, page_address, &smp);
6526                 if (rval != DDI_SUCCESS) {
6527                         mptsas_log(mpt, CE_WARN, "failed to online smp, "
6528                             "handle %x", devhdl);
6529                         return;
6530                 }
6531 
6532                 psmp = mptsas_smp_alloc(smptbl, &smp);
6533                 if (psmp == NULL) {
6534                         return;
6535                 }
6536 
6537                 mutex_exit(&mpt->m_mutex);
6538                 ndi_devi_enter(parent, &circ1);
6539                 (void) mptsas_online_smp(parent, psmp, &smpdip);
6540                 ndi_devi_exit(parent, circ1);
6541 
6542                 mutex_enter(&mpt->m_mutex);
6543                 break;
6544         }
6545         case MPTSAS_DR_EVENT_OFFLINE_SMP:
6546         {
6547                 mptsas_hash_table_t *smptbl = &mpt->m_active->m_smptbl;
6548                 devhdl = topo_node->devhdl;
6549                 uint32_t dev_info;
6550 
6551                 psmp = mptsas_search_by_devhdl(smptbl, devhdl);
6552                 if (psmp == NULL)
6553                         break;
6554                 /*
6555                  * The mptsas_smp_t data is released only if the dip is offlined
6556                  * successfully.
6557                  */
6558                 mutex_exit(&mpt->m_mutex);
6559 
6560                 ndi_devi_enter(parent, &circ1);
6561                 rval = mptsas_offline_smp(parent, psmp, NDI_DEVI_REMOVE);
6562                 ndi_devi_exit(parent, circ1);
6563 
6564                 dev_info = psmp->m_deviceinfo;
6565                 if ((dev_info & DEVINFO_DIRECT_ATTACHED) ==
6566                     DEVINFO_DIRECT_ATTACHED) {
6567                         if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6568                             MPTSAS_VIRTUAL_PORT, 1) !=
6569                             DDI_PROP_SUCCESS) {
6570                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6571                                     MPTSAS_VIRTUAL_PORT);
6572                                 mptsas_log(mpt, CE_WARN, "mptsas virtual port "
6573                                     "prop update failed");
6574                                 return;
6575                         }
6576                         /*
6577                          * Check whether the smp connected to the iport,
6578                          */
6579                         if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6580                             MPTSAS_NUM_PHYS, 0) !=
6581                             DDI_PROP_SUCCESS) {
6582                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6583                                     MPTSAS_NUM_PHYS);
6584                                 mptsas_log(mpt, CE_WARN, "mptsas num phys"
6585                                     "prop update failed");
6586                                 return;
6587                         }
6588                         /*
6589                          * Clear parent's attached-port props
6590                          */
6591                         bzero(attached_wwnstr, sizeof (attached_wwnstr));
6592                         if (ddi_prop_update_string(DDI_DEV_T_NONE, parent,
6593                             SCSI_ADDR_PROP_ATTACHED_PORT, attached_wwnstr) !=
6594                             DDI_PROP_SUCCESS) {
6595                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6596                                     SCSI_ADDR_PROP_ATTACHED_PORT);
6597                                 mptsas_log(mpt, CE_WARN, "mptsas attached port "
6598                                     "prop update failed");
6599                                 return;
6600                         }
6601                 }
6602 
6603                 mutex_enter(&mpt->m_mutex);
6604                 NDBG20(("mptsas%d handle_topo_change to remove devhdl:%x, "
6605                     "rval:%x", mpt->m_instance, psmp->m_devhdl, rval));
6606                 if (rval == DDI_SUCCESS) {
6607                         mptsas_smp_free(smptbl, psmp->m_sasaddr,
6608                             psmp->m_phymask);
6609                 } else {
6610                         psmp->m_devhdl = MPTSAS_INVALID_DEVHDL;
6611                 }
6612 
6613                 bzero(attached_wwnstr, sizeof (attached_wwnstr));
6614 
6615                 break;
6616         }
6617         default:
6618                 return;
6619         }
6620 }
6621 
6622 /*
6623  * Record the event if its type is enabled in mpt instance by ioctl.
6624  */
6625 static void
6626 mptsas_record_event(void *args)
6627 {
6628         m_replyh_arg_t                  *replyh_arg;
6629         pMpi2EventNotificationReply_t   eventreply;
6630         uint32_t                        event, rfm;
6631         mptsas_t                        *mpt;
6632         int                             i, j;
6633         uint16_t                        event_data_len;
6634         boolean_t                       sendAEN = FALSE;
6635 
6636         replyh_arg = (m_replyh_arg_t *)args;
6637         rfm = replyh_arg->rfm;
6638         mpt = replyh_arg->mpt;
6639 
6640         eventreply = (pMpi2EventNotificationReply_t)
6641             (mpt->m_reply_frame + (rfm - mpt->m_reply_frame_dma_addr));
6642         event = ddi_get16(mpt->m_acc_reply_frame_hdl, &eventreply->Event);
6643 
6644 
6645         /*
6646          * Generate a system event to let anyone who cares know that a
6647          * LOG_ENTRY_ADDED event has occurred.  This is sent no matter what the
6648          * event mask is set to.
6649          */
6650         if (event == MPI2_EVENT_LOG_ENTRY_ADDED) {
6651                 sendAEN = TRUE;
6652         }
6653 
6654         /*
6655          * Record the event only if it is not masked.  Determine which dword
6656          * and bit of event mask to test.
6657          */
6658         i = (uint8_t)(event / 32);
6659         j = (uint8_t)(event % 32);
6660         if ((i < 4) && ((1 << j) & mpt->m_event_mask[i])) {
6661                 i = mpt->m_event_index;
6662                 mpt->m_events[i].Type = event;
6663                 mpt->m_events[i].Number = ++mpt->m_event_number;
6664                 bzero(mpt->m_events[i].Data, MPTSAS_MAX_EVENT_DATA_LENGTH * 4);
6665                 event_data_len = ddi_get16(mpt->m_acc_reply_frame_hdl,
6666                     &eventreply->EventDataLength);
6667 
6668                 if (event_data_len > 0) {
6669                         /*
6670                          * Limit data to size in m_event entry
6671                          */
6672                         if (event_data_len > MPTSAS_MAX_EVENT_DATA_LENGTH) {
6673                                 event_data_len = MPTSAS_MAX_EVENT_DATA_LENGTH;
6674                         }
6675                         for (j = 0; j < event_data_len; j++) {
6676                                 mpt->m_events[i].Data[j] =
6677                                     ddi_get32(mpt->m_acc_reply_frame_hdl,
6678                                     &(eventreply->EventData[j]));
6679                         }
6680 
6681                         /*
6682                          * check for index wrap-around
6683                          */
6684                         if (++i == MPTSAS_EVENT_QUEUE_SIZE) {
6685                                 i = 0;
6686                         }
6687                         mpt->m_event_index = (uint8_t)i;
6688 
6689                         /*
6690                          * Set flag to send the event.
6691                          */
6692                         sendAEN = TRUE;
6693                 }
6694         }
6695 
6696         /*
6697          * Generate a system event if flag is set to let anyone who cares know
6698          * that an event has occurred.
6699          */
6700         if (sendAEN) {
6701                 (void) ddi_log_sysevent(mpt->m_dip, DDI_VENDOR_LSI, "MPT_SAS",
6702                     "SAS", NULL, NULL, DDI_NOSLEEP);
6703         }
6704 }
6705 
6706 #define SMP_RESET_IN_PROGRESS MPI2_EVENT_SAS_TOPO_LR_SMP_RESET_IN_PROGRESS
6707 /*
6708  * handle sync events from ioc in interrupt
6709  * return value:
6710  * DDI_SUCCESS: The event is handled by this func
6711  * DDI_FAILURE: Event is not handled
6712  */
6713 static int
6714 mptsas_handle_event_sync(void *args)
6715 {
6716         m_replyh_arg_t                  *replyh_arg;
6717         pMpi2EventNotificationReply_t   eventreply;
6718         uint32_t                        event, rfm;
6719         mptsas_t                        *mpt;
6720         uint_t                          iocstatus;
6721 
6722         replyh_arg = (m_replyh_arg_t *)args;
6723         rfm = replyh_arg->rfm;
6724         mpt = replyh_arg->mpt;
6725 
6726         ASSERT(mutex_owned(&mpt->m_mutex));
6727 
6728         eventreply = (pMpi2EventNotificationReply_t)
6729             (mpt->m_reply_frame + (rfm - mpt->m_reply_frame_dma_addr));
6730         event = ddi_get16(mpt->m_acc_reply_frame_hdl, &eventreply->Event);
6731 
6732         if (iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
6733             &eventreply->IOCStatus)) {
6734                 if (iocstatus == MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
6735                         mptsas_log(mpt, CE_WARN,
6736                             "!mptsas_handle_event_sync: IOCStatus=0x%x, "
6737                             "IOCLogInfo=0x%x", iocstatus,
6738                             ddi_get32(mpt->m_acc_reply_frame_hdl,
6739                             &eventreply->IOCLogInfo));
6740                 } else {
6741                         mptsas_log(mpt, CE_WARN,
6742                             "mptsas_handle_event_sync: IOCStatus=0x%x, "
6743                             "IOCLogInfo=0x%x", iocstatus,
6744                             ddi_get32(mpt->m_acc_reply_frame_hdl,
6745                             &eventreply->IOCLogInfo));
6746                 }
6747         }
6748 
6749         /*
6750          * figure out what kind of event we got and handle accordingly
6751          */
6752         switch (event) {
6753         case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
6754         {
6755                 pMpi2EventDataSasTopologyChangeList_t   sas_topo_change_list;
6756                 uint8_t                         num_entries, expstatus, phy;
6757                 uint8_t                         phystatus, physport, state, i;
6758                 uint8_t                         start_phy_num, link_rate;
6759                 uint16_t                        dev_handle, reason_code;
6760                 uint16_t                        enc_handle, expd_handle;
6761                 char                            string[80], curr[80], prev[80];
6762                 mptsas_topo_change_list_t       *topo_head = NULL;
6763                 mptsas_topo_change_list_t       *topo_tail = NULL;
6764                 mptsas_topo_change_list_t       *topo_node = NULL;
6765                 mptsas_target_t                 *ptgt;
6766                 mptsas_smp_t                    *psmp;
6767                 mptsas_hash_table_t             *tgttbl, *smptbl;
6768                 uint8_t                         flags = 0, exp_flag;
6769                 smhba_info_t                    *pSmhba = NULL;
6770 
6771                 NDBG20(("mptsas_handle_event_sync: SAS topology change"));
6772 
6773                 tgttbl = &mpt->m_active->m_tgttbl;
6774                 smptbl = &mpt->m_active->m_smptbl;
6775 
6776                 sas_topo_change_list = (pMpi2EventDataSasTopologyChangeList_t)
6777                     eventreply->EventData;
6778 
6779                 enc_handle = ddi_get16(mpt->m_acc_reply_frame_hdl,
6780                     &sas_topo_change_list->EnclosureHandle);
6781                 expd_handle = ddi_get16(mpt->m_acc_reply_frame_hdl,
6782                     &sas_topo_change_list->ExpanderDevHandle);
6783                 num_entries = ddi_get8(mpt->m_acc_reply_frame_hdl,
6784                     &sas_topo_change_list->NumEntries);
6785                 start_phy_num = ddi_get8(mpt->m_acc_reply_frame_hdl,
6786                     &sas_topo_change_list->StartPhyNum);
6787                 expstatus = ddi_get8(mpt->m_acc_reply_frame_hdl,
6788                     &sas_topo_change_list->ExpStatus);
6789                 physport = ddi_get8(mpt->m_acc_reply_frame_hdl,
6790                     &sas_topo_change_list->PhysicalPort);
6791 
6792                 string[0] = 0;
6793                 if (expd_handle) {
6794                         flags = MPTSAS_TOPO_FLAG_EXPANDER_ASSOCIATED;
6795                         switch (expstatus) {
6796                         case MPI2_EVENT_SAS_TOPO_ES_ADDED:
6797                                 (void) sprintf(string, " added");
6798                                 /*
6799                                  * New expander device added
6800                                  */
6801                                 mpt->m_port_chng = 1;
6802                                 topo_node = kmem_zalloc(
6803                                     sizeof (mptsas_topo_change_list_t),
6804                                     KM_SLEEP);
6805                                 topo_node->mpt = mpt;
6806                                 topo_node->event = MPTSAS_DR_EVENT_RECONFIG_SMP;
6807                                 topo_node->un.physport = physport;
6808                                 topo_node->devhdl = expd_handle;
6809                                 topo_node->flags = flags;
6810                                 topo_node->object = NULL;
6811                                 if (topo_head == NULL) {
6812                                         topo_head = topo_tail = topo_node;
6813                                 } else {
6814                                         topo_tail->next = topo_node;
6815                                         topo_tail = topo_node;
6816                                 }
6817                                 break;
6818                         case MPI2_EVENT_SAS_TOPO_ES_NOT_RESPONDING:
6819                                 (void) sprintf(string, " not responding, "
6820                                     "removed");
6821                                 psmp = mptsas_search_by_devhdl(smptbl,
6822                                     expd_handle);
6823                                 if (psmp == NULL)
6824                                         break;
6825 
6826                                 topo_node = kmem_zalloc(
6827                                     sizeof (mptsas_topo_change_list_t),
6828                                     KM_SLEEP);
6829                                 topo_node->mpt = mpt;
6830                                 topo_node->un.phymask = psmp->m_phymask;
6831                                 topo_node->event = MPTSAS_DR_EVENT_OFFLINE_SMP;
6832                                 topo_node->devhdl = expd_handle;
6833                                 topo_node->flags = flags;
6834                                 topo_node->object = NULL;
6835                                 if (topo_head == NULL) {
6836                                         topo_head = topo_tail = topo_node;
6837                                 } else {
6838                                         topo_tail->next = topo_node;
6839                                         topo_tail = topo_node;
6840                                 }
6841                                 break;
6842                         case MPI2_EVENT_SAS_TOPO_ES_RESPONDING:
6843                                 break;
6844                         case MPI2_EVENT_SAS_TOPO_ES_DELAY_NOT_RESPONDING:
6845                                 (void) sprintf(string, " not responding, "
6846                                     "delaying removal");
6847                                 break;
6848                         default:
6849                                 break;
6850                         }
6851                 } else {
6852                         flags = MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE;
6853                 }
6854 
6855                 NDBG20(("SAS TOPOLOGY CHANGE for enclosure %x expander %x%s\n",
6856                     enc_handle, expd_handle, string));
6857                 for (i = 0; i < num_entries; i++) {
6858                         phy = i + start_phy_num;
6859                         phystatus = ddi_get8(mpt->m_acc_reply_frame_hdl,
6860                             &sas_topo_change_list->PHY[i].PhyStatus);
6861                         dev_handle = ddi_get16(mpt->m_acc_reply_frame_hdl,
6862                             &sas_topo_change_list->PHY[i].AttachedDevHandle);
6863                         reason_code = phystatus & MPI2_EVENT_SAS_TOPO_RC_MASK;
6864                         /*
6865                          * Filter out processing of Phy Vacant Status unless
6866                          * the reason code is "Not Responding".  Process all
6867                          * other combinations of Phy Status and Reason Codes.
6868                          */
6869                         if ((phystatus &
6870                             MPI2_EVENT_SAS_TOPO_PHYSTATUS_VACANT) &&
6871                             (reason_code !=
6872                             MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING)) {
6873                                 continue;
6874                         }
6875                         curr[0] = 0;
6876                         prev[0] = 0;
6877                         string[0] = 0;
6878                         switch (reason_code) {
6879                         case MPI2_EVENT_SAS_TOPO_RC_TARG_ADDED:
6880                         {
6881                                 NDBG20(("mptsas%d phy %d physical_port %d "
6882                                     "dev_handle %d added", mpt->m_instance, phy,
6883                                     physport, dev_handle));
6884                                 link_rate = ddi_get8(mpt->m_acc_reply_frame_hdl,
6885                                     &sas_topo_change_list->PHY[i].LinkRate);
6886                                 state = (link_rate &
6887                                     MPI2_EVENT_SAS_TOPO_LR_CURRENT_MASK) >>
6888                                     MPI2_EVENT_SAS_TOPO_LR_CURRENT_SHIFT;
6889                                 switch (state) {
6890                                 case MPI2_EVENT_SAS_TOPO_LR_PHY_DISABLED:
6891                                         (void) sprintf(curr, "is disabled");
6892                                         break;
6893                                 case MPI2_EVENT_SAS_TOPO_LR_NEGOTIATION_FAILED:
6894                                         (void) sprintf(curr, "is offline, "
6895                                             "failed speed negotiation");
6896                                         break;
6897                                 case MPI2_EVENT_SAS_TOPO_LR_SATA_OOB_COMPLETE:
6898                                         (void) sprintf(curr, "SATA OOB "
6899                                             "complete");
6900                                         break;
6901                                 case SMP_RESET_IN_PROGRESS:
6902                                         (void) sprintf(curr, "SMP reset in "
6903                                             "progress");
6904                                         break;
6905                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_1_5:
6906                                         (void) sprintf(curr, "is online at "
6907                                             "1.5 Gbps");
6908                                         break;
6909                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_3_0:
6910                                         (void) sprintf(curr, "is online at 3.0 "
6911                                             "Gbps");
6912                                         break;
6913                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_6_0:
6914                                         (void) sprintf(curr, "is online at 6.0 "
6915                                             "Gbps");
6916                                         break;
6917                                 default:
6918                                         (void) sprintf(curr, "state is "
6919                                             "unknown");
6920                                         break;
6921                                 }
6922                                 /*
6923                                  * New target device added into the system.
6924                                  * Set association flag according to if an
6925                                  * expander is used or not.
6926                                  */
6927                                 exp_flag =
6928                                     MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE;
6929                                 if (flags ==
6930                                     MPTSAS_TOPO_FLAG_EXPANDER_ASSOCIATED) {
6931                                         flags = exp_flag;
6932                                 }
6933                                 topo_node = kmem_zalloc(
6934                                     sizeof (mptsas_topo_change_list_t),
6935                                     KM_SLEEP);
6936                                 topo_node->mpt = mpt;
6937                                 topo_node->event =
6938                                     MPTSAS_DR_EVENT_RECONFIG_TARGET;
6939                                 if (expd_handle == 0) {
6940                                         /*
6941                                          * Per MPI 2, if expander dev handle
6942                                          * is 0, it's a directly attached
6943                                          * device. So driver use PHY to decide
6944                                          * which iport is associated
6945                                          */
6946                                         physport = phy;
6947                                         mpt->m_port_chng = 1;
6948                                 }
6949                                 topo_node->un.physport = physport;
6950                                 topo_node->devhdl = dev_handle;
6951                                 topo_node->flags = flags;
6952                                 topo_node->object = NULL;
6953                                 if (topo_head == NULL) {
6954                                         topo_head = topo_tail = topo_node;
6955                                 } else {
6956                                         topo_tail->next = topo_node;
6957                                         topo_tail = topo_node;
6958                                 }
6959                                 break;
6960                         }
6961                         case MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING:
6962                         {
6963                                 NDBG20(("mptsas%d phy %d physical_port %d "
6964                                     "dev_handle %d removed", mpt->m_instance,
6965                                     phy, physport, dev_handle));
6966                                 /*
6967                                  * Set association flag according to if an
6968                                  * expander is used or not.
6969                                  */
6970                                 exp_flag =
6971                                     MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE;
6972                                 if (flags ==
6973                                     MPTSAS_TOPO_FLAG_EXPANDER_ASSOCIATED) {
6974                                         flags = exp_flag;
6975                                 }
6976                                 /*
6977                                  * Target device is removed from the system
6978                                  * Before the device is really offline from
6979                                  * from system.
6980                                  */
6981                                 ptgt = mptsas_search_by_devhdl(tgttbl,
6982                                     dev_handle);
6983                                 /*
6984                                  * If ptgt is NULL here, it means that the
6985                                  * DevHandle is not in the hash table.  This is
6986                                  * reasonable sometimes.  For example, if a
6987                                  * disk was pulled, then added, then pulled
6988                                  * again, the disk will not have been put into
6989                                  * the hash table because the add event will
6990                                  * have an invalid phymask.  BUT, this does not
6991                                  * mean that the DevHandle is invalid.  The
6992                                  * controller will still have a valid DevHandle
6993                                  * that must be removed.  To do this, use the
6994                                  * MPTSAS_TOPO_FLAG_REMOVE_HANDLE event.
6995                                  */
6996                                 if (ptgt == NULL) {
6997                                         topo_node = kmem_zalloc(
6998                                             sizeof (mptsas_topo_change_list_t),
6999                                             KM_SLEEP);
7000                                         topo_node->mpt = mpt;
7001                                         topo_node->un.phymask = 0;
7002                                         topo_node->event =
7003                                             MPTSAS_TOPO_FLAG_REMOVE_HANDLE;
7004                                         topo_node->devhdl = dev_handle;
7005                                         topo_node->flags = flags;
7006                                         topo_node->object = NULL;
7007                                         if (topo_head == NULL) {
7008                                                 topo_head = topo_tail =
7009                                                     topo_node;
7010                                         } else {
7011                                                 topo_tail->next = topo_node;
7012                                                 topo_tail = topo_node;
7013                                         }
7014                                         break;
7015                                 }
7016 
7017                                 /*
7018                                  * Update DR flag immediately avoid I/O failure
7019                                  * before failover finish. Pay attention to the
7020                                  * mutex protect, we need grab the per target
7021                                  * mutex during set m_dr_flag because the
7022                                  * m_mutex would not be held all the time in
7023                                  * mptsas_scsi_start().
7024                                  */
7025                                 mutex_enter(&ptgt->m_tgt_intr_mutex);
7026                                 ptgt->m_dr_flag = MPTSAS_DR_INTRANSITION;
7027                                 mutex_exit(&ptgt->m_tgt_intr_mutex);
7028 
7029                                 topo_node = kmem_zalloc(
7030                                     sizeof (mptsas_topo_change_list_t),
7031                                     KM_SLEEP);
7032                                 topo_node->mpt = mpt;
7033                                 topo_node->un.phymask = ptgt->m_phymask;
7034                                 topo_node->event =
7035                                     MPTSAS_DR_EVENT_OFFLINE_TARGET;
7036                                 topo_node->devhdl = dev_handle;
7037                                 topo_node->flags = flags;
7038                                 topo_node->object = NULL;
7039                                 if (topo_head == NULL) {
7040                                         topo_head = topo_tail = topo_node;
7041                                 } else {
7042                                         topo_tail->next = topo_node;
7043                                         topo_tail = topo_node;
7044                                 }
7045                                 break;
7046                         }
7047                         case MPI2_EVENT_SAS_TOPO_RC_PHY_CHANGED:
7048                                 link_rate = ddi_get8(mpt->m_acc_reply_frame_hdl,
7049                                     &sas_topo_change_list->PHY[i].LinkRate);
7050                                 state = (link_rate &
7051                                     MPI2_EVENT_SAS_TOPO_LR_CURRENT_MASK) >>
7052                                     MPI2_EVENT_SAS_TOPO_LR_CURRENT_SHIFT;
7053                                 pSmhba = &mpt->m_phy_info[i].smhba_info;
7054                                 pSmhba->negotiated_link_rate = state;
7055                                 switch (state) {
7056                                 case MPI2_EVENT_SAS_TOPO_LR_PHY_DISABLED:
7057                                         (void) sprintf(curr, "is disabled");
7058                                         mptsas_smhba_log_sysevent(mpt,
7059                                             ESC_SAS_PHY_EVENT,
7060                                             SAS_PHY_REMOVE,
7061                                             &mpt->m_phy_info[i].smhba_info);
7062                                         mpt->m_phy_info[i].smhba_info.
7063                                             negotiated_link_rate
7064                                             = 0x1;
7065                                         break;
7066                                 case MPI2_EVENT_SAS_TOPO_LR_NEGOTIATION_FAILED:
7067                                         (void) sprintf(curr, "is offline, "
7068                                             "failed speed negotiation");
7069                                         mptsas_smhba_log_sysevent(mpt,
7070                                             ESC_SAS_PHY_EVENT,
7071                                             SAS_PHY_OFFLINE,
7072                                             &mpt->m_phy_info[i].smhba_info);
7073                                         break;
7074                                 case MPI2_EVENT_SAS_TOPO_LR_SATA_OOB_COMPLETE:
7075                                         (void) sprintf(curr, "SATA OOB "
7076                                             "complete");
7077                                         break;
7078                                 case SMP_RESET_IN_PROGRESS:
7079                                         (void) sprintf(curr, "SMP reset in "
7080                                             "progress");
7081                                         break;
7082                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_1_5:
7083                                         (void) sprintf(curr, "is online at "
7084                                             "1.5 Gbps");
7085                                         if ((expd_handle == 0) &&
7086                                             (enc_handle == 1)) {
7087                                                 mpt->m_port_chng = 1;
7088                                         }
7089                                         mptsas_smhba_log_sysevent(mpt,
7090                                             ESC_SAS_PHY_EVENT,
7091                                             SAS_PHY_ONLINE,
7092                                             &mpt->m_phy_info[i].smhba_info);
7093                                         break;
7094                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_3_0:
7095                                         (void) sprintf(curr, "is online at 3.0 "
7096                                             "Gbps");
7097                                         if ((expd_handle == 0) &&
7098                                             (enc_handle == 1)) {
7099                                                 mpt->m_port_chng = 1;
7100                                         }
7101                                         mptsas_smhba_log_sysevent(mpt,
7102                                             ESC_SAS_PHY_EVENT,
7103                                             SAS_PHY_ONLINE,
7104                                             &mpt->m_phy_info[i].smhba_info);
7105                                         break;
7106                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_6_0:
7107                                         (void) sprintf(curr, "is online at "
7108                                             "6.0 Gbps");
7109                                         if ((expd_handle == 0) &&
7110                                             (enc_handle == 1)) {
7111                                                 mpt->m_port_chng = 1;
7112                                         }
7113                                         mptsas_smhba_log_sysevent(mpt,
7114                                             ESC_SAS_PHY_EVENT,
7115                                             SAS_PHY_ONLINE,
7116                                             &mpt->m_phy_info[i].smhba_info);
7117                                         break;
7118                                 default:
7119                                         (void) sprintf(curr, "state is "
7120                                             "unknown");
7121                                         break;
7122                                 }
7123 
7124                                 state = (link_rate &
7125                                     MPI2_EVENT_SAS_TOPO_LR_PREV_MASK) >>
7126                                     MPI2_EVENT_SAS_TOPO_LR_PREV_SHIFT;
7127                                 switch (state) {
7128                                 case MPI2_EVENT_SAS_TOPO_LR_PHY_DISABLED:
7129                                         (void) sprintf(prev, ", was disabled");
7130                                         break;
7131                                 case MPI2_EVENT_SAS_TOPO_LR_NEGOTIATION_FAILED:
7132                                         (void) sprintf(prev, ", was offline, "
7133                                             "failed speed negotiation");
7134                                         break;
7135                                 case MPI2_EVENT_SAS_TOPO_LR_SATA_OOB_COMPLETE:
7136                                         (void) sprintf(prev, ", was SATA OOB "
7137                                             "complete");
7138                                         break;
7139                                 case SMP_RESET_IN_PROGRESS:
7140                                         (void) sprintf(prev, ", was SMP reset "
7141                                             "in progress");
7142                                         break;
7143                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_1_5:
7144                                         (void) sprintf(prev, ", was online at "
7145                                             "1.5 Gbps");
7146                                         break;
7147                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_3_0:
7148                                         (void) sprintf(prev, ", was online at "
7149                                             "3.0 Gbps");
7150                                         break;
7151                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_6_0:
7152                                         (void) sprintf(prev, ", was online at "
7153                                             "6.0 Gbps");
7154                                         break;
7155                                 default:
7156                                 break;
7157                                 }
7158                                 (void) sprintf(&string[strlen(string)], "link "
7159                                     "changed, ");
7160                                 break;
7161                         case MPI2_EVENT_SAS_TOPO_RC_NO_CHANGE:
7162                                 continue;
7163                         case MPI2_EVENT_SAS_TOPO_RC_DELAY_NOT_RESPONDING:
7164                                 (void) sprintf(&string[strlen(string)],
7165                                     "target not responding, delaying "
7166                                     "removal");
7167                                 break;
7168                         }
7169                         NDBG20(("mptsas%d phy %d DevHandle %x, %s%s%s\n",
7170                             mpt->m_instance, phy, dev_handle, string, curr,
7171                             prev));
7172                 }
7173                 if (topo_head != NULL) {
7174                         /*
7175                          * Launch DR taskq to handle topology change
7176                          */
7177                         if ((ddi_taskq_dispatch(mpt->m_dr_taskq,
7178                             mptsas_handle_dr, (void *)topo_head,
7179                             DDI_NOSLEEP)) != DDI_SUCCESS) {
7180                                 mptsas_log(mpt, CE_NOTE, "mptsas start taskq "
7181                                     "for handle SAS DR event failed. \n");
7182                         }
7183                 }
7184                 break;
7185         }
7186         case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
7187         {
7188                 Mpi2EventDataIrConfigChangeList_t       *irChangeList;
7189                 mptsas_topo_change_list_t               *topo_head = NULL;
7190                 mptsas_topo_change_list_t               *topo_tail = NULL;
7191                 mptsas_topo_change_list_t               *topo_node = NULL;
7192                 mptsas_target_t                         *ptgt;
7193                 mptsas_hash_table_t                     *tgttbl;
7194                 uint8_t                                 num_entries, i, reason;
7195                 uint16_t                                volhandle, diskhandle;
7196 
7197                 irChangeList = (pMpi2EventDataIrConfigChangeList_t)
7198                     eventreply->EventData;
7199                 num_entries = ddi_get8(mpt->m_acc_reply_frame_hdl,
7200                     &irChangeList->NumElements);
7201 
7202                 tgttbl = &mpt->m_active->m_tgttbl;
7203 
7204                 NDBG20(("mptsas%d IR_CONFIGURATION_CHANGE_LIST event received",
7205                     mpt->m_instance));
7206 
7207                 for (i = 0; i < num_entries; i++) {
7208                         reason = ddi_get8(mpt->m_acc_reply_frame_hdl,
7209                             &irChangeList->ConfigElement[i].ReasonCode);
7210                         volhandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7211                             &irChangeList->ConfigElement[i].VolDevHandle);
7212                         diskhandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7213                             &irChangeList->ConfigElement[i].PhysDiskDevHandle);
7214 
7215                         switch (reason) {
7216                         case MPI2_EVENT_IR_CHANGE_RC_ADDED:
7217                         case MPI2_EVENT_IR_CHANGE_RC_VOLUME_CREATED:
7218                         {
7219                                 NDBG20(("mptsas %d volume added\n",
7220                                     mpt->m_instance));
7221 
7222                                 topo_node = kmem_zalloc(
7223                                     sizeof (mptsas_topo_change_list_t),
7224                                     KM_SLEEP);
7225 
7226                                 topo_node->mpt = mpt;
7227                                 topo_node->event =
7228                                     MPTSAS_DR_EVENT_RECONFIG_TARGET;
7229                                 topo_node->un.physport = 0xff;
7230                                 topo_node->devhdl = volhandle;
7231                                 topo_node->flags =
7232                                     MPTSAS_TOPO_FLAG_RAID_ASSOCIATED;
7233                                 topo_node->object = NULL;
7234                                 if (topo_head == NULL) {
7235                                         topo_head = topo_tail = topo_node;
7236                                 } else {
7237                                         topo_tail->next = topo_node;
7238                                         topo_tail = topo_node;
7239                                 }
7240                                 break;
7241                         }
7242                         case MPI2_EVENT_IR_CHANGE_RC_REMOVED:
7243                         case MPI2_EVENT_IR_CHANGE_RC_VOLUME_DELETED:
7244                         {
7245                                 NDBG20(("mptsas %d volume deleted\n",
7246                                     mpt->m_instance));
7247                                 ptgt = mptsas_search_by_devhdl(tgttbl,
7248                                     volhandle);
7249                                 if (ptgt == NULL)
7250                                         break;
7251 
7252                                 /*
7253                                  * Clear any flags related to volume
7254                                  */
7255                                 (void) mptsas_delete_volume(mpt, volhandle);
7256 
7257                                 /*
7258                                  * Update DR flag immediately avoid I/O failure
7259                                  */
7260                                 mutex_enter(&ptgt->m_tgt_intr_mutex);
7261                                 ptgt->m_dr_flag = MPTSAS_DR_INTRANSITION;
7262                                 mutex_exit(&ptgt->m_tgt_intr_mutex);
7263 
7264                                 topo_node = kmem_zalloc(
7265                                     sizeof (mptsas_topo_change_list_t),
7266                                     KM_SLEEP);
7267                                 topo_node->mpt = mpt;
7268                                 topo_node->un.phymask = ptgt->m_phymask;
7269                                 topo_node->event =
7270                                     MPTSAS_DR_EVENT_OFFLINE_TARGET;
7271                                 topo_node->devhdl = volhandle;
7272                                 topo_node->flags =
7273                                     MPTSAS_TOPO_FLAG_RAID_ASSOCIATED;
7274                                 topo_node->object = (void *)ptgt;
7275                                 if (topo_head == NULL) {
7276                                         topo_head = topo_tail = topo_node;
7277                                 } else {
7278                                         topo_tail->next = topo_node;
7279                                         topo_tail = topo_node;
7280                                 }
7281                                 break;
7282                         }
7283                         case MPI2_EVENT_IR_CHANGE_RC_PD_CREATED:
7284                         case MPI2_EVENT_IR_CHANGE_RC_HIDE:
7285                         {
7286                                 ptgt = mptsas_search_by_devhdl(tgttbl,
7287                                     diskhandle);
7288                                 if (ptgt == NULL)
7289                                         break;
7290 
7291                                 /*
7292                                  * Update DR flag immediately avoid I/O failure
7293                                  */
7294                                 mutex_enter(&ptgt->m_tgt_intr_mutex);
7295                                 ptgt->m_dr_flag = MPTSAS_DR_INTRANSITION;
7296                                 mutex_exit(&ptgt->m_tgt_intr_mutex);
7297 
7298                                 topo_node = kmem_zalloc(
7299                                     sizeof (mptsas_topo_change_list_t),
7300                                     KM_SLEEP);
7301                                 topo_node->mpt = mpt;
7302                                 topo_node->un.phymask = ptgt->m_phymask;
7303                                 topo_node->event =
7304                                     MPTSAS_DR_EVENT_OFFLINE_TARGET;
7305                                 topo_node->devhdl = diskhandle;
7306                                 topo_node->flags =
7307                                     MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED;
7308                                 topo_node->object = (void *)ptgt;
7309                                 if (topo_head == NULL) {
7310                                         topo_head = topo_tail = topo_node;
7311                                 } else {
7312                                         topo_tail->next = topo_node;
7313                                         topo_tail = topo_node;
7314                                 }
7315                                 break;
7316                         }
7317                         case MPI2_EVENT_IR_CHANGE_RC_UNHIDE:
7318                         case MPI2_EVENT_IR_CHANGE_RC_PD_DELETED:
7319                         {
7320                                 /*
7321                                  * The physical drive is released by a IR
7322                                  * volume. But we cannot get the the physport
7323                                  * or phynum from the event data, so we only
7324                                  * can get the physport/phynum after SAS
7325                                  * Device Page0 request for the devhdl.
7326                                  */
7327                                 topo_node = kmem_zalloc(
7328                                     sizeof (mptsas_topo_change_list_t),
7329                                     KM_SLEEP);
7330                                 topo_node->mpt = mpt;
7331                                 topo_node->un.phymask = 0;
7332                                 topo_node->event =
7333                                     MPTSAS_DR_EVENT_RECONFIG_TARGET;
7334                                 topo_node->devhdl = diskhandle;
7335                                 topo_node->flags =
7336                                     MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED;
7337                                 topo_node->object = NULL;
7338                                 mpt->m_port_chng = 1;
7339                                 if (topo_head == NULL) {
7340                                         topo_head = topo_tail = topo_node;
7341                                 } else {
7342                                         topo_tail->next = topo_node;
7343                                         topo_tail = topo_node;
7344                                 }
7345                                 break;
7346                         }
7347                         default:
7348                                 break;
7349                         }
7350                 }
7351 
7352                 if (topo_head != NULL) {
7353                         /*
7354                          * Launch DR taskq to handle topology change
7355                          */
7356                         if ((ddi_taskq_dispatch(mpt->m_dr_taskq,
7357                             mptsas_handle_dr, (void *)topo_head,
7358                             DDI_NOSLEEP)) != DDI_SUCCESS) {
7359                                 mptsas_log(mpt, CE_NOTE, "mptsas start taskq "
7360                                     "for handle SAS DR event failed. \n");
7361                         }
7362                 }
7363                 break;
7364         }
7365         default:
7366                 return (DDI_FAILURE);
7367         }
7368 
7369         return (DDI_SUCCESS);
7370 }
7371 
7372 /*
7373  * handle events from ioc
7374  */
7375 static void
7376 mptsas_handle_event(void *args)
7377 {
7378         m_replyh_arg_t                  *replyh_arg;
7379         pMpi2EventNotificationReply_t   eventreply;
7380         uint32_t                        event, iocloginfo, rfm;
7381         uint32_t                        status;
7382         uint8_t                         port;
7383         mptsas_t                        *mpt;
7384         uint_t                          iocstatus;
7385 
7386         replyh_arg = (m_replyh_arg_t *)args;
7387         rfm = replyh_arg->rfm;
7388         mpt = replyh_arg->mpt;
7389 
7390         mutex_enter(&mpt->m_mutex);
7391 
7392         eventreply = (pMpi2EventNotificationReply_t)
7393             (mpt->m_reply_frame + (rfm - mpt->m_reply_frame_dma_addr));
7394         event = ddi_get16(mpt->m_acc_reply_frame_hdl, &eventreply->Event);
7395 
7396         if (iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
7397             &eventreply->IOCStatus)) {
7398                 if (iocstatus == MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
7399                         mptsas_log(mpt, CE_WARN,
7400                             "!mptsas_handle_event: IOCStatus=0x%x, "
7401                             "IOCLogInfo=0x%x", iocstatus,
7402                             ddi_get32(mpt->m_acc_reply_frame_hdl,
7403                             &eventreply->IOCLogInfo));
7404                 } else {
7405                         mptsas_log(mpt, CE_WARN,
7406                             "mptsas_handle_event: IOCStatus=0x%x, "
7407                             "IOCLogInfo=0x%x", iocstatus,
7408                             ddi_get32(mpt->m_acc_reply_frame_hdl,
7409                             &eventreply->IOCLogInfo));
7410                 }
7411         }
7412 
7413         /*
7414          * figure out what kind of event we got and handle accordingly
7415          */
7416         switch (event) {
7417         case MPI2_EVENT_LOG_ENTRY_ADDED:
7418                 break;
7419         case MPI2_EVENT_LOG_DATA:
7420                 iocloginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
7421                     &eventreply->IOCLogInfo);
7422                 NDBG20(("mptsas %d log info %x received.\n", mpt->m_instance,
7423                     iocloginfo));
7424                 break;
7425         case MPI2_EVENT_STATE_CHANGE:
7426                 NDBG20(("mptsas%d state change.", mpt->m_instance));
7427                 break;
7428         case MPI2_EVENT_HARD_RESET_RECEIVED:
7429                 NDBG20(("mptsas%d event change.", mpt->m_instance));
7430                 break;
7431         case MPI2_EVENT_SAS_DISCOVERY:
7432         {
7433                 MPI2_EVENT_DATA_SAS_DISCOVERY   *sasdiscovery;
7434                 char                            string[80];
7435                 uint8_t                         rc;
7436 
7437                 sasdiscovery =
7438                     (pMpi2EventDataSasDiscovery_t)eventreply->EventData;
7439 
7440                 rc = ddi_get8(mpt->m_acc_reply_frame_hdl,
7441                     &sasdiscovery->ReasonCode);
7442                 port = ddi_get8(mpt->m_acc_reply_frame_hdl,
7443                     &sasdiscovery->PhysicalPort);
7444                 status = ddi_get32(mpt->m_acc_reply_frame_hdl,
7445                     &sasdiscovery->DiscoveryStatus);
7446 
7447                 string[0] = 0;
7448                 switch (rc) {
7449                 case MPI2_EVENT_SAS_DISC_RC_STARTED:
7450                         (void) sprintf(string, "STARTING");
7451                         break;
7452                 case MPI2_EVENT_SAS_DISC_RC_COMPLETED:
7453                         (void) sprintf(string, "COMPLETED");
7454                         break;
7455                 default:
7456                         (void) sprintf(string, "UNKNOWN");
7457                         break;
7458                 }
7459 
7460                 NDBG20(("SAS DISCOVERY is %s for port %d, status %x", string,
7461                     port, status));
7462 
7463                 break;
7464         }
7465         case MPI2_EVENT_EVENT_CHANGE:
7466                 NDBG20(("mptsas%d event change.", mpt->m_instance));
7467                 break;
7468         case MPI2_EVENT_TASK_SET_FULL:
7469         {
7470                 pMpi2EventDataTaskSetFull_t     taskfull;
7471 
7472                 taskfull = (pMpi2EventDataTaskSetFull_t)eventreply->EventData;
7473 
7474                 NDBG20(("TASK_SET_FULL received for mptsas%d, depth %d\n",
7475                     mpt->m_instance,  ddi_get16(mpt->m_acc_reply_frame_hdl,
7476                     &taskfull->CurrentDepth)));
7477                 break;
7478         }
7479         case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
7480         {
7481                 /*
7482                  * SAS TOPOLOGY CHANGE LIST Event has already been handled
7483                  * in mptsas_handle_event_sync() of interrupt context
7484                  */
7485                 break;
7486         }
7487         case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
7488         {
7489                 pMpi2EventDataSasEnclDevStatusChange_t  encstatus;
7490                 uint8_t                                 rc;
7491                 char                                    string[80];
7492 
7493                 encstatus = (pMpi2EventDataSasEnclDevStatusChange_t)
7494                     eventreply->EventData;
7495 
7496                 rc = ddi_get8(mpt->m_acc_reply_frame_hdl,
7497                     &encstatus->ReasonCode);
7498                 switch (rc) {
7499                 case MPI2_EVENT_SAS_ENCL_RC_ADDED:
7500                         (void) sprintf(string, "added");
7501                         break;
7502                 case MPI2_EVENT_SAS_ENCL_RC_NOT_RESPONDING:
7503                         (void) sprintf(string, ", not responding");
7504                         break;
7505                 default:
7506                 break;
7507                 }
7508                 NDBG20(("mptsas%d ENCLOSURE STATUS CHANGE for enclosure %x%s\n",
7509                     mpt->m_instance, ddi_get16(mpt->m_acc_reply_frame_hdl,
7510                     &encstatus->EnclosureHandle), string));
7511                 break;
7512         }
7513 
7514         /*
7515          * MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE is handled by
7516          * mptsas_handle_event_sync,in here just send ack message.
7517          */
7518         case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
7519         {
7520                 pMpi2EventDataSasDeviceStatusChange_t   statuschange;
7521                 uint8_t                                 rc;
7522                 uint16_t                                devhdl;
7523                 uint64_t                                wwn = 0;
7524                 uint32_t                                wwn_lo, wwn_hi;
7525 
7526                 statuschange = (pMpi2EventDataSasDeviceStatusChange_t)
7527                     eventreply->EventData;
7528                 rc = ddi_get8(mpt->m_acc_reply_frame_hdl,
7529                     &statuschange->ReasonCode);
7530                 wwn_lo = ddi_get32(mpt->m_acc_reply_frame_hdl,
7531                     (uint32_t *)(void *)&statuschange->SASAddress);
7532                 wwn_hi = ddi_get32(mpt->m_acc_reply_frame_hdl,
7533                     (uint32_t *)(void *)&statuschange->SASAddress + 1);
7534                 wwn = ((uint64_t)wwn_hi << 32) | wwn_lo;
7535                 devhdl =  ddi_get16(mpt->m_acc_reply_frame_hdl,
7536                     &statuschange->DevHandle);
7537 
7538                 NDBG13(("MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE wwn is %"PRIx64,
7539                     wwn));
7540 
7541                 switch (rc) {
7542                 case MPI2_EVENT_SAS_DEV_STAT_RC_SMART_DATA:
7543                         NDBG20(("SMART data received, ASC/ASCQ = %02x/%02x",
7544                             ddi_get8(mpt->m_acc_reply_frame_hdl,
7545                             &statuschange->ASC),
7546                             ddi_get8(mpt->m_acc_reply_frame_hdl,
7547                             &statuschange->ASCQ)));
7548                         break;
7549 
7550                 case MPI2_EVENT_SAS_DEV_STAT_RC_UNSUPPORTED:
7551                         NDBG20(("Device not supported"));
7552                         break;
7553 
7554                 case MPI2_EVENT_SAS_DEV_STAT_RC_INTERNAL_DEVICE_RESET:
7555                         NDBG20(("IOC internally generated the Target Reset "
7556                             "for devhdl:%x", devhdl));
7557                         break;
7558 
7559                 case MPI2_EVENT_SAS_DEV_STAT_RC_CMP_INTERNAL_DEV_RESET:
7560                         NDBG20(("IOC's internally generated Target Reset "
7561                             "completed for devhdl:%x", devhdl));
7562                         break;
7563 
7564                 case MPI2_EVENT_SAS_DEV_STAT_RC_TASK_ABORT_INTERNAL:
7565                         NDBG20(("IOC internally generated Abort Task"));
7566                         break;
7567 
7568                 case MPI2_EVENT_SAS_DEV_STAT_RC_CMP_TASK_ABORT_INTERNAL:
7569                         NDBG20(("IOC's internally generated Abort Task "
7570                             "completed"));
7571                         break;
7572 
7573                 case MPI2_EVENT_SAS_DEV_STAT_RC_ABORT_TASK_SET_INTERNAL:
7574                         NDBG20(("IOC internally generated Abort Task Set"));
7575                         break;
7576 
7577                 case MPI2_EVENT_SAS_DEV_STAT_RC_CLEAR_TASK_SET_INTERNAL:
7578                         NDBG20(("IOC internally generated Clear Task Set"));
7579                         break;
7580 
7581                 case MPI2_EVENT_SAS_DEV_STAT_RC_QUERY_TASK_INTERNAL:
7582                         NDBG20(("IOC internally generated Query Task"));
7583                         break;
7584 
7585                 case MPI2_EVENT_SAS_DEV_STAT_RC_ASYNC_NOTIFICATION:
7586                         NDBG20(("Device sent an Asynchronous Notification"));
7587                         break;
7588 
7589                 default:
7590                         break;
7591                 }
7592                 break;
7593         }
7594         case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
7595         {
7596                 /*
7597                  * IR TOPOLOGY CHANGE LIST Event has already been handled
7598                  * in mpt_handle_event_sync() of interrupt context
7599                  */
7600                 break;
7601         }
7602         case MPI2_EVENT_IR_OPERATION_STATUS:
7603         {
7604                 Mpi2EventDataIrOperationStatus_t        *irOpStatus;
7605                 char                                    reason_str[80];
7606                 uint8_t                                 rc, percent;
7607                 uint16_t                                handle;
7608 
7609                 irOpStatus = (pMpi2EventDataIrOperationStatus_t)
7610                     eventreply->EventData;
7611                 rc = ddi_get8(mpt->m_acc_reply_frame_hdl,
7612                     &irOpStatus->RAIDOperation);
7613                 percent = ddi_get8(mpt->m_acc_reply_frame_hdl,
7614                     &irOpStatus->PercentComplete);
7615                 handle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7616                     &irOpStatus->VolDevHandle);
7617 
7618                 switch (rc) {
7619                         case MPI2_EVENT_IR_RAIDOP_RESYNC:
7620                                 (void) sprintf(reason_str, "resync");
7621                                 break;
7622                         case MPI2_EVENT_IR_RAIDOP_ONLINE_CAP_EXPANSION:
7623                                 (void) sprintf(reason_str, "online capacity "
7624                                     "expansion");
7625                                 break;
7626                         case MPI2_EVENT_IR_RAIDOP_CONSISTENCY_CHECK:
7627                                 (void) sprintf(reason_str, "consistency check");
7628                                 break;
7629                         default:
7630                                 (void) sprintf(reason_str, "unknown reason %x",
7631                                     rc);
7632                 }
7633 
7634                 NDBG20(("mptsas%d raid operational status: (%s)"
7635                     "\thandle(0x%04x), percent complete(%d)\n",
7636                     mpt->m_instance, reason_str, handle, percent));
7637                 break;
7638         }
7639         case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
7640         {
7641                 pMpi2EventDataSasBroadcastPrimitive_t   sas_broadcast;
7642                 uint8_t                                 phy_num;
7643                 uint8_t                                 primitive;
7644 
7645                 sas_broadcast = (pMpi2EventDataSasBroadcastPrimitive_t)
7646                     eventreply->EventData;
7647 
7648                 phy_num = ddi_get8(mpt->m_acc_reply_frame_hdl,
7649                     &sas_broadcast->PhyNum);
7650                 primitive = ddi_get8(mpt->m_acc_reply_frame_hdl,
7651                     &sas_broadcast->Primitive);
7652 
7653                 switch (primitive) {
7654                 case MPI2_EVENT_PRIMITIVE_CHANGE:
7655                         mptsas_smhba_log_sysevent(mpt,
7656                             ESC_SAS_HBA_PORT_BROADCAST,
7657                             SAS_PORT_BROADCAST_CHANGE,
7658                             &mpt->m_phy_info[phy_num].smhba_info);
7659                         break;
7660                 case MPI2_EVENT_PRIMITIVE_SES:
7661                         mptsas_smhba_log_sysevent(mpt,
7662                             ESC_SAS_HBA_PORT_BROADCAST,
7663                             SAS_PORT_BROADCAST_SES,
7664                             &mpt->m_phy_info[phy_num].smhba_info);
7665                         break;
7666                 case MPI2_EVENT_PRIMITIVE_EXPANDER:
7667                         mptsas_smhba_log_sysevent(mpt,
7668                             ESC_SAS_HBA_PORT_BROADCAST,
7669                             SAS_PORT_BROADCAST_D01_4,
7670                             &mpt->m_phy_info[phy_num].smhba_info);
7671                         break;
7672                 case MPI2_EVENT_PRIMITIVE_ASYNCHRONOUS_EVENT:
7673                         mptsas_smhba_log_sysevent(mpt,
7674                             ESC_SAS_HBA_PORT_BROADCAST,
7675                             SAS_PORT_BROADCAST_D04_7,
7676                             &mpt->m_phy_info[phy_num].smhba_info);
7677                         break;
7678                 case MPI2_EVENT_PRIMITIVE_RESERVED3:
7679                         mptsas_smhba_log_sysevent(mpt,
7680                             ESC_SAS_HBA_PORT_BROADCAST,
7681                             SAS_PORT_BROADCAST_D16_7,
7682                             &mpt->m_phy_info[phy_num].smhba_info);
7683                         break;
7684                 case MPI2_EVENT_PRIMITIVE_RESERVED4:
7685                         mptsas_smhba_log_sysevent(mpt,
7686                             ESC_SAS_HBA_PORT_BROADCAST,
7687                             SAS_PORT_BROADCAST_D29_7,
7688                             &mpt->m_phy_info[phy_num].smhba_info);
7689                         break;
7690                 case MPI2_EVENT_PRIMITIVE_CHANGE0_RESERVED:
7691                         mptsas_smhba_log_sysevent(mpt,
7692                             ESC_SAS_HBA_PORT_BROADCAST,
7693                             SAS_PORT_BROADCAST_D24_0,
7694                             &mpt->m_phy_info[phy_num].smhba_info);
7695                         break;
7696                 case MPI2_EVENT_PRIMITIVE_CHANGE1_RESERVED:
7697                         mptsas_smhba_log_sysevent(mpt,
7698                             ESC_SAS_HBA_PORT_BROADCAST,
7699                             SAS_PORT_BROADCAST_D27_4,
7700                             &mpt->m_phy_info[phy_num].smhba_info);
7701                         break;
7702                 default:
7703                         NDBG20(("mptsas%d: unknown BROADCAST PRIMITIVE"
7704                             " %x received",
7705                             mpt->m_instance, primitive));
7706                         break;
7707                 }
7708                 NDBG20(("mptsas%d sas broadcast primitive: "
7709                     "\tprimitive(0x%04x), phy(%d) complete\n",
7710                     mpt->m_instance, primitive, phy_num));
7711                 break;
7712         }
7713         case MPI2_EVENT_IR_VOLUME:
7714         {
7715                 Mpi2EventDataIrVolume_t         *irVolume;
7716                 uint16_t                        devhandle;
7717                 uint32_t                        state;
7718                 int                             config, vol;
7719                 mptsas_slots_t                  *slots = mpt->m_active;
7720                 uint8_t                         found = FALSE;
7721 
7722                 irVolume = (pMpi2EventDataIrVolume_t)eventreply->EventData;
7723                 state = ddi_get32(mpt->m_acc_reply_frame_hdl,
7724                     &irVolume->NewValue);
7725                 devhandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7726                     &irVolume->VolDevHandle);
7727 
7728                 NDBG20(("EVENT_IR_VOLUME event is received"));
7729 
7730                 /*
7731                  * Get latest RAID info and then find the DevHandle for this
7732                  * event in the configuration.  If the DevHandle is not found
7733                  * just exit the event.
7734                  */
7735                 (void) mptsas_get_raid_info(mpt);
7736                 for (config = 0; (config < slots->m_num_raid_configs) &&
7737                     (!found); config++) {
7738                         for (vol = 0; vol < MPTSAS_MAX_RAIDVOLS; vol++) {
7739                                 if (slots->m_raidconfig[config].m_raidvol[vol].
7740                                     m_raidhandle == devhandle) {
7741                                         found = TRUE;
7742                                         break;
7743                                 }
7744                         }
7745                 }
7746                 if (!found) {
7747                         break;
7748                 }
7749 
7750                 switch (irVolume->ReasonCode) {
7751                 case MPI2_EVENT_IR_VOLUME_RC_SETTINGS_CHANGED:
7752                 {
7753                         uint32_t i;
7754                         slots->m_raidconfig[config].m_raidvol[vol].m_settings =
7755                             state;
7756 
7757                         i = state & MPI2_RAIDVOL0_SETTING_MASK_WRITE_CACHING;
7758                         mptsas_log(mpt, CE_NOTE, " Volume %d settings changed"
7759                             ", auto-config of hot-swap drives is %s"
7760                             ", write caching is %s"
7761                             ", hot-spare pool mask is %02x\n",
7762                             vol, state &
7763                             MPI2_RAIDVOL0_SETTING_AUTO_CONFIG_HSWAP_DISABLE
7764                             ? "disabled" : "enabled",
7765                             i == MPI2_RAIDVOL0_SETTING_UNCHANGED
7766                             ? "controlled by member disks" :
7767                             i == MPI2_RAIDVOL0_SETTING_DISABLE_WRITE_CACHING
7768                             ? "disabled" :
7769                             i == MPI2_RAIDVOL0_SETTING_ENABLE_WRITE_CACHING
7770                             ? "enabled" :
7771                             "incorrectly set",
7772                             (state >> 16) & 0xff);
7773                                 break;
7774                 }
7775                 case MPI2_EVENT_IR_VOLUME_RC_STATE_CHANGED:
7776                 {
7777                         slots->m_raidconfig[config].m_raidvol[vol].m_state =
7778                             (uint8_t)state;
7779 
7780                         mptsas_log(mpt, CE_NOTE,
7781                             "Volume %d is now %s\n", vol,
7782                             state == MPI2_RAID_VOL_STATE_OPTIMAL
7783                             ? "optimal" :
7784                             state == MPI2_RAID_VOL_STATE_DEGRADED
7785                             ? "degraded" :
7786                             state == MPI2_RAID_VOL_STATE_ONLINE
7787                             ? "online" :
7788                             state == MPI2_RAID_VOL_STATE_INITIALIZING
7789                             ? "initializing" :
7790                             state == MPI2_RAID_VOL_STATE_FAILED
7791                             ? "failed" :
7792                             state == MPI2_RAID_VOL_STATE_MISSING
7793                             ? "missing" :
7794                             "state unknown");
7795                         break;
7796                 }
7797                 case MPI2_EVENT_IR_VOLUME_RC_STATUS_FLAGS_CHANGED:
7798                 {
7799                         slots->m_raidconfig[config].m_raidvol[vol].
7800                             m_statusflags = state;
7801 
7802                         mptsas_log(mpt, CE_NOTE,
7803                             " Volume %d is now %s%s%s%s%s%s%s%s%s\n",
7804                             vol,
7805                             state & MPI2_RAIDVOL0_STATUS_FLAG_ENABLED
7806                             ? ", enabled" : ", disabled",
7807                             state & MPI2_RAIDVOL0_STATUS_FLAG_QUIESCED
7808                             ? ", quiesced" : "",
7809                             state & MPI2_RAIDVOL0_STATUS_FLAG_VOLUME_INACTIVE
7810                             ? ", inactive" : ", active",
7811                             state &
7812                             MPI2_RAIDVOL0_STATUS_FLAG_BAD_BLOCK_TABLE_FULL
7813                             ? ", bad block table is full" : "",
7814                             state &
7815                             MPI2_RAIDVOL0_STATUS_FLAG_RESYNC_IN_PROGRESS
7816                             ? ", resync in progress" : "",
7817                             state & MPI2_RAIDVOL0_STATUS_FLAG_BACKGROUND_INIT
7818                             ? ", background initialization in progress" : "",
7819                             state &
7820                             MPI2_RAIDVOL0_STATUS_FLAG_CAPACITY_EXPANSION
7821                             ? ", capacity expansion in progress" : "",
7822                             state &
7823                             MPI2_RAIDVOL0_STATUS_FLAG_CONSISTENCY_CHECK
7824                             ? ", consistency check in progress" : "",
7825                             state & MPI2_RAIDVOL0_STATUS_FLAG_DATA_SCRUB
7826                             ? ", data scrub in progress" : "");
7827                         break;
7828                 }
7829                 default:
7830                         break;
7831                 }
7832                 break;
7833         }
7834         case MPI2_EVENT_IR_PHYSICAL_DISK:
7835         {
7836                 Mpi2EventDataIrPhysicalDisk_t   *irPhysDisk;
7837                 uint16_t                        devhandle, enchandle, slot;
7838                 uint32_t                        status, state;
7839                 uint8_t                         physdisknum, reason;
7840 
7841                 irPhysDisk = (Mpi2EventDataIrPhysicalDisk_t *)
7842                     eventreply->EventData;
7843                 physdisknum = ddi_get8(mpt->m_acc_reply_frame_hdl,
7844                     &irPhysDisk->PhysDiskNum);
7845                 devhandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7846                     &irPhysDisk->PhysDiskDevHandle);
7847                 enchandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7848                     &irPhysDisk->EnclosureHandle);
7849                 slot = ddi_get16(mpt->m_acc_reply_frame_hdl,
7850                     &irPhysDisk->Slot);
7851                 state = ddi_get32(mpt->m_acc_reply_frame_hdl,
7852                     &irPhysDisk->NewValue);
7853                 reason = ddi_get8(mpt->m_acc_reply_frame_hdl,
7854                     &irPhysDisk->ReasonCode);
7855 
7856                 NDBG20(("EVENT_IR_PHYSICAL_DISK event is received"));
7857 
7858                 switch (reason) {
7859                 case MPI2_EVENT_IR_PHYSDISK_RC_SETTINGS_CHANGED:
7860                         mptsas_log(mpt, CE_NOTE,
7861                             " PhysDiskNum %d with DevHandle 0x%x in slot %d "
7862                             "for enclosure with handle 0x%x is now in hot "
7863                             "spare pool %d",
7864                             physdisknum, devhandle, slot, enchandle,
7865                             (state >> 16) & 0xff);
7866                         break;
7867 
7868                 case MPI2_EVENT_IR_PHYSDISK_RC_STATUS_FLAGS_CHANGED:
7869                         status = state;
7870                         mptsas_log(mpt, CE_NOTE,
7871                             " PhysDiskNum %d with DevHandle 0x%x in slot %d "
7872                             "for enclosure with handle 0x%x is now "
7873                             "%s%s%s%s%s\n", physdisknum, devhandle, slot,
7874                             enchandle,
7875                             status & MPI2_PHYSDISK0_STATUS_FLAG_INACTIVE_VOLUME
7876                             ? ", inactive" : ", active",
7877                             status & MPI2_PHYSDISK0_STATUS_FLAG_OUT_OF_SYNC
7878                             ? ", out of sync" : "",
7879                             status & MPI2_PHYSDISK0_STATUS_FLAG_QUIESCED
7880                             ? ", quiesced" : "",
7881                             status &
7882                             MPI2_PHYSDISK0_STATUS_FLAG_WRITE_CACHE_ENABLED
7883                             ? ", write cache enabled" : "",
7884                             status & MPI2_PHYSDISK0_STATUS_FLAG_OCE_TARGET
7885                             ? ", capacity expansion target" : "");
7886                         break;
7887 
7888                 case MPI2_EVENT_IR_PHYSDISK_RC_STATE_CHANGED:
7889                         mptsas_log(mpt, CE_NOTE,
7890                             " PhysDiskNum %d with DevHandle 0x%x in slot %d "
7891                             "for enclosure with handle 0x%x is now %s\n",
7892                             physdisknum, devhandle, slot, enchandle,
7893                             state == MPI2_RAID_PD_STATE_OPTIMAL
7894                             ? "optimal" :
7895                             state == MPI2_RAID_PD_STATE_REBUILDING
7896                             ? "rebuilding" :
7897                             state == MPI2_RAID_PD_STATE_DEGRADED
7898                             ? "degraded" :
7899                             state == MPI2_RAID_PD_STATE_HOT_SPARE
7900                             ? "a hot spare" :
7901                             state == MPI2_RAID_PD_STATE_ONLINE
7902                             ? "online" :
7903                             state == MPI2_RAID_PD_STATE_OFFLINE
7904                             ? "offline" :
7905                             state == MPI2_RAID_PD_STATE_NOT_COMPATIBLE
7906                             ? "not compatible" :
7907                             state == MPI2_RAID_PD_STATE_NOT_CONFIGURED
7908                             ? "not configured" :
7909                             "state unknown");
7910                         break;
7911                 }
7912                 break;
7913         }
7914         default:
7915                 NDBG20(("mptsas%d: unknown event %x received",
7916                     mpt->m_instance, event));
7917                 break;
7918         }
7919 
7920         /*
7921          * Return the reply frame to the free queue.
7922          */
7923         ddi_put32(mpt->m_acc_free_queue_hdl,
7924             &((uint32_t *)(void *)mpt->m_free_queue)[mpt->m_free_index], rfm);
7925         (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
7926             DDI_DMA_SYNC_FORDEV);
7927         if (++mpt->m_free_index == mpt->m_free_queue_depth) {
7928                 mpt->m_free_index = 0;
7929         }
7930         ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex,
7931             mpt->m_free_index);
7932         mutex_exit(&mpt->m_mutex);
7933 }
7934 
7935 /*
7936  * invoked from timeout() to restart qfull cmds with throttle == 0
7937  */
7938 static void
7939 mptsas_restart_cmd(void *arg)
7940 {
7941         mptsas_t        *mpt = arg;
7942         mptsas_target_t *ptgt = NULL;
7943 
7944         mutex_enter(&mpt->m_mutex);
7945 
7946         mpt->m_restart_cmd_timeid = 0;
7947 
7948         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
7949             MPTSAS_HASH_FIRST);
7950         while (ptgt != NULL) {
7951                 mutex_enter(&ptgt->m_tgt_intr_mutex);
7952                 if (ptgt->m_reset_delay == 0) {
7953                         if (ptgt->m_t_throttle == QFULL_THROTTLE) {
7954                                 mptsas_set_throttle(mpt, ptgt,
7955                                     MAX_THROTTLE);
7956                         }
7957                 }
7958                 mutex_exit(&ptgt->m_tgt_intr_mutex);
7959 
7960                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
7961                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
7962         }
7963         mptsas_restart_hba(mpt);
7964         mutex_exit(&mpt->m_mutex);
7965 }
7966 
7967 /*
7968  * mptsas_remove_cmd0 is similar to mptsas_remove_cmd except that it is called
7969  * where m_intr_mutex has already been held.
7970  */
7971 void
7972 mptsas_remove_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
7973 {
7974         ASSERT(mutex_owned(&mpt->m_mutex));
7975 
7976         /*
7977          * With new fine-grained lock mechanism, the outstanding cmd is only
7978          * linked to m_active before the dma is triggerred(MPTSAS_START_CMD)
7979          * to send it. that is, mptsas_save_cmd() doesn't link the outstanding
7980          * cmd now. So when mptsas_remove_cmd is called, a mptsas_save_cmd must
7981          * have been called, but the cmd may have not been linked.
7982          * For mptsas_remove_cmd0, the cmd must have been linked.
7983          * In order to keep the same semantic, we link the cmd to the
7984          * outstanding cmd list.
7985          */
7986         mpt->m_active->m_slot[cmd->cmd_slot] = cmd;
7987 
7988         mutex_enter(&mpt->m_intr_mutex);
7989         mptsas_remove_cmd0(mpt, cmd);
7990         mutex_exit(&mpt->m_intr_mutex);
7991 }
7992 
7993 static inline void
7994 mptsas_remove_cmd0(mptsas_t *mpt, mptsas_cmd_t *cmd)
7995 {
7996         int             slot;
7997         mptsas_slots_t  *slots = mpt->m_active;
7998         int             t;
7999         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
8000         mptsas_slot_free_e_t    *pe;
8001 
8002         ASSERT(cmd != NULL);
8003         ASSERT(cmd->cmd_queued == FALSE);
8004 
8005         /*
8006          * Task Management cmds are removed in their own routines.  Also,
8007          * we don't want to modify timeout based on TM cmds.
8008          */
8009         if (cmd->cmd_flags & CFLAG_TM_CMD) {
8010                 return;
8011         }
8012 
8013         t = Tgt(cmd);
8014         slot = cmd->cmd_slot;
8015         pe = mpt->m_slot_free_ae + slot - 1;
8016         ASSERT(cmd == slots->m_slot[slot]);
8017         ASSERT((slot > 0) && slot < (mpt->m_max_requests - 1));
8018 
8019         /*
8020          * remove the cmd.
8021          */
8022         mutex_enter(&mpt->m_slot_freeq_pairp[pe->cpuid].
8023             m_slot_releq.s.m_fq_mutex);
8024         NDBG31(("mptsas_remove_cmd0: removing cmd=0x%p", (void *)cmd));
8025         slots->m_slot[slot] = NULL;
8026         ASSERT(pe->slot == slot);
8027         list_insert_tail(&mpt->m_slot_freeq_pairp[pe->cpuid].
8028             m_slot_releq.s.m_fq_list, pe);
8029         mpt->m_slot_freeq_pairp[pe->cpuid].m_slot_releq.s.m_fq_n++;
8030         ASSERT(mpt->m_slot_freeq_pairp[pe->cpuid].
8031             m_slot_releq.s.m_fq_n <= mpt->m_max_requests - 2);
8032         mutex_exit(&mpt->m_slot_freeq_pairp[pe->cpuid].
8033             m_slot_releq.s.m_fq_mutex);
8034 
8035         /*
8036          * only decrement per target ncmds if command
8037          * has a target associated with it.
8038          */
8039         if ((cmd->cmd_flags & CFLAG_CMDIOC) == 0) {
8040                 mutex_enter(&ptgt->m_tgt_intr_mutex);
8041                 ptgt->m_t_ncmds--;
8042                 /*
8043                  * reset throttle if we just ran an untagged command
8044                  * to a tagged target
8045                  */
8046                 if ((ptgt->m_t_ncmds == 0) &&
8047                     ((cmd->cmd_pkt_flags & FLAG_TAGMASK) == 0)) {
8048                         mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
8049                 }
8050                 mutex_exit(&ptgt->m_tgt_intr_mutex);
8051         }
8052 
8053         /*
8054          * This is all we need to do for ioc commands.
8055          * The ioc cmds would never be handled in fastpath in ISR, so we make
8056          * sure the mptsas_return_to_pool() would always be called with
8057          * m_mutex protected.
8058          */
8059         if (cmd->cmd_flags & CFLAG_CMDIOC) {
8060                 ASSERT(mutex_owned(&mpt->m_mutex));
8061                 mptsas_return_to_pool(mpt, cmd);
8062                 return;
8063         }
8064 
8065         /*
8066          * Figure out what to set tag Q timeout for...
8067          *
8068          * Optimize: If we have duplicate's of same timeout
8069          * we're using, then we'll use it again until we run
8070          * out of duplicates.  This should be the normal case
8071          * for block and raw I/O.
8072          * If no duplicates, we have to scan through tag que and
8073          * find the longest timeout value and use it.  This is
8074          * going to take a while...
8075          * Add 1 to m_n_slots to account for TM request.
8076          */
8077         mutex_enter(&ptgt->m_tgt_intr_mutex);
8078         if (cmd->cmd_pkt->pkt_time == ptgt->m_timebase) {
8079                 if (--(ptgt->m_dups) == 0) {
8080                         if (ptgt->m_t_ncmds) {
8081                                 mptsas_cmd_t *ssp;
8082                                 uint_t n = 0;
8083                                 ushort_t nslots = (slots->m_n_slots + 1);
8084                                 ushort_t i;
8085                                 /*
8086                                  * This crude check assumes we don't do
8087                                  * this too often which seems reasonable
8088                                  * for block and raw I/O.
8089                                  */
8090                                 for (i = 0; i < nslots; i++) {
8091                                         ssp = slots->m_slot[i];
8092                                         if (ssp && (Tgt(ssp) == t) &&
8093                                             (ssp->cmd_pkt->pkt_time > n)) {
8094                                                 n = ssp->cmd_pkt->pkt_time;
8095                                                 ptgt->m_dups = 1;
8096                                         } else if (ssp && (Tgt(ssp) == t) &&
8097                                             (ssp->cmd_pkt->pkt_time == n)) {
8098                                                 ptgt->m_dups++;
8099                                         }
8100                                 }
8101                                 ptgt->m_timebase = n;
8102                         } else {
8103                                 ptgt->m_dups = 0;
8104                                 ptgt->m_timebase = 0;
8105                         }
8106                 }
8107         }
8108         ptgt->m_timeout = ptgt->m_timebase;
8109 
8110         ASSERT(cmd != slots->m_slot[cmd->cmd_slot]);
8111         mutex_exit(&ptgt->m_tgt_intr_mutex);
8112 }
8113 
8114 /*
8115  * start a fresh request from the top of the device queue.
8116  */
8117 static void
8118 mptsas_restart_hba(mptsas_t *mpt)
8119 {
8120         mptsas_cmd_t    *cmd, *next_cmd;
8121         mptsas_target_t *ptgt = NULL;
8122 
8123         NDBG1(("mptsas_restart_hba: mpt=0x%p", (void *)mpt));
8124 
8125         ASSERT(mutex_owned(&mpt->m_mutex));
8126 
8127         /*
8128          * If there is a reset delay, don't start any cmds.  Otherwise, start
8129          * as many cmds as possible.
8130          * Since SMID 0 is reserved and the TM slot is reserved, the actual max
8131          * commands is m_max_requests - 2.
8132          */
8133         cmd = mpt->m_waitq;
8134 
8135         while (cmd != NULL) {
8136                 next_cmd = cmd->cmd_linkp;
8137                 if (cmd->cmd_flags & CFLAG_PASSTHRU) {
8138                         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
8139                                 /*
8140                                  * passthru command get slot need
8141                                  * set CFLAG_PREPARED.
8142                                  */
8143                                 cmd->cmd_flags |= CFLAG_PREPARED;
8144                                 mptsas_waitq_delete(mpt, cmd);
8145                                 mptsas_start_passthru(mpt, cmd);
8146                         }
8147                         cmd = next_cmd;
8148                         continue;
8149                 }
8150                 if (cmd->cmd_flags & CFLAG_CONFIG) {
8151                         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
8152                                 /*
8153                                  * Send the config page request and delete it
8154                                  * from the waitq.
8155                                  */
8156                                 cmd->cmd_flags |= CFLAG_PREPARED;
8157                                 mptsas_waitq_delete(mpt, cmd);
8158                                 mptsas_start_config_page_access(mpt, cmd);
8159                         }
8160                         cmd = next_cmd;
8161                         continue;
8162                 }
8163                 if (cmd->cmd_flags & CFLAG_FW_DIAG) {
8164                         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
8165                                 /*
8166                                  * Send the FW Diag request and delete if from
8167                                  * the waitq.
8168                                  */
8169                                 cmd->cmd_flags |= CFLAG_PREPARED;
8170                                 mptsas_waitq_delete(mpt, cmd);
8171                                 mptsas_start_diag(mpt, cmd);
8172                         }
8173                         cmd = next_cmd;
8174                         continue;
8175                 }
8176 
8177                 ptgt = cmd->cmd_tgt_addr;
8178                 if (ptgt) {
8179                         mutex_enter(&mpt->m_intr_mutex);
8180                         mutex_enter(&ptgt->m_tgt_intr_mutex);
8181                         if ((ptgt->m_t_throttle == DRAIN_THROTTLE) &&
8182                             (ptgt->m_t_ncmds == 0)) {
8183                                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
8184                         }
8185                         if ((ptgt->m_reset_delay == 0) &&
8186                             (ptgt->m_t_ncmds < ptgt->m_t_throttle)) {
8187                                 mutex_exit(&ptgt->m_tgt_intr_mutex);
8188                                 mutex_exit(&mpt->m_intr_mutex);
8189                                 if (mptsas_save_cmd(mpt, cmd) == TRUE) {
8190                                         mptsas_waitq_delete(mpt, cmd);
8191                                         (void) mptsas_start_cmd(mpt, cmd);
8192                                 }
8193                                 goto out;
8194                         }
8195                         mutex_exit(&ptgt->m_tgt_intr_mutex);
8196                         mutex_exit(&mpt->m_intr_mutex);
8197                 }
8198 out:
8199                 cmd = next_cmd;
8200         }
8201 }
8202 
8203 /*
8204  * mpt tag type lookup
8205  */
8206 static char mptsas_tag_lookup[] =
8207         {0, MSG_HEAD_QTAG, MSG_ORDERED_QTAG, 0, MSG_SIMPLE_QTAG};
8208 
8209 /*
8210  * mptsas_start_cmd0 is similar to mptsas_start_cmd, except that, it is called
8211  * without ANY mutex protected, while, mptsas_start_cmd is called with m_mutex
8212  * protected.
8213  *
8214  * the relevant field in ptgt should be protected by m_tgt_intr_mutex in both
8215  * functions.
8216  *
8217  * before the cmds are linked on the slot for monitor as outstanding cmds, they
8218  * are accessed as slab objects, so slab framework ensures the exclusive access,
8219  * and no other mutex is requireed. Linking for monitor and the trigger of dma
8220  * must be done exclusively.
8221  */
8222 static int
8223 mptsas_start_cmd0(mptsas_t *mpt, mptsas_cmd_t *cmd)
8224 {
8225         struct scsi_pkt         *pkt = CMD2PKT(cmd);
8226         uint32_t                control = 0;
8227         int                     n;
8228         caddr_t                 mem;
8229         pMpi2SCSIIORequest_t    io_request;
8230         ddi_dma_handle_t        dma_hdl = mpt->m_dma_req_frame_hdl;
8231         ddi_acc_handle_t        acc_hdl = mpt->m_acc_req_frame_hdl;
8232         mptsas_target_t         *ptgt = cmd->cmd_tgt_addr;
8233         uint16_t                SMID, io_flags = 0;
8234         uint32_t                request_desc_low, request_desc_high;
8235 
8236         NDBG1(("mptsas_start_cmd0: cmd=0x%p", (void *)cmd));
8237 
8238         /*
8239          * Set SMID and increment index.  Rollover to 1 instead of 0 if index
8240          * is at the max.  0 is an invalid SMID, so we call the first index 1.
8241          */
8242         SMID = cmd->cmd_slot;
8243 
8244         /*
8245          * It is possible for back to back device reset to
8246          * happen before the reset delay has expired.  That's
8247          * ok, just let the device reset go out on the bus.
8248          */
8249         if ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0) {
8250                 ASSERT(ptgt->m_reset_delay == 0);
8251         }
8252 
8253         /*
8254          * if a non-tagged cmd is submitted to an active tagged target
8255          * then drain before submitting this cmd; SCSI-2 allows RQSENSE
8256          * to be untagged
8257          */
8258         mutex_enter(&ptgt->m_tgt_intr_mutex);
8259         if (((cmd->cmd_pkt_flags & FLAG_TAGMASK) == 0) &&
8260             (ptgt->m_t_ncmds > 1) &&
8261             ((cmd->cmd_flags & CFLAG_TM_CMD) == 0) &&
8262             (*(cmd->cmd_pkt->pkt_cdbp) != SCMD_REQUEST_SENSE)) {
8263                 if ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0) {
8264                         NDBG23(("target=%d, untagged cmd, start draining\n",
8265                             ptgt->m_devhdl));
8266 
8267                         if (ptgt->m_reset_delay == 0) {
8268                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
8269                         }
8270                         mutex_exit(&ptgt->m_tgt_intr_mutex);
8271 
8272                         mutex_enter(&mpt->m_mutex);
8273                         mptsas_remove_cmd(mpt, cmd);
8274                         cmd->cmd_pkt_flags |= FLAG_HEAD;
8275                         mptsas_waitq_add(mpt, cmd);
8276                         mutex_exit(&mpt->m_mutex);
8277                         return (DDI_FAILURE);
8278                 }
8279                 mutex_exit(&ptgt->m_tgt_intr_mutex);
8280                 return (DDI_FAILURE);
8281         }
8282         mutex_exit(&ptgt->m_tgt_intr_mutex);
8283 
8284         /*
8285          * Set correct tag bits.
8286          */
8287         if (cmd->cmd_pkt_flags & FLAG_TAGMASK) {
8288                 switch (mptsas_tag_lookup[((cmd->cmd_pkt_flags &
8289                     FLAG_TAGMASK) >> 12)]) {
8290                 case MSG_SIMPLE_QTAG:
8291                         control |= MPI2_SCSIIO_CONTROL_SIMPLEQ;
8292                         break;
8293                 case MSG_HEAD_QTAG:
8294                         control |= MPI2_SCSIIO_CONTROL_HEADOFQ;
8295                         break;
8296                 case MSG_ORDERED_QTAG:
8297                         control |= MPI2_SCSIIO_CONTROL_ORDEREDQ;
8298                         break;
8299                 default:
8300                         mptsas_log(mpt, CE_WARN, "mpt: Invalid tag type\n");
8301                         break;
8302                 }
8303         } else {
8304                 if (*(cmd->cmd_pkt->pkt_cdbp) != SCMD_REQUEST_SENSE) {
8305                                 ptgt->m_t_throttle = 1;
8306                 }
8307                 control |= MPI2_SCSIIO_CONTROL_SIMPLEQ;
8308         }
8309 
8310         if (cmd->cmd_pkt_flags & FLAG_TLR) {
8311                 control |= MPI2_SCSIIO_CONTROL_TLR_ON;
8312         }
8313 
8314         mem = mpt->m_req_frame + (mpt->m_req_frame_size * SMID);
8315         io_request = (pMpi2SCSIIORequest_t)mem;
8316 
8317         bzero(io_request, sizeof (Mpi2SCSIIORequest_t));
8318         ddi_put8(acc_hdl, &io_request->SGLOffset0, offsetof
8319             (MPI2_SCSI_IO_REQUEST, SGL) / 4);
8320         mptsas_init_std_hdr(acc_hdl, io_request, ptgt->m_devhdl, Lun(cmd), 0,
8321             MPI2_FUNCTION_SCSI_IO_REQUEST);
8322 
8323         (void) ddi_rep_put8(acc_hdl, (uint8_t *)pkt->pkt_cdbp,
8324             io_request->CDB.CDB32, cmd->cmd_cdblen, DDI_DEV_AUTOINCR);
8325 
8326         io_flags = cmd->cmd_cdblen;
8327         ddi_put16(acc_hdl, &io_request->IoFlags, io_flags);
8328         /*
8329          * setup the Scatter/Gather DMA list for this request
8330          */
8331         if (cmd->cmd_cookiec > 0) {
8332                 mptsas_sge_setup(mpt, cmd, &control, io_request, acc_hdl);
8333         } else {
8334                 ddi_put32(acc_hdl, &io_request->SGL.MpiSimple.FlagsLength,
8335                     ((uint32_t)MPI2_SGE_FLAGS_LAST_ELEMENT |
8336                     MPI2_SGE_FLAGS_END_OF_BUFFER |
8337                     MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
8338                     MPI2_SGE_FLAGS_END_OF_LIST) << MPI2_SGE_FLAGS_SHIFT);
8339         }
8340 
8341         /*
8342          * save ARQ information
8343          */
8344         ddi_put8(acc_hdl, &io_request->SenseBufferLength, cmd->cmd_rqslen);
8345         if ((cmd->cmd_flags & (CFLAG_SCBEXTERN | CFLAG_EXTARQBUFVALID)) ==
8346             (CFLAG_SCBEXTERN | CFLAG_EXTARQBUFVALID)) {
8347                 ddi_put32(acc_hdl, &io_request->SenseBufferLowAddress,
8348                     cmd->cmd_ext_arqcookie.dmac_address);
8349         } else {
8350                 ddi_put32(acc_hdl, &io_request->SenseBufferLowAddress,
8351                     cmd->cmd_arqcookie.dmac_address);
8352         }
8353 
8354         ddi_put32(acc_hdl, &io_request->Control, control);
8355 
8356         NDBG31(("starting message=0x%p, with cmd=0x%p",
8357             (void *)(uintptr_t)mpt->m_req_frame_dma_addr, (void *)cmd));
8358 
8359         (void) ddi_dma_sync(dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);
8360 
8361         /*
8362          * Build request descriptor and write it to the request desc post reg.
8363          */
8364         request_desc_low = (SMID << 16) + MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
8365         request_desc_high = ptgt->m_devhdl << 16;
8366 
8367         mutex_enter(&mpt->m_mutex);
8368         mpt->m_active->m_slot[cmd->cmd_slot] = cmd;
8369         MPTSAS_START_CMD(mpt, request_desc_low, request_desc_high);
8370         mutex_exit(&mpt->m_mutex);
8371 
8372         /*
8373          * Start timeout.
8374          */
8375         mutex_enter(&ptgt->m_tgt_intr_mutex);
8376 #ifdef MPTSAS_TEST
8377         /*
8378          * Temporarily set timebase = 0;  needed for
8379          * timeout torture test.
8380          */
8381         if (mptsas_test_timeouts) {
8382                 ptgt->m_timebase = 0;
8383         }
8384 #endif
8385         n = pkt->pkt_time - ptgt->m_timebase;
8386 
8387         if (n == 0) {
8388                 (ptgt->m_dups)++;
8389                 ptgt->m_timeout = ptgt->m_timebase;
8390         } else if (n > 0) {
8391                 ptgt->m_timeout =
8392                     ptgt->m_timebase = pkt->pkt_time;
8393                 ptgt->m_dups = 1;
8394         } else if (n < 0) {
8395                 ptgt->m_timeout = ptgt->m_timebase;
8396         }
8397 #ifdef MPTSAS_TEST
8398         /*
8399          * Set back to a number higher than
8400          * mptsas_scsi_watchdog_tick
8401          * so timeouts will happen in mptsas_watchsubr
8402          */
8403         if (mptsas_test_timeouts) {
8404                 ptgt->m_timebase = 60;
8405         }
8406 #endif
8407         mutex_exit(&ptgt->m_tgt_intr_mutex);
8408 
8409         if ((mptsas_check_dma_handle(dma_hdl) != DDI_SUCCESS) ||
8410             (mptsas_check_acc_handle(acc_hdl) != DDI_SUCCESS)) {
8411                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8412                 return (DDI_FAILURE);
8413         }
8414         return (DDI_SUCCESS);
8415 }
8416 
8417 static int
8418 mptsas_start_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
8419 {
8420         struct scsi_pkt         *pkt = CMD2PKT(cmd);
8421         uint32_t                control = 0;
8422         int                     n;
8423         caddr_t                 mem;
8424         pMpi2SCSIIORequest_t    io_request;
8425         ddi_dma_handle_t        dma_hdl = mpt->m_dma_req_frame_hdl;
8426         ddi_acc_handle_t        acc_hdl = mpt->m_acc_req_frame_hdl;
8427         mptsas_target_t         *ptgt = cmd->cmd_tgt_addr;
8428         uint16_t                SMID, io_flags = 0;
8429         uint32_t                request_desc_low, request_desc_high;
8430 
8431         NDBG1(("mptsas_start_cmd: cmd=0x%p", (void *)cmd));
8432 
8433         /*
8434          * Set SMID and increment index.  Rollover to 1 instead of 0 if index
8435          * is at the max.  0 is an invalid SMID, so we call the first index 1.
8436          */
8437         SMID = cmd->cmd_slot;
8438 
8439         /*
8440          * It is possible for back to back device reset to
8441          * happen before the reset delay has expired.  That's
8442          * ok, just let the device reset go out on the bus.
8443          */
8444         if ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0) {
8445                 ASSERT(ptgt->m_reset_delay == 0);
8446         }
8447 
8448         /*
8449          * if a non-tagged cmd is submitted to an active tagged target
8450          * then drain before submitting this cmd; SCSI-2 allows RQSENSE
8451          * to be untagged
8452          */
8453         mutex_enter(&ptgt->m_tgt_intr_mutex);
8454         if (((cmd->cmd_pkt_flags & FLAG_TAGMASK) == 0) &&
8455             (ptgt->m_t_ncmds > 1) &&
8456             ((cmd->cmd_flags & CFLAG_TM_CMD) == 0) &&
8457             (*(cmd->cmd_pkt->pkt_cdbp) != SCMD_REQUEST_SENSE)) {
8458                 if ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0) {
8459                         NDBG23(("target=%d, untagged cmd, start draining\n",
8460                             ptgt->m_devhdl));
8461 
8462                         if (ptgt->m_reset_delay == 0) {
8463                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
8464                         }
8465                         mutex_exit(&ptgt->m_tgt_intr_mutex);
8466 
8467                         mptsas_remove_cmd(mpt, cmd);
8468                         cmd->cmd_pkt_flags |= FLAG_HEAD;
8469                         mptsas_waitq_add(mpt, cmd);
8470                         return (DDI_FAILURE);
8471                 }
8472                 mutex_exit(&ptgt->m_tgt_intr_mutex);
8473                 return (DDI_FAILURE);
8474         }
8475         mutex_exit(&ptgt->m_tgt_intr_mutex);
8476 
8477         /*
8478          * Set correct tag bits.
8479          */
8480         if (cmd->cmd_pkt_flags & FLAG_TAGMASK) {
8481                 switch (mptsas_tag_lookup[((cmd->cmd_pkt_flags &
8482                     FLAG_TAGMASK) >> 12)]) {
8483                 case MSG_SIMPLE_QTAG:
8484                         control |= MPI2_SCSIIO_CONTROL_SIMPLEQ;
8485                         break;
8486                 case MSG_HEAD_QTAG:
8487                         control |= MPI2_SCSIIO_CONTROL_HEADOFQ;
8488                         break;
8489                 case MSG_ORDERED_QTAG:
8490                         control |= MPI2_SCSIIO_CONTROL_ORDEREDQ;
8491                         break;
8492                 default:
8493                         mptsas_log(mpt, CE_WARN, "mpt: Invalid tag type\n");
8494                         break;
8495                 }
8496         } else {
8497                 if (*(cmd->cmd_pkt->pkt_cdbp) != SCMD_REQUEST_SENSE) {
8498                                 ptgt->m_t_throttle = 1;
8499                 }
8500                 control |= MPI2_SCSIIO_CONTROL_SIMPLEQ;
8501         }
8502 
8503         if (cmd->cmd_pkt_flags & FLAG_TLR) {
8504                 control |= MPI2_SCSIIO_CONTROL_TLR_ON;
8505         }
8506 
8507         mem = mpt->m_req_frame + (mpt->m_req_frame_size * SMID);
8508         io_request = (pMpi2SCSIIORequest_t)mem;
8509 
8510         bzero(io_request, sizeof (Mpi2SCSIIORequest_t));
8511         ddi_put8(acc_hdl, &io_request->SGLOffset0, offsetof
8512             (MPI2_SCSI_IO_REQUEST, SGL) / 4);
8513         mptsas_init_std_hdr(acc_hdl, io_request, ptgt->m_devhdl, Lun(cmd), 0,
8514             MPI2_FUNCTION_SCSI_IO_REQUEST);
8515 
8516         (void) ddi_rep_put8(acc_hdl, (uint8_t *)pkt->pkt_cdbp,
8517             io_request->CDB.CDB32, cmd->cmd_cdblen, DDI_DEV_AUTOINCR);
8518 
8519         io_flags = cmd->cmd_cdblen;
8520         ddi_put16(acc_hdl, &io_request->IoFlags, io_flags);
8521         /*
8522          * setup the Scatter/Gather DMA list for this request
8523          */
8524         if (cmd->cmd_cookiec > 0) {
8525                 mptsas_sge_setup(mpt, cmd, &control, io_request, acc_hdl);
8526         } else {
8527                 ddi_put32(acc_hdl, &io_request->SGL.MpiSimple.FlagsLength,
8528                     ((uint32_t)MPI2_SGE_FLAGS_LAST_ELEMENT |
8529                     MPI2_SGE_FLAGS_END_OF_BUFFER |
8530                     MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
8531                     MPI2_SGE_FLAGS_END_OF_LIST) << MPI2_SGE_FLAGS_SHIFT);
8532         }
8533 
8534         /*
8535          * save ARQ information
8536          */
8537         ddi_put8(acc_hdl, &io_request->SenseBufferLength, cmd->cmd_rqslen);
8538         if ((cmd->cmd_flags & (CFLAG_SCBEXTERN | CFLAG_EXTARQBUFVALID)) ==
8539             (CFLAG_SCBEXTERN | CFLAG_EXTARQBUFVALID)) {
8540                 ddi_put32(acc_hdl, &io_request->SenseBufferLowAddress,
8541                     cmd->cmd_ext_arqcookie.dmac_address);
8542         } else {
8543                 ddi_put32(acc_hdl, &io_request->SenseBufferLowAddress,
8544                     cmd->cmd_arqcookie.dmac_address);
8545         }
8546 
8547         ddi_put32(acc_hdl, &io_request->Control, control);
8548 
8549         NDBG31(("starting message=0x%p, with cmd=0x%p",
8550             (void *)(uintptr_t)mpt->m_req_frame_dma_addr, (void *)cmd));
8551 
8552         (void) ddi_dma_sync(dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);
8553 
8554         /*
8555          * Build request descriptor and write it to the request desc post reg.
8556          */
8557         request_desc_low = (SMID << 16) + MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
8558         request_desc_high = ptgt->m_devhdl << 16;
8559 
8560         mpt->m_active->m_slot[cmd->cmd_slot] = cmd;
8561         MPTSAS_START_CMD(mpt, request_desc_low, request_desc_high);
8562 
8563         /*
8564          * Start timeout.
8565          */
8566         mutex_enter(&ptgt->m_tgt_intr_mutex);
8567 #ifdef MPTSAS_TEST
8568         /*
8569          * Temporarily set timebase = 0;  needed for
8570          * timeout torture test.
8571          */
8572         if (mptsas_test_timeouts) {
8573                 ptgt->m_timebase = 0;
8574         }
8575 #endif
8576         n = pkt->pkt_time - ptgt->m_timebase;
8577 
8578         if (n == 0) {
8579                 (ptgt->m_dups)++;
8580                 ptgt->m_timeout = ptgt->m_timebase;
8581         } else if (n > 0) {
8582                 ptgt->m_timeout =
8583                     ptgt->m_timebase = pkt->pkt_time;
8584                 ptgt->m_dups = 1;
8585         } else if (n < 0) {
8586                 ptgt->m_timeout = ptgt->m_timebase;
8587         }
8588 #ifdef MPTSAS_TEST
8589         /*
8590          * Set back to a number higher than
8591          * mptsas_scsi_watchdog_tick
8592          * so timeouts will happen in mptsas_watchsubr
8593          */
8594         if (mptsas_test_timeouts) {
8595                 ptgt->m_timebase = 60;
8596         }
8597 #endif
8598         mutex_exit(&ptgt->m_tgt_intr_mutex);
8599 
8600         if ((mptsas_check_dma_handle(dma_hdl) != DDI_SUCCESS) ||
8601             (mptsas_check_acc_handle(acc_hdl) != DDI_SUCCESS)) {
8602                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8603                 return (DDI_FAILURE);
8604         }
8605         return (DDI_SUCCESS);
8606 }
8607 
8608 /*
8609  * Select a helper thread to handle current doneq
8610  */
8611 static void
8612 mptsas_deliver_doneq_thread(mptsas_t *mpt)
8613 {
8614         uint64_t                        t, i;
8615         uint32_t                        min = 0xffffffff;
8616         mptsas_doneq_thread_list_t      *item;
8617 
8618         for (i = 0; i < mpt->m_doneq_thread_n; i++) {
8619                 item = &mpt->m_doneq_thread_id[i];
8620                 /*
8621                  * If the completed command on help thread[i] less than
8622                  * doneq_thread_threshold, then pick the thread[i]. Otherwise
8623                  * pick a thread which has least completed command.
8624                  */
8625 
8626                 mutex_enter(&item->mutex);
8627                 if (item->len < mpt->m_doneq_thread_threshold) {
8628                         t = i;
8629                         mutex_exit(&item->mutex);
8630                         break;
8631                 }
8632                 if (item->len < min) {
8633                         min = item->len;
8634                         t = i;
8635                 }
8636                 mutex_exit(&item->mutex);
8637         }
8638         mutex_enter(&mpt->m_doneq_thread_id[t].mutex);
8639         mptsas_doneq_mv(mpt, t);
8640         cv_signal(&mpt->m_doneq_thread_id[t].cv);
8641         mutex_exit(&mpt->m_doneq_thread_id[t].mutex);
8642 }
8643 
8644 /*
8645  * move the current global doneq to the doneq of thread[t]
8646  */
8647 static void
8648 mptsas_doneq_mv(mptsas_t *mpt, uint64_t t)
8649 {
8650         mptsas_cmd_t                    *cmd;
8651         mptsas_doneq_thread_list_t      *item = &mpt->m_doneq_thread_id[t];
8652 
8653         ASSERT(mutex_owned(&item->mutex));
8654         mutex_enter(&mpt->m_intr_mutex);
8655         while ((cmd = mpt->m_doneq) != NULL) {
8656                 if ((mpt->m_doneq = cmd->cmd_linkp) == NULL) {
8657                         mpt->m_donetail = &mpt->m_doneq;
8658                 }
8659                 cmd->cmd_linkp = NULL;
8660                 *item->donetail = cmd;
8661                 item->donetail = &cmd->cmd_linkp;
8662                 mpt->m_doneq_len--;
8663                 item->len++;
8664         }
8665         mutex_exit(&mpt->m_intr_mutex);
8666 }
8667 
8668 void
8669 mptsas_fma_check(mptsas_t *mpt, mptsas_cmd_t *cmd)
8670 {
8671         struct scsi_pkt *pkt = CMD2PKT(cmd);
8672 
8673         /* Check all acc and dma handles */
8674         if ((mptsas_check_acc_handle(mpt->m_datap) !=
8675             DDI_SUCCESS) ||
8676             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl) !=
8677             DDI_SUCCESS) ||
8678             (mptsas_check_acc_handle(mpt->m_acc_reply_frame_hdl) !=
8679             DDI_SUCCESS) ||
8680             (mptsas_check_acc_handle(mpt->m_acc_free_queue_hdl) !=
8681             DDI_SUCCESS) ||
8682             (mptsas_check_acc_handle(mpt->m_acc_post_queue_hdl) !=
8683             DDI_SUCCESS) ||
8684             (mptsas_check_acc_handle(mpt->m_hshk_acc_hdl) !=
8685             DDI_SUCCESS) ||
8686             (mptsas_check_acc_handle(mpt->m_config_handle) !=
8687             DDI_SUCCESS)) {
8688                 ddi_fm_service_impact(mpt->m_dip,
8689                     DDI_SERVICE_UNAFFECTED);
8690                 ddi_fm_acc_err_clear(mpt->m_config_handle,
8691                     DDI_FME_VER0);
8692                 pkt->pkt_reason = CMD_TRAN_ERR;
8693                 pkt->pkt_statistics = 0;
8694         }
8695         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl) !=
8696             DDI_SUCCESS) ||
8697             (mptsas_check_dma_handle(mpt->m_dma_reply_frame_hdl) !=
8698             DDI_SUCCESS) ||
8699             (mptsas_check_dma_handle(mpt->m_dma_free_queue_hdl) !=
8700             DDI_SUCCESS) ||
8701             (mptsas_check_dma_handle(mpt->m_dma_post_queue_hdl) !=
8702             DDI_SUCCESS) ||
8703             (mptsas_check_dma_handle(mpt->m_hshk_dma_hdl) !=
8704             DDI_SUCCESS)) {
8705                 ddi_fm_service_impact(mpt->m_dip,
8706                     DDI_SERVICE_UNAFFECTED);
8707                 pkt->pkt_reason = CMD_TRAN_ERR;
8708                 pkt->pkt_statistics = 0;
8709         }
8710         if (cmd->cmd_dmahandle &&
8711             (mptsas_check_dma_handle(cmd->cmd_dmahandle) != DDI_SUCCESS)) {
8712                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8713                 pkt->pkt_reason = CMD_TRAN_ERR;
8714                 pkt->pkt_statistics = 0;
8715         }
8716         if ((cmd->cmd_extra_frames &&
8717             ((mptsas_check_dma_handle(cmd->cmd_extra_frames->m_dma_hdl) !=
8718             DDI_SUCCESS) ||
8719             (mptsas_check_acc_handle(cmd->cmd_extra_frames->m_acc_hdl) !=
8720             DDI_SUCCESS)))) {
8721                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8722                 pkt->pkt_reason = CMD_TRAN_ERR;
8723                 pkt->pkt_statistics = 0;
8724         }
8725         if (cmd->cmd_arqhandle &&
8726             (mptsas_check_dma_handle(cmd->cmd_arqhandle) != DDI_SUCCESS)) {
8727                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8728                 pkt->pkt_reason = CMD_TRAN_ERR;
8729                 pkt->pkt_statistics = 0;
8730         }
8731         if (cmd->cmd_ext_arqhandle &&
8732             (mptsas_check_dma_handle(cmd->cmd_ext_arqhandle) != DDI_SUCCESS)) {
8733                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8734                 pkt->pkt_reason = CMD_TRAN_ERR;
8735                 pkt->pkt_statistics = 0;
8736         }
8737 }
8738 
8739 /*
8740  * mptsas_doneq_add0 is similar to mptsas_doneq_add except that it is called
8741  * where m_intr_mutex has already been held.
8742  */
8743 static inline void
8744 mptsas_doneq_add0(mptsas_t *mpt, mptsas_cmd_t *cmd)
8745 {
8746         struct scsi_pkt *pkt = CMD2PKT(cmd);
8747 
8748         NDBG31(("mptsas_doneq_add0: cmd=0x%p", (void *)cmd));
8749 
8750         ASSERT((cmd->cmd_flags & CFLAG_COMPLETED) == 0);
8751         cmd->cmd_linkp = NULL;
8752         cmd->cmd_flags |= CFLAG_FINISHED;
8753         cmd->cmd_flags &= ~CFLAG_IN_TRANSPORT;
8754 
8755         /*
8756          * only add scsi pkts that have completion routines to
8757          * the doneq.  no intr cmds do not have callbacks.
8758          */
8759         if (pkt && (pkt->pkt_comp)) {
8760                 *mpt->m_donetail = cmd;
8761                 mpt->m_donetail = &cmd->cmd_linkp;
8762                 mpt->m_doneq_len++;
8763         }
8764 }
8765 
8766 /*
8767  * These routines manipulate the queue of commands that
8768  * are waiting for their completion routines to be called.
8769  * The queue is usually in FIFO order but on an MP system
8770  * it's possible for the completion routines to get out
8771  * of order. If that's a problem you need to add a global
8772  * mutex around the code that calls the completion routine
8773  * in the interrupt handler.
8774  */
8775 static void
8776 mptsas_doneq_add(mptsas_t *mpt, mptsas_cmd_t *cmd)
8777 {
8778         ASSERT(mutex_owned(&mpt->m_mutex));
8779 
8780         mptsas_fma_check(mpt, cmd);
8781 
8782         mutex_enter(&mpt->m_intr_mutex);
8783         mptsas_doneq_add0(mpt, cmd);
8784         mutex_exit(&mpt->m_intr_mutex);
8785 }
8786 
8787 static mptsas_cmd_t *
8788 mptsas_doneq_thread_rm(mptsas_t *mpt, uint64_t t)
8789 {
8790         mptsas_cmd_t                    *cmd;
8791         mptsas_doneq_thread_list_t      *item = &mpt->m_doneq_thread_id[t];
8792 
8793         /* pop one off the done queue */
8794         if ((cmd = item->doneq) != NULL) {
8795                 /* if the queue is now empty fix the tail pointer */
8796                 NDBG31(("mptsas_doneq_thread_rm: cmd=0x%p", (void *)cmd));
8797                 if ((item->doneq = cmd->cmd_linkp) == NULL) {
8798                         item->donetail = &item->doneq;
8799                 }
8800                 cmd->cmd_linkp = NULL;
8801                 item->len--;
8802         }
8803         return (cmd);
8804 }
8805 
8806 static void
8807 mptsas_doneq_empty(mptsas_t *mpt)
8808 {
8809         mutex_enter(&mpt->m_intr_mutex);
8810         if (mpt->m_doneq && !mpt->m_in_callback) {
8811                 mptsas_cmd_t    *cmd, *next;
8812                 struct scsi_pkt *pkt;
8813 
8814                 mpt->m_in_callback = 1;
8815                 cmd = mpt->m_doneq;
8816                 mpt->m_doneq = NULL;
8817                 mpt->m_donetail = &mpt->m_doneq;
8818                 mpt->m_doneq_len = 0;
8819 
8820                 mutex_exit(&mpt->m_intr_mutex);
8821 
8822                 /*
8823                  * ONLY in ISR, is it called without m_mutex held, otherwise,
8824                  * it is always called with m_mutex held.
8825                  */
8826                 if ((curthread->t_flag & T_INTR_THREAD) == 0)
8827                         mutex_exit(&mpt->m_mutex);
8828                 /*
8829                  * run the completion routines of all the
8830                  * completed commands
8831                  */
8832                 while (cmd != NULL) {
8833                         next = cmd->cmd_linkp;
8834                         cmd->cmd_linkp = NULL;
8835                         /* run this command's completion routine */
8836                         cmd->cmd_flags |= CFLAG_COMPLETED;
8837                         pkt = CMD2PKT(cmd);
8838                         mptsas_pkt_comp(pkt, cmd);
8839                         cmd = next;
8840                 }
8841                 if ((curthread->t_flag & T_INTR_THREAD) == 0)
8842                         mutex_enter(&mpt->m_mutex);
8843                 mpt->m_in_callback = 0;
8844                 return;
8845         }
8846         mutex_exit(&mpt->m_intr_mutex);
8847 }
8848 
8849 /*
8850  * These routines manipulate the target's queue of pending requests
8851  */
8852 void
8853 mptsas_waitq_add(mptsas_t *mpt, mptsas_cmd_t *cmd)
8854 {
8855         NDBG7(("mptsas_waitq_add: cmd=0x%p", (void *)cmd));
8856         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
8857         cmd->cmd_queued = TRUE;
8858         if (ptgt)
8859                 ptgt->m_t_nwait++;
8860         if (cmd->cmd_pkt_flags & FLAG_HEAD) {
8861                 mutex_enter(&mpt->m_intr_mutex);
8862                 if ((cmd->cmd_linkp = mpt->m_waitq) == NULL) {
8863                         mpt->m_waitqtail = &cmd->cmd_linkp;
8864                 }
8865                 mpt->m_waitq = cmd;
8866                 mutex_exit(&mpt->m_intr_mutex);
8867         } else {
8868                 cmd->cmd_linkp = NULL;
8869                 *(mpt->m_waitqtail) = cmd;
8870                 mpt->m_waitqtail = &cmd->cmd_linkp;
8871         }
8872 }
8873 
8874 static mptsas_cmd_t *
8875 mptsas_waitq_rm(mptsas_t *mpt)
8876 {
8877         mptsas_cmd_t    *cmd;
8878         mptsas_target_t *ptgt;
8879         NDBG7(("mptsas_waitq_rm"));
8880 
8881         mutex_enter(&mpt->m_intr_mutex);
8882         MPTSAS_WAITQ_RM(mpt, cmd);
8883         mutex_exit(&mpt->m_intr_mutex);
8884 
8885         NDBG7(("mptsas_waitq_rm: cmd=0x%p", (void *)cmd));
8886         if (cmd) {
8887                 ptgt = cmd->cmd_tgt_addr;
8888                 if (ptgt) {
8889                         ptgt->m_t_nwait--;
8890                         ASSERT(ptgt->m_t_nwait >= 0);
8891                 }
8892         }
8893         return (cmd);
8894 }
8895 
8896 /*
8897  * remove specified cmd from the middle of the wait queue.
8898  */
8899 static void
8900 mptsas_waitq_delete(mptsas_t *mpt, mptsas_cmd_t *cmd)
8901 {
8902         mptsas_cmd_t    *prevp = mpt->m_waitq;
8903         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
8904 
8905         NDBG7(("mptsas_waitq_delete: mpt=0x%p cmd=0x%p",
8906             (void *)mpt, (void *)cmd));
8907         if (ptgt) {
8908                 ptgt->m_t_nwait--;
8909                 ASSERT(ptgt->m_t_nwait >= 0);
8910         }
8911 
8912         if (prevp == cmd) {
8913                 mutex_enter(&mpt->m_intr_mutex);
8914                 if ((mpt->m_waitq = cmd->cmd_linkp) == NULL)
8915                         mpt->m_waitqtail = &mpt->m_waitq;
8916                 mutex_exit(&mpt->m_intr_mutex);
8917 
8918                 cmd->cmd_linkp = NULL;
8919                 cmd->cmd_queued = FALSE;
8920                 NDBG7(("mptsas_waitq_delete: mpt=0x%p cmd=0x%p",
8921                     (void *)mpt, (void *)cmd));
8922                 return;
8923         }
8924 
8925         while (prevp != NULL) {
8926                 if (prevp->cmd_linkp == cmd) {
8927                         if ((prevp->cmd_linkp = cmd->cmd_linkp) == NULL)
8928                                 mpt->m_waitqtail = &prevp->cmd_linkp;
8929 
8930                         cmd->cmd_linkp = NULL;
8931                         cmd->cmd_queued = FALSE;
8932                         NDBG7(("mptsas_waitq_delete: mpt=0x%p cmd=0x%p",
8933                             (void *)mpt, (void *)cmd));
8934                         return;
8935                 }
8936                 prevp = prevp->cmd_linkp;
8937         }
8938         cmn_err(CE_PANIC, "mpt: mptsas_waitq_delete: queue botch");
8939 }
8940 
8941 /*
8942  * device and bus reset handling
8943  *
8944  * Notes:
8945  *      - RESET_ALL:    reset the controller
8946  *      - RESET_TARGET: reset the target specified in scsi_address
8947  */
8948 static int
8949 mptsas_scsi_reset(struct scsi_address *ap, int level)
8950 {
8951         mptsas_t                *mpt = ADDR2MPT(ap);
8952         int                     rval;
8953         mptsas_tgt_private_t    *tgt_private;
8954         mptsas_target_t         *ptgt = NULL;
8955 
8956         tgt_private = (mptsas_tgt_private_t *)ap->a_hba_tran->tran_tgt_private;
8957         ptgt = tgt_private->t_private;
8958         if (ptgt == NULL) {
8959                 return (FALSE);
8960         }
8961         NDBG22(("mptsas_scsi_reset: target=%d level=%d", ptgt->m_devhdl,
8962             level));
8963 
8964         mutex_enter(&mpt->m_mutex);
8965         /*
8966          * if we are not in panic set up a reset delay for this target
8967          */
8968         if (!ddi_in_panic()) {
8969                 mptsas_setup_bus_reset_delay(mpt);
8970         } else {
8971                 drv_usecwait(mpt->m_scsi_reset_delay * 1000);
8972         }
8973         rval = mptsas_do_scsi_reset(mpt, ptgt->m_devhdl);
8974         mutex_exit(&mpt->m_mutex);
8975 
8976         /*
8977          * The transport layer expect to only see TRUE and
8978          * FALSE. Therefore, we will adjust the return value
8979          * if mptsas_do_scsi_reset returns FAILED.
8980          */
8981         if (rval == FAILED)
8982                 rval = FALSE;
8983         return (rval);
8984 }
8985 
8986 static int
8987 mptsas_do_scsi_reset(mptsas_t *mpt, uint16_t devhdl)
8988 {
8989         int             rval = FALSE;
8990         uint8_t         config, disk;
8991         mptsas_slots_t  *slots = mpt->m_active;
8992 
8993         ASSERT(mutex_owned(&mpt->m_mutex));
8994 
8995         if (mptsas_debug_resets) {
8996                 mptsas_log(mpt, CE_WARN, "mptsas_do_scsi_reset: target=%d",
8997                     devhdl);
8998         }
8999 
9000         /*
9001          * Issue a Target Reset message to the target specified but not to a
9002          * disk making up a raid volume.  Just look through the RAID config
9003          * Phys Disk list of DevHandles.  If the target's DevHandle is in this
9004          * list, then don't reset this target.
9005          */
9006         for (config = 0; config < slots->m_num_raid_configs; config++) {
9007                 for (disk = 0; disk < MPTSAS_MAX_DISKS_IN_CONFIG; disk++) {
9008                         if (devhdl == slots->m_raidconfig[config].
9009                             m_physdisk_devhdl[disk]) {
9010                                 return (TRUE);
9011                         }
9012                 }
9013         }
9014 
9015         rval = mptsas_ioc_task_management(mpt,
9016             MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET, devhdl, 0, NULL, 0, 0);
9017 
9018         mptsas_doneq_empty(mpt);
9019         return (rval);
9020 }
9021 
9022 static int
9023 mptsas_scsi_reset_notify(struct scsi_address *ap, int flag,
9024         void (*callback)(caddr_t), caddr_t arg)
9025 {
9026         mptsas_t        *mpt = ADDR2MPT(ap);
9027 
9028         NDBG22(("mptsas_scsi_reset_notify: tgt=%d", ap->a_target));
9029 
9030         return (scsi_hba_reset_notify_setup(ap, flag, callback, arg,
9031             &mpt->m_mutex, &mpt->m_reset_notify_listf));
9032 }
9033 
9034 static int
9035 mptsas_get_name(struct scsi_device *sd, char *name, int len)
9036 {
9037         dev_info_t      *lun_dip = NULL;
9038 
9039         ASSERT(sd != NULL);
9040         ASSERT(name != NULL);
9041         lun_dip = sd->sd_dev;
9042         ASSERT(lun_dip != NULL);
9043 
9044         if (mptsas_name_child(lun_dip, name, len) == DDI_SUCCESS) {
9045                 return (1);
9046         } else {
9047                 return (0);
9048         }
9049 }
9050 
9051 static int
9052 mptsas_get_bus_addr(struct scsi_device *sd, char *name, int len)
9053 {
9054         return (mptsas_get_name(sd, name, len));
9055 }
9056 
9057 void
9058 mptsas_set_throttle(mptsas_t *mpt, mptsas_target_t *ptgt, int what)
9059 {
9060 
9061         NDBG25(("mptsas_set_throttle: throttle=%x", what));
9062 
9063         /*
9064          * if the bus is draining/quiesced, no changes to the throttles
9065          * are allowed. Not allowing change of throttles during draining
9066          * limits error recovery but will reduce draining time
9067          *
9068          * all throttles should have been set to HOLD_THROTTLE
9069          */
9070         if (mpt->m_softstate & (MPTSAS_SS_QUIESCED | MPTSAS_SS_DRAINING)) {
9071                 return;
9072         }
9073 
9074         if (what == HOLD_THROTTLE) {
9075                 ptgt->m_t_throttle = HOLD_THROTTLE;
9076         } else if (ptgt->m_reset_delay == 0) {
9077                 ptgt->m_t_throttle = what;
9078         }
9079 }
9080 
9081 /*
9082  * Clean up from a device reset.
9083  * For the case of target reset, this function clears the waitq of all
9084  * commands for a particular target.   For the case of abort task set, this
9085  * function clears the waitq of all commonds for a particular target/lun.
9086  */
9087 static void
9088 mptsas_flush_target(mptsas_t *mpt, ushort_t target, int lun, uint8_t tasktype)
9089 {
9090         mptsas_slots_t  *slots = mpt->m_active;
9091         mptsas_cmd_t    *cmd, *next_cmd;
9092         int             slot;
9093         uchar_t         reason;
9094         uint_t          stat;
9095 
9096         NDBG25(("mptsas_flush_target: target=%d lun=%d", target, lun));
9097 
9098         /*
9099          * Make sure the I/O Controller has flushed all cmds
9100          * that are associated with this target for a target reset
9101          * and target/lun for abort task set.
9102          * Account for TM requests, which use the last SMID.
9103          */
9104         mutex_enter(&mpt->m_intr_mutex);
9105         for (slot = 0; slot <= mpt->m_active->m_n_slots; slot++) {
9106                 if ((cmd = slots->m_slot[slot]) == NULL) {
9107                         continue;
9108                 }
9109                 reason = CMD_RESET;
9110                 stat = STAT_DEV_RESET;
9111                 switch (tasktype) {
9112                 case MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET:
9113                         if (Tgt(cmd) == target) {
9114                                 NDBG25(("mptsas_flush_target discovered non-"
9115                                     "NULL cmd in slot %d, tasktype 0x%x", slot,
9116                                     tasktype));
9117                                 mptsas_dump_cmd(mpt, cmd);
9118                                 mptsas_remove_cmd0(mpt, cmd);
9119                                 mptsas_set_pkt_reason(mpt, cmd, reason, stat);
9120                                 mptsas_doneq_add0(mpt, cmd);
9121                         }
9122                         break;
9123                 case MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET:
9124                         reason = CMD_ABORTED;
9125                         stat = STAT_ABORTED;
9126                         /*FALLTHROUGH*/
9127                 case MPI2_SCSITASKMGMT_TASKTYPE_LOGICAL_UNIT_RESET:
9128                         if ((Tgt(cmd) == target) && (Lun(cmd) == lun)) {
9129 
9130                                 NDBG25(("mptsas_flush_target discovered non-"
9131                                     "NULL cmd in slot %d, tasktype 0x%x", slot,
9132                                     tasktype));
9133                                 mptsas_dump_cmd(mpt, cmd);
9134                                 mptsas_remove_cmd0(mpt, cmd);
9135                                 mptsas_set_pkt_reason(mpt, cmd, reason,
9136                                     stat);
9137                                 mptsas_doneq_add0(mpt, cmd);
9138                         }
9139                         break;
9140                 default:
9141                         break;
9142                 }
9143         }
9144         mutex_exit(&mpt->m_intr_mutex);
9145 
9146         /*
9147          * Flush the waitq of this target's cmds
9148          */
9149         cmd = mpt->m_waitq;
9150 
9151         reason = CMD_RESET;
9152         stat = STAT_DEV_RESET;
9153 
9154         switch (tasktype) {
9155         case MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET:
9156                 while (cmd != NULL) {
9157                         next_cmd = cmd->cmd_linkp;
9158                         if (Tgt(cmd) == target) {
9159                                 mptsas_waitq_delete(mpt, cmd);
9160                                 mptsas_set_pkt_reason(mpt, cmd,
9161                                     reason, stat);
9162                                 mptsas_doneq_add(mpt, cmd);
9163                         }
9164                         cmd = next_cmd;
9165                 }
9166                 break;
9167         case MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET:
9168                 reason = CMD_ABORTED;
9169                 stat =  STAT_ABORTED;
9170                 /*FALLTHROUGH*/
9171         case MPI2_SCSITASKMGMT_TASKTYPE_LOGICAL_UNIT_RESET:
9172                 while (cmd != NULL) {
9173                         next_cmd = cmd->cmd_linkp;
9174                         if ((Tgt(cmd) == target) && (Lun(cmd) == lun)) {
9175                                 mptsas_waitq_delete(mpt, cmd);
9176                                 mptsas_set_pkt_reason(mpt, cmd,
9177                                     reason, stat);
9178                                 mptsas_doneq_add(mpt, cmd);
9179                         }
9180                         cmd = next_cmd;
9181                 }
9182                 break;
9183         default:
9184                 mptsas_log(mpt, CE_WARN, "Unknown task management type %d.",
9185                     tasktype);
9186                 break;
9187         }
9188 }
9189 
9190 /*
9191  * Clean up hba state, abort all outstanding command and commands in waitq
9192  * reset timeout of all targets.
9193  */
9194 static void
9195 mptsas_flush_hba(mptsas_t *mpt)
9196 {
9197         mptsas_slots_t  *slots = mpt->m_active;
9198         mptsas_cmd_t    *cmd;
9199         int             slot;
9200 
9201         NDBG25(("mptsas_flush_hba"));
9202 
9203         /*
9204          * The I/O Controller should have already sent back
9205          * all commands via the scsi I/O reply frame.  Make
9206          * sure all commands have been flushed.
9207          * Account for TM request, which use the last SMID.
9208          */
9209         mutex_enter(&mpt->m_intr_mutex);
9210         for (slot = 0; slot <= mpt->m_active->m_n_slots; slot++) {
9211                 if ((cmd = slots->m_slot[slot]) == NULL) {
9212                         continue;
9213                 }
9214 
9215                 if (cmd->cmd_flags & CFLAG_CMDIOC) {
9216                         /*
9217                          * Need to make sure to tell everyone that might be
9218                          * waiting on this command that it's going to fail.  If
9219                          * we get here, this command will never timeout because
9220                          * the active command table is going to be re-allocated,
9221                          * so there will be nothing to check against a time out.
9222                          * Instead, mark the command as failed due to reset.
9223                          */
9224                         mptsas_set_pkt_reason(mpt, cmd, CMD_RESET,
9225                             STAT_BUS_RESET);
9226                         if ((cmd->cmd_flags & CFLAG_PASSTHRU) ||
9227                             (cmd->cmd_flags & CFLAG_CONFIG) ||
9228                             (cmd->cmd_flags & CFLAG_FW_DIAG)) {
9229                                 cmd->cmd_flags |= CFLAG_FINISHED;
9230                                 cv_broadcast(&mpt->m_passthru_cv);
9231                                 cv_broadcast(&mpt->m_config_cv);
9232                                 cv_broadcast(&mpt->m_fw_diag_cv);
9233                         }
9234                         continue;
9235                 }
9236 
9237                 NDBG25(("mptsas_flush_hba discovered non-NULL cmd in slot %d",
9238                     slot));
9239                 mptsas_dump_cmd(mpt, cmd);
9240 
9241                 mptsas_remove_cmd0(mpt, cmd);
9242                 mptsas_set_pkt_reason(mpt, cmd, CMD_RESET, STAT_BUS_RESET);
9243                 mptsas_doneq_add0(mpt, cmd);
9244         }
9245         mutex_exit(&mpt->m_intr_mutex);
9246 
9247         /*
9248          * Flush the waitq.
9249          */
9250         while ((cmd = mptsas_waitq_rm(mpt)) != NULL) {
9251                 mptsas_set_pkt_reason(mpt, cmd, CMD_RESET, STAT_BUS_RESET);
9252                 if ((cmd->cmd_flags & CFLAG_PASSTHRU) ||
9253                     (cmd->cmd_flags & CFLAG_CONFIG) ||
9254                     (cmd->cmd_flags & CFLAG_FW_DIAG)) {
9255                         cmd->cmd_flags |= CFLAG_FINISHED;
9256                         cv_broadcast(&mpt->m_passthru_cv);
9257                         cv_broadcast(&mpt->m_config_cv);
9258                         cv_broadcast(&mpt->m_fw_diag_cv);
9259                 } else {
9260                         mptsas_doneq_add(mpt, cmd);
9261                 }
9262         }
9263 }
9264 
9265 /*
9266  * set pkt_reason and OR in pkt_statistics flag
9267  */
9268 static void
9269 mptsas_set_pkt_reason(mptsas_t *mpt, mptsas_cmd_t *cmd, uchar_t reason,
9270     uint_t stat)
9271 {
9272 #ifndef __lock_lint
9273         _NOTE(ARGUNUSED(mpt))
9274 #endif
9275 
9276         NDBG25(("mptsas_set_pkt_reason: cmd=0x%p reason=%x stat=%x",
9277             (void *)cmd, reason, stat));
9278 
9279         if (cmd) {
9280                 if (cmd->cmd_pkt->pkt_reason == CMD_CMPLT) {
9281                         cmd->cmd_pkt->pkt_reason = reason;
9282                 }
9283                 cmd->cmd_pkt->pkt_statistics |= stat;
9284         }
9285 }
9286 
9287 static void
9288 mptsas_start_watch_reset_delay()
9289 {
9290         NDBG22(("mptsas_start_watch_reset_delay"));
9291 
9292         mutex_enter(&mptsas_global_mutex);
9293         if (mptsas_reset_watch == NULL && mptsas_timeouts_enabled) {
9294                 mptsas_reset_watch = timeout(mptsas_watch_reset_delay, NULL,
9295                     drv_usectohz((clock_t)
9296                     MPTSAS_WATCH_RESET_DELAY_TICK * 1000));
9297                 ASSERT(mptsas_reset_watch != NULL);
9298         }
9299         mutex_exit(&mptsas_global_mutex);
9300 }
9301 
9302 static void
9303 mptsas_setup_bus_reset_delay(mptsas_t *mpt)
9304 {
9305         mptsas_target_t *ptgt = NULL;
9306 
9307         NDBG22(("mptsas_setup_bus_reset_delay"));
9308         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
9309             MPTSAS_HASH_FIRST);
9310         while (ptgt != NULL) {
9311                 mutex_enter(&ptgt->m_tgt_intr_mutex);
9312                 mptsas_set_throttle(mpt, ptgt, HOLD_THROTTLE);
9313                 ptgt->m_reset_delay = mpt->m_scsi_reset_delay;
9314                 mutex_exit(&ptgt->m_tgt_intr_mutex);
9315 
9316                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
9317                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
9318         }
9319 
9320         mptsas_start_watch_reset_delay();
9321 }
9322 
9323 /*
9324  * mptsas_watch_reset_delay(_subr) is invoked by timeout() and checks every
9325  * mpt instance for active reset delays
9326  */
9327 static void
9328 mptsas_watch_reset_delay(void *arg)
9329 {
9330 #ifndef __lock_lint
9331         _NOTE(ARGUNUSED(arg))
9332 #endif
9333 
9334         mptsas_t        *mpt;
9335         int             not_done = 0;
9336 
9337         NDBG22(("mptsas_watch_reset_delay"));
9338 
9339         mutex_enter(&mptsas_global_mutex);
9340         mptsas_reset_watch = 0;
9341         mutex_exit(&mptsas_global_mutex);
9342         rw_enter(&mptsas_global_rwlock, RW_READER);
9343         for (mpt = mptsas_head; mpt != NULL; mpt = mpt->m_next) {
9344                 if (mpt->m_tran == 0) {
9345                         continue;
9346                 }
9347                 mutex_enter(&mpt->m_mutex);
9348                 not_done += mptsas_watch_reset_delay_subr(mpt);
9349                 mutex_exit(&mpt->m_mutex);
9350         }
9351         rw_exit(&mptsas_global_rwlock);
9352 
9353         if (not_done) {
9354                 mptsas_start_watch_reset_delay();
9355         }
9356 }
9357 
9358 static int
9359 mptsas_watch_reset_delay_subr(mptsas_t *mpt)
9360 {
9361         int             done = 0;
9362         int             restart = 0;
9363         mptsas_target_t *ptgt = NULL;
9364 
9365         NDBG22(("mptsas_watch_reset_delay_subr: mpt=0x%p", (void *)mpt));
9366 
9367         ASSERT(mutex_owned(&mpt->m_mutex));
9368 
9369         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
9370             MPTSAS_HASH_FIRST);
9371         while (ptgt != NULL) {
9372                 mutex_enter(&ptgt->m_tgt_intr_mutex);
9373                 if (ptgt->m_reset_delay != 0) {
9374                         ptgt->m_reset_delay -=
9375                             MPTSAS_WATCH_RESET_DELAY_TICK;
9376                         if (ptgt->m_reset_delay <= 0) {
9377                                 ptgt->m_reset_delay = 0;
9378                                 mptsas_set_throttle(mpt, ptgt,
9379                                     MAX_THROTTLE);
9380                                 restart++;
9381                         } else {
9382                                 done = -1;
9383                         }
9384                 }
9385                 mutex_exit(&ptgt->m_tgt_intr_mutex);
9386 
9387                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
9388                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
9389         }
9390 
9391         if (restart > 0) {
9392                 mptsas_restart_hba(mpt);
9393         }
9394         return (done);
9395 }
9396 
9397 #ifdef MPTSAS_TEST
9398 static void
9399 mptsas_test_reset(mptsas_t *mpt, int target)
9400 {
9401         mptsas_target_t    *ptgt = NULL;
9402 
9403         if (mptsas_rtest == target) {
9404                 if (mptsas_do_scsi_reset(mpt, target) == TRUE) {
9405                         mptsas_rtest = -1;
9406                 }
9407                 if (mptsas_rtest == -1) {
9408                         NDBG22(("mptsas_test_reset success"));
9409                 }
9410         }
9411 }
9412 #endif
9413 
9414 /*
9415  * abort handling:
9416  *
9417  * Notes:
9418  *      - if pkt is not NULL, abort just that command
9419  *      - if pkt is NULL, abort all outstanding commands for target
9420  */
9421 static int
9422 mptsas_scsi_abort(struct scsi_address *ap, struct scsi_pkt *pkt)
9423 {
9424         mptsas_t                *mpt = ADDR2MPT(ap);
9425         int                     rval;
9426         mptsas_tgt_private_t    *tgt_private;
9427         int                     target, lun;
9428 
9429         tgt_private = (mptsas_tgt_private_t *)ap->a_hba_tran->
9430             tran_tgt_private;
9431         ASSERT(tgt_private != NULL);
9432         target = tgt_private->t_private->m_devhdl;
9433         lun = tgt_private->t_lun;
9434 
9435         NDBG23(("mptsas_scsi_abort: target=%d.%d", target, lun));
9436 
9437         mutex_enter(&mpt->m_mutex);
9438         rval = mptsas_do_scsi_abort(mpt, target, lun, pkt);
9439         mutex_exit(&mpt->m_mutex);
9440         return (rval);
9441 }
9442 
9443 static int
9444 mptsas_do_scsi_abort(mptsas_t *mpt, int target, int lun, struct scsi_pkt *pkt)
9445 {
9446         mptsas_cmd_t    *sp = NULL;
9447         mptsas_slots_t  *slots = mpt->m_active;
9448         int             rval = FALSE;
9449 
9450         ASSERT(mutex_owned(&mpt->m_mutex));
9451 
9452         /*
9453          * Abort the command pkt on the target/lun in ap.  If pkt is
9454          * NULL, abort all outstanding commands on that target/lun.
9455          * If you can abort them, return 1, else return 0.
9456          * Each packet that's aborted should be sent back to the target
9457          * driver through the callback routine, with pkt_reason set to
9458          * CMD_ABORTED.
9459          *
9460          * abort cmd pkt on HBA hardware; clean out of outstanding
9461          * command lists, etc.
9462          */
9463         if (pkt != NULL) {
9464                 /* abort the specified packet */
9465                 sp = PKT2CMD(pkt);
9466 
9467                 if (sp->cmd_queued) {
9468                         NDBG23(("mptsas_do_scsi_abort: queued sp=0x%p aborted",
9469                             (void *)sp));
9470                         mptsas_waitq_delete(mpt, sp);
9471                         mptsas_set_pkt_reason(mpt, sp, CMD_ABORTED,
9472                             STAT_ABORTED);
9473                         mptsas_doneq_add(mpt, sp);
9474                         rval = TRUE;
9475                         goto done;
9476                 }
9477 
9478                 /*
9479                  * Have mpt firmware abort this command
9480                  */
9481                 mutex_enter(&mpt->m_intr_mutex);
9482                 if (slots->m_slot[sp->cmd_slot] != NULL) {
9483                         mutex_exit(&mpt->m_intr_mutex);
9484                         rval = mptsas_ioc_task_management(mpt,
9485                             MPI2_SCSITASKMGMT_TASKTYPE_ABORT_TASK, target,
9486                             lun, NULL, 0, 0);
9487 
9488                         /*
9489                          * The transport layer expects only TRUE and FALSE.
9490                          * Therefore, if mptsas_ioc_task_management returns
9491                          * FAILED we will return FALSE.
9492                          */
9493                         if (rval == FAILED)
9494                                 rval = FALSE;
9495                         goto done;
9496                 }
9497                 mutex_exit(&mpt->m_intr_mutex);
9498         }
9499 
9500         /*
9501          * If pkt is NULL then abort task set
9502          */
9503         rval = mptsas_ioc_task_management(mpt,
9504             MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET, target, lun, NULL, 0, 0);
9505 
9506         /*
9507          * The transport layer expects only TRUE and FALSE.
9508          * Therefore, if mptsas_ioc_task_management returns
9509          * FAILED we will return FALSE.
9510          */
9511         if (rval == FAILED)
9512                 rval = FALSE;
9513 
9514 #ifdef MPTSAS_TEST
9515         if (rval && mptsas_test_stop) {
9516                 debug_enter("mptsas_do_scsi_abort");
9517         }
9518 #endif
9519 
9520 done:
9521         mptsas_doneq_empty(mpt);
9522         return (rval);
9523 }
9524 
9525 /*
9526  * capability handling:
9527  * (*tran_getcap).  Get the capability named, and return its value.
9528  */
9529 static int
9530 mptsas_scsi_getcap(struct scsi_address *ap, char *cap, int tgtonly)
9531 {
9532         mptsas_t        *mpt = ADDR2MPT(ap);
9533         int             ckey;
9534         int             rval = FALSE;
9535 
9536         NDBG24(("mptsas_scsi_getcap: target=%d, cap=%s tgtonly=%x",
9537             ap->a_target, cap, tgtonly));
9538 
9539         mutex_enter(&mpt->m_mutex);
9540 
9541         if ((mptsas_scsi_capchk(cap, tgtonly, &ckey)) != TRUE) {
9542                 mutex_exit(&mpt->m_mutex);
9543                 return (UNDEFINED);
9544         }
9545 
9546         switch (ckey) {
9547         case SCSI_CAP_DMA_MAX:
9548                 rval = (int)mpt->m_msg_dma_attr.dma_attr_maxxfer;
9549                 break;
9550         case SCSI_CAP_ARQ:
9551                 rval = TRUE;
9552                 break;
9553         case SCSI_CAP_MSG_OUT:
9554         case SCSI_CAP_PARITY:
9555         case SCSI_CAP_UNTAGGED_QING:
9556                 rval = TRUE;
9557                 break;
9558         case SCSI_CAP_TAGGED_QING:
9559                 rval = TRUE;
9560                 break;
9561         case SCSI_CAP_RESET_NOTIFICATION:
9562                 rval = TRUE;
9563                 break;
9564         case SCSI_CAP_LINKED_CMDS:
9565                 rval = FALSE;
9566                 break;
9567         case SCSI_CAP_QFULL_RETRIES:
9568                 rval = ((mptsas_tgt_private_t *)(ap->a_hba_tran->
9569                     tran_tgt_private))->t_private->m_qfull_retries;
9570                 break;
9571         case SCSI_CAP_QFULL_RETRY_INTERVAL:
9572                 rval = drv_hztousec(((mptsas_tgt_private_t *)
9573                     (ap->a_hba_tran->tran_tgt_private))->
9574                     t_private->m_qfull_retry_interval) / 1000;
9575                 break;
9576         case SCSI_CAP_CDB_LEN:
9577                 rval = CDB_GROUP4;
9578                 break;
9579         case SCSI_CAP_INTERCONNECT_TYPE:
9580                 rval = INTERCONNECT_SAS;
9581                 break;
9582         case SCSI_CAP_TRAN_LAYER_RETRIES:
9583                 if (mpt->m_ioc_capabilities &
9584                     MPI2_IOCFACTS_CAPABILITY_TLR)
9585                         rval = TRUE;
9586                 else
9587                         rval = FALSE;
9588                 break;
9589         default:
9590                 rval = UNDEFINED;
9591                 break;
9592         }
9593 
9594         NDBG24(("mptsas_scsi_getcap: %s, rval=%x", cap, rval));
9595 
9596         mutex_exit(&mpt->m_mutex);
9597         return (rval);
9598 }
9599 
9600 /*
9601  * (*tran_setcap).  Set the capability named to the value given.
9602  */
9603 static int
9604 mptsas_scsi_setcap(struct scsi_address *ap, char *cap, int value, int tgtonly)
9605 {
9606         mptsas_t        *mpt = ADDR2MPT(ap);
9607         int             ckey;
9608         int             rval = FALSE;
9609         mptsas_target_t *ptgt;
9610 
9611         NDBG24(("mptsas_scsi_setcap: target=%d, cap=%s value=%x tgtonly=%x",
9612             ap->a_target, cap, value, tgtonly));
9613 
9614         if (!tgtonly) {
9615                 return (rval);
9616         }
9617 
9618         mutex_enter(&mpt->m_mutex);
9619 
9620         if ((mptsas_scsi_capchk(cap, tgtonly, &ckey)) != TRUE) {
9621                 mutex_exit(&mpt->m_mutex);
9622                 return (UNDEFINED);
9623         }
9624 
9625         switch (ckey) {
9626         case SCSI_CAP_DMA_MAX:
9627         case SCSI_CAP_MSG_OUT:
9628         case SCSI_CAP_PARITY:
9629         case SCSI_CAP_INITIATOR_ID:
9630         case SCSI_CAP_LINKED_CMDS:
9631         case SCSI_CAP_UNTAGGED_QING:
9632         case SCSI_CAP_RESET_NOTIFICATION:
9633                 /*
9634                  * None of these are settable via
9635                  * the capability interface.
9636                  */
9637                 break;
9638         case SCSI_CAP_ARQ:
9639                 /*
9640                  * We cannot turn off arq so return false if asked to
9641                  */
9642                 if (value) {
9643                         rval = TRUE;
9644                 } else {
9645                         rval = FALSE;
9646                 }
9647                 break;
9648         case SCSI_CAP_TAGGED_QING:
9649                 ptgt = ((mptsas_tgt_private_t *)
9650                     (ap->a_hba_tran->tran_tgt_private))->t_private;
9651                 mutex_enter(&ptgt->m_tgt_intr_mutex);
9652                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
9653                 mutex_exit(&ptgt->m_tgt_intr_mutex);
9654                 rval = TRUE;
9655                 break;
9656         case SCSI_CAP_QFULL_RETRIES:
9657                 ((mptsas_tgt_private_t *)(ap->a_hba_tran->tran_tgt_private))->
9658                     t_private->m_qfull_retries = (uchar_t)value;
9659                 rval = TRUE;
9660                 break;
9661         case SCSI_CAP_QFULL_RETRY_INTERVAL:
9662                 ((mptsas_tgt_private_t *)(ap->a_hba_tran->tran_tgt_private))->
9663                     t_private->m_qfull_retry_interval =
9664                     drv_usectohz(value * 1000);
9665                 rval = TRUE;
9666                 break;
9667         default:
9668                 rval = UNDEFINED;
9669                 break;
9670         }
9671         mutex_exit(&mpt->m_mutex);
9672         return (rval);
9673 }
9674 
9675 /*
9676  * Utility routine for mptsas_ifsetcap/ifgetcap
9677  */
9678 /*ARGSUSED*/
9679 static int
9680 mptsas_scsi_capchk(char *cap, int tgtonly, int *cidxp)
9681 {
9682         NDBG24(("mptsas_scsi_capchk: cap=%s", cap));
9683 
9684         if (!cap)
9685                 return (FALSE);
9686 
9687         *cidxp = scsi_hba_lookup_capstr(cap);
9688         return (TRUE);
9689 }
9690 
9691 static int
9692 mptsas_alloc_active_slots(mptsas_t *mpt, int flag)
9693 {
9694         mptsas_slots_t  *old_active = mpt->m_active;
9695         mptsas_slots_t  *new_active;
9696         size_t          size;
9697         int             rval = -1, nslot, i;
9698         mptsas_slot_free_e_t    *pe;
9699 
9700         if (mptsas_outstanding_cmds_n(mpt)) {
9701                 NDBG9(("cannot change size of active slots array"));
9702                 return (rval);
9703         }
9704 
9705         size = MPTSAS_SLOTS_SIZE(mpt);
9706         new_active = kmem_zalloc(size, flag);
9707         if (new_active == NULL) {
9708                 NDBG1(("new active alloc failed"));
9709                 return (rval);
9710         }
9711         /*
9712          * Since SMID 0 is reserved and the TM slot is reserved, the
9713          * number of slots that can be used at any one time is
9714          * m_max_requests - 2.
9715          */
9716         new_active->m_n_slots = nslot = (mpt->m_max_requests - 2);
9717         new_active->m_size = size;
9718         new_active->m_tags = 1;
9719 
9720         if (old_active) {
9721                 new_active->m_tgttbl = old_active->m_tgttbl;
9722                 new_active->m_smptbl = old_active->m_smptbl;
9723                 new_active->m_num_raid_configs =
9724                     old_active->m_num_raid_configs;
9725                 for (i = 0; i < new_active->m_num_raid_configs; i++) {
9726                         new_active->m_raidconfig[i] =
9727                             old_active->m_raidconfig[i];
9728                 }
9729                 mptsas_free_active_slots(mpt);
9730         }
9731 
9732         if (max_ncpus & (max_ncpus - 1)) {
9733                 mpt->m_slot_freeq_pair_n = (1 << highbit(max_ncpus));
9734         } else {
9735                 mpt->m_slot_freeq_pair_n = max_ncpus;
9736         }
9737         mpt->m_slot_freeq_pairp = kmem_zalloc(
9738             mpt->m_slot_freeq_pair_n *
9739             sizeof (mptsas_slot_freeq_pair_t), KM_SLEEP);
9740         for (i = 0; i < mpt->m_slot_freeq_pair_n; i++) {
9741                 list_create(&mpt->m_slot_freeq_pairp[i].
9742                     m_slot_allocq.s.m_fq_list,
9743                     sizeof (mptsas_slot_free_e_t),
9744                     offsetof(mptsas_slot_free_e_t, node));
9745                 list_create(&mpt->m_slot_freeq_pairp[i].
9746                     m_slot_releq.s.m_fq_list,
9747                     sizeof (mptsas_slot_free_e_t),
9748                     offsetof(mptsas_slot_free_e_t, node));
9749                 mpt->m_slot_freeq_pairp[i].m_slot_allocq.s.m_fq_n = 0;
9750                 mpt->m_slot_freeq_pairp[i].m_slot_releq.s.m_fq_n = 0;
9751                 mutex_init(&mpt->m_slot_freeq_pairp[i].
9752                     m_slot_allocq.s.m_fq_mutex, NULL, MUTEX_DRIVER,
9753                     DDI_INTR_PRI(mpt->m_intr_pri));
9754                 mutex_init(&mpt->m_slot_freeq_pairp[i].
9755                     m_slot_releq.s.m_fq_mutex, NULL, MUTEX_DRIVER,
9756                     DDI_INTR_PRI(mpt->m_intr_pri));
9757         }
9758         pe = mpt->m_slot_free_ae = kmem_zalloc(nslot *
9759             sizeof (mptsas_slot_free_e_t), KM_SLEEP);
9760         /*
9761          * An array of Mpi2ReplyDescriptorsUnion_t is defined here.
9762          * We are trying to eliminate the m_mutex in the context
9763          * reply code path in the ISR. Since the read of the
9764          * ReplyDescriptor and update/write of the ReplyIndex must
9765          * be atomic (since the poll thread may also update them at
9766          * the same time) so we first read out of the ReplyDescriptor
9767          * into this array and update the ReplyIndex register with a
9768          * separate mutex m_intr_mutex protected, and then release the
9769          * mutex and process all of them. the length of the array is
9770          * defined as max as 128(128*64=8k), which is
9771          * assumed as the maxmium depth of the interrupt coalese.
9772          */
9773         mpt->m_reply = kmem_zalloc(MPI_ADDRESS_COALSCE_MAX *
9774             sizeof (Mpi2ReplyDescriptorsUnion_t), KM_SLEEP);
9775         for (i = 0; i < nslot; i++, pe++) {
9776                 pe->slot = i + 1; /* SMID 0 is reserved */
9777                 pe->cpuid = i % mpt->m_slot_freeq_pair_n;
9778                 list_insert_tail(&mpt->m_slot_freeq_pairp
9779                     [i % mpt->m_slot_freeq_pair_n]
9780                     .m_slot_allocq.s.m_fq_list, pe);
9781                 mpt->m_slot_freeq_pairp[i % mpt->m_slot_freeq_pair_n]
9782                     .m_slot_allocq.s.m_fq_n++;
9783                 mpt->m_slot_freeq_pairp[i % mpt->m_slot_freeq_pair_n]
9784                     .m_slot_allocq.s.m_fq_n_init++;
9785         }
9786 
9787         mpt->m_active = new_active;
9788         rval = 0;
9789 
9790         return (rval);
9791 }
9792 
9793 static void
9794 mptsas_free_active_slots(mptsas_t *mpt)
9795 {
9796         mptsas_slots_t  *active = mpt->m_active;
9797         size_t          size;
9798         mptsas_slot_free_e_t    *pe;
9799         int     i;
9800 
9801         if (active == NULL)
9802                 return;
9803 
9804         if (mpt->m_slot_freeq_pairp) {
9805                 for (i = 0; i < mpt->m_slot_freeq_pair_n; i++) {
9806                         while ((pe = list_head(&mpt->m_slot_freeq_pairp
9807                             [i].m_slot_allocq.s.m_fq_list)) != NULL) {
9808                                 list_remove(&mpt->m_slot_freeq_pairp[i]
9809                                     .m_slot_allocq.s.m_fq_list, pe);
9810                         }
9811                         list_destroy(&mpt->m_slot_freeq_pairp
9812                             [i].m_slot_allocq.s.m_fq_list);
9813                         while ((pe = list_head(&mpt->m_slot_freeq_pairp
9814                             [i].m_slot_releq.s.m_fq_list)) != NULL) {
9815                                 list_remove(&mpt->m_slot_freeq_pairp[i]
9816                                     .m_slot_releq.s.m_fq_list, pe);
9817                         }
9818                         list_destroy(&mpt->m_slot_freeq_pairp
9819                             [i].m_slot_releq.s.m_fq_list);
9820                         mutex_destroy(&mpt->m_slot_freeq_pairp
9821                             [i].m_slot_allocq.s.m_fq_mutex);
9822                         mutex_destroy(&mpt->m_slot_freeq_pairp
9823                             [i].m_slot_releq.s.m_fq_mutex);
9824                 }
9825                 kmem_free(mpt->m_slot_freeq_pairp, mpt->m_slot_freeq_pair_n *
9826                     sizeof (mptsas_slot_freeq_pair_t));
9827         }
9828         if (mpt->m_slot_free_ae)
9829                 kmem_free(mpt->m_slot_free_ae, mpt->m_active->m_n_slots *
9830                     sizeof (mptsas_slot_free_e_t));
9831 
9832         if (mpt->m_reply)
9833                 kmem_free(mpt->m_reply, MPI_ADDRESS_COALSCE_MAX *
9834                     sizeof (Mpi2ReplyDescriptorsUnion_t));
9835 
9836         size = active->m_size;
9837         kmem_free(active, size);
9838         mpt->m_active = NULL;
9839 }
9840 
9841 /*
9842  * Error logging, printing, and debug print routines.
9843  */
9844 static char *mptsas_label = "mpt_sas";
9845 
9846 /*PRINTFLIKE3*/
9847 void
9848 mptsas_log(mptsas_t *mpt, int level, char *fmt, ...)
9849 {
9850         dev_info_t      *dev;
9851         va_list         ap;
9852 
9853         if (mpt) {
9854                 dev = mpt->m_dip;
9855         } else {
9856                 dev = 0;
9857         }
9858 
9859         mutex_enter(&mptsas_log_mutex);
9860 
9861         va_start(ap, fmt);
9862         (void) vsprintf(mptsas_log_buf, fmt, ap);
9863         va_end(ap);
9864 
9865         if (level == CE_CONT) {
9866                 scsi_log(dev, mptsas_label, level, "%s\n", mptsas_log_buf);
9867         } else {
9868                 scsi_log(dev, mptsas_label, level, "%s", mptsas_log_buf);
9869         }
9870 
9871         mutex_exit(&mptsas_log_mutex);
9872 }
9873 
9874 #ifdef MPTSAS_DEBUG
9875 /*PRINTFLIKE1*/
9876 void
9877 mptsas_printf(char *fmt, ...)
9878 {
9879         dev_info_t      *dev = 0;
9880         va_list         ap;
9881 
9882         mutex_enter(&mptsas_log_mutex);
9883 
9884         va_start(ap, fmt);
9885         (void) vsprintf(mptsas_log_buf, fmt, ap);
9886         va_end(ap);
9887 
9888 #ifdef PROM_PRINTF
9889         prom_printf("%s:\t%s\n", mptsas_label, mptsas_log_buf);
9890 #else
9891         scsi_log(dev, mptsas_label, SCSI_DEBUG, "%s\n", mptsas_log_buf);
9892 #endif
9893         mutex_exit(&mptsas_log_mutex);
9894 }
9895 #endif
9896 
9897 /*
9898  * timeout handling
9899  */
9900 static void
9901 mptsas_watch(void *arg)
9902 {
9903 #ifndef __lock_lint
9904         _NOTE(ARGUNUSED(arg))
9905 #endif
9906 
9907         mptsas_t        *mpt;
9908         uint32_t        doorbell;
9909 
9910         NDBG30(("mptsas_watch"));
9911 
9912         rw_enter(&mptsas_global_rwlock, RW_READER);
9913         for (mpt = mptsas_head; mpt != (mptsas_t *)NULL; mpt = mpt->m_next) {
9914 
9915                 mutex_enter(&mpt->m_mutex);
9916 
9917                 /* Skip device if not powered on */
9918                 if (mpt->m_options & MPTSAS_OPT_PM) {
9919                         if (mpt->m_power_level == PM_LEVEL_D0) {
9920                                 (void) pm_busy_component(mpt->m_dip, 0);
9921                                 mpt->m_busy = 1;
9922                         } else {
9923                                 mutex_exit(&mpt->m_mutex);
9924                                 continue;
9925                         }
9926                 }
9927 
9928                 /*
9929                  * Check if controller is in a FAULT state. If so, reset it.
9930                  */
9931                 doorbell = ddi_get32(mpt->m_datap, &mpt->m_reg->Doorbell);
9932                 if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
9933                         doorbell &= MPI2_DOORBELL_DATA_MASK;
9934                         mptsas_log(mpt, CE_WARN, "MPT Firmware Fault, "
9935                             "code: %04x", doorbell);
9936                         mpt->m_softstate &= ~MPTSAS_SS_MSG_UNIT_RESET;
9937                         if ((mptsas_restart_ioc(mpt)) == DDI_FAILURE) {
9938                                 mptsas_log(mpt, CE_WARN, "Reset failed"
9939                                     "after fault was detected");
9940                         }
9941                 }
9942 
9943                 /*
9944                  * For now, always call mptsas_watchsubr.
9945                  */
9946                 mptsas_watchsubr(mpt);
9947 
9948                 if (mpt->m_options & MPTSAS_OPT_PM) {
9949                         mpt->m_busy = 0;
9950                         (void) pm_idle_component(mpt->m_dip, 0);
9951                 }
9952 
9953                 mutex_exit(&mpt->m_mutex);
9954         }
9955         rw_exit(&mptsas_global_rwlock);
9956 
9957         mutex_enter(&mptsas_global_mutex);
9958         if (mptsas_timeouts_enabled)
9959                 mptsas_timeout_id = timeout(mptsas_watch, NULL, mptsas_tick);
9960         mutex_exit(&mptsas_global_mutex);
9961 }
9962 
9963 static void
9964 mptsas_watchsubr(mptsas_t *mpt)
9965 {
9966         int             i;
9967         mptsas_cmd_t    *cmd;
9968         mptsas_target_t *ptgt = NULL;
9969 
9970         NDBG30(("mptsas_watchsubr: mpt=0x%p", (void *)mpt));
9971 
9972 #ifdef MPTSAS_TEST
9973         if (mptsas_enable_untagged) {
9974                 mptsas_test_untagged++;
9975         }
9976 #endif
9977 
9978         /*
9979          * Check for commands stuck in active slot
9980          * Account for TM requests, which use the last SMID.
9981          */
9982         mutex_enter(&mpt->m_intr_mutex);
9983         for (i = 0; i <= mpt->m_active->m_n_slots; i++) {
9984                 if ((cmd = mpt->m_active->m_slot[i]) != NULL) {
9985                         if ((cmd->cmd_flags & CFLAG_CMDIOC) == 0) {
9986                                 cmd->cmd_active_timeout -=
9987                                     mptsas_scsi_watchdog_tick;
9988                                 if (cmd->cmd_active_timeout <= 0) {
9989                                         /*
9990                                          * There seems to be a command stuck
9991                                          * in the active slot.  Drain throttle.
9992                                          */
9993                                         ptgt = cmd->cmd_tgt_addr;
9994                                         mutex_enter(&ptgt->m_tgt_intr_mutex);
9995                                         mptsas_set_throttle(mpt, ptgt,
9996                                             DRAIN_THROTTLE);
9997                                         mutex_exit(&ptgt->m_tgt_intr_mutex);
9998                                 }
9999                         }
10000                         if ((cmd->cmd_flags & CFLAG_PASSTHRU) ||
10001                             (cmd->cmd_flags & CFLAG_CONFIG) ||
10002                             (cmd->cmd_flags & CFLAG_FW_DIAG)) {
10003                                 cmd->cmd_active_timeout -=
10004                                     mptsas_scsi_watchdog_tick;
10005                                 if (cmd->cmd_active_timeout <= 0) {
10006                                         /*
10007                                          * passthrough command timeout
10008                                          */
10009                                         cmd->cmd_flags |= (CFLAG_FINISHED |
10010                                             CFLAG_TIMEOUT);
10011                                         cv_broadcast(&mpt->m_passthru_cv);
10012                                         cv_broadcast(&mpt->m_config_cv);
10013                                         cv_broadcast(&mpt->m_fw_diag_cv);
10014                                 }
10015                         }
10016                 }
10017         }
10018         mutex_exit(&mpt->m_intr_mutex);
10019 
10020         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
10021             MPTSAS_HASH_FIRST);
10022         while (ptgt != NULL) {
10023                 /*
10024                  * In order to avoid using m_mutex in the key code path in ISR,
10025                  * separate mutexs are introduced to protect those elements
10026                  * shown in ISR.
10027                  */
10028                 mutex_enter(&ptgt->m_tgt_intr_mutex);
10029 
10030                 /*
10031                  * If we were draining due to a qfull condition,
10032                  * go back to full throttle.
10033                  */
10034                 if ((ptgt->m_t_throttle < MAX_THROTTLE) &&
10035                     (ptgt->m_t_throttle > HOLD_THROTTLE) &&
10036                     (ptgt->m_t_ncmds < ptgt->m_t_throttle)) {
10037                         mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
10038                         mptsas_restart_hba(mpt);
10039                 }
10040 
10041                 if ((ptgt->m_t_ncmds > 0) &&
10042                     (ptgt->m_timebase)) {
10043 
10044                         if (ptgt->m_timebase <=
10045                             mptsas_scsi_watchdog_tick) {
10046                                 ptgt->m_timebase +=
10047                                     mptsas_scsi_watchdog_tick;
10048                                 mutex_exit(&ptgt->m_tgt_intr_mutex);
10049                                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
10050                                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
10051                                 continue;
10052                         }
10053 
10054                         ptgt->m_timeout -= mptsas_scsi_watchdog_tick;
10055 
10056                         if (ptgt->m_timeout < 0) {
10057                                 mutex_exit(&ptgt->m_tgt_intr_mutex);
10058                                 mptsas_cmd_timeout(mpt, ptgt->m_devhdl);
10059                                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
10060                                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
10061                                 continue;
10062                         }
10063 
10064                         if ((ptgt->m_timeout) <=
10065                             mptsas_scsi_watchdog_tick) {
10066                                 NDBG23(("pending timeout"));
10067                                 mptsas_set_throttle(mpt, ptgt,
10068                                     DRAIN_THROTTLE);
10069                         }
10070                 }
10071                 mutex_exit(&ptgt->m_tgt_intr_mutex);
10072                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
10073                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
10074         }
10075 }
10076 
10077 /*
10078  * timeout recovery
10079  */
10080 static void
10081 mptsas_cmd_timeout(mptsas_t *mpt, uint16_t devhdl)
10082 {
10083 
10084         NDBG29(("mptsas_cmd_timeout: target=%d", devhdl));
10085         mptsas_log(mpt, CE_WARN, "Disconnected command timeout for "
10086             "Target %d", devhdl);
10087 
10088         /*
10089          * If the current target is not the target passed in,
10090          * try to reset that target.
10091          */
10092         NDBG29(("mptsas_cmd_timeout: device reset"));
10093         if (mptsas_do_scsi_reset(mpt, devhdl) != TRUE) {
10094                 mptsas_log(mpt, CE_WARN, "Target %d reset for command timeout "
10095                     "recovery failed!", devhdl);
10096         }
10097 }
10098 
10099 /*
10100  * Device / Hotplug control
10101  */
10102 static int
10103 mptsas_scsi_quiesce(dev_info_t *dip)
10104 {
10105         mptsas_t        *mpt;
10106         scsi_hba_tran_t *tran;
10107 
10108         tran = ddi_get_driver_private(dip);
10109         if (tran == NULL || (mpt = TRAN2MPT(tran)) == NULL)
10110                 return (-1);
10111 
10112         return (mptsas_quiesce_bus(mpt));
10113 }
10114 
10115 static int
10116 mptsas_scsi_unquiesce(dev_info_t *dip)
10117 {
10118         mptsas_t                *mpt;
10119         scsi_hba_tran_t *tran;
10120 
10121         tran = ddi_get_driver_private(dip);
10122         if (tran == NULL || (mpt = TRAN2MPT(tran)) == NULL)
10123                 return (-1);
10124 
10125         return (mptsas_unquiesce_bus(mpt));
10126 }
10127 
10128 static int
10129 mptsas_quiesce_bus(mptsas_t *mpt)
10130 {
10131         mptsas_target_t *ptgt = NULL;
10132 
10133         NDBG28(("mptsas_quiesce_bus"));
10134         mutex_enter(&mpt->m_mutex);
10135 
10136         /* Set all the throttles to zero */
10137         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
10138             MPTSAS_HASH_FIRST);
10139         while (ptgt != NULL) {
10140                 mutex_enter(&ptgt->m_tgt_intr_mutex);
10141                 mptsas_set_throttle(mpt, ptgt, HOLD_THROTTLE);
10142                 mutex_exit(&ptgt->m_tgt_intr_mutex);
10143 
10144                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
10145                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
10146         }
10147 
10148         /* If there are any outstanding commands in the queue */
10149         mutex_enter(&mpt->m_intr_mutex);
10150         if (mptsas_outstanding_cmds_n(mpt)) {
10151                 mutex_exit(&mpt->m_intr_mutex);
10152                 mpt->m_softstate |= MPTSAS_SS_DRAINING;
10153                 mpt->m_quiesce_timeid = timeout(mptsas_ncmds_checkdrain,
10154                     mpt, (MPTSAS_QUIESCE_TIMEOUT * drv_usectohz(1000000)));
10155                 if (cv_wait_sig(&mpt->m_cv, &mpt->m_mutex) == 0) {
10156                         /*
10157                          * Quiesce has been interrupted
10158                          */
10159                         mpt->m_softstate &= ~MPTSAS_SS_DRAINING;
10160                         ptgt = (mptsas_target_t *)mptsas_hash_traverse(
10161                             &mpt->m_active->m_tgttbl, MPTSAS_HASH_FIRST);
10162                         while (ptgt != NULL) {
10163                                 mutex_enter(&ptgt->m_tgt_intr_mutex);
10164                                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
10165                                 mutex_exit(&ptgt->m_tgt_intr_mutex);
10166 
10167                                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
10168                                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
10169                         }
10170                         mptsas_restart_hba(mpt);
10171                         if (mpt->m_quiesce_timeid != 0) {
10172                                 timeout_id_t tid = mpt->m_quiesce_timeid;
10173                                 mpt->m_quiesce_timeid = 0;
10174                                 mutex_exit(&mpt->m_mutex);
10175                                 (void) untimeout(tid);
10176                                 return (-1);
10177                         }
10178                         mutex_exit(&mpt->m_mutex);
10179                         return (-1);
10180                 } else {
10181                         /* Bus has been quiesced */
10182                         ASSERT(mpt->m_quiesce_timeid == 0);
10183                         mpt->m_softstate &= ~MPTSAS_SS_DRAINING;
10184                         mpt->m_softstate |= MPTSAS_SS_QUIESCED;
10185                         mutex_exit(&mpt->m_mutex);
10186                         return (0);
10187                 }
10188         }
10189         mutex_exit(&mpt->m_intr_mutex);
10190         /* Bus was not busy - QUIESCED */
10191         mutex_exit(&mpt->m_mutex);
10192 
10193         return (0);
10194 }
10195 
10196 static int
10197 mptsas_unquiesce_bus(mptsas_t *mpt)
10198 {
10199         mptsas_target_t *ptgt = NULL;
10200 
10201         NDBG28(("mptsas_unquiesce_bus"));
10202         mutex_enter(&mpt->m_mutex);
10203         mpt->m_softstate &= ~MPTSAS_SS_QUIESCED;
10204         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
10205             MPTSAS_HASH_FIRST);
10206         while (ptgt != NULL) {
10207                 mutex_enter(&ptgt->m_tgt_intr_mutex);
10208                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
10209                 mutex_exit(&ptgt->m_tgt_intr_mutex);
10210 
10211                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
10212                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
10213         }
10214         mptsas_restart_hba(mpt);
10215         mutex_exit(&mpt->m_mutex);
10216         return (0);
10217 }
10218 
10219 static void
10220 mptsas_ncmds_checkdrain(void *arg)
10221 {
10222         mptsas_t        *mpt = arg;
10223         mptsas_target_t *ptgt = NULL;
10224 
10225         mutex_enter(&mpt->m_mutex);
10226         if (mpt->m_softstate & MPTSAS_SS_DRAINING) {
10227                 mpt->m_quiesce_timeid = 0;
10228                 mutex_enter(&mpt->m_intr_mutex);
10229                 if (mptsas_outstanding_cmds_n(mpt)) {
10230                         mutex_exit(&mpt->m_intr_mutex);
10231                         /*
10232                          * The throttle may have been reset because
10233                          * of a SCSI bus reset
10234                          */
10235                         ptgt = (mptsas_target_t *)mptsas_hash_traverse(
10236                             &mpt->m_active->m_tgttbl, MPTSAS_HASH_FIRST);
10237                         while (ptgt != NULL) {
10238                                 mutex_enter(&ptgt->m_tgt_intr_mutex);
10239                                 mptsas_set_throttle(mpt, ptgt, HOLD_THROTTLE);
10240                                 mutex_exit(&ptgt->m_tgt_intr_mutex);
10241 
10242                                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
10243                                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
10244                         }
10245 
10246                         mpt->m_quiesce_timeid = timeout(mptsas_ncmds_checkdrain,
10247                             mpt, (MPTSAS_QUIESCE_TIMEOUT *
10248                             drv_usectohz(1000000)));
10249                 } else {
10250                         mutex_exit(&mpt->m_intr_mutex);
10251                         /* Command queue has been drained */
10252                         cv_signal(&mpt->m_cv);
10253                 }
10254         }
10255         mutex_exit(&mpt->m_mutex);
10256 }
10257 
10258 /*ARGSUSED*/
10259 static void
10260 mptsas_dump_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
10261 {
10262         int     i;
10263         uint8_t *cp = (uchar_t *)cmd->cmd_pkt->pkt_cdbp;
10264         char    buf[128];
10265 
10266         buf[0] = '\0';
10267         NDBG25(("?Cmd (0x%p) dump for Target %d Lun %d:\n", (void *)cmd,
10268             Tgt(cmd), Lun(cmd)));
10269         (void) sprintf(&buf[0], "\tcdb=[");
10270         for (i = 0; i < (int)cmd->cmd_cdblen; i++) {
10271                 (void) sprintf(&buf[strlen(buf)], " 0x%x", *cp++);
10272         }
10273         (void) sprintf(&buf[strlen(buf)], " ]");
10274         NDBG25(("?%s\n", buf));
10275         NDBG25(("?pkt_flags=0x%x pkt_statistics=0x%x pkt_state=0x%x\n",
10276             cmd->cmd_pkt->pkt_flags, cmd->cmd_pkt->pkt_statistics,
10277             cmd->cmd_pkt->pkt_state));
10278         NDBG25(("?pkt_scbp=0x%x cmd_flags=0x%x\n", cmd->cmd_pkt->pkt_scbp ?
10279             *(cmd->cmd_pkt->pkt_scbp) : 0, cmd->cmd_flags));
10280 }
10281 
10282 static void
10283 mptsas_start_passthru(mptsas_t *mpt, mptsas_cmd_t *cmd)
10284 {
10285         caddr_t                 memp;
10286         pMPI2RequestHeader_t    request_hdrp;
10287         struct scsi_pkt         *pkt = cmd->cmd_pkt;
10288         mptsas_pt_request_t     *pt = pkt->pkt_ha_private;
10289         uint32_t                request_size, data_size, dataout_size;
10290         uint32_t                direction;
10291         ddi_dma_cookie_t        data_cookie;
10292         ddi_dma_cookie_t        dataout_cookie;
10293         uint32_t                request_desc_low, request_desc_high = 0;
10294         uint32_t                i, sense_bufp;
10295         uint8_t                 desc_type;
10296         uint8_t                 *request, function;
10297         ddi_dma_handle_t        dma_hdl = mpt->m_dma_req_frame_hdl;
10298         ddi_acc_handle_t        acc_hdl = mpt->m_acc_req_frame_hdl;
10299 
10300         desc_type = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
10301 
10302         request = pt->request;
10303         direction = pt->direction;
10304         request_size = pt->request_size;
10305         data_size = pt->data_size;
10306         dataout_size = pt->dataout_size;
10307         data_cookie = pt->data_cookie;
10308         dataout_cookie = pt->dataout_cookie;
10309 
10310         /*
10311          * Store the passthrough message in memory location
10312          * corresponding to our slot number
10313          */
10314         memp = mpt->m_req_frame + (mpt->m_req_frame_size * cmd->cmd_slot);
10315         request_hdrp = (pMPI2RequestHeader_t)memp;
10316         bzero(memp, mpt->m_req_frame_size);
10317 
10318         for (i = 0; i < request_size; i++) {
10319                 bcopy(request + i, memp + i, 1);
10320         }
10321 
10322         if (data_size || dataout_size) {
10323                 pMpi2SGESimple64_t      sgep;
10324                 uint32_t                sge_flags;
10325 
10326                 sgep = (pMpi2SGESimple64_t)((uint8_t *)request_hdrp +
10327                     request_size);
10328                 if (dataout_size) {
10329 
10330                         sge_flags = dataout_size |
10331                             ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
10332                             MPI2_SGE_FLAGS_END_OF_BUFFER |
10333                             MPI2_SGE_FLAGS_HOST_TO_IOC |
10334                             MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
10335                             MPI2_SGE_FLAGS_SHIFT);
10336                         ddi_put32(acc_hdl, &sgep->FlagsLength, sge_flags);
10337                         ddi_put32(acc_hdl, &sgep->Address.Low,
10338                             (uint32_t)(dataout_cookie.dmac_laddress &
10339                             0xffffffffull));
10340                         ddi_put32(acc_hdl, &sgep->Address.High,
10341                             (uint32_t)(dataout_cookie.dmac_laddress
10342                             >> 32));
10343                         sgep++;
10344                 }
10345                 sge_flags = data_size;
10346                 sge_flags |= ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
10347                     MPI2_SGE_FLAGS_LAST_ELEMENT |
10348                     MPI2_SGE_FLAGS_END_OF_BUFFER |
10349                     MPI2_SGE_FLAGS_END_OF_LIST |
10350                     MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
10351                     MPI2_SGE_FLAGS_SHIFT);
10352                 if (direction == MPTSAS_PASS_THRU_DIRECTION_WRITE) {
10353                         sge_flags |= ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
10354                             MPI2_SGE_FLAGS_SHIFT);
10355                 } else {
10356                         sge_flags |= ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
10357                             MPI2_SGE_FLAGS_SHIFT);
10358                 }
10359                 ddi_put32(acc_hdl, &sgep->FlagsLength,
10360                     sge_flags);
10361                 ddi_put32(acc_hdl, &sgep->Address.Low,
10362                     (uint32_t)(data_cookie.dmac_laddress &
10363                     0xffffffffull));
10364                 ddi_put32(acc_hdl, &sgep->Address.High,
10365                     (uint32_t)(data_cookie.dmac_laddress >> 32));
10366         }
10367 
10368         function = request_hdrp->Function;
10369         if ((function == MPI2_FUNCTION_SCSI_IO_REQUEST) ||
10370             (function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
10371                 pMpi2SCSIIORequest_t    scsi_io_req;
10372 
10373                 scsi_io_req = (pMpi2SCSIIORequest_t)request_hdrp;
10374                 /*
10375                  * Put SGE for data and data_out buffer at the end of
10376                  * scsi_io_request message header.(64 bytes in total)
10377                  * Following above SGEs, the residual space will be
10378                  * used by sense data.
10379                  */
10380                 ddi_put8(acc_hdl,
10381                     &scsi_io_req->SenseBufferLength,
10382                     (uint8_t)(request_size - 64));
10383 
10384                 sense_bufp = mpt->m_req_frame_dma_addr +
10385                     (mpt->m_req_frame_size * cmd->cmd_slot);
10386                 sense_bufp += 64;
10387                 ddi_put32(acc_hdl,
10388                     &scsi_io_req->SenseBufferLowAddress, sense_bufp);
10389 
10390                 /*
10391                  * Set SGLOffset0 value
10392                  */
10393                 ddi_put8(acc_hdl, &scsi_io_req->SGLOffset0,
10394                     offsetof(MPI2_SCSI_IO_REQUEST, SGL) / 4);
10395 
10396                 /*
10397                  * Setup descriptor info.  RAID passthrough must use the
10398                  * default request descriptor which is already set, so if this
10399                  * is a SCSI IO request, change the descriptor to SCSI IO.
10400                  */
10401                 if (function == MPI2_FUNCTION_SCSI_IO_REQUEST) {
10402                         desc_type = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
10403                         request_desc_high = (ddi_get16(acc_hdl,
10404                             &scsi_io_req->DevHandle) << 16);
10405                 }
10406         }
10407 
10408         /*
10409          * We must wait till the message has been completed before
10410          * beginning the next message so we wait for this one to
10411          * finish.
10412          */
10413         (void) ddi_dma_sync(dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);
10414         request_desc_low = (cmd->cmd_slot << 16) + desc_type;
10415         cmd->cmd_rfm = NULL;
10416         mpt->m_active->m_slot[cmd->cmd_slot] = cmd;
10417         MPTSAS_START_CMD(mpt, request_desc_low, request_desc_high);
10418         if ((mptsas_check_dma_handle(dma_hdl) != DDI_SUCCESS) ||
10419             (mptsas_check_acc_handle(acc_hdl) != DDI_SUCCESS)) {
10420                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
10421         }
10422 }
10423 
10424 
10425 
10426 static int
10427 mptsas_do_passthru(mptsas_t *mpt, uint8_t *request, uint8_t *reply,
10428     uint8_t *data, uint32_t request_size, uint32_t reply_size,
10429     uint32_t data_size, uint32_t direction, uint8_t *dataout,
10430     uint32_t dataout_size, short timeout, int mode)
10431 {
10432         mptsas_pt_request_t             pt;
10433         mptsas_dma_alloc_state_t        data_dma_state;
10434         mptsas_dma_alloc_state_t        dataout_dma_state;
10435         caddr_t                         memp;
10436         mptsas_cmd_t                    *cmd = NULL;
10437         struct scsi_pkt                 *pkt;
10438         uint32_t                        reply_len = 0, sense_len = 0;
10439         pMPI2RequestHeader_t            request_hdrp;
10440         pMPI2RequestHeader_t            request_msg;
10441         pMPI2DefaultReply_t             reply_msg;
10442         Mpi2SCSIIOReply_t               rep_msg;
10443         int                             i, status = 0, pt_flags = 0, rv = 0;
10444         int                             rvalue;
10445         uint8_t                         function;
10446 
10447         ASSERT(mutex_owned(&mpt->m_mutex));
10448 
10449         reply_msg = (pMPI2DefaultReply_t)(&rep_msg);
10450         bzero(reply_msg, sizeof (MPI2_DEFAULT_REPLY));
10451         request_msg = kmem_zalloc(request_size, KM_SLEEP);
10452 
10453         mutex_exit(&mpt->m_mutex);
10454         /*
10455          * copy in the request buffer since it could be used by
10456          * another thread when the pt request into waitq
10457          */
10458         if (ddi_copyin(request, request_msg, request_size, mode)) {
10459                 mutex_enter(&mpt->m_mutex);
10460                 status = EFAULT;
10461                 mptsas_log(mpt, CE_WARN, "failed to copy request data");
10462                 goto out;
10463         }
10464         mutex_enter(&mpt->m_mutex);
10465 
10466         function = request_msg->Function;
10467         if (function == MPI2_FUNCTION_SCSI_TASK_MGMT) {
10468                 pMpi2SCSITaskManagementRequest_t        task;
10469                 task = (pMpi2SCSITaskManagementRequest_t)request_msg;
10470                 mptsas_setup_bus_reset_delay(mpt);
10471                 rv = mptsas_ioc_task_management(mpt, task->TaskType,
10472                     task->DevHandle, (int)task->LUN[1], reply, reply_size,
10473                     mode);
10474 
10475                 if (rv != TRUE) {
10476                         status = EIO;
10477                         mptsas_log(mpt, CE_WARN, "task management failed");
10478                 }
10479                 goto out;
10480         }
10481 
10482         if (data_size != 0) {
10483                 data_dma_state.size = data_size;
10484                 if (mptsas_dma_alloc(mpt, &data_dma_state) != DDI_SUCCESS) {
10485                         status = ENOMEM;
10486                         mptsas_log(mpt, CE_WARN, "failed to alloc DMA "
10487                             "resource");
10488                         goto out;
10489                 }
10490                 pt_flags |= MPTSAS_DATA_ALLOCATED;
10491                 if (direction == MPTSAS_PASS_THRU_DIRECTION_WRITE) {
10492                         mutex_exit(&mpt->m_mutex);
10493                         for (i = 0; i < data_size; i++) {
10494                                 if (ddi_copyin(data + i, (uint8_t *)
10495                                     data_dma_state.memp + i, 1, mode)) {
10496                                         mutex_enter(&mpt->m_mutex);
10497                                         status = EFAULT;
10498                                         mptsas_log(mpt, CE_WARN, "failed to "
10499                                             "copy read data");
10500                                         goto out;
10501                                 }
10502                         }
10503                         mutex_enter(&mpt->m_mutex);
10504                 }
10505         }
10506 
10507         if (dataout_size != 0) {
10508                 dataout_dma_state.size = dataout_size;
10509                 if (mptsas_dma_alloc(mpt, &dataout_dma_state) != DDI_SUCCESS) {
10510                         status = ENOMEM;
10511                         mptsas_log(mpt, CE_WARN, "failed to alloc DMA "
10512                             "resource");
10513                         goto out;
10514                 }
10515                 pt_flags |= MPTSAS_DATAOUT_ALLOCATED;
10516                 mutex_exit(&mpt->m_mutex);
10517                 for (i = 0; i < dataout_size; i++) {
10518                         if (ddi_copyin(dataout + i, (uint8_t *)
10519                             dataout_dma_state.memp + i, 1, mode)) {
10520                                 mutex_enter(&mpt->m_mutex);
10521                                 mptsas_log(mpt, CE_WARN, "failed to copy out"
10522                                     " data");
10523                                 status = EFAULT;
10524                                 goto out;
10525                         }
10526                 }
10527                 mutex_enter(&mpt->m_mutex);
10528         }
10529 
10530         if ((rvalue = (mptsas_request_from_pool(mpt, &cmd, &pkt))) == -1) {
10531                 status = EAGAIN;
10532                 mptsas_log(mpt, CE_NOTE, "event ack command pool is full");
10533                 goto out;
10534         }
10535         pt_flags |= MPTSAS_REQUEST_POOL_CMD;
10536 
10537         bzero((caddr_t)cmd, sizeof (*cmd));
10538         bzero((caddr_t)pkt, scsi_pkt_size());
10539         bzero((caddr_t)&pt, sizeof (pt));
10540 
10541         cmd->ioc_cmd_slot = (uint32_t)(rvalue);
10542 
10543         pt.request = (uint8_t *)request_msg;
10544         pt.direction = direction;
10545         pt.request_size = request_size;
10546         pt.data_size = data_size;
10547         pt.dataout_size = dataout_size;
10548         pt.data_cookie = data_dma_state.cookie;
10549         pt.dataout_cookie = dataout_dma_state.cookie;
10550 
10551         /*
10552          * Form a blank cmd/pkt to store the acknowledgement message
10553          */
10554         pkt->pkt_cdbp                = (opaque_t)&cmd->cmd_cdb[0];
10555         pkt->pkt_scbp                = (opaque_t)&cmd->cmd_scb;
10556         pkt->pkt_ha_private  = (opaque_t)&pt;
10557         pkt->pkt_flags               = FLAG_HEAD;
10558         pkt->pkt_time                = timeout;
10559         cmd->cmd_pkt         = pkt;
10560         cmd->cmd_flags               = CFLAG_CMDIOC | CFLAG_PASSTHRU;
10561 
10562         /*
10563          * Save the command in a slot
10564          */
10565         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
10566                 /*
10567                  * Once passthru command get slot, set cmd_flags
10568                  * CFLAG_PREPARED.
10569                  */
10570                 cmd->cmd_flags |= CFLAG_PREPARED;
10571                 mptsas_start_passthru(mpt, cmd);
10572         } else {
10573                 mptsas_waitq_add(mpt, cmd);
10574         }
10575 
10576         while ((cmd->cmd_flags & CFLAG_FINISHED) == 0) {
10577                 cv_wait(&mpt->m_passthru_cv, &mpt->m_mutex);
10578         }
10579 
10580         if (cmd->cmd_flags & CFLAG_PREPARED) {
10581                 memp = mpt->m_req_frame + (mpt->m_req_frame_size *
10582                     cmd->cmd_slot);
10583                 request_hdrp = (pMPI2RequestHeader_t)memp;
10584         }
10585 
10586         if (cmd->cmd_flags & CFLAG_TIMEOUT) {
10587                 status = ETIMEDOUT;
10588                 mptsas_log(mpt, CE_WARN, "passthrough command timeout");
10589                 pt_flags |= MPTSAS_CMD_TIMEOUT;
10590                 goto out;
10591         }
10592 
10593         if (cmd->cmd_rfm) {
10594                 /*
10595                  * cmd_rfm is zero means the command reply is a CONTEXT
10596                  * reply and no PCI Write to post the free reply SMFA
10597                  * because no reply message frame is used.
10598                  * cmd_rfm is non-zero means the reply is a ADDRESS
10599                  * reply and reply message frame is used.
10600                  */
10601                 pt_flags |= MPTSAS_ADDRESS_REPLY;
10602                 (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
10603                     DDI_DMA_SYNC_FORCPU);
10604                 reply_msg = (pMPI2DefaultReply_t)
10605                     (mpt->m_reply_frame + (cmd->cmd_rfm -
10606                     mpt->m_reply_frame_dma_addr));
10607         }
10608 
10609         mptsas_fma_check(mpt, cmd);
10610         if (pkt->pkt_reason == CMD_TRAN_ERR) {
10611                 status = EAGAIN;
10612                 mptsas_log(mpt, CE_WARN, "passthru fma error");
10613                 goto out;
10614         }
10615         if (pkt->pkt_reason == CMD_RESET) {
10616                 status = EAGAIN;
10617                 mptsas_log(mpt, CE_WARN, "ioc reset abort passthru");
10618                 goto out;
10619         }
10620 
10621         if (pkt->pkt_reason == CMD_INCOMPLETE) {
10622                 status = EIO;
10623                 mptsas_log(mpt, CE_WARN, "passthrough command incomplete");
10624                 goto out;
10625         }
10626 
10627         mutex_exit(&mpt->m_mutex);
10628         if (cmd->cmd_flags & CFLAG_PREPARED) {
10629                 function = request_hdrp->Function;
10630                 if ((function == MPI2_FUNCTION_SCSI_IO_REQUEST) ||
10631                     (function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
10632                         reply_len = sizeof (MPI2_SCSI_IO_REPLY);
10633                         sense_len = reply_size - reply_len;
10634                 } else {
10635                         reply_len = reply_size;
10636                         sense_len = 0;
10637                 }
10638 
10639                 for (i = 0; i < reply_len; i++) {
10640                         if (ddi_copyout((uint8_t *)reply_msg + i, reply + i, 1,
10641                             mode)) {
10642                                 mutex_enter(&mpt->m_mutex);
10643                                 status = EFAULT;
10644                                 mptsas_log(mpt, CE_WARN, "failed to copy out "
10645                                     "reply data");
10646                                 goto out;
10647                         }
10648                 }
10649                 for (i = 0; i < sense_len; i++) {
10650                         if (ddi_copyout((uint8_t *)request_hdrp + 64 + i,
10651                             reply + reply_len + i, 1, mode)) {
10652                                 mutex_enter(&mpt->m_mutex);
10653                                 status = EFAULT;
10654                                 mptsas_log(mpt, CE_WARN, "failed to copy out "
10655                                     "sense data");
10656                                 goto out;
10657                         }
10658                 }
10659         }
10660 
10661         if (data_size) {
10662                 if (direction != MPTSAS_PASS_THRU_DIRECTION_WRITE) {
10663                         (void) ddi_dma_sync(data_dma_state.handle, 0, 0,
10664                             DDI_DMA_SYNC_FORCPU);
10665                         for (i = 0; i < data_size; i++) {
10666                                 if (ddi_copyout((uint8_t *)(
10667                                     data_dma_state.memp + i), data + i,  1,
10668                                     mode)) {
10669                                         mutex_enter(&mpt->m_mutex);
10670                                         status = EFAULT;
10671                                         mptsas_log(mpt, CE_WARN, "failed to "
10672                                             "copy out the reply data");
10673                                         goto out;
10674                                 }
10675                         }
10676                 }
10677         }
10678         mutex_enter(&mpt->m_mutex);
10679 out:
10680         /*
10681          * Put the reply frame back on the free queue, increment the free
10682          * index, and write the new index to the free index register.  But only
10683          * if this reply is an ADDRESS reply.
10684          */
10685         if (pt_flags & MPTSAS_ADDRESS_REPLY) {
10686                 ddi_put32(mpt->m_acc_free_queue_hdl,
10687                     &((uint32_t *)(void *)mpt->m_free_queue)[mpt->m_free_index],
10688                     cmd->cmd_rfm);
10689                 (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
10690                     DDI_DMA_SYNC_FORDEV);
10691                 if (++mpt->m_free_index == mpt->m_free_queue_depth) {
10692                         mpt->m_free_index = 0;
10693                 }
10694                 ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex,
10695                     mpt->m_free_index);
10696         }
10697         if (cmd && (cmd->cmd_flags & CFLAG_PREPARED)) {
10698                 mptsas_remove_cmd(mpt, cmd);
10699                 pt_flags &= (~MPTSAS_REQUEST_POOL_CMD);
10700         }
10701         if (pt_flags & MPTSAS_REQUEST_POOL_CMD)
10702                 mptsas_return_to_pool(mpt, cmd);
10703         if (pt_flags & MPTSAS_DATA_ALLOCATED) {
10704                 if (mptsas_check_dma_handle(data_dma_state.handle) !=
10705                     DDI_SUCCESS) {
10706                         ddi_fm_service_impact(mpt->m_dip,
10707                             DDI_SERVICE_UNAFFECTED);
10708                         status = EFAULT;
10709                 }
10710                 mptsas_dma_free(&data_dma_state);
10711         }
10712         if (pt_flags & MPTSAS_DATAOUT_ALLOCATED) {
10713                 if (mptsas_check_dma_handle(dataout_dma_state.handle) !=
10714                     DDI_SUCCESS) {
10715                         ddi_fm_service_impact(mpt->m_dip,
10716                             DDI_SERVICE_UNAFFECTED);
10717                         status = EFAULT;
10718                 }
10719                 mptsas_dma_free(&dataout_dma_state);
10720         }
10721         if (pt_flags & MPTSAS_CMD_TIMEOUT) {
10722                 if ((mptsas_restart_ioc(mpt)) == DDI_FAILURE) {
10723                         mptsas_log(mpt, CE_WARN, "mptsas_restart_ioc failed");
10724                 }
10725         }
10726         if (request_msg)
10727                 kmem_free(request_msg, request_size);
10728 
10729         return (status);
10730 }
10731 
10732 static int
10733 mptsas_pass_thru(mptsas_t *mpt, mptsas_pass_thru_t *data, int mode)
10734 {
10735         /*
10736          * If timeout is 0, set timeout to default of 60 seconds.
10737          */
10738         if (data->Timeout == 0) {
10739                 data->Timeout = MPTSAS_PASS_THRU_TIME_DEFAULT;
10740         }
10741 
10742         if (((data->DataSize == 0) &&
10743             (data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_NONE)) ||
10744             ((data->DataSize != 0) &&
10745             ((data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_READ) ||
10746             (data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_WRITE) ||
10747             ((data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_BOTH) &&
10748             (data->DataOutSize != 0))))) {
10749                 if (data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_BOTH) {
10750                         data->DataDirection = MPTSAS_PASS_THRU_DIRECTION_READ;
10751                 } else {
10752                         data->DataOutSize = 0;
10753                 }
10754                 /*
10755                  * Send passthru request messages
10756                  */
10757                 return (mptsas_do_passthru(mpt,
10758                     (uint8_t *)((uintptr_t)data->PtrRequest),
10759                     (uint8_t *)((uintptr_t)data->PtrReply),
10760                     (uint8_t *)((uintptr_t)data->PtrData),
10761                     data->RequestSize, data->ReplySize,
10762                     data->DataSize, data->DataDirection,
10763                     (uint8_t *)((uintptr_t)data->PtrDataOut),
10764                     data->DataOutSize, data->Timeout, mode));
10765         } else {
10766                 return (EINVAL);
10767         }
10768 }
10769 
10770 static uint8_t
10771 mptsas_get_fw_diag_buffer_number(mptsas_t *mpt, uint32_t unique_id)
10772 {
10773         uint8_t index;
10774 
10775         for (index = 0; index < MPI2_DIAG_BUF_TYPE_COUNT; index++) {
10776                 if (mpt->m_fw_diag_buffer_list[index].unique_id == unique_id) {
10777                         return (index);
10778                 }
10779         }
10780 
10781         return (MPTSAS_FW_DIAGNOSTIC_UID_NOT_FOUND);
10782 }
10783 
10784 static void
10785 mptsas_start_diag(mptsas_t *mpt, mptsas_cmd_t *cmd)
10786 {
10787         pMpi2DiagBufferPostRequest_t    pDiag_post_msg;
10788         pMpi2DiagReleaseRequest_t       pDiag_release_msg;
10789         struct scsi_pkt                 *pkt = cmd->cmd_pkt;
10790         mptsas_diag_request_t           *diag = pkt->pkt_ha_private;
10791         uint32_t                        request_desc_low, i;
10792 
10793         ASSERT(mutex_owned(&mpt->m_mutex));
10794 
10795         /*
10796          * Form the diag message depending on the post or release function.
10797          */
10798         if (diag->function == MPI2_FUNCTION_DIAG_BUFFER_POST) {
10799                 pDiag_post_msg = (pMpi2DiagBufferPostRequest_t)
10800                     (mpt->m_req_frame + (mpt->m_req_frame_size *
10801                     cmd->cmd_slot));
10802                 bzero(pDiag_post_msg, mpt->m_req_frame_size);
10803                 ddi_put8(mpt->m_acc_req_frame_hdl, &pDiag_post_msg->Function,
10804                     diag->function);
10805                 ddi_put8(mpt->m_acc_req_frame_hdl, &pDiag_post_msg->BufferType,
10806                     diag->pBuffer->buffer_type);
10807                 ddi_put8(mpt->m_acc_req_frame_hdl,
10808                     &pDiag_post_msg->ExtendedType,
10809                     diag->pBuffer->extended_type);
10810                 ddi_put32(mpt->m_acc_req_frame_hdl,
10811                     &pDiag_post_msg->BufferLength,
10812                     diag->pBuffer->buffer_data.size);
10813                 for (i = 0; i < (sizeof (pDiag_post_msg->ProductSpecific) / 4);
10814                     i++) {
10815                         ddi_put32(mpt->m_acc_req_frame_hdl,
10816                             &pDiag_post_msg->ProductSpecific[i],
10817                             diag->pBuffer->product_specific[i]);
10818                 }
10819                 ddi_put32(mpt->m_acc_req_frame_hdl,
10820                     &pDiag_post_msg->BufferAddress.Low,
10821                     (uint32_t)(diag->pBuffer->buffer_data.cookie.dmac_laddress
10822                     & 0xffffffffull));
10823                 ddi_put32(mpt->m_acc_req_frame_hdl,
10824                     &pDiag_post_msg->BufferAddress.High,
10825                     (uint32_t)(diag->pBuffer->buffer_data.cookie.dmac_laddress
10826                     >> 32));
10827         } else {
10828                 pDiag_release_msg = (pMpi2DiagReleaseRequest_t)
10829                     (mpt->m_req_frame + (mpt->m_req_frame_size *
10830                     cmd->cmd_slot));
10831                 bzero(pDiag_release_msg, mpt->m_req_frame_size);
10832                 ddi_put8(mpt->m_acc_req_frame_hdl,
10833                     &pDiag_release_msg->Function, diag->function);
10834                 ddi_put8(mpt->m_acc_req_frame_hdl,
10835                     &pDiag_release_msg->BufferType,
10836                     diag->pBuffer->buffer_type);
10837         }
10838 
10839         /*
10840          * Send the message
10841          */
10842         (void) ddi_dma_sync(mpt->m_dma_req_frame_hdl, 0, 0,
10843             DDI_DMA_SYNC_FORDEV);
10844         request_desc_low = (cmd->cmd_slot << 16) +
10845             MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
10846         cmd->cmd_rfm = NULL;
10847         mpt->m_active->m_slot[cmd->cmd_slot] = cmd;
10848         MPTSAS_START_CMD(mpt, request_desc_low, 0);
10849         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl) !=
10850             DDI_SUCCESS) ||
10851             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl) !=
10852             DDI_SUCCESS)) {
10853                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
10854         }
10855 }
10856 
10857 static int
10858 mptsas_post_fw_diag_buffer(mptsas_t *mpt,
10859     mptsas_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code)
10860 {
10861         mptsas_diag_request_t           diag;
10862         int                             status, slot_num, post_flags = 0;
10863         mptsas_cmd_t                    *cmd = NULL;
10864         struct scsi_pkt                 *pkt;
10865         pMpi2DiagBufferPostReply_t      reply;
10866         uint16_t                        iocstatus;
10867         uint32_t                        iocloginfo, transfer_length;
10868 
10869         /*
10870          * If buffer is not enabled, just leave.
10871          */
10872         *return_code = MPTSAS_FW_DIAG_ERROR_POST_FAILED;
10873         if (!pBuffer->enabled) {
10874                 status = DDI_FAILURE;
10875                 goto out;
10876         }
10877 
10878         /*
10879          * Clear some flags initially.
10880          */
10881         pBuffer->force_release = FALSE;
10882         pBuffer->valid_data = FALSE;
10883         pBuffer->owned_by_firmware = FALSE;
10884 
10885         /*
10886          * Get a cmd buffer from the cmd buffer pool
10887          */
10888         if ((slot_num = (mptsas_request_from_pool(mpt, &cmd, &pkt))) == -1) {
10889                 status = DDI_FAILURE;
10890                 mptsas_log(mpt, CE_NOTE, "command pool is full: Post FW Diag");
10891                 goto out;
10892         }
10893         post_flags |= MPTSAS_REQUEST_POOL_CMD;
10894 
10895         bzero((caddr_t)cmd, sizeof (*cmd));
10896         bzero((caddr_t)pkt, scsi_pkt_size());
10897 
10898         cmd->ioc_cmd_slot = (uint32_t)(slot_num);
10899 
10900         diag.pBuffer = pBuffer;
10901         diag.function = MPI2_FUNCTION_DIAG_BUFFER_POST;
10902 
10903         /*
10904          * Form a blank cmd/pkt to store the acknowledgement message
10905          */
10906         pkt->pkt_ha_private  = (opaque_t)&diag;
10907         pkt->pkt_flags               = FLAG_HEAD;
10908         pkt->pkt_time                = 60;
10909         cmd->cmd_pkt         = pkt;
10910         cmd->cmd_flags               = CFLAG_CMDIOC | CFLAG_FW_DIAG;
10911 
10912         /*
10913          * Save the command in a slot
10914          */
10915         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
10916                 /*
10917                  * Once passthru command get slot, set cmd_flags
10918                  * CFLAG_PREPARED.
10919                  */
10920                 cmd->cmd_flags |= CFLAG_PREPARED;
10921                 mptsas_start_diag(mpt, cmd);
10922         } else {
10923                 mptsas_waitq_add(mpt, cmd);
10924         }
10925 
10926         while ((cmd->cmd_flags & CFLAG_FINISHED) == 0) {
10927                 cv_wait(&mpt->m_fw_diag_cv, &mpt->m_mutex);
10928         }
10929 
10930         if (cmd->cmd_flags & CFLAG_TIMEOUT) {
10931                 status = DDI_FAILURE;
10932                 mptsas_log(mpt, CE_WARN, "Post FW Diag command timeout");
10933                 goto out;
10934         }
10935 
10936         /*
10937          * cmd_rfm points to the reply message if a reply was given.  Check the
10938          * IOCStatus to make sure everything went OK with the FW diag request
10939          * and set buffer flags.
10940          */
10941         if (cmd->cmd_rfm) {
10942                 post_flags |= MPTSAS_ADDRESS_REPLY;
10943                 (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
10944                     DDI_DMA_SYNC_FORCPU);
10945                 reply = (pMpi2DiagBufferPostReply_t)(mpt->m_reply_frame +
10946                     (cmd->cmd_rfm - mpt->m_reply_frame_dma_addr));
10947 
10948                 /*
10949                  * Get the reply message data
10950                  */
10951                 iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
10952                     &reply->IOCStatus);
10953                 iocloginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
10954                     &reply->IOCLogInfo);
10955                 transfer_length = ddi_get32(mpt->m_acc_reply_frame_hdl,
10956                     &reply->TransferLength);
10957 
10958                 /*
10959                  * If post failed quit.
10960                  */
10961                 if (iocstatus != MPI2_IOCSTATUS_SUCCESS) {
10962                         status = DDI_FAILURE;
10963                         NDBG13(("post FW Diag Buffer failed: IOCStatus=0x%x, "
10964                             "IOCLogInfo=0x%x, TransferLength=0x%x", iocstatus,
10965                             iocloginfo, transfer_length));
10966                         goto out;
10967                 }
10968 
10969                 /*
10970                  * Post was successful.
10971                  */
10972                 pBuffer->valid_data = TRUE;
10973                 pBuffer->owned_by_firmware = TRUE;
10974                 *return_code = MPTSAS_FW_DIAG_ERROR_SUCCESS;
10975                 status = DDI_SUCCESS;
10976         }
10977 
10978 out:
10979         /*
10980          * Put the reply frame back on the free queue, increment the free
10981          * index, and write the new index to the free index register.  But only
10982          * if this reply is an ADDRESS reply.
10983          */
10984         if (post_flags & MPTSAS_ADDRESS_REPLY) {
10985                 ddi_put32(mpt->m_acc_free_queue_hdl,
10986                     &((uint32_t *)(void *)mpt->m_free_queue)[mpt->m_free_index],
10987                     cmd->cmd_rfm);
10988                 (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
10989                     DDI_DMA_SYNC_FORDEV);
10990                 if (++mpt->m_free_index == mpt->m_free_queue_depth) {
10991                         mpt->m_free_index = 0;
10992                 }
10993                 ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex,
10994                     mpt->m_free_index);
10995         }
10996         if (cmd && (cmd->cmd_flags & CFLAG_PREPARED)) {
10997                 mptsas_remove_cmd(mpt, cmd);
10998                 post_flags &= (~MPTSAS_REQUEST_POOL_CMD);
10999         }
11000         if (post_flags & MPTSAS_REQUEST_POOL_CMD) {
11001                 mptsas_return_to_pool(mpt, cmd);
11002         }
11003 
11004         return (status);
11005 }
11006 
11007 static int
11008 mptsas_release_fw_diag_buffer(mptsas_t *mpt,
11009     mptsas_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code,
11010     uint32_t diag_type)
11011 {
11012         mptsas_diag_request_t   diag;
11013         int                     status, slot_num, rel_flags = 0;
11014         mptsas_cmd_t            *cmd = NULL;
11015         struct scsi_pkt         *pkt;
11016         pMpi2DiagReleaseReply_t reply;
11017         uint16_t                iocstatus;
11018         uint32_t                iocloginfo;
11019 
11020         /*
11021          * If buffer is not enabled, just leave.
11022          */
11023         *return_code = MPTSAS_FW_DIAG_ERROR_RELEASE_FAILED;
11024         if (!pBuffer->enabled) {
11025                 mptsas_log(mpt, CE_NOTE, "This buffer type is not supported "
11026                     "by the IOC");
11027                 status = DDI_FAILURE;
11028                 goto out;
11029         }
11030 
11031         /*
11032          * Clear some flags initially.
11033          */
11034         pBuffer->force_release = FALSE;
11035         pBuffer->valid_data = FALSE;
11036         pBuffer->owned_by_firmware = FALSE;
11037 
11038         /*
11039          * Get a cmd buffer from the cmd buffer pool
11040          */
11041         if ((slot_num = (mptsas_request_from_pool(mpt, &cmd, &pkt))) == -1) {
11042                 status = DDI_FAILURE;
11043                 mptsas_log(mpt, CE_NOTE, "command pool is full: Release FW "
11044                     "Diag");
11045                 goto out;
11046         }
11047         rel_flags |= MPTSAS_REQUEST_POOL_CMD;
11048 
11049         bzero((caddr_t)cmd, sizeof (*cmd));
11050         bzero((caddr_t)pkt, scsi_pkt_size());
11051 
11052         cmd->ioc_cmd_slot = (uint32_t)(slot_num);
11053 
11054         diag.pBuffer = pBuffer;
11055         diag.function = MPI2_FUNCTION_DIAG_RELEASE;
11056 
11057         /*
11058          * Form a blank cmd/pkt to store the acknowledgement message
11059          */
11060         pkt->pkt_ha_private  = (opaque_t)&diag;
11061         pkt->pkt_flags               = FLAG_HEAD;
11062         pkt->pkt_time                = 60;
11063         cmd->cmd_pkt         = pkt;
11064         cmd->cmd_flags               = CFLAG_CMDIOC | CFLAG_FW_DIAG;
11065 
11066         /*
11067          * Save the command in a slot
11068          */
11069         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
11070                 /*
11071                  * Once passthru command get slot, set cmd_flags
11072                  * CFLAG_PREPARED.
11073                  */
11074                 cmd->cmd_flags |= CFLAG_PREPARED;
11075                 mptsas_start_diag(mpt, cmd);
11076         } else {
11077                 mptsas_waitq_add(mpt, cmd);
11078         }
11079 
11080         while ((cmd->cmd_flags & CFLAG_FINISHED) == 0) {
11081                 cv_wait(&mpt->m_fw_diag_cv, &mpt->m_mutex);
11082         }
11083 
11084         if (cmd->cmd_flags & CFLAG_TIMEOUT) {
11085                 status = DDI_FAILURE;
11086                 mptsas_log(mpt, CE_WARN, "Release FW Diag command timeout");
11087                 goto out;
11088         }
11089 
11090         /*
11091          * cmd_rfm points to the reply message if a reply was given.  Check the
11092          * IOCStatus to make sure everything went OK with the FW diag request
11093          * and set buffer flags.
11094          */
11095         if (cmd->cmd_rfm) {
11096                 rel_flags |= MPTSAS_ADDRESS_REPLY;
11097                 (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
11098                     DDI_DMA_SYNC_FORCPU);
11099                 reply = (pMpi2DiagReleaseReply_t)(mpt->m_reply_frame +
11100                     (cmd->cmd_rfm - mpt->m_reply_frame_dma_addr));
11101 
11102                 /*
11103                  * Get the reply message data
11104                  */
11105                 iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
11106                     &reply->IOCStatus);
11107                 iocloginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
11108                     &reply->IOCLogInfo);
11109 
11110                 /*
11111                  * If release failed quit.
11112                  */
11113                 if ((iocstatus != MPI2_IOCSTATUS_SUCCESS) ||
11114                     pBuffer->owned_by_firmware) {
11115                         status = DDI_FAILURE;
11116                         NDBG13(("release FW Diag Buffer failed: "
11117                             "IOCStatus=0x%x, IOCLogInfo=0x%x", iocstatus,
11118                             iocloginfo));
11119                         goto out;
11120                 }
11121 
11122                 /*
11123                  * Release was successful.
11124                  */
11125                 *return_code = MPTSAS_FW_DIAG_ERROR_SUCCESS;
11126                 status = DDI_SUCCESS;
11127 
11128                 /*
11129                  * If this was for an UNREGISTER diag type command, clear the
11130                  * unique ID.
11131                  */
11132                 if (diag_type == MPTSAS_FW_DIAG_TYPE_UNREGISTER) {
11133                         pBuffer->unique_id = MPTSAS_FW_DIAG_INVALID_UID;
11134                 }
11135         }
11136 
11137 out:
11138         /*
11139          * Put the reply frame back on the free queue, increment the free
11140          * index, and write the new index to the free index register.  But only
11141          * if this reply is an ADDRESS reply.
11142          */
11143         if (rel_flags & MPTSAS_ADDRESS_REPLY) {
11144                 ddi_put32(mpt->m_acc_free_queue_hdl,
11145                     &((uint32_t *)(void *)mpt->m_free_queue)[mpt->m_free_index],
11146                     cmd->cmd_rfm);
11147                 (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
11148                     DDI_DMA_SYNC_FORDEV);
11149                 if (++mpt->m_free_index == mpt->m_free_queue_depth) {
11150                         mpt->m_free_index = 0;
11151                 }
11152                 ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex,
11153                     mpt->m_free_index);
11154         }
11155         if (cmd && (cmd->cmd_flags & CFLAG_PREPARED)) {
11156                 mptsas_remove_cmd(mpt, cmd);
11157                 rel_flags &= (~MPTSAS_REQUEST_POOL_CMD);
11158         }
11159         if (rel_flags & MPTSAS_REQUEST_POOL_CMD) {
11160                 mptsas_return_to_pool(mpt, cmd);
11161         }
11162 
11163         return (status);
11164 }
11165 
11166 static int
11167 mptsas_diag_register(mptsas_t *mpt, mptsas_fw_diag_register_t *diag_register,
11168     uint32_t *return_code)
11169 {
11170         mptsas_fw_diagnostic_buffer_t   *pBuffer;
11171         uint8_t                         extended_type, buffer_type, i;
11172         uint32_t                        buffer_size;
11173         uint32_t                        unique_id;
11174         int                             status;
11175 
11176         ASSERT(mutex_owned(&mpt->m_mutex));
11177 
11178         extended_type = diag_register->ExtendedType;
11179         buffer_type = diag_register->BufferType;
11180         buffer_size = diag_register->RequestedBufferSize;
11181         unique_id = diag_register->UniqueId;
11182 
11183         /*
11184          * Check for valid buffer type
11185          */
11186         if (buffer_type >= MPI2_DIAG_BUF_TYPE_COUNT) {
11187                 *return_code = MPTSAS_FW_DIAG_ERROR_INVALID_PARAMETER;
11188                 return (DDI_FAILURE);
11189         }
11190 
11191         /*
11192          * Get the current buffer and look up the unique ID.  The unique ID
11193          * should not be found.  If it is, the ID is already in use.
11194          */
11195         i = mptsas_get_fw_diag_buffer_number(mpt, unique_id);
11196         pBuffer = &mpt->m_fw_diag_buffer_list[buffer_type];
11197         if (i != MPTSAS_FW_DIAGNOSTIC_UID_NOT_FOUND) {
11198                 *return_code = MPTSAS_FW_DIAG_ERROR_INVALID_UID;
11199                 return (DDI_FAILURE);
11200         }
11201 
11202         /*
11203          * The buffer's unique ID should not be registered yet, and the given
11204          * unique ID cannot be 0.
11205          */
11206         if ((pBuffer->unique_id != MPTSAS_FW_DIAG_INVALID_UID) ||
11207             (unique_id == MPTSAS_FW_DIAG_INVALID_UID)) {
11208                 *return_code = MPTSAS_FW_DIAG_ERROR_INVALID_UID;
11209                 return (DDI_FAILURE);
11210         }
11211 
11212         /*
11213          * If this buffer is already posted as immediate, just change owner.
11214          */
11215         if (pBuffer->immediate && pBuffer->owned_by_firmware &&
11216             (pBuffer->unique_id == MPTSAS_FW_DIAG_INVALID_UID)) {
11217                 pBuffer->immediate = FALSE;
11218                 pBuffer->unique_id = unique_id;
11219                 return (DDI_SUCCESS);
11220         }
11221 
11222         /*
11223          * Post a new buffer after checking if it's enabled.  The DMA buffer
11224          * that is allocated will be contiguous (sgl_len = 1).
11225          */
11226         if (!pBuffer->enabled) {
11227                 *return_code = MPTSAS_FW_DIAG_ERROR_NO_BUFFER;
11228                 return (DDI_FAILURE);
11229         }
11230         bzero(&pBuffer->buffer_data, sizeof (mptsas_dma_alloc_state_t));
11231         pBuffer->buffer_data.size = buffer_size;
11232         if (mptsas_dma_alloc(mpt, &pBuffer->buffer_data) != DDI_SUCCESS) {
11233                 mptsas_log(mpt, CE_WARN, "failed to alloc DMA resource for "
11234                     "diag buffer: size = %d bytes", buffer_size);
11235                 *return_code = MPTSAS_FW_DIAG_ERROR_NO_BUFFER;
11236                 return (DDI_FAILURE);
11237         }
11238 
11239         /*
11240          * Copy the given info to the diag buffer and post the buffer.
11241          */
11242         pBuffer->buffer_type = buffer_type;
11243         pBuffer->immediate = FALSE;
11244         if (buffer_type == MPI2_DIAG_BUF_TYPE_TRACE) {
11245                 for (i = 0; i < (sizeof (pBuffer->product_specific) / 4);
11246                     i++) {
11247                         pBuffer->product_specific[i] =
11248                             diag_register->ProductSpecific[i];
11249                 }
11250         }
11251         pBuffer->extended_type = extended_type;
11252         pBuffer->unique_id = unique_id;
11253         status = mptsas_post_fw_diag_buffer(mpt, pBuffer, return_code);
11254 
11255         if (mptsas_check_dma_handle(pBuffer->buffer_data.handle) !=
11256             DDI_SUCCESS) {
11257                 mptsas_log(mpt, CE_WARN, "Check of DMA handle failed in "
11258                     "mptsas_diag_register.");
11259                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
11260                         status = DDI_FAILURE;
11261         }
11262 
11263         /*
11264          * In case there was a failure, free the DMA buffer.
11265          */
11266         if (status == DDI_FAILURE) {
11267                 mptsas_dma_free(&pBuffer->buffer_data);
11268         }
11269 
11270         return (status);
11271 }
11272 
11273 static int
11274 mptsas_diag_unregister(mptsas_t *mpt,
11275     mptsas_fw_diag_unregister_t *diag_unregister, uint32_t *return_code)
11276 {
11277         mptsas_fw_diagnostic_buffer_t   *pBuffer;
11278         uint8_t                         i;
11279         uint32_t                        unique_id;
11280         int                             status;
11281 
11282         ASSERT(mutex_owned(&mpt->m_mutex));
11283 
11284         unique_id = diag_unregister->UniqueId;
11285 
11286         /*
11287          * Get the current buffer and look up the unique ID.  The unique ID
11288          * should be there.
11289          */
11290         i = mptsas_get_fw_diag_buffer_number(mpt, unique_id);
11291         if (i == MPTSAS_FW_DIAGNOSTIC_UID_NOT_FOUND) {
11292                 *return_code = MPTSAS_FW_DIAG_ERROR_INVALID_UID;
11293                 return (DDI_FAILURE);
11294         }
11295 
11296         pBuffer = &mpt->m_fw_diag_buffer_list[i];
11297 
11298         /*
11299          * Try to release the buffer from FW before freeing it.  If release
11300          * fails, don't free the DMA buffer in case FW tries to access it
11301          * later.  If buffer is not owned by firmware, can't release it.
11302          */
11303         if (!pBuffer->owned_by_firmware) {
11304                 status = DDI_SUCCESS;
11305         } else {
11306                 status = mptsas_release_fw_diag_buffer(mpt, pBuffer,
11307                     return_code, MPTSAS_FW_DIAG_TYPE_UNREGISTER);
11308         }
11309 
11310         /*
11311          * At this point, return the current status no matter what happens with
11312          * the DMA buffer.
11313          */
11314         pBuffer->unique_id = MPTSAS_FW_DIAG_INVALID_UID;
11315         if (status == DDI_SUCCESS) {
11316                 if (mptsas_check_dma_handle(pBuffer->buffer_data.handle) !=
11317                     DDI_SUCCESS) {
11318                         mptsas_log(mpt, CE_WARN, "Check of DMA handle failed "
11319                             "in mptsas_diag_unregister.");
11320                         ddi_fm_service_impact(mpt->m_dip,
11321                             DDI_SERVICE_UNAFFECTED);
11322                 }
11323                 mptsas_dma_free(&pBuffer->buffer_data);
11324         }
11325 
11326         return (status);
11327 }
11328 
11329 static int
11330 mptsas_diag_query(mptsas_t *mpt, mptsas_fw_diag_query_t *diag_query,
11331     uint32_t *return_code)
11332 {
11333         mptsas_fw_diagnostic_buffer_t   *pBuffer;
11334         uint8_t                         i;
11335         uint32_t                        unique_id;
11336 
11337         ASSERT(mutex_owned(&mpt->m_mutex));
11338 
11339         unique_id = diag_query->UniqueId;
11340 
11341         /*
11342          * If ID is valid, query on ID.
11343          * If ID is invalid, query on buffer type.
11344          */
11345         if (unique_id == MPTSAS_FW_DIAG_INVALID_UID) {
11346                 i = diag_query->BufferType;
11347                 if (i >= MPI2_DIAG_BUF_TYPE_COUNT) {
11348                         *return_code = MPTSAS_FW_DIAG_ERROR_INVALID_UID;
11349                         return (DDI_FAILURE);
11350                 }
11351         } else {
11352                 i = mptsas_get_fw_diag_buffer_number(mpt, unique_id);
11353                 if (i == MPTSAS_FW_DIAGNOSTIC_UID_NOT_FOUND) {
11354                         *return_code = MPTSAS_FW_DIAG_ERROR_INVALID_UID;
11355                         return (DDI_FAILURE);
11356                 }
11357         }
11358 
11359         /*
11360          * Fill query structure with the diag buffer info.
11361          */
11362         pBuffer = &mpt->m_fw_diag_buffer_list[i];
11363         diag_query->BufferType = pBuffer->buffer_type;
11364         diag_query->ExtendedType = pBuffer->extended_type;
11365         if (diag_query->BufferType == MPI2_DIAG_BUF_TYPE_TRACE) {
11366                 for (i = 0; i < (sizeof (diag_query->ProductSpecific) / 4);
11367                     i++) {
11368                         diag_query->ProductSpecific[i] =
11369                             pBuffer->product_specific[i];
11370                 }
11371         }
11372         diag_query->TotalBufferSize = pBuffer->buffer_data.size;
11373         diag_query->DriverAddedBufferSize = 0;
11374         diag_query->UniqueId = pBuffer->unique_id;
11375         diag_query->ApplicationFlags = 0;
11376         diag_query->DiagnosticFlags = 0;
11377 
11378         /*
11379          * Set/Clear application flags
11380          */
11381         if (pBuffer->immediate) {
11382                 diag_query->ApplicationFlags &= ~MPTSAS_FW_DIAG_FLAG_APP_OWNED;
11383         } else {
11384                 diag_query->ApplicationFlags |= MPTSAS_FW_DIAG_FLAG_APP_OWNED;
11385         }
11386         if (pBuffer->valid_data || pBuffer->owned_by_firmware) {
11387                 diag_query->ApplicationFlags |=
11388                     MPTSAS_FW_DIAG_FLAG_BUFFER_VALID;
11389         } else {
11390                 diag_query->ApplicationFlags &=
11391                     ~MPTSAS_FW_DIAG_FLAG_BUFFER_VALID;
11392         }
11393         if (pBuffer->owned_by_firmware) {
11394                 diag_query->ApplicationFlags |=
11395                     MPTSAS_FW_DIAG_FLAG_FW_BUFFER_ACCESS;
11396         } else {
11397                 diag_query->ApplicationFlags &=
11398                     ~MPTSAS_FW_DIAG_FLAG_FW_BUFFER_ACCESS;
11399         }
11400 
11401         return (DDI_SUCCESS);
11402 }
11403 
11404 static int
11405 mptsas_diag_read_buffer(mptsas_t *mpt,
11406     mptsas_diag_read_buffer_t *diag_read_buffer, uint8_t *ioctl_buf,
11407     uint32_t *return_code, int ioctl_mode)
11408 {
11409         mptsas_fw_diagnostic_buffer_t   *pBuffer;
11410         uint8_t                         i, *pData;
11411         uint32_t                        unique_id, byte;
11412         int                             status;
11413 
11414         ASSERT(mutex_owned(&mpt->m_mutex));
11415 
11416         unique_id = diag_read_buffer->UniqueId;
11417 
11418         /*
11419          * Get the current buffer and look up the unique ID.  The unique ID
11420          * should be there.
11421          */
11422         i = mptsas_get_fw_diag_buffer_number(mpt, unique_id);
11423         if (i == MPTSAS_FW_DIAGNOSTIC_UID_NOT_FOUND) {
11424                 *return_code = MPTSAS_FW_DIAG_ERROR_INVALID_UID;
11425                 return (DDI_FAILURE);
11426         }
11427 
11428         pBuffer = &mpt->m_fw_diag_buffer_list[i];
11429 
11430         /*
11431          * Make sure requested read is within limits
11432          */
11433         if (diag_read_buffer->StartingOffset + diag_read_buffer->BytesToRead >
11434             pBuffer->buffer_data.size) {
11435                 *return_code = MPTSAS_FW_DIAG_ERROR_INVALID_PARAMETER;
11436                 return (DDI_FAILURE);
11437         }
11438 
11439         /*
11440          * Copy the requested data from DMA to the diag_read_buffer.  The DMA
11441          * buffer that was allocated is one contiguous buffer.
11442          */
11443         pData = (uint8_t *)(pBuffer->buffer_data.memp +
11444             diag_read_buffer->StartingOffset);
11445         (void) ddi_dma_sync(pBuffer->buffer_data.handle, 0, 0,
11446             DDI_DMA_SYNC_FORCPU);
11447         for (byte = 0; byte < diag_read_buffer->BytesToRead; byte++) {
11448                 if (ddi_copyout(pData + byte, ioctl_buf + byte, 1, ioctl_mode)
11449                     != 0) {
11450                         return (DDI_FAILURE);
11451                 }
11452         }
11453         diag_read_buffer->Status = 0;
11454 
11455         /*
11456          * Set or clear the Force Release flag.
11457          */
11458         if (pBuffer->force_release) {
11459                 diag_read_buffer->Flags |= MPTSAS_FW_DIAG_FLAG_FORCE_RELEASE;
11460         } else {
11461                 diag_read_buffer->Flags &= ~MPTSAS_FW_DIAG_FLAG_FORCE_RELEASE;
11462         }
11463 
11464         /*
11465          * If buffer is to be reregistered, make sure it's not already owned by
11466          * firmware first.
11467          */
11468         status = DDI_SUCCESS;
11469         if (!pBuffer->owned_by_firmware) {
11470                 if (diag_read_buffer->Flags & MPTSAS_FW_DIAG_FLAG_REREGISTER) {
11471                         status = mptsas_post_fw_diag_buffer(mpt, pBuffer,
11472                             return_code);
11473                 }
11474         }
11475 
11476         return (status);
11477 }
11478 
11479 static int
11480 mptsas_diag_release(mptsas_t *mpt, mptsas_fw_diag_release_t *diag_release,
11481     uint32_t *return_code)
11482 {
11483         mptsas_fw_diagnostic_buffer_t   *pBuffer;
11484         uint8_t                         i;
11485         uint32_t                        unique_id;
11486         int                             status;
11487 
11488         ASSERT(mutex_owned(&mpt->m_mutex));
11489 
11490         unique_id = diag_release->UniqueId;
11491 
11492         /*
11493          * Get the current buffer and look up the unique ID.  The unique ID
11494          * should be there.
11495          */
11496         i = mptsas_get_fw_diag_buffer_number(mpt, unique_id);
11497         if (i == MPTSAS_FW_DIAGNOSTIC_UID_NOT_FOUND) {
11498                 *return_code = MPTSAS_FW_DIAG_ERROR_INVALID_UID;
11499                 return (DDI_FAILURE);
11500         }
11501 
11502         pBuffer = &mpt->m_fw_diag_buffer_list[i];
11503 
11504         /*
11505          * If buffer is not owned by firmware, it's already been released.
11506          */
11507         if (!pBuffer->owned_by_firmware) {
11508                 *return_code = MPTSAS_FW_DIAG_ERROR_ALREADY_RELEASED;
11509                 return (DDI_FAILURE);
11510         }
11511 
11512         /*
11513          * Release the buffer.
11514          */
11515         status = mptsas_release_fw_diag_buffer(mpt, pBuffer, return_code,
11516             MPTSAS_FW_DIAG_TYPE_RELEASE);
11517         return (status);
11518 }
11519 
11520 static int
11521 mptsas_do_diag_action(mptsas_t *mpt, uint32_t action, uint8_t *diag_action,
11522     uint32_t length, uint32_t *return_code, int ioctl_mode)
11523 {
11524         mptsas_fw_diag_register_t       diag_register;
11525         mptsas_fw_diag_unregister_t     diag_unregister;
11526         mptsas_fw_diag_query_t          diag_query;
11527         mptsas_diag_read_buffer_t       diag_read_buffer;
11528         mptsas_fw_diag_release_t        diag_release;
11529         int                             status = DDI_SUCCESS;
11530         uint32_t                        original_return_code, read_buf_len;
11531 
11532         ASSERT(mutex_owned(&mpt->m_mutex));
11533 
11534         original_return_code = *return_code;
11535         *return_code = MPTSAS_FW_DIAG_ERROR_SUCCESS;
11536 
11537         switch (action) {
11538                 case MPTSAS_FW_DIAG_TYPE_REGISTER:
11539                         if (!length) {
11540                                 *return_code =
11541                                     MPTSAS_FW_DIAG_ERROR_INVALID_PARAMETER;
11542                                 status = DDI_FAILURE;
11543                                 break;
11544                         }
11545                         if (ddi_copyin(diag_action, &diag_register,
11546                             sizeof (diag_register), ioctl_mode) != 0) {
11547                                 return (DDI_FAILURE);
11548                         }
11549                         status = mptsas_diag_register(mpt, &diag_register,
11550                             return_code);
11551                         break;
11552 
11553                 case MPTSAS_FW_DIAG_TYPE_UNREGISTER:
11554                         if (length < sizeof (diag_unregister)) {
11555                                 *return_code =
11556                                     MPTSAS_FW_DIAG_ERROR_INVALID_PARAMETER;
11557                                 status = DDI_FAILURE;
11558                                 break;
11559                         }
11560                         if (ddi_copyin(diag_action, &diag_unregister,
11561                             sizeof (diag_unregister), ioctl_mode) != 0) {
11562                                 return (DDI_FAILURE);
11563                         }
11564                         status = mptsas_diag_unregister(mpt, &diag_unregister,
11565                             return_code);
11566                         break;
11567 
11568                 case MPTSAS_FW_DIAG_TYPE_QUERY:
11569                         if (length < sizeof (diag_query)) {
11570                                 *return_code =
11571                                     MPTSAS_FW_DIAG_ERROR_INVALID_PARAMETER;
11572                                 status = DDI_FAILURE;
11573                                 break;
11574                         }
11575                         if (ddi_copyin(diag_action, &diag_query,
11576                             sizeof (diag_query), ioctl_mode) != 0) {
11577                                 return (DDI_FAILURE);
11578                         }
11579                         status = mptsas_diag_query(mpt, &diag_query,
11580                             return_code);
11581                         if (status == DDI_SUCCESS) {
11582                                 if (ddi_copyout(&diag_query, diag_action,
11583                                     sizeof (diag_query), ioctl_mode) != 0) {
11584                                         return (DDI_FAILURE);
11585                                 }
11586                         }
11587                         break;
11588 
11589                 case MPTSAS_FW_DIAG_TYPE_READ_BUFFER:
11590                         if (ddi_copyin(diag_action, &diag_read_buffer,
11591                             sizeof (diag_read_buffer) - 4, ioctl_mode) != 0) {
11592                                 return (DDI_FAILURE);
11593                         }
11594                         read_buf_len = sizeof (diag_read_buffer) -
11595                             sizeof (diag_read_buffer.DataBuffer) +
11596                             diag_read_buffer.BytesToRead;
11597                         if (length < read_buf_len) {
11598                                 *return_code =
11599                                     MPTSAS_FW_DIAG_ERROR_INVALID_PARAMETER;
11600                                 status = DDI_FAILURE;
11601                                 break;
11602                         }
11603                         status = mptsas_diag_read_buffer(mpt,
11604                             &diag_read_buffer, diag_action +
11605                             sizeof (diag_read_buffer) - 4, return_code,
11606                             ioctl_mode);
11607                         if (status == DDI_SUCCESS) {
11608                                 if (ddi_copyout(&diag_read_buffer, diag_action,
11609                                     sizeof (diag_read_buffer) - 4, ioctl_mode)
11610                                     != 0) {
11611                                         return (DDI_FAILURE);
11612                                 }
11613                         }
11614                         break;
11615 
11616                 case MPTSAS_FW_DIAG_TYPE_RELEASE:
11617                         if (length < sizeof (diag_release)) {
11618                                 *return_code =
11619                                     MPTSAS_FW_DIAG_ERROR_INVALID_PARAMETER;
11620                                 status = DDI_FAILURE;
11621                                 break;
11622                         }
11623                         if (ddi_copyin(diag_action, &diag_release,
11624                             sizeof (diag_release), ioctl_mode) != 0) {
11625                                 return (DDI_FAILURE);
11626                         }
11627                         status = mptsas_diag_release(mpt, &diag_release,
11628                             return_code);
11629                         break;
11630 
11631                 default:
11632                         *return_code = MPTSAS_FW_DIAG_ERROR_INVALID_PARAMETER;
11633                         status = DDI_FAILURE;
11634                         break;
11635         }
11636 
11637         if ((status == DDI_FAILURE) &&
11638             (original_return_code == MPTSAS_FW_DIAG_NEW) &&
11639             (*return_code != MPTSAS_FW_DIAG_ERROR_SUCCESS)) {
11640                 status = DDI_SUCCESS;
11641         }
11642 
11643         return (status);
11644 }
11645 
11646 static int
11647 mptsas_diag_action(mptsas_t *mpt, mptsas_diag_action_t *user_data, int mode)
11648 {
11649         int                     status;
11650         mptsas_diag_action_t    driver_data;
11651 
11652         ASSERT(mutex_owned(&mpt->m_mutex));
11653 
11654         /*
11655          * Copy the user data to a driver data buffer.
11656          */
11657         if (ddi_copyin(user_data, &driver_data, sizeof (mptsas_diag_action_t),
11658             mode) == 0) {
11659                 /*
11660                  * Send diag action request if Action is valid
11661                  */
11662                 if (driver_data.Action == MPTSAS_FW_DIAG_TYPE_REGISTER ||
11663                     driver_data.Action == MPTSAS_FW_DIAG_TYPE_UNREGISTER ||
11664                     driver_data.Action == MPTSAS_FW_DIAG_TYPE_QUERY ||
11665                     driver_data.Action == MPTSAS_FW_DIAG_TYPE_READ_BUFFER ||
11666                     driver_data.Action == MPTSAS_FW_DIAG_TYPE_RELEASE) {
11667                         status = mptsas_do_diag_action(mpt, driver_data.Action,
11668                             (void *)(uintptr_t)driver_data.PtrDiagAction,
11669                             driver_data.Length, &driver_data.ReturnCode,
11670                             mode);
11671                         if (status == DDI_SUCCESS) {
11672                                 if (ddi_copyout(&driver_data.ReturnCode,
11673                                     &user_data->ReturnCode,
11674                                     sizeof (user_data->ReturnCode), mode)
11675                                     != 0) {
11676                                         status = EFAULT;
11677                                 } else {
11678                                         status = 0;
11679                                 }
11680                         } else {
11681                                 status = EIO;
11682                         }
11683                 } else {
11684                         status = EINVAL;
11685                 }
11686         } else {
11687                 status = EFAULT;
11688         }
11689 
11690         return (status);
11691 }
11692 
11693 /*
11694  * This routine handles the "event query" ioctl.
11695  */
11696 static int
11697 mptsas_event_query(mptsas_t *mpt, mptsas_event_query_t *data, int mode,
11698     int *rval)
11699 {
11700         int                     status;
11701         mptsas_event_query_t    driverdata;
11702         uint8_t                 i;
11703 
11704         driverdata.Entries = MPTSAS_EVENT_QUEUE_SIZE;
11705 
11706         mutex_enter(&mpt->m_mutex);
11707         for (i = 0; i < 4; i++) {
11708                 driverdata.Types[i] = mpt->m_event_mask[i];
11709         }
11710         mutex_exit(&mpt->m_mutex);
11711 
11712         if (ddi_copyout(&driverdata, data, sizeof (driverdata), mode) != 0) {
11713                 status = EFAULT;
11714         } else {
11715                 *rval = MPTIOCTL_STATUS_GOOD;
11716                 status = 0;
11717         }
11718 
11719         return (status);
11720 }
11721 
11722 /*
11723  * This routine handles the "event enable" ioctl.
11724  */
11725 static int
11726 mptsas_event_enable(mptsas_t *mpt, mptsas_event_enable_t *data, int mode,
11727     int *rval)
11728 {
11729         int                     status;
11730         mptsas_event_enable_t   driverdata;
11731         uint8_t                 i;
11732 
11733         if (ddi_copyin(data, &driverdata, sizeof (driverdata), mode) == 0) {
11734                 mutex_enter(&mpt->m_mutex);
11735                 for (i = 0; i < 4; i++) {
11736                         mpt->m_event_mask[i] = driverdata.Types[i];
11737                 }
11738                 mutex_exit(&mpt->m_mutex);
11739 
11740                 *rval = MPTIOCTL_STATUS_GOOD;
11741                 status = 0;
11742         } else {
11743                 status = EFAULT;
11744         }
11745         return (status);
11746 }
11747 
11748 /*
11749  * This routine handles the "event report" ioctl.
11750  */
11751 static int
11752 mptsas_event_report(mptsas_t *mpt, mptsas_event_report_t *data, int mode,
11753     int *rval)
11754 {
11755         int                     status;
11756         mptsas_event_report_t   driverdata;
11757 
11758         mutex_enter(&mpt->m_mutex);
11759 
11760         if (ddi_copyin(&data->Size, &driverdata.Size, sizeof (driverdata.Size),
11761             mode) == 0) {
11762                 if (driverdata.Size >= sizeof (mpt->m_events)) {
11763                         if (ddi_copyout(mpt->m_events, data->Events,
11764                             sizeof (mpt->m_events), mode) != 0) {
11765                                 status = EFAULT;
11766                         } else {
11767                                 if (driverdata.Size > sizeof (mpt->m_events)) {
11768                                         driverdata.Size =
11769                                             sizeof (mpt->m_events);
11770                                         if (ddi_copyout(&driverdata.Size,
11771                                             &data->Size,
11772                                             sizeof (driverdata.Size),
11773                                             mode) != 0) {
11774                                                 status = EFAULT;
11775                                         } else {
11776                                                 *rval = MPTIOCTL_STATUS_GOOD;
11777                                                 status = 0;
11778                                         }
11779                                 } else {
11780                                         *rval = MPTIOCTL_STATUS_GOOD;
11781                                         status = 0;
11782                                 }
11783                         }
11784                 } else {
11785                         *rval = MPTIOCTL_STATUS_LEN_TOO_SHORT;
11786                         status = 0;
11787                 }
11788         } else {
11789                 status = EFAULT;
11790         }
11791 
11792         mutex_exit(&mpt->m_mutex);
11793         return (status);
11794 }
11795 
11796 static void
11797 mptsas_lookup_pci_data(mptsas_t *mpt, mptsas_adapter_data_t *adapter_data)
11798 {
11799         int     *reg_data;
11800         uint_t  reglen;
11801 
11802         /*
11803          * Lookup the 'reg' property and extract the other data
11804          */
11805         if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, mpt->m_dip,
11806             DDI_PROP_DONTPASS, "reg", &reg_data, &reglen) ==
11807             DDI_PROP_SUCCESS) {
11808                 /*
11809                  * Extract the PCI data from the 'reg' property first DWORD.
11810                  * The entry looks like the following:
11811                  * First DWORD:
11812                  * Bits 0 - 7 8-bit Register number
11813                  * Bits 8 - 10 3-bit Function number
11814                  * Bits 11 - 15 5-bit Device number
11815                  * Bits 16 - 23 8-bit Bus number
11816                  * Bits 24 - 25 2-bit Address Space type identifier
11817                  *
11818                  */
11819                 adapter_data->PciInformation.u.bits.BusNumber =
11820                     (reg_data[0] & 0x00FF0000) >> 16;
11821                 adapter_data->PciInformation.u.bits.DeviceNumber =
11822                     (reg_data[0] & 0x0000F800) >> 11;
11823                 adapter_data->PciInformation.u.bits.FunctionNumber =
11824                     (reg_data[0] & 0x00000700) >> 8;
11825                 ddi_prop_free((void *)reg_data);
11826         } else {
11827                 /*
11828                  * If we can't determine the PCI data then we fill in FF's for
11829                  * the data to indicate this.
11830                  */
11831                 adapter_data->PCIDeviceHwId = 0xFFFFFFFF;
11832                 adapter_data->MpiPortNumber = 0xFFFFFFFF;
11833                 adapter_data->PciInformation.u.AsDWORD = 0xFFFFFFFF;
11834         }
11835 
11836         /*
11837          * Saved in the mpt->m_fwversion
11838          */
11839         adapter_data->MpiFirmwareVersion = mpt->m_fwversion;
11840 }
11841 
11842 static void
11843 mptsas_read_adapter_data(mptsas_t *mpt, mptsas_adapter_data_t *adapter_data)
11844 {
11845         char    *driver_verstr = MPTSAS_MOD_STRING;
11846 
11847         mptsas_lookup_pci_data(mpt, adapter_data);
11848         adapter_data->AdapterType = MPTIOCTL_ADAPTER_TYPE_SAS2;
11849         adapter_data->PCIDeviceHwId = (uint32_t)mpt->m_devid;
11850         adapter_data->PCIDeviceHwRev = (uint32_t)mpt->m_revid;
11851         adapter_data->SubSystemId = (uint32_t)mpt->m_ssid;
11852         adapter_data->SubsystemVendorId = (uint32_t)mpt->m_svid;
11853         (void) strcpy((char *)&adapter_data->DriverVersion[0], driver_verstr);
11854         adapter_data->BiosVersion = 0;
11855         (void) mptsas_get_bios_page3(mpt, &adapter_data->BiosVersion);
11856 }
11857 
11858 static void
11859 mptsas_read_pci_info(mptsas_t *mpt, mptsas_pci_info_t *pci_info)
11860 {
11861         int     *reg_data, i;
11862         uint_t  reglen;
11863 
11864         /*
11865          * Lookup the 'reg' property and extract the other data
11866          */
11867         if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, mpt->m_dip,
11868             DDI_PROP_DONTPASS, "reg", &reg_data, &reglen) ==
11869             DDI_PROP_SUCCESS) {
11870                 /*
11871                  * Extract the PCI data from the 'reg' property first DWORD.
11872                  * The entry looks like the following:
11873                  * First DWORD:
11874                  * Bits 8 - 10 3-bit Function number
11875                  * Bits 11 - 15 5-bit Device number
11876                  * Bits 16 - 23 8-bit Bus number
11877                  */
11878                 pci_info->BusNumber = (reg_data[0] & 0x00FF0000) >> 16;
11879                 pci_info->DeviceNumber = (reg_data[0] & 0x0000F800) >> 11;
11880                 pci_info->FunctionNumber = (reg_data[0] & 0x00000700) >> 8;
11881                 ddi_prop_free((void *)reg_data);
11882         } else {
11883                 /*
11884                  * If we can't determine the PCI info then we fill in FF's for
11885                  * the data to indicate this.
11886                  */
11887                 pci_info->BusNumber = 0xFFFFFFFF;
11888                 pci_info->DeviceNumber = 0xFF;
11889                 pci_info->FunctionNumber = 0xFF;
11890         }
11891 
11892         /*
11893          * Now get the interrupt vector and the pci header.  The vector can
11894          * only be 0 right now.  The header is the first 256 bytes of config
11895          * space.
11896          */
11897         pci_info->InterruptVector = 0;
11898         for (i = 0; i < sizeof (pci_info->PciHeader); i++) {
11899                 pci_info->PciHeader[i] = pci_config_get8(mpt->m_config_handle,
11900                     i);
11901         }
11902 }
11903 
11904 static int
11905 mptsas_reg_access(mptsas_t *mpt, mptsas_reg_access_t *data, int mode)
11906 {
11907         int                     status = 0;
11908         mptsas_reg_access_t     driverdata;
11909 
11910         mutex_enter(&mpt->m_mutex);
11911         if (ddi_copyin(data, &driverdata, sizeof (driverdata), mode) == 0) {
11912                 switch (driverdata.Command) {
11913                         /*
11914                          * IO access is not supported.
11915                          */
11916                         case REG_IO_READ:
11917                         case REG_IO_WRITE:
11918                                 mptsas_log(mpt, CE_WARN, "IO access is not "
11919                                     "supported.  Use memory access.");
11920                                 status = EINVAL;
11921                                 break;
11922 
11923                         case REG_MEM_READ:
11924                                 driverdata.RegData = ddi_get32(mpt->m_datap,
11925                                     (uint32_t *)(void *)mpt->m_reg +
11926                                     driverdata.RegOffset);
11927                                 if (ddi_copyout(&driverdata.RegData,
11928                                     &data->RegData,
11929                                     sizeof (driverdata.RegData), mode) != 0) {
11930                                         mptsas_log(mpt, CE_WARN, "Register "
11931                                             "Read Failed");
11932                                         status = EFAULT;
11933                                 }
11934                                 break;
11935 
11936                         case REG_MEM_WRITE:
11937                                 ddi_put32(mpt->m_datap,
11938                                     (uint32_t *)(void *)mpt->m_reg +
11939                                     driverdata.RegOffset,
11940                                     driverdata.RegData);
11941                                 break;
11942 
11943                         default:
11944                                 status = EINVAL;
11945                                 break;
11946                 }
11947         } else {
11948                 status = EFAULT;
11949         }
11950 
11951         mutex_exit(&mpt->m_mutex);
11952         return (status);
11953 }
11954 
11955 static int
11956 get_disk_info(mptsas_t *mpt, intptr_t data, int mode)
11957 {
11958         int i = 0;
11959         int count = 0;
11960         int ret = 0;
11961         mptsas_target_t *ptgt;
11962         mptsas_disk_info_t *di;
11963         STRUCT_DECL(mptsas_get_disk_info, gdi);
11964 
11965         STRUCT_INIT(gdi, get_udatamodel());
11966 
11967         if (ddi_copyin((void *)data, STRUCT_BUF(gdi), STRUCT_SIZE(gdi),
11968             mode) != 0) {
11969                 return (EFAULT);
11970         }
11971 
11972         /* Find out how many targets there are. */
11973         mutex_enter(&mpt->m_mutex);
11974         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
11975             MPTSAS_HASH_FIRST);
11976         while (ptgt != NULL) {
11977                 count++;
11978                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
11979                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
11980         }
11981         mutex_exit(&mpt->m_mutex);
11982 
11983         /*
11984          * If we haven't been asked to copy out information on each target,
11985          * then just return the count.
11986          */
11987         STRUCT_FSET(gdi, DiskCount, count);
11988         if (STRUCT_FGETP(gdi, PtrDiskInfoArray) == NULL)
11989                 goto copy_out;
11990 
11991         /*
11992          * If we haven't been given a large enough buffer to copy out into,
11993          * let the caller know.
11994          */
11995         if (STRUCT_FGET(gdi, DiskInfoArraySize) <
11996             count * sizeof (mptsas_disk_info_t)) {
11997                 ret = ENOSPC;
11998                 goto copy_out;
11999         }
12000 
12001         di = kmem_zalloc(count * sizeof (mptsas_disk_info_t), KM_SLEEP);
12002 
12003         mutex_enter(&mpt->m_mutex);
12004         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
12005             MPTSAS_HASH_FIRST);
12006         while (ptgt != NULL) {
12007                 if (i >= count) {
12008                         /*
12009                          * The number of targets changed while we weren't
12010                          * looking, so give up.
12011                          */
12012                         mutex_exit(&mpt->m_mutex);
12013                         kmem_free(di, count * sizeof (mptsas_disk_info_t));
12014                         return (EAGAIN);
12015                 }
12016                 di[i].Instance = mpt->m_instance;
12017                 di[i].Enclosure = ptgt->m_enclosure;
12018                 di[i].Slot = ptgt->m_slot_num;
12019                 di[i].SasAddress = ptgt->m_sas_wwn;
12020 
12021                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
12022                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
12023                 i++;
12024         }
12025         mutex_exit(&mpt->m_mutex);
12026         STRUCT_FSET(gdi, DiskCount, i);
12027 
12028         /* Copy out the disk information to the caller. */
12029         if (ddi_copyout((void *)di, STRUCT_FGETP(gdi, PtrDiskInfoArray),
12030             i * sizeof (mptsas_disk_info_t), mode) != 0) {
12031                 ret = EFAULT;
12032         }
12033 
12034         kmem_free(di, count * sizeof (mptsas_disk_info_t));
12035 
12036 copy_out:
12037         if (ddi_copyout(STRUCT_BUF(gdi), (void *)data, STRUCT_SIZE(gdi),
12038             mode) != 0) {
12039                 ret = EFAULT;
12040         }
12041 
12042         return (ret);
12043 }
12044 
12045 static int
12046 mptsas_ioctl(dev_t dev, int cmd, intptr_t data, int mode, cred_t *credp,
12047     int *rval)
12048 {
12049         int                     status = 0;
12050         mptsas_t                *mpt;
12051         mptsas_update_flash_t   flashdata;
12052         mptsas_pass_thru_t      passthru_data;
12053         mptsas_adapter_data_t   adapter_data;
12054         mptsas_pci_info_t       pci_info;
12055         int                     copylen;
12056 
12057         int                     iport_flag = 0;
12058         dev_info_t              *dip = NULL;
12059         mptsas_phymask_t        phymask = 0;
12060         struct devctl_iocdata   *dcp = NULL;
12061         uint32_t                slotstatus = 0;
12062         char                    *addr = NULL;
12063         mptsas_target_t         *ptgt = NULL;
12064 
12065         *rval = MPTIOCTL_STATUS_GOOD;
12066         if (secpolicy_sys_config(credp, B_FALSE) != 0) {
12067                 return (EPERM);
12068         }
12069 
12070         mpt = ddi_get_soft_state(mptsas_state, MINOR2INST(getminor(dev)));
12071         if (mpt == NULL) {
12072                 /*
12073                  * Called from iport node, get the states
12074                  */
12075                 iport_flag = 1;
12076                 dip = mptsas_get_dip_from_dev(dev, &phymask);
12077                 if (dip == NULL) {
12078                         return (ENXIO);
12079                 }
12080                 mpt = DIP2MPT(dip);
12081         }
12082         /* Make sure power level is D0 before accessing registers */
12083         mutex_enter(&mpt->m_mutex);
12084         if (mpt->m_options & MPTSAS_OPT_PM) {
12085                 (void) pm_busy_component(mpt->m_dip, 0);
12086                 if (mpt->m_power_level != PM_LEVEL_D0) {
12087                         mutex_exit(&mpt->m_mutex);
12088                         if (pm_raise_power(mpt->m_dip, 0, PM_LEVEL_D0) !=
12089                             DDI_SUCCESS) {
12090                                 mptsas_log(mpt, CE_WARN,
12091                                     "mptsas%d: mptsas_ioctl: Raise power "
12092                                     "request failed.", mpt->m_instance);
12093                                 (void) pm_idle_component(mpt->m_dip, 0);
12094                                 return (ENXIO);
12095                         }
12096                 } else {
12097                         mutex_exit(&mpt->m_mutex);
12098                 }
12099         } else {
12100                 mutex_exit(&mpt->m_mutex);
12101         }
12102 
12103         if (iport_flag) {
12104                 status = scsi_hba_ioctl(dev, cmd, data, mode, credp, rval);
12105                 if (status != 0) {
12106                         goto out;
12107                 }
12108                 /*
12109                  * The following code control the OK2RM LED, it doesn't affect
12110                  * the ioctl return status.
12111                  */
12112                 if ((cmd == DEVCTL_DEVICE_ONLINE) ||
12113                     (cmd == DEVCTL_DEVICE_OFFLINE)) {
12114                         if (ndi_dc_allochdl((void *)data, &dcp) !=
12115                             NDI_SUCCESS) {
12116                                 goto out;
12117                         }
12118                         addr = ndi_dc_getaddr(dcp);
12119                         ptgt = mptsas_addr_to_ptgt(mpt, addr, phymask);
12120                         if (ptgt == NULL) {
12121                                 NDBG14(("mptsas_ioctl led control: tgt %s not "
12122                                     "found", addr));
12123                                 ndi_dc_freehdl(dcp);
12124                                 goto out;
12125                         }
12126                         mutex_enter(&mpt->m_mutex);
12127                         if (cmd == DEVCTL_DEVICE_ONLINE) {
12128                                 ptgt->m_tgt_unconfigured = 0;
12129                         } else if (cmd == DEVCTL_DEVICE_OFFLINE) {
12130                                 ptgt->m_tgt_unconfigured = 1;
12131                         }
12132                         slotstatus = 0;
12133 #ifdef MPTSAS_GET_LED
12134                         /*
12135                          * The get led status can't get a valid/reasonable
12136                          * state, so ignore the get led status, and write the
12137                          * required value directly
12138                          */
12139                         if (mptsas_get_led_status(mpt, ptgt, &slotstatus) !=
12140                             DDI_SUCCESS) {
12141                                 NDBG14(("mptsas_ioctl: get LED for tgt %s "
12142                                     "failed %x", addr, slotstatus));
12143                                 slotstatus = 0;
12144                         }
12145                         NDBG14(("mptsas_ioctl: LED status %x for %s",
12146                             slotstatus, addr));
12147 #endif
12148                         if (cmd == DEVCTL_DEVICE_OFFLINE) {
12149                                 slotstatus |=
12150                                     MPI2_SEP_REQ_SLOTSTATUS_REQUEST_REMOVE;
12151                         } else {
12152                                 slotstatus &=
12153                                     ~MPI2_SEP_REQ_SLOTSTATUS_REQUEST_REMOVE;
12154                         }
12155                         if (mptsas_set_led_status(mpt, ptgt, slotstatus) !=
12156                             DDI_SUCCESS) {
12157                                 NDBG14(("mptsas_ioctl: set LED for tgt %s "
12158                                     "failed %x", addr, slotstatus));
12159                         }
12160                         mutex_exit(&mpt->m_mutex);
12161                         ndi_dc_freehdl(dcp);
12162                 }
12163                 goto out;
12164         }
12165         switch (cmd) {
12166                 case MPTIOCTL_GET_DISK_INFO:
12167                         status = get_disk_info(mpt, data, mode);
12168                         break;
12169                 case MPTIOCTL_UPDATE_FLASH:
12170                         if (ddi_copyin((void *)data, &flashdata,
12171                                 sizeof (struct mptsas_update_flash), mode)) {
12172                                 status = EFAULT;
12173                                 break;
12174                         }
12175 
12176                         mutex_enter(&mpt->m_mutex);
12177                         if (mptsas_update_flash(mpt,
12178                             (caddr_t)(long)flashdata.PtrBuffer,
12179                             flashdata.ImageSize, flashdata.ImageType, mode)) {
12180                                 status = EFAULT;
12181                         }
12182 
12183                         /*
12184                          * Reset the chip to start using the new
12185                          * firmware.  Reset if failed also.
12186                          */
12187                         mpt->m_softstate &= ~MPTSAS_SS_MSG_UNIT_RESET;
12188                         if (mptsas_restart_ioc(mpt) == DDI_FAILURE) {
12189                                 status = EFAULT;
12190                         }
12191                         mutex_exit(&mpt->m_mutex);
12192                         break;
12193                 case MPTIOCTL_PASS_THRU:
12194                         /*
12195                          * The user has requested to pass through a command to
12196                          * be executed by the MPT firmware.  Call our routine
12197                          * which does this.  Only allow one passthru IOCTL at
12198                          * one time. Other threads will block on
12199                          * m_passthru_mutex, which is of adaptive variant.
12200                          */
12201                         if (ddi_copyin((void *)data, &passthru_data,
12202                             sizeof (mptsas_pass_thru_t), mode)) {
12203                                 status = EFAULT;
12204                                 break;
12205                         }
12206                         mutex_enter(&mpt->m_passthru_mutex);
12207                         mutex_enter(&mpt->m_mutex);
12208                         status = mptsas_pass_thru(mpt, &passthru_data, mode);
12209                         mutex_exit(&mpt->m_mutex);
12210                         mutex_exit(&mpt->m_passthru_mutex);
12211 
12212                         break;
12213                 case MPTIOCTL_GET_ADAPTER_DATA:
12214                         /*
12215                          * The user has requested to read adapter data.  Call
12216                          * our routine which does this.
12217                          */
12218                         bzero(&adapter_data, sizeof (mptsas_adapter_data_t));
12219                         if (ddi_copyin((void *)data, (void *)&adapter_data,
12220                             sizeof (mptsas_adapter_data_t), mode)) {
12221                                 status = EFAULT;
12222                                 break;
12223                         }
12224                         if (adapter_data.StructureLength >=
12225                             sizeof (mptsas_adapter_data_t)) {
12226                                 adapter_data.StructureLength = (uint32_t)
12227                                     sizeof (mptsas_adapter_data_t);
12228                                 copylen = sizeof (mptsas_adapter_data_t);
12229                                 mutex_enter(&mpt->m_mutex);
12230                                 mptsas_read_adapter_data(mpt, &adapter_data);
12231                                 mutex_exit(&mpt->m_mutex);
12232                         } else {
12233                                 adapter_data.StructureLength = (uint32_t)
12234                                     sizeof (mptsas_adapter_data_t);
12235                                 copylen = sizeof (adapter_data.StructureLength);
12236                                 *rval = MPTIOCTL_STATUS_LEN_TOO_SHORT;
12237                         }
12238                         if (ddi_copyout((void *)(&adapter_data), (void *)data,
12239                             copylen, mode) != 0) {
12240                                 status = EFAULT;
12241                         }
12242                         break;
12243                 case MPTIOCTL_GET_PCI_INFO:
12244                         /*
12245                          * The user has requested to read pci info.  Call
12246                          * our routine which does this.
12247                          */
12248                         bzero(&pci_info, sizeof (mptsas_pci_info_t));
12249                         mutex_enter(&mpt->m_mutex);
12250                         mptsas_read_pci_info(mpt, &pci_info);
12251                         mutex_exit(&mpt->m_mutex);
12252                         if (ddi_copyout((void *)(&pci_info), (void *)data,
12253                             sizeof (mptsas_pci_info_t), mode) != 0) {
12254                                 status = EFAULT;
12255                         }
12256                         break;
12257                 case MPTIOCTL_RESET_ADAPTER:
12258                         mutex_enter(&mpt->m_mutex);
12259                         mpt->m_softstate &= ~MPTSAS_SS_MSG_UNIT_RESET;
12260                         if ((mptsas_restart_ioc(mpt)) == DDI_FAILURE) {
12261                                 mptsas_log(mpt, CE_WARN, "reset adapter IOCTL "
12262                                     "failed");
12263                                 status = EFAULT;
12264                         }
12265                         mutex_exit(&mpt->m_mutex);
12266                         break;
12267                 case MPTIOCTL_DIAG_ACTION:
12268                         /*
12269                          * The user has done a diag buffer action.  Call our
12270                          * routine which does this.  Only allow one diag action
12271                          * at one time.
12272                          */
12273                         mutex_enter(&mpt->m_mutex);
12274                         if (mpt->m_diag_action_in_progress) {
12275                                 mutex_exit(&mpt->m_mutex);
12276                                 return (EBUSY);
12277                         }
12278                         mpt->m_diag_action_in_progress = 1;
12279                         status = mptsas_diag_action(mpt,
12280                             (mptsas_diag_action_t *)data, mode);
12281                         mpt->m_diag_action_in_progress = 0;
12282                         mutex_exit(&mpt->m_mutex);
12283                         break;
12284                 case MPTIOCTL_EVENT_QUERY:
12285                         /*
12286                          * The user has done an event query. Call our routine
12287                          * which does this.
12288                          */
12289                         status = mptsas_event_query(mpt,
12290                             (mptsas_event_query_t *)data, mode, rval);
12291                         break;
12292                 case MPTIOCTL_EVENT_ENABLE:
12293                         /*
12294                          * The user has done an event enable. Call our routine
12295                          * which does this.
12296                          */
12297                         status = mptsas_event_enable(mpt,
12298                             (mptsas_event_enable_t *)data, mode, rval);
12299                         break;
12300                 case MPTIOCTL_EVENT_REPORT:
12301                         /*
12302                          * The user has done an event report. Call our routine
12303                          * which does this.
12304                          */
12305                         status = mptsas_event_report(mpt,
12306                             (mptsas_event_report_t *)data, mode, rval);
12307                         break;
12308                 case MPTIOCTL_REG_ACCESS:
12309                         /*
12310                          * The user has requested register access.  Call our
12311                          * routine which does this.
12312                          */
12313                         status = mptsas_reg_access(mpt,
12314                             (mptsas_reg_access_t *)data, mode);
12315                         break;
12316                 default:
12317                         status = scsi_hba_ioctl(dev, cmd, data, mode, credp,
12318                             rval);
12319                         break;
12320         }
12321 
12322 out:
12323         if (mpt->m_options & MPTSAS_OPT_PM)
12324                 (void) pm_idle_component(mpt->m_dip, 0);
12325         return (status);
12326 }
12327 
12328 int
12329 mptsas_restart_ioc(mptsas_t *mpt)
12330 {
12331         int             rval = DDI_SUCCESS;
12332         mptsas_target_t *ptgt = NULL;
12333 
12334         ASSERT(mutex_owned(&mpt->m_mutex));
12335 
12336         /*
12337          * Set a flag telling I/O path that we're processing a reset.  This is
12338          * needed because after the reset is complete, the hash table still
12339          * needs to be rebuilt.  If I/Os are started before the hash table is
12340          * rebuilt, I/O errors will occur.  This flag allows I/Os to be marked
12341          * so that they can be retried.
12342          */
12343         mpt->m_in_reset = TRUE;
12344 
12345         /*
12346          * Set all throttles to HOLD
12347          */
12348         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
12349             MPTSAS_HASH_FIRST);
12350         while (ptgt != NULL) {
12351                 mutex_enter(&ptgt->m_tgt_intr_mutex);
12352                 mptsas_set_throttle(mpt, ptgt, HOLD_THROTTLE);
12353                 mutex_exit(&ptgt->m_tgt_intr_mutex);
12354 
12355                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
12356                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
12357         }
12358 
12359         /*
12360          * Disable interrupts
12361          */
12362         MPTSAS_DISABLE_INTR(mpt);
12363 
12364         /*
12365          * Abort all commands: outstanding commands, commands in waitq
12366          */
12367         mptsas_flush_hba(mpt);
12368 
12369         /*
12370          * Reinitialize the chip.
12371          */
12372         if (mptsas_init_chip(mpt, FALSE) == DDI_FAILURE) {
12373                 rval = DDI_FAILURE;
12374         }
12375 
12376         /*
12377          * Enable interrupts again
12378          */
12379         MPTSAS_ENABLE_INTR(mpt);
12380 
12381         /*
12382          * If mptsas_init_chip was successful, update the driver data.
12383          */
12384         if (rval == DDI_SUCCESS) {
12385                 mptsas_update_driver_data(mpt);
12386         }
12387 
12388         /*
12389          * Reset the throttles
12390          */
12391         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
12392             MPTSAS_HASH_FIRST);
12393         while (ptgt != NULL) {
12394                 mutex_enter(&ptgt->m_tgt_intr_mutex);
12395                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
12396                 mutex_exit(&ptgt->m_tgt_intr_mutex);
12397 
12398                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
12399                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
12400         }
12401 
12402         mptsas_doneq_empty(mpt);
12403         mptsas_restart_hba(mpt);
12404 
12405         if (rval != DDI_SUCCESS) {
12406                 mptsas_fm_ereport(mpt, DDI_FM_DEVICE_NO_RESPONSE);
12407                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_LOST);
12408         }
12409 
12410         /*
12411          * Clear the reset flag so that I/Os can continue.
12412          */
12413         mpt->m_in_reset = FALSE;
12414 
12415         return (rval);
12416 }
12417 
12418 static int
12419 mptsas_init_chip(mptsas_t *mpt, int first_time)
12420 {
12421         ddi_dma_cookie_t        cookie;
12422         uint32_t                i;
12423         int                     rval;
12424 
12425         /*
12426          * Check to see if the firmware image is valid
12427          */
12428         if (ddi_get32(mpt->m_datap, &mpt->m_reg->HostDiagnostic) &
12429             MPI2_DIAG_FLASH_BAD_SIG) {
12430                 mptsas_log(mpt, CE_WARN, "mptsas bad flash signature!");
12431                 goto fail;
12432         }
12433 
12434         /*
12435          * Reset the chip
12436          */
12437         rval = mptsas_ioc_reset(mpt, first_time);
12438         if (rval == MPTSAS_RESET_FAIL) {
12439                 mptsas_log(mpt, CE_WARN, "hard reset failed!");
12440                 goto fail;
12441         }
12442 
12443         if ((rval == MPTSAS_SUCCESS_MUR) && (!first_time)) {
12444                 goto mur;
12445         }
12446         /*
12447          * Setup configuration space
12448          */
12449         if (mptsas_config_space_init(mpt) == FALSE) {
12450                 mptsas_log(mpt, CE_WARN, "mptsas_config_space_init "
12451                     "failed!");
12452                 goto fail;
12453         }
12454 
12455         /*
12456          * IOC facts can change after a diag reset so all buffers that are
12457          * based on these numbers must be de-allocated and re-allocated.  Get
12458          * new IOC facts each time chip is initialized.
12459          */
12460         if (mptsas_ioc_get_facts(mpt) == DDI_FAILURE) {
12461                 mptsas_log(mpt, CE_WARN, "mptsas_ioc_get_facts failed");
12462                 goto fail;
12463         }
12464 
12465         if (mptsas_alloc_active_slots(mpt, KM_SLEEP)) {
12466                 goto fail;
12467         }
12468         /*
12469          * Allocate request message frames, reply free queue, reply descriptor
12470          * post queue, and reply message frames using latest IOC facts.
12471          */
12472         if (mptsas_alloc_request_frames(mpt) == DDI_FAILURE) {
12473                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_request_frames failed");
12474                 goto fail;
12475         }
12476         if (mptsas_alloc_free_queue(mpt) == DDI_FAILURE) {
12477                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_free_queue failed!");
12478                 goto fail;
12479         }
12480         if (mptsas_alloc_post_queue(mpt) == DDI_FAILURE) {
12481                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_post_queue failed!");
12482                 goto fail;
12483         }
12484         if (mptsas_alloc_reply_frames(mpt) == DDI_FAILURE) {
12485                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_reply_frames failed!");
12486                 goto fail;
12487         }
12488 
12489 mur:
12490         /*
12491          * Re-Initialize ioc to operational state
12492          */
12493         if (mptsas_ioc_init(mpt) == DDI_FAILURE) {
12494                 mptsas_log(mpt, CE_WARN, "mptsas_ioc_init failed");
12495                 goto fail;
12496         }
12497 
12498         mptsas_alloc_reply_args(mpt);
12499 
12500         /*
12501          * Initialize reply post index.  Reply free index is initialized after
12502          * the next loop.
12503          */
12504         mpt->m_post_index = 0;
12505 
12506         /*
12507          * Initialize the Reply Free Queue with the physical addresses of our
12508          * reply frames.
12509          */
12510         cookie.dmac_address = mpt->m_reply_frame_dma_addr;
12511         for (i = 0; i < mpt->m_max_replies; i++) {
12512                 ddi_put32(mpt->m_acc_free_queue_hdl,
12513                     &((uint32_t *)(void *)mpt->m_free_queue)[i],
12514                     cookie.dmac_address);
12515                 cookie.dmac_address += mpt->m_reply_frame_size;
12516         }
12517         (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
12518             DDI_DMA_SYNC_FORDEV);
12519 
12520         /*
12521          * Initialize the reply free index to one past the last frame on the
12522          * queue.  This will signify that the queue is empty to start with.
12523          */
12524         mpt->m_free_index = i;
12525         ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex, i);
12526 
12527         /*
12528          * Initialize the reply post queue to 0xFFFFFFFF,0xFFFFFFFF's.
12529          */
12530         for (i = 0; i < mpt->m_post_queue_depth; i++) {
12531                 ddi_put64(mpt->m_acc_post_queue_hdl,
12532                     &((uint64_t *)(void *)mpt->m_post_queue)[i],
12533                     0xFFFFFFFFFFFFFFFF);
12534         }
12535         (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
12536             DDI_DMA_SYNC_FORDEV);
12537 
12538         /*
12539          * Enable ports
12540          */
12541         if (mptsas_ioc_enable_port(mpt) == DDI_FAILURE) {
12542                 mptsas_log(mpt, CE_WARN, "mptsas_ioc_enable_port failed");
12543                 goto fail;
12544         }
12545 
12546         /*
12547          * enable events
12548          */
12549         if (mptsas_ioc_enable_event_notification(mpt)) {
12550                 goto fail;
12551         }
12552 
12553         /*
12554          * We need checks in attach and these.
12555          * chip_init is called in mult. places
12556          */
12557 
12558         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl) !=
12559             DDI_SUCCESS) ||
12560             (mptsas_check_dma_handle(mpt->m_dma_reply_frame_hdl) !=
12561             DDI_SUCCESS) ||
12562             (mptsas_check_dma_handle(mpt->m_dma_free_queue_hdl) !=
12563             DDI_SUCCESS) ||
12564             (mptsas_check_dma_handle(mpt->m_dma_post_queue_hdl) !=
12565             DDI_SUCCESS) ||
12566             (mptsas_check_dma_handle(mpt->m_hshk_dma_hdl) !=
12567             DDI_SUCCESS)) {
12568                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
12569                 goto fail;
12570         }
12571 
12572         /* Check all acc handles */
12573         if ((mptsas_check_acc_handle(mpt->m_datap) != DDI_SUCCESS) ||
12574             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl) !=
12575             DDI_SUCCESS) ||
12576             (mptsas_check_acc_handle(mpt->m_acc_reply_frame_hdl) !=
12577             DDI_SUCCESS) ||
12578             (mptsas_check_acc_handle(mpt->m_acc_free_queue_hdl) !=
12579             DDI_SUCCESS) ||
12580             (mptsas_check_acc_handle(mpt->m_acc_post_queue_hdl) !=
12581             DDI_SUCCESS) ||
12582             (mptsas_check_acc_handle(mpt->m_hshk_acc_hdl) !=
12583             DDI_SUCCESS) ||
12584             (mptsas_check_acc_handle(mpt->m_config_handle) !=
12585             DDI_SUCCESS)) {
12586                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
12587                 goto fail;
12588         }
12589 
12590         return (DDI_SUCCESS);
12591 
12592 fail:
12593         return (DDI_FAILURE);
12594 }
12595 
12596 static int
12597 mptsas_get_pci_cap(mptsas_t *mpt)
12598 {
12599         ushort_t caps_ptr, cap, cap_count;
12600 
12601         if (mpt->m_config_handle == NULL)
12602                 return (FALSE);
12603         /*
12604          * Check if capabilities list is supported and if so,
12605          * get initial capabilities pointer and clear bits 0,1.
12606          */
12607         if (pci_config_get16(mpt->m_config_handle, PCI_CONF_STAT)
12608             & PCI_STAT_CAP) {
12609                 caps_ptr = P2ALIGN(pci_config_get8(mpt->m_config_handle,
12610                     PCI_CONF_CAP_PTR), 4);
12611         } else {
12612                 caps_ptr = PCI_CAP_NEXT_PTR_NULL;
12613         }
12614 
12615         /*
12616          * Walk capabilities if supported.
12617          */
12618         for (cap_count = 0; caps_ptr != PCI_CAP_NEXT_PTR_NULL; ) {
12619 
12620                 /*
12621                  * Check that we haven't exceeded the maximum number of
12622                  * capabilities and that the pointer is in a valid range.
12623                  */
12624                 if (++cap_count > 48) {
12625                         mptsas_log(mpt, CE_WARN,
12626                             "too many device capabilities.\n");
12627                         break;
12628                 }
12629                 if (caps_ptr < 64) {
12630                         mptsas_log(mpt, CE_WARN,
12631                             "capabilities pointer 0x%x out of range.\n",
12632                             caps_ptr);
12633                         break;
12634                 }
12635 
12636                 /*
12637                  * Get next capability and check that it is valid.
12638                  * For now, we only support power management.
12639                  */
12640                 cap = pci_config_get8(mpt->m_config_handle, caps_ptr);
12641                 switch (cap) {
12642                         case PCI_CAP_ID_PM:
12643                                 mptsas_log(mpt, CE_NOTE,
12644                                     "?mptsas%d supports power management.\n",
12645                                     mpt->m_instance);
12646                                 mpt->m_options |= MPTSAS_OPT_PM;
12647 
12648                                 /* Save PMCSR offset */
12649                                 mpt->m_pmcsr_offset = caps_ptr + PCI_PMCSR;
12650                                 break;
12651                         /*
12652                          * The following capabilities are valid.  Any others
12653                          * will cause a message to be logged.
12654                          */
12655                         case PCI_CAP_ID_VPD:
12656                         case PCI_CAP_ID_MSI:
12657                         case PCI_CAP_ID_PCIX:
12658                         case PCI_CAP_ID_PCI_E:
12659                         case PCI_CAP_ID_MSI_X:
12660                                 break;
12661                         default:
12662                                 mptsas_log(mpt, CE_NOTE,
12663                                     "?mptsas%d unrecognized capability "
12664                                     "0x%x.\n", mpt->m_instance, cap);
12665                                 break;
12666                 }
12667 
12668                 /*
12669                  * Get next capabilities pointer and clear bits 0,1.
12670                  */
12671                 caps_ptr = P2ALIGN(pci_config_get8(mpt->m_config_handle,
12672                     (caps_ptr + PCI_CAP_NEXT_PTR)), 4);
12673         }
12674         return (TRUE);
12675 }
12676 
12677 static int
12678 mptsas_init_pm(mptsas_t *mpt)
12679 {
12680         char            pmc_name[16];
12681         char            *pmc[] = {
12682                                 NULL,
12683                                 "0=Off (PCI D3 State)",
12684                                 "3=On (PCI D0 State)",
12685                                 NULL
12686                         };
12687         uint16_t        pmcsr_stat;
12688 
12689         if (mptsas_get_pci_cap(mpt) == FALSE) {
12690                 return (DDI_FAILURE);
12691         }
12692         /*
12693          * If PCI's capability does not support PM, then don't need
12694          * to registe the pm-components
12695          */
12696         if (!(mpt->m_options & MPTSAS_OPT_PM))
12697                 return (DDI_SUCCESS);
12698         /*
12699          * If power management is supported by this chip, create
12700          * pm-components property for the power management framework
12701          */
12702         (void) sprintf(pmc_name, "NAME=mptsas%d", mpt->m_instance);
12703         pmc[0] = pmc_name;
12704         if (ddi_prop_update_string_array(DDI_DEV_T_NONE, mpt->m_dip,
12705             "pm-components", pmc, 3) != DDI_PROP_SUCCESS) {
12706                 mutex_enter(&mpt->m_intr_mutex);
12707                 mpt->m_options &= ~MPTSAS_OPT_PM;
12708                 mutex_exit(&mpt->m_intr_mutex);
12709                 mptsas_log(mpt, CE_WARN,
12710                     "mptsas%d: pm-component property creation failed.",
12711                     mpt->m_instance);
12712                 return (DDI_FAILURE);
12713         }
12714 
12715         /*
12716          * Power on device.
12717          */
12718         (void) pm_busy_component(mpt->m_dip, 0);
12719         pmcsr_stat = pci_config_get16(mpt->m_config_handle,
12720             mpt->m_pmcsr_offset);
12721         if ((pmcsr_stat & PCI_PMCSR_STATE_MASK) != PCI_PMCSR_D0) {
12722                 mptsas_log(mpt, CE_WARN, "mptsas%d: Power up the device",
12723                     mpt->m_instance);
12724                 pci_config_put16(mpt->m_config_handle, mpt->m_pmcsr_offset,
12725                     PCI_PMCSR_D0);
12726         }
12727         if (pm_power_has_changed(mpt->m_dip, 0, PM_LEVEL_D0) != DDI_SUCCESS) {
12728                 mptsas_log(mpt, CE_WARN, "pm_power_has_changed failed");
12729                 return (DDI_FAILURE);
12730         }
12731         mutex_enter(&mpt->m_intr_mutex);
12732         mpt->m_power_level = PM_LEVEL_D0;
12733         mutex_exit(&mpt->m_intr_mutex);
12734         /*
12735          * Set pm idle delay.
12736          */
12737         mpt->m_pm_idle_delay = ddi_prop_get_int(DDI_DEV_T_ANY,
12738             mpt->m_dip, 0, "mptsas-pm-idle-delay", MPTSAS_PM_IDLE_TIMEOUT);
12739 
12740         return (DDI_SUCCESS);
12741 }
12742 
12743 static int
12744 mptsas_register_intrs(mptsas_t *mpt)
12745 {
12746         dev_info_t *dip;
12747         int intr_types;
12748 
12749         dip = mpt->m_dip;
12750 
12751         /* Get supported interrupt types */
12752         if (ddi_intr_get_supported_types(dip, &intr_types) != DDI_SUCCESS) {
12753                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_supported_types "
12754                     "failed\n");
12755                 return (FALSE);
12756         }
12757 
12758         NDBG6(("ddi_intr_get_supported_types() returned: 0x%x", intr_types));
12759 
12760         /*
12761          * Try MSI, but fall back to FIXED
12762          */
12763         if (mptsas_enable_msi && (intr_types & DDI_INTR_TYPE_MSI)) {
12764                 if (mptsas_add_intrs(mpt, DDI_INTR_TYPE_MSI) == DDI_SUCCESS) {
12765                         NDBG0(("Using MSI interrupt type"));
12766                         mpt->m_intr_type = DDI_INTR_TYPE_MSI;
12767                         return (TRUE);
12768                 }
12769         }
12770         if (intr_types & DDI_INTR_TYPE_FIXED) {
12771                 if (mptsas_add_intrs(mpt, DDI_INTR_TYPE_FIXED) == DDI_SUCCESS) {
12772                         NDBG0(("Using FIXED interrupt type"));
12773                         mpt->m_intr_type = DDI_INTR_TYPE_FIXED;
12774                         return (TRUE);
12775                 } else {
12776                         NDBG0(("FIXED interrupt registration failed"));
12777                         return (FALSE);
12778                 }
12779         }
12780 
12781         return (FALSE);
12782 }
12783 
12784 static void
12785 mptsas_unregister_intrs(mptsas_t *mpt)
12786 {
12787         mptsas_rem_intrs(mpt);
12788 }
12789 
12790 /*
12791  * mptsas_add_intrs:
12792  *
12793  * Register FIXED or MSI interrupts.
12794  */
12795 static int
12796 mptsas_add_intrs(mptsas_t *mpt, int intr_type)
12797 {
12798         dev_info_t      *dip = mpt->m_dip;
12799         int             avail, actual, count = 0;
12800         int             i, flag, ret;
12801 
12802         NDBG6(("mptsas_add_intrs:interrupt type 0x%x", intr_type));
12803 
12804         /* Get number of interrupts */
12805         ret = ddi_intr_get_nintrs(dip, intr_type, &count);
12806         if ((ret != DDI_SUCCESS) || (count <= 0)) {
12807                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_nintrs() failed, "
12808                     "ret %d count %d\n", ret, count);
12809 
12810                 return (DDI_FAILURE);
12811         }
12812 
12813         /* Get number of available interrupts */
12814         ret = ddi_intr_get_navail(dip, intr_type, &avail);
12815         if ((ret != DDI_SUCCESS) || (avail == 0)) {
12816                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_navail() failed, "
12817                     "ret %d avail %d\n", ret, avail);
12818 
12819                 return (DDI_FAILURE);
12820         }
12821 
12822         if (avail < count) {
12823                 mptsas_log(mpt, CE_NOTE, "ddi_intr_get_nvail returned %d, "
12824                     "navail() returned %d", count, avail);
12825         }
12826 
12827         /* Mpt only have one interrupt routine */
12828         if ((intr_type == DDI_INTR_TYPE_MSI) && (count > 1)) {
12829                 count = 1;
12830         }
12831 
12832         /* Allocate an array of interrupt handles */
12833         mpt->m_intr_size = count * sizeof (ddi_intr_handle_t);
12834         mpt->m_htable = kmem_alloc(mpt->m_intr_size, KM_SLEEP);
12835 
12836         flag = DDI_INTR_ALLOC_NORMAL;
12837 
12838         /* call ddi_intr_alloc() */
12839         ret = ddi_intr_alloc(dip, mpt->m_htable, intr_type, 0,
12840             count, &actual, flag);
12841 
12842         if ((ret != DDI_SUCCESS) || (actual == 0)) {
12843                 mptsas_log(mpt, CE_WARN, "ddi_intr_alloc() failed, ret %d\n",
12844                     ret);
12845                 kmem_free(mpt->m_htable, mpt->m_intr_size);
12846                 return (DDI_FAILURE);
12847         }
12848 
12849         /* use interrupt count returned or abort? */
12850         if (actual < count) {
12851                 mptsas_log(mpt, CE_NOTE, "Requested: %d, Received: %d\n",
12852                     count, actual);
12853         }
12854 
12855         mpt->m_intr_cnt = actual;
12856 
12857         /*
12858          * Get priority for first msi, assume remaining are all the same
12859          */
12860         if ((ret = ddi_intr_get_pri(mpt->m_htable[0],
12861             &mpt->m_intr_pri)) != DDI_SUCCESS) {
12862                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_pri() failed %d\n", ret);
12863 
12864                 /* Free already allocated intr */
12865                 for (i = 0; i < actual; i++) {
12866                         (void) ddi_intr_free(mpt->m_htable[i]);
12867                 }
12868 
12869                 kmem_free(mpt->m_htable, mpt->m_intr_size);
12870                 return (DDI_FAILURE);
12871         }
12872 
12873         /* Test for high level mutex */
12874         if (mpt->m_intr_pri >= ddi_intr_get_hilevel_pri()) {
12875                 mptsas_log(mpt, CE_WARN, "mptsas_add_intrs: "
12876                     "Hi level interrupt not supported\n");
12877 
12878                 /* Free already allocated intr */
12879                 for (i = 0; i < actual; i++) {
12880                         (void) ddi_intr_free(mpt->m_htable[i]);
12881                 }
12882 
12883                 kmem_free(mpt->m_htable, mpt->m_intr_size);
12884                 return (DDI_FAILURE);
12885         }
12886 
12887         /* Call ddi_intr_add_handler() */
12888         for (i = 0; i < actual; i++) {
12889                 if ((ret = ddi_intr_add_handler(mpt->m_htable[i], mptsas_intr,
12890                     (caddr_t)mpt, (caddr_t)(uintptr_t)i)) != DDI_SUCCESS) {
12891                         mptsas_log(mpt, CE_WARN, "ddi_intr_add_handler() "
12892                             "failed %d\n", ret);
12893 
12894                         /* Free already allocated intr */
12895                         for (i = 0; i < actual; i++) {
12896                                 (void) ddi_intr_free(mpt->m_htable[i]);
12897                         }
12898 
12899                         kmem_free(mpt->m_htable, mpt->m_intr_size);
12900                         return (DDI_FAILURE);
12901                 }
12902         }
12903 
12904         if ((ret = ddi_intr_get_cap(mpt->m_htable[0], &mpt->m_intr_cap))
12905             != DDI_SUCCESS) {
12906                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_cap() failed %d\n", ret);
12907 
12908                 /* Free already allocated intr */
12909                 for (i = 0; i < actual; i++) {
12910                         (void) ddi_intr_free(mpt->m_htable[i]);
12911                 }
12912 
12913                 kmem_free(mpt->m_htable, mpt->m_intr_size);
12914                 return (DDI_FAILURE);
12915         }
12916 
12917         /*
12918          * Enable interrupts
12919          */
12920         if (mpt->m_intr_cap & DDI_INTR_FLAG_BLOCK) {
12921                 /* Call ddi_intr_block_enable() for MSI interrupts */
12922                 (void) ddi_intr_block_enable(mpt->m_htable, mpt->m_intr_cnt);
12923         } else {
12924                 /* Call ddi_intr_enable for MSI or FIXED interrupts */
12925                 for (i = 0; i < mpt->m_intr_cnt; i++) {
12926                         (void) ddi_intr_enable(mpt->m_htable[i]);
12927                 }
12928         }
12929         return (DDI_SUCCESS);
12930 }
12931 
12932 /*
12933  * mptsas_rem_intrs:
12934  *
12935  * Unregister FIXED or MSI interrupts
12936  */
12937 static void
12938 mptsas_rem_intrs(mptsas_t *mpt)
12939 {
12940         int     i;
12941 
12942         NDBG6(("mptsas_rem_intrs"));
12943 
12944         /* Disable all interrupts */
12945         if (mpt->m_intr_cap & DDI_INTR_FLAG_BLOCK) {
12946                 /* Call ddi_intr_block_disable() */
12947                 (void) ddi_intr_block_disable(mpt->m_htable, mpt->m_intr_cnt);
12948         } else {
12949                 for (i = 0; i < mpt->m_intr_cnt; i++) {
12950                         (void) ddi_intr_disable(mpt->m_htable[i]);
12951                 }
12952         }
12953 
12954         /* Call ddi_intr_remove_handler() */
12955         for (i = 0; i < mpt->m_intr_cnt; i++) {
12956                 (void) ddi_intr_remove_handler(mpt->m_htable[i]);
12957                 (void) ddi_intr_free(mpt->m_htable[i]);
12958         }
12959 
12960         kmem_free(mpt->m_htable, mpt->m_intr_size);
12961 }
12962 
12963 /*
12964  * The IO fault service error handling callback function
12965  */
12966 /*ARGSUSED*/
12967 static int
12968 mptsas_fm_error_cb(dev_info_t *dip, ddi_fm_error_t *err, const void *impl_data)
12969 {
12970         /*
12971          * as the driver can always deal with an error in any dma or
12972          * access handle, we can just return the fme_status value.
12973          */
12974         pci_ereport_post(dip, err, NULL);
12975         return (err->fme_status);
12976 }
12977 
12978 /*
12979  * mptsas_fm_init - initialize fma capabilities and register with IO
12980  *               fault services.
12981  */
12982 static void
12983 mptsas_fm_init(mptsas_t *mpt)
12984 {
12985         /*
12986          * Need to change iblock to priority for new MSI intr
12987          */
12988         ddi_iblock_cookie_t     fm_ibc;
12989 
12990         /* Only register with IO Fault Services if we have some capability */
12991         if (mpt->m_fm_capabilities) {
12992                 /* Adjust access and dma attributes for FMA */
12993                 mpt->m_reg_acc_attr.devacc_attr_access = DDI_FLAGERR_ACC;
12994                 mpt->m_msg_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
12995                 mpt->m_io_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
12996 
12997                 /*
12998                  * Register capabilities with IO Fault Services.
12999                  * mpt->m_fm_capabilities will be updated to indicate
13000                  * capabilities actually supported (not requested.)
13001                  */
13002                 ddi_fm_init(mpt->m_dip, &mpt->m_fm_capabilities, &fm_ibc);
13003 
13004                 /*
13005                  * Initialize pci ereport capabilities if ereport
13006                  * capable (should always be.)
13007                  */
13008                 if (DDI_FM_EREPORT_CAP(mpt->m_fm_capabilities) ||
13009                     DDI_FM_ERRCB_CAP(mpt->m_fm_capabilities)) {
13010                         pci_ereport_setup(mpt->m_dip);
13011                 }
13012 
13013                 /*
13014                  * Register error callback if error callback capable.
13015                  */
13016                 if (DDI_FM_ERRCB_CAP(mpt->m_fm_capabilities)) {
13017                         ddi_fm_handler_register(mpt->m_dip,
13018                             mptsas_fm_error_cb, (void *) mpt);
13019                 }
13020         }
13021 }
13022 
13023 /*
13024  * mptsas_fm_fini - Releases fma capabilities and un-registers with IO
13025  *               fault services.
13026  *
13027  */
13028 static void
13029 mptsas_fm_fini(mptsas_t *mpt)
13030 {
13031         /* Only unregister FMA capabilities if registered */
13032         if (mpt->m_fm_capabilities) {
13033 
13034                 /*
13035                  * Un-register error callback if error callback capable.
13036                  */
13037 
13038                 if (DDI_FM_ERRCB_CAP(mpt->m_fm_capabilities)) {
13039                         ddi_fm_handler_unregister(mpt->m_dip);
13040                 }
13041 
13042                 /*
13043                  * Release any resources allocated by pci_ereport_setup()
13044                  */
13045 
13046                 if (DDI_FM_EREPORT_CAP(mpt->m_fm_capabilities) ||
13047                     DDI_FM_ERRCB_CAP(mpt->m_fm_capabilities)) {
13048                         pci_ereport_teardown(mpt->m_dip);
13049                 }
13050 
13051                 /* Unregister from IO Fault Services */
13052                 ddi_fm_fini(mpt->m_dip);
13053 
13054                 /* Adjust access and dma attributes for FMA */
13055                 mpt->m_reg_acc_attr.devacc_attr_access = DDI_DEFAULT_ACC;
13056                 mpt->m_msg_dma_attr.dma_attr_flags &= ~DDI_DMA_FLAGERR;
13057                 mpt->m_io_dma_attr.dma_attr_flags &= ~DDI_DMA_FLAGERR;
13058 
13059         }
13060 }
13061 
13062 int
13063 mptsas_check_acc_handle(ddi_acc_handle_t handle)
13064 {
13065         ddi_fm_error_t  de;
13066 
13067         if (handle == NULL)
13068                 return (DDI_FAILURE);
13069         ddi_fm_acc_err_get(handle, &de, DDI_FME_VER0);
13070         return (de.fme_status);
13071 }
13072 
13073 int
13074 mptsas_check_dma_handle(ddi_dma_handle_t handle)
13075 {
13076         ddi_fm_error_t  de;
13077 
13078         if (handle == NULL)
13079                 return (DDI_FAILURE);
13080         ddi_fm_dma_err_get(handle, &de, DDI_FME_VER0);
13081         return (de.fme_status);
13082 }
13083 
13084 void
13085 mptsas_fm_ereport(mptsas_t *mpt, char *detail)
13086 {
13087         uint64_t        ena;
13088         char            buf[FM_MAX_CLASS];
13089 
13090         (void) snprintf(buf, FM_MAX_CLASS, "%s.%s", DDI_FM_DEVICE, detail);
13091         ena = fm_ena_generate(0, FM_ENA_FMT1);
13092         if (DDI_FM_EREPORT_CAP(mpt->m_fm_capabilities)) {
13093                 ddi_fm_ereport_post(mpt->m_dip, buf, ena, DDI_NOSLEEP,
13094                     FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0, NULL);
13095         }
13096 }
13097 
13098 static int
13099 mptsas_get_target_device_info(mptsas_t *mpt, uint32_t page_address,
13100     uint16_t *dev_handle, mptsas_target_t **pptgt)
13101 {
13102         int             rval;
13103         uint32_t        dev_info;
13104         uint64_t        sas_wwn;
13105         mptsas_phymask_t phymask;
13106         uint8_t         physport, phynum, config, disk;
13107         mptsas_slots_t  *slots = mpt->m_active;
13108         uint64_t        devicename;
13109         uint16_t        pdev_hdl;
13110         mptsas_target_t *tmp_tgt = NULL;
13111         uint16_t        bay_num, enclosure;
13112 
13113         ASSERT(*pptgt == NULL);
13114 
13115         rval = mptsas_get_sas_device_page0(mpt, page_address, dev_handle,
13116             &sas_wwn, &dev_info, &physport, &phynum, &pdev_hdl,
13117             &bay_num, &enclosure);
13118         if (rval != DDI_SUCCESS) {
13119                 rval = DEV_INFO_FAIL_PAGE0;
13120                 return (rval);
13121         }
13122 
13123         if ((dev_info & (MPI2_SAS_DEVICE_INFO_SSP_TARGET |
13124             MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
13125             MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) == NULL) {
13126                 rval = DEV_INFO_WRONG_DEVICE_TYPE;
13127                 return (rval);
13128         }
13129 
13130         /*
13131          * Check if the dev handle is for a Phys Disk. If so, set return value
13132          * and exit.  Don't add Phys Disks to hash.
13133          */
13134         for (config = 0; config < slots->m_num_raid_configs; config++) {
13135                 for (disk = 0; disk < MPTSAS_MAX_DISKS_IN_CONFIG; disk++) {
13136                         if (*dev_handle == slots->m_raidconfig[config].
13137                             m_physdisk_devhdl[disk]) {
13138                                 rval = DEV_INFO_PHYS_DISK;
13139                                 return (rval);
13140                         }
13141                 }
13142         }
13143 
13144         /*
13145          * Get SATA Device Name from SAS device page0 for
13146          * sata device, if device name doesn't exist, set m_sas_wwn to
13147          * 0 for direct attached SATA. For the device behind the expander
13148          * we still can use STP address assigned by expander.
13149          */
13150         if (dev_info & (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
13151             MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
13152                 mutex_exit(&mpt->m_mutex);
13153                 /* alloc a tmp_tgt to send the cmd */
13154                 tmp_tgt = kmem_zalloc(sizeof (struct mptsas_target),
13155                     KM_SLEEP);
13156                 tmp_tgt->m_devhdl = *dev_handle;
13157                 tmp_tgt->m_deviceinfo = dev_info;
13158                 tmp_tgt->m_qfull_retries = QFULL_RETRIES;
13159                 tmp_tgt->m_qfull_retry_interval =
13160                     drv_usectohz(QFULL_RETRY_INTERVAL * 1000);
13161                 tmp_tgt->m_t_throttle = MAX_THROTTLE;
13162                 devicename = mptsas_get_sata_guid(mpt, tmp_tgt, 0);
13163                 kmem_free(tmp_tgt, sizeof (struct mptsas_target));
13164                 mutex_enter(&mpt->m_mutex);
13165                 if (devicename != 0 && (((devicename >> 56) & 0xf0) == 0x50)) {
13166                         sas_wwn = devicename;
13167                 } else if (dev_info & MPI2_SAS_DEVICE_INFO_DIRECT_ATTACH) {
13168                         sas_wwn = 0;
13169                 }
13170         }
13171 
13172         phymask = mptsas_physport_to_phymask(mpt, physport);
13173         *pptgt = mptsas_tgt_alloc(&slots->m_tgttbl, *dev_handle, sas_wwn,
13174             dev_info, phymask, phynum, mpt);
13175         if (*pptgt == NULL) {
13176                 mptsas_log(mpt, CE_WARN, "Failed to allocated target"
13177                     "structure!");
13178                 rval = DEV_INFO_FAIL_ALLOC;
13179                 return (rval);
13180         }
13181         (*pptgt)->m_enclosure = enclosure;
13182         (*pptgt)->m_slot_num = bay_num;
13183         return (DEV_INFO_SUCCESS);
13184 }
13185 
13186 uint64_t
13187 mptsas_get_sata_guid(mptsas_t *mpt, mptsas_target_t *ptgt, int lun)
13188 {
13189         uint64_t        sata_guid = 0, *pwwn = NULL;
13190         int             target = ptgt->m_devhdl;
13191         uchar_t         *inq83 = NULL;
13192         int             inq83_len = 0xFF;
13193         uchar_t         *dblk = NULL;
13194         int             inq83_retry = 3;
13195         int             rval = DDI_FAILURE;
13196 
13197         inq83   = kmem_zalloc(inq83_len, KM_SLEEP);
13198 
13199 inq83_retry:
13200         rval = mptsas_inquiry(mpt, ptgt, lun, 0x83, inq83,
13201             inq83_len, NULL, 1);
13202         if (rval != DDI_SUCCESS) {
13203                 mptsas_log(mpt, CE_WARN, "!mptsas request inquiry page "
13204                     "0x83 for target:%x, lun:%x failed!", target, lun);
13205                 goto out;
13206         }
13207         /* According to SAT2, the first descriptor is logic unit name */
13208         dblk = &inq83[4];
13209         if ((dblk[1] & 0x30) != 0) {
13210                 mptsas_log(mpt, CE_WARN, "!Descriptor is not lun associated.");
13211                 goto out;
13212         }
13213         pwwn = (uint64_t *)(void *)(&dblk[4]);
13214         if ((dblk[4] & 0xf0) == 0x50) {
13215                 sata_guid = BE_64(*pwwn);
13216                 goto out;
13217         } else if (dblk[4] == 'A') {
13218                 NDBG20(("SATA drive has no NAA format GUID."));
13219                 goto out;
13220         } else {
13221                 /* The data is not ready, wait and retry */
13222                 inq83_retry--;
13223                 if (inq83_retry <= 0) {
13224                         goto out;
13225                 }
13226                 NDBG20(("The GUID is not ready, retry..."));
13227                 delay(1 * drv_usectohz(1000000));
13228                 goto inq83_retry;
13229         }
13230 out:
13231         kmem_free(inq83, inq83_len);
13232         return (sata_guid);
13233 }
13234 
13235 static int
13236 mptsas_inquiry(mptsas_t *mpt, mptsas_target_t *ptgt, int lun, uchar_t page,
13237     unsigned char *buf, int len, int *reallen, uchar_t evpd)
13238 {
13239         uchar_t                 cdb[CDB_GROUP0];
13240         struct scsi_address     ap;
13241         struct buf              *data_bp = NULL;
13242         int                     resid = 0;
13243         int                     ret = DDI_FAILURE;
13244 
13245         ASSERT(len <= 0xffff);
13246 
13247         ap.a_target = MPTSAS_INVALID_DEVHDL;
13248         ap.a_lun = (uchar_t)(lun);
13249         ap.a_hba_tran = mpt->m_tran;
13250 
13251         data_bp = scsi_alloc_consistent_buf(&ap,
13252             (struct buf *)NULL, len, B_READ, NULL_FUNC, NULL);
13253         if (data_bp == NULL) {
13254                 return (ret);
13255         }
13256         bzero(cdb, CDB_GROUP0);
13257         cdb[0] = SCMD_INQUIRY;
13258         cdb[1] = evpd;
13259         cdb[2] = page;
13260         cdb[3] = (len & 0xff00) >> 8;
13261         cdb[4] = (len & 0x00ff);
13262         cdb[5] = 0;
13263 
13264         ret = mptsas_send_scsi_cmd(mpt, &ap, ptgt, &cdb[0], CDB_GROUP0, data_bp,
13265             &resid);
13266         if (ret == DDI_SUCCESS) {
13267                 if (reallen) {
13268                         *reallen = len - resid;
13269                 }
13270                 bcopy((caddr_t)data_bp->b_un.b_addr, buf, len);
13271         }
13272         if (data_bp) {
13273                 scsi_free_consistent_buf(data_bp);
13274         }
13275         return (ret);
13276 }
13277 
13278 static int
13279 mptsas_send_scsi_cmd(mptsas_t *mpt, struct scsi_address *ap,
13280     mptsas_target_t *ptgt, uchar_t *cdb, int cdblen, struct buf *data_bp,
13281     int *resid)
13282 {
13283         struct scsi_pkt         *pktp = NULL;
13284         scsi_hba_tran_t         *tran_clone = NULL;
13285         mptsas_tgt_private_t    *tgt_private = NULL;
13286         int                     ret = DDI_FAILURE;
13287 
13288         /*
13289          * scsi_hba_tran_t->tran_tgt_private is used to pass the address
13290          * information to scsi_init_pkt, allocate a scsi_hba_tran structure
13291          * to simulate the cmds from sd
13292          */
13293         tran_clone = kmem_alloc(
13294             sizeof (scsi_hba_tran_t), KM_SLEEP);
13295         if (tran_clone == NULL) {
13296                 goto out;
13297         }
13298         bcopy((caddr_t)mpt->m_tran,
13299             (caddr_t)tran_clone, sizeof (scsi_hba_tran_t));
13300         tgt_private = kmem_alloc(
13301             sizeof (mptsas_tgt_private_t), KM_SLEEP);
13302         if (tgt_private == NULL) {
13303                 goto out;
13304         }
13305         tgt_private->t_lun = ap->a_lun;
13306         tgt_private->t_private = ptgt;
13307         tran_clone->tran_tgt_private = tgt_private;
13308         ap->a_hba_tran = tran_clone;
13309 
13310         pktp = scsi_init_pkt(ap, (struct scsi_pkt *)NULL,
13311             data_bp, cdblen, sizeof (struct scsi_arq_status),
13312             0, PKT_CONSISTENT, NULL, NULL);
13313         if (pktp == NULL) {
13314                 goto out;
13315         }
13316         bcopy(cdb, pktp->pkt_cdbp, cdblen);
13317         pktp->pkt_flags = FLAG_NOPARITY;
13318         if (scsi_poll(pktp) < 0) {
13319                 goto out;
13320         }
13321         if (((struct scsi_status *)pktp->pkt_scbp)->sts_chk) {
13322                 goto out;
13323         }
13324         if (resid != NULL) {
13325                 *resid = pktp->pkt_resid;
13326         }
13327 
13328         ret = DDI_SUCCESS;
13329 out:
13330         if (pktp) {
13331                 scsi_destroy_pkt(pktp);
13332         }
13333         if (tran_clone) {
13334                 kmem_free(tran_clone, sizeof (scsi_hba_tran_t));
13335         }
13336         if (tgt_private) {
13337                 kmem_free(tgt_private, sizeof (mptsas_tgt_private_t));
13338         }
13339         return (ret);
13340 }
13341 static int
13342 mptsas_parse_address(char *name, uint64_t *wwid, uint8_t *phy, int *lun)
13343 {
13344         char    *cp = NULL;
13345         char    *ptr = NULL;
13346         size_t  s = 0;
13347         char    *wwid_str = NULL;
13348         char    *lun_str = NULL;
13349         long    lunnum;
13350         long    phyid = -1;
13351         int     rc = DDI_FAILURE;
13352 
13353         ptr = name;
13354         ASSERT(ptr[0] == 'w' || ptr[0] == 'p');
13355         ptr++;
13356         if ((cp = strchr(ptr, ',')) == NULL) {
13357                 return (DDI_FAILURE);
13358         }
13359 
13360         wwid_str = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
13361         s = (uintptr_t)cp - (uintptr_t)ptr;
13362 
13363         bcopy(ptr, wwid_str, s);
13364         wwid_str[s] = '\0';
13365 
13366         ptr = ++cp;
13367 
13368         if ((cp = strchr(ptr, '\0')) == NULL) {
13369                 goto out;
13370         }
13371         lun_str =  kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
13372         s = (uintptr_t)cp - (uintptr_t)ptr;
13373 
13374         bcopy(ptr, lun_str, s);
13375         lun_str[s] = '\0';
13376 
13377         if (name[0] == 'p') {
13378                 rc = ddi_strtol(wwid_str, NULL, 0x10, &phyid);
13379         } else {
13380                 rc = scsi_wwnstr_to_wwn(wwid_str, wwid);
13381         }
13382         if (rc != DDI_SUCCESS)
13383                 goto out;
13384 
13385         if (phyid != -1) {
13386                 ASSERT(phyid < MPTSAS_MAX_PHYS);
13387                 *phy = (uint8_t)phyid;
13388         }
13389         rc = ddi_strtol(lun_str, NULL, 0x10, &lunnum);
13390         if (rc != 0)
13391                 goto out;
13392 
13393         *lun = (int)lunnum;
13394         rc = DDI_SUCCESS;
13395 out:
13396         if (wwid_str)
13397                 kmem_free(wwid_str, SCSI_MAXNAMELEN);
13398         if (lun_str)
13399                 kmem_free(lun_str, SCSI_MAXNAMELEN);
13400 
13401         return (rc);
13402 }
13403 
13404 /*
13405  * mptsas_parse_smp_name() is to parse sas wwn string
13406  * which format is "wWWN"
13407  */
13408 static int
13409 mptsas_parse_smp_name(char *name, uint64_t *wwn)
13410 {
13411         char    *ptr = name;
13412 
13413         if (*ptr != 'w') {
13414                 return (DDI_FAILURE);
13415         }
13416 
13417         ptr++;
13418         if (scsi_wwnstr_to_wwn(ptr, wwn)) {
13419                 return (DDI_FAILURE);
13420         }
13421         return (DDI_SUCCESS);
13422 }
13423 
13424 static int
13425 mptsas_bus_config(dev_info_t *pdip, uint_t flag,
13426     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
13427 {
13428         int             ret = NDI_FAILURE;
13429         int             circ = 0;
13430         int             circ1 = 0;
13431         mptsas_t        *mpt;
13432         char            *ptr = NULL;
13433         char            *devnm = NULL;
13434         uint64_t        wwid = 0;
13435         uint8_t         phy = 0xFF;
13436         int             lun = 0;
13437         uint_t          mflags = flag;
13438         int             bconfig = TRUE;
13439 
13440         if (scsi_hba_iport_unit_address(pdip) == 0) {
13441                 return (DDI_FAILURE);
13442         }
13443 
13444         mpt = DIP2MPT(pdip);
13445         if (!mpt) {
13446                 return (DDI_FAILURE);
13447         }
13448         /*
13449          * Hold the nexus across the bus_config
13450          */
13451         ndi_devi_enter(scsi_vhci_dip, &circ);
13452         ndi_devi_enter(pdip, &circ1);
13453         switch (op) {
13454         case BUS_CONFIG_ONE:
13455                 /* parse wwid/target name out of name given */
13456                 if ((ptr = strchr((char *)arg, '@')) == NULL) {
13457                         ret = NDI_FAILURE;
13458                         break;
13459                 }
13460                 ptr++;
13461                 if (strncmp((char *)arg, "smp", 3) == 0) {
13462                         /*
13463                          * This is a SMP target device
13464                          */
13465                         ret = mptsas_parse_smp_name(ptr, &wwid);
13466                         if (ret != DDI_SUCCESS) {
13467                                 ret = NDI_FAILURE;
13468                                 break;
13469                         }
13470                         ret = mptsas_config_smp(pdip, wwid, childp);
13471                 } else if ((ptr[0] == 'w') || (ptr[0] == 'p')) {
13472                         /*
13473                          * OBP could pass down a non-canonical form
13474                          * bootpath without LUN part when LUN is 0.
13475                          * So driver need adjust the string.
13476                          */
13477                         if (strchr(ptr, ',') == NULL) {
13478                                 devnm = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
13479                                 (void) sprintf(devnm, "%s,0", (char *)arg);
13480                                 ptr = strchr(devnm, '@');
13481                                 ptr++;
13482                         }
13483 
13484                         /*
13485                          * The device path is wWWID format and the device
13486                          * is not SMP target device.
13487                          */
13488                         ret = mptsas_parse_address(ptr, &wwid, &phy, &lun);
13489                         if (ret != DDI_SUCCESS) {
13490                                 ret = NDI_FAILURE;
13491                                 break;
13492                         }
13493                         *childp = NULL;
13494                         if (ptr[0] == 'w') {
13495                                 ret = mptsas_config_one_addr(pdip, wwid,
13496                                     lun, childp);
13497                         } else if (ptr[0] == 'p') {
13498                                 ret = mptsas_config_one_phy(pdip, phy, lun,
13499                                     childp);
13500                         }
13501 
13502                         /*
13503                          * If this is CD/DVD device in OBP path, the
13504                          * ndi_busop_bus_config can be skipped as config one
13505                          * operation is done above.
13506                          */
13507                         if ((ret == NDI_SUCCESS) && (*childp != NULL) &&
13508                             (strcmp(ddi_node_name(*childp), "cdrom") == 0) &&
13509                             (strncmp((char *)arg, "disk", 4) == 0)) {
13510                                 bconfig = FALSE;
13511                                 ndi_hold_devi(*childp);
13512                         }
13513                 } else {
13514                         ret = NDI_FAILURE;
13515                         break;
13516                 }
13517 
13518                 /*
13519                  * DDI group instructed us to use this flag.
13520                  */
13521                 mflags |= NDI_MDI_FALLBACK;
13522                 break;
13523         case BUS_CONFIG_DRIVER:
13524         case BUS_CONFIG_ALL:
13525                 mptsas_config_all(pdip);
13526                 ret = NDI_SUCCESS;
13527                 break;
13528         }
13529 
13530         if ((ret == NDI_SUCCESS) && bconfig) {
13531                 ret = ndi_busop_bus_config(pdip, mflags, op,
13532                     (devnm == NULL) ? arg : devnm, childp, 0);
13533         }
13534 
13535         ndi_devi_exit(pdip, circ1);
13536         ndi_devi_exit(scsi_vhci_dip, circ);
13537         if (devnm != NULL)
13538                 kmem_free(devnm, SCSI_MAXNAMELEN);
13539         return (ret);
13540 }
13541 
13542 static int
13543 mptsas_probe_lun(dev_info_t *pdip, int lun, dev_info_t **dip,
13544     mptsas_target_t *ptgt)
13545 {
13546         int                     rval = DDI_FAILURE;
13547         struct scsi_inquiry     *sd_inq = NULL;
13548         mptsas_t                *mpt = DIP2MPT(pdip);
13549 
13550         sd_inq = (struct scsi_inquiry *)kmem_alloc(SUN_INQSIZE, KM_SLEEP);
13551 
13552         rval = mptsas_inquiry(mpt, ptgt, lun, 0, (uchar_t *)sd_inq,
13553             SUN_INQSIZE, 0, (uchar_t)0);
13554 
13555         if ((rval == DDI_SUCCESS) && MPTSAS_VALID_LUN(sd_inq)) {
13556                 rval = mptsas_create_lun(pdip, sd_inq, dip, ptgt, lun);
13557         } else {
13558                 rval = DDI_FAILURE;
13559         }
13560 
13561         kmem_free(sd_inq, SUN_INQSIZE);
13562         return (rval);
13563 }
13564 
13565 static int
13566 mptsas_config_one_addr(dev_info_t *pdip, uint64_t sasaddr, int lun,
13567     dev_info_t **lundip)
13568 {
13569         int             rval;
13570         mptsas_t                *mpt = DIP2MPT(pdip);
13571         int             phymask;
13572         mptsas_target_t *ptgt = NULL;
13573 
13574         /*
13575          * Get the physical port associated to the iport
13576          */
13577         phymask = ddi_prop_get_int(DDI_DEV_T_ANY, pdip, 0,
13578             "phymask", 0);
13579 
13580         ptgt = mptsas_wwid_to_ptgt(mpt, phymask, sasaddr);
13581         if (ptgt == NULL) {
13582                 /*
13583                  * didn't match any device by searching
13584                  */
13585                 return (DDI_FAILURE);
13586         }
13587         /*
13588          * If the LUN already exists and the status is online,
13589          * we just return the pointer to dev_info_t directly.
13590          * For the mdi_pathinfo node, we'll handle it in
13591          * mptsas_create_virt_lun()
13592          * TODO should be also in mptsas_handle_dr
13593          */
13594 
13595         *lundip = mptsas_find_child_addr(pdip, sasaddr, lun);
13596         if (*lundip != NULL) {
13597                 /*
13598                  * TODO Another senario is, we hotplug the same disk
13599                  * on the same slot, the devhdl changed, is this
13600                  * possible?
13601                  * tgt_private->t_private != ptgt
13602                  */
13603                 if (sasaddr != ptgt->m_sas_wwn) {
13604                         /*
13605                          * The device has changed although the devhdl is the
13606                          * same (Enclosure mapping mode, change drive on the
13607                          * same slot)
13608                          */
13609                         return (DDI_FAILURE);
13610                 }
13611                 return (DDI_SUCCESS);
13612         }
13613 
13614         if (phymask == 0) {
13615                 /*
13616                  * Configure IR volume
13617                  */
13618                 rval =  mptsas_config_raid(pdip, ptgt->m_devhdl, lundip);
13619                 return (rval);
13620         }
13621         rval = mptsas_probe_lun(pdip, lun, lundip, ptgt);
13622 
13623         return (rval);
13624 }
13625 
13626 static int
13627 mptsas_config_one_phy(dev_info_t *pdip, uint8_t phy, int lun,
13628     dev_info_t **lundip)
13629 {
13630         int             rval;
13631         mptsas_t        *mpt = DIP2MPT(pdip);
13632         int             phymask;
13633         mptsas_target_t *ptgt = NULL;
13634 
13635         /*
13636          * Get the physical port associated to the iport
13637          */
13638         phymask = ddi_prop_get_int(DDI_DEV_T_ANY, pdip, 0,
13639             "phymask", 0);
13640 
13641         ptgt = mptsas_phy_to_tgt(mpt, phymask, phy);
13642         if (ptgt == NULL) {
13643                 /*
13644                  * didn't match any device by searching
13645                  */
13646                 return (DDI_FAILURE);
13647         }
13648 
13649         /*
13650          * If the LUN already exists and the status is online,
13651          * we just return the pointer to dev_info_t directly.
13652          * For the mdi_pathinfo node, we'll handle it in
13653          * mptsas_create_virt_lun().
13654          */
13655 
13656         *lundip = mptsas_find_child_phy(pdip, phy);
13657         if (*lundip != NULL) {
13658                 return (DDI_SUCCESS);
13659         }
13660 
13661         rval = mptsas_probe_lun(pdip, lun, lundip, ptgt);
13662 
13663         return (rval);
13664 }
13665 
13666 static int
13667 mptsas_retrieve_lundata(int lun_cnt, uint8_t *buf, uint16_t *lun_num,
13668     uint8_t *lun_addr_type)
13669 {
13670         uint32_t        lun_idx = 0;
13671 
13672         ASSERT(lun_num != NULL);
13673         ASSERT(lun_addr_type != NULL);
13674 
13675         lun_idx = (lun_cnt + 1) * MPTSAS_SCSI_REPORTLUNS_ADDRESS_SIZE;
13676         /* determine report luns addressing type */
13677         switch (buf[lun_idx] & MPTSAS_SCSI_REPORTLUNS_ADDRESS_MASK) {
13678                 /*
13679                  * Vendors in the field have been found to be concatenating
13680                  * bus/target/lun to equal the complete lun value instead
13681                  * of switching to flat space addressing
13682                  */
13683                 /* 00b - peripheral device addressing method */
13684         case MPTSAS_SCSI_REPORTLUNS_ADDRESS_PERIPHERAL:
13685                 /* FALLTHRU */
13686                 /* 10b - logical unit addressing method */
13687         case MPTSAS_SCSI_REPORTLUNS_ADDRESS_LOGICAL_UNIT:
13688                 /* FALLTHRU */
13689                 /* 01b - flat space addressing method */
13690         case MPTSAS_SCSI_REPORTLUNS_ADDRESS_FLAT_SPACE:
13691                 /* byte0 bit0-5=msb lun byte1 bit0-7=lsb lun */
13692                 *lun_addr_type = (buf[lun_idx] &
13693                     MPTSAS_SCSI_REPORTLUNS_ADDRESS_MASK) >> 6;
13694                 *lun_num = (buf[lun_idx] & 0x3F) << 8;
13695                 *lun_num |= buf[lun_idx + 1];
13696                 return (DDI_SUCCESS);
13697         default:
13698                 return (DDI_FAILURE);
13699         }
13700 }
13701 
13702 static int
13703 mptsas_config_luns(dev_info_t *pdip, mptsas_target_t *ptgt)
13704 {
13705         struct buf              *repluns_bp = NULL;
13706         struct scsi_address     ap;
13707         uchar_t                 cdb[CDB_GROUP5];
13708         int                     ret = DDI_FAILURE;
13709         int                     retry = 0;
13710         int                     lun_list_len = 0;
13711         uint16_t                lun_num = 0;
13712         uint8_t                 lun_addr_type = 0;
13713         uint32_t                lun_cnt = 0;
13714         uint32_t                lun_total = 0;
13715         dev_info_t              *cdip = NULL;
13716         uint16_t                *saved_repluns = NULL;
13717         char                    *buffer = NULL;
13718         int                     buf_len = 128;
13719         mptsas_t                *mpt = DIP2MPT(pdip);
13720         uint64_t                sas_wwn = 0;
13721         uint8_t                 phy = 0xFF;
13722         uint32_t                dev_info = 0;
13723 
13724         mutex_enter(&mpt->m_mutex);
13725         sas_wwn = ptgt->m_sas_wwn;
13726         phy = ptgt->m_phynum;
13727         dev_info = ptgt->m_deviceinfo;
13728         mutex_exit(&mpt->m_mutex);
13729 
13730         if (sas_wwn == 0) {
13731                 /*
13732                  * It's a SATA without Device Name
13733                  * So don't try multi-LUNs
13734                  */
13735                 if (mptsas_find_child_phy(pdip, phy)) {
13736                         return (DDI_SUCCESS);
13737                 } else {
13738                         /*
13739                          * need configure and create node
13740                          */
13741                         return (DDI_FAILURE);
13742                 }
13743         }
13744 
13745         /*
13746          * WWN (SAS address or Device Name exist)
13747          */
13748         if (dev_info & (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
13749             MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
13750                 /*
13751                  * SATA device with Device Name
13752                  * So don't try multi-LUNs
13753                  */
13754                 if (mptsas_find_child_addr(pdip, sas_wwn, 0)) {
13755                         return (DDI_SUCCESS);
13756                 } else {
13757                         return (DDI_FAILURE);
13758                 }
13759         }
13760 
13761         do {
13762                 ap.a_target = MPTSAS_INVALID_DEVHDL;
13763                 ap.a_lun = 0;
13764                 ap.a_hba_tran = mpt->m_tran;
13765                 repluns_bp = scsi_alloc_consistent_buf(&ap,
13766                     (struct buf *)NULL, buf_len, B_READ, NULL_FUNC, NULL);
13767                 if (repluns_bp == NULL) {
13768                         retry++;
13769                         continue;
13770                 }
13771                 bzero(cdb, CDB_GROUP5);
13772                 cdb[0] = SCMD_REPORT_LUNS;
13773                 cdb[6] = (buf_len & 0xff000000) >> 24;
13774                 cdb[7] = (buf_len & 0x00ff0000) >> 16;
13775                 cdb[8] = (buf_len & 0x0000ff00) >> 8;
13776                 cdb[9] = (buf_len & 0x000000ff);
13777 
13778                 ret = mptsas_send_scsi_cmd(mpt, &ap, ptgt, &cdb[0], CDB_GROUP5,
13779                     repluns_bp, NULL);
13780                 if (ret != DDI_SUCCESS) {
13781                         scsi_free_consistent_buf(repluns_bp);
13782                         retry++;
13783                         continue;
13784                 }
13785                 lun_list_len = BE_32(*(int *)((void *)(
13786                     repluns_bp->b_un.b_addr)));
13787                 if (buf_len >= lun_list_len + 8) {
13788                         ret = DDI_SUCCESS;
13789                         break;
13790                 }
13791                 scsi_free_consistent_buf(repluns_bp);
13792                 buf_len = lun_list_len + 8;
13793 
13794         } while (retry < 3);
13795 
13796         if (ret != DDI_SUCCESS)
13797                 return (ret);
13798         buffer = (char *)repluns_bp->b_un.b_addr;
13799         /*
13800          * find out the number of luns returned by the SCSI ReportLun call
13801          * and allocate buffer space
13802          */
13803         lun_total = lun_list_len / MPTSAS_SCSI_REPORTLUNS_ADDRESS_SIZE;
13804         saved_repluns = kmem_zalloc(sizeof (uint16_t) * lun_total, KM_SLEEP);
13805         if (saved_repluns == NULL) {
13806                 scsi_free_consistent_buf(repluns_bp);
13807                 return (DDI_FAILURE);
13808         }
13809         for (lun_cnt = 0; lun_cnt < lun_total; lun_cnt++) {
13810                 if (mptsas_retrieve_lundata(lun_cnt, (uint8_t *)(buffer),
13811                     &lun_num, &lun_addr_type) != DDI_SUCCESS) {
13812                         continue;
13813                 }
13814                 saved_repluns[lun_cnt] = lun_num;
13815                 if (cdip = mptsas_find_child_addr(pdip, sas_wwn, lun_num))
13816                         ret = DDI_SUCCESS;
13817                 else
13818                         ret = mptsas_probe_lun(pdip, lun_num, &cdip,
13819                             ptgt);
13820                 if ((ret == DDI_SUCCESS) && (cdip != NULL)) {
13821                         (void) ndi_prop_remove(DDI_DEV_T_NONE, cdip,
13822                             MPTSAS_DEV_GONE);
13823                 }
13824         }
13825         mptsas_offline_missed_luns(pdip, saved_repluns, lun_total, ptgt);
13826         kmem_free(saved_repluns, sizeof (uint16_t) * lun_total);
13827         scsi_free_consistent_buf(repluns_bp);
13828         return (DDI_SUCCESS);
13829 }
13830 
13831 static int
13832 mptsas_config_raid(dev_info_t *pdip, uint16_t target, dev_info_t **dip)
13833 {
13834         int                     rval = DDI_FAILURE;
13835         struct scsi_inquiry     *sd_inq = NULL;
13836         mptsas_t                *mpt = DIP2MPT(pdip);
13837         mptsas_target_t         *ptgt = NULL;
13838 
13839         mutex_enter(&mpt->m_mutex);
13840         ptgt = mptsas_search_by_devhdl(&mpt->m_active->m_tgttbl, target);
13841         mutex_exit(&mpt->m_mutex);
13842         if (ptgt == NULL) {
13843                 mptsas_log(mpt, CE_WARN, "Volume with VolDevHandle of 0x%x "
13844                     "not found.", target);
13845                 return (rval);
13846         }
13847 
13848         sd_inq = (struct scsi_inquiry *)kmem_alloc(SUN_INQSIZE, KM_SLEEP);
13849         rval = mptsas_inquiry(mpt, ptgt, 0, 0, (uchar_t *)sd_inq,
13850             SUN_INQSIZE, 0, (uchar_t)0);
13851 
13852         if ((rval == DDI_SUCCESS) && MPTSAS_VALID_LUN(sd_inq)) {
13853                 rval = mptsas_create_phys_lun(pdip, sd_inq, NULL, dip, ptgt,
13854                     0);
13855         } else {
13856                 rval = DDI_FAILURE;
13857         }
13858 
13859         kmem_free(sd_inq, SUN_INQSIZE);
13860         return (rval);
13861 }
13862 
13863 /*
13864  * configure all RAID volumes for virtual iport
13865  */
13866 static void
13867 mptsas_config_all_viport(dev_info_t *pdip)
13868 {
13869         mptsas_t        *mpt = DIP2MPT(pdip);
13870         int             config, vol;
13871         int             target;
13872         dev_info_t      *lundip = NULL;
13873         mptsas_slots_t  *slots = mpt->m_active;
13874 
13875         /*
13876          * Get latest RAID info and search for any Volume DevHandles.  If any
13877          * are found, configure the volume.
13878          */
13879         mutex_enter(&mpt->m_mutex);
13880         for (config = 0; config < slots->m_num_raid_configs; config++) {
13881                 for (vol = 0; vol < MPTSAS_MAX_RAIDVOLS; vol++) {
13882                         if (slots->m_raidconfig[config].m_raidvol[vol].m_israid
13883                             == 1) {
13884                                 target = slots->m_raidconfig[config].
13885                                     m_raidvol[vol].m_raidhandle;
13886                                 mutex_exit(&mpt->m_mutex);
13887                                 (void) mptsas_config_raid(pdip, target,
13888                                     &lundip);
13889                                 mutex_enter(&mpt->m_mutex);
13890                         }
13891                 }
13892         }
13893         mutex_exit(&mpt->m_mutex);
13894 }
13895 
13896 static void
13897 mptsas_offline_missed_luns(dev_info_t *pdip, uint16_t *repluns,
13898     int lun_cnt, mptsas_target_t *ptgt)
13899 {
13900         dev_info_t      *child = NULL, *savechild = NULL;
13901         mdi_pathinfo_t  *pip = NULL, *savepip = NULL;
13902         uint64_t        sas_wwn, wwid;
13903         uint8_t         phy;
13904         int             lun;
13905         int             i;
13906         int             find;
13907         char            *addr;
13908         char            *nodename;
13909         mptsas_t        *mpt = DIP2MPT(pdip);
13910 
13911         mutex_enter(&mpt->m_mutex);
13912         wwid = ptgt->m_sas_wwn;
13913         mutex_exit(&mpt->m_mutex);
13914 
13915         child = ddi_get_child(pdip);
13916         while (child) {
13917                 find = 0;
13918                 savechild = child;
13919                 child = ddi_get_next_sibling(child);
13920 
13921                 nodename = ddi_node_name(savechild);
13922                 if (strcmp(nodename, "smp") == 0) {
13923                         continue;
13924                 }
13925 
13926                 addr = ddi_get_name_addr(savechild);
13927                 if (addr == NULL) {
13928                         continue;
13929                 }
13930 
13931                 if (mptsas_parse_address(addr, &sas_wwn, &phy, &lun) !=
13932                     DDI_SUCCESS) {
13933                         continue;
13934                 }
13935 
13936                 if (wwid == sas_wwn) {
13937                         for (i = 0; i < lun_cnt; i++) {
13938                                 if (repluns[i] == lun) {
13939                                         find = 1;
13940                                         break;
13941                                 }
13942                         }
13943                 } else {
13944                         continue;
13945                 }
13946                 if (find == 0) {
13947                         /*
13948                          * The lun has not been there already
13949                          */
13950                         (void) mptsas_offline_lun(pdip, savechild, NULL,
13951                             NDI_DEVI_REMOVE);
13952                 }
13953         }
13954 
13955         pip = mdi_get_next_client_path(pdip, NULL);
13956         while (pip) {
13957                 find = 0;
13958                 savepip = pip;
13959                 addr = MDI_PI(pip)->pi_addr;
13960 
13961                 pip = mdi_get_next_client_path(pdip, pip);
13962 
13963                 if (addr == NULL) {
13964                         continue;
13965                 }
13966 
13967                 if (mptsas_parse_address(addr, &sas_wwn, &phy,
13968                     &lun) != DDI_SUCCESS) {
13969                         continue;
13970                 }
13971 
13972                 if (sas_wwn == wwid) {
13973                         for (i = 0; i < lun_cnt; i++) {
13974                                 if (repluns[i] == lun) {
13975                                         find = 1;
13976                                         break;
13977                                 }
13978                         }
13979                 } else {
13980                         continue;
13981                 }
13982 
13983                 if (find == 0) {
13984                         /*
13985                          * The lun has not been there already
13986                          */
13987                         (void) mptsas_offline_lun(pdip, NULL, savepip,
13988                             NDI_DEVI_REMOVE);
13989                 }
13990         }
13991 }
13992 
13993 void
13994 mptsas_update_hashtab(struct mptsas *mpt)
13995 {
13996         uint32_t        page_address;
13997         int             rval = 0;
13998         uint16_t        dev_handle;
13999         mptsas_target_t *ptgt = NULL;
14000         mptsas_smp_t    smp_node;
14001 
14002         /*
14003          * Get latest RAID info.
14004          */
14005         (void) mptsas_get_raid_info(mpt);
14006 
14007         dev_handle = mpt->m_smp_devhdl;
14008         for (; mpt->m_done_traverse_smp == 0; ) {
14009                 page_address = (MPI2_SAS_EXPAND_PGAD_FORM_GET_NEXT_HNDL &
14010                     MPI2_SAS_EXPAND_PGAD_FORM_MASK) | (uint32_t)dev_handle;
14011                 if (mptsas_get_sas_expander_page0(mpt, page_address, &smp_node)
14012                     != DDI_SUCCESS) {
14013                         break;
14014                 }
14015                 mpt->m_smp_devhdl = dev_handle = smp_node.m_devhdl;
14016                 (void) mptsas_smp_alloc(&mpt->m_active->m_smptbl, &smp_node);
14017         }
14018 
14019         /*
14020          * Config target devices
14021          */
14022         dev_handle = mpt->m_dev_handle;
14023 
14024         /*
14025          * Do loop to get sas device page 0 by GetNextHandle till the
14026          * the last handle. If the sas device is a SATA/SSP target,
14027          * we try to config it.
14028          */
14029         for (; mpt->m_done_traverse_dev == 0; ) {
14030                 ptgt = NULL;
14031                 page_address =
14032                     (MPI2_SAS_DEVICE_PGAD_FORM_GET_NEXT_HANDLE &
14033                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
14034                     (uint32_t)dev_handle;
14035                 rval = mptsas_get_target_device_info(mpt, page_address,
14036                     &dev_handle, &ptgt);
14037                 if ((rval == DEV_INFO_FAIL_PAGE0) ||
14038                     (rval == DEV_INFO_FAIL_ALLOC)) {
14039                         break;
14040                 }
14041 
14042                 mpt->m_dev_handle = dev_handle;
14043         }
14044 
14045 }
14046 
14047 void
14048 mptsas_invalid_hashtab(mptsas_hash_table_t *hashtab)
14049 {
14050         mptsas_hash_data_t *data;
14051         data = mptsas_hash_traverse(hashtab, MPTSAS_HASH_FIRST);
14052         while (data != NULL) {
14053                 data->devhdl = MPTSAS_INVALID_DEVHDL;
14054                 data->device_info = 0;
14055                 /*
14056                  * For tgttbl, clear dr_flag.
14057                  */
14058                 data->dr_flag = MPTSAS_DR_INACTIVE;
14059                 data = mptsas_hash_traverse(hashtab, MPTSAS_HASH_NEXT);
14060         }
14061 }
14062 
14063 void
14064 mptsas_update_driver_data(struct mptsas *mpt)
14065 {
14066         /*
14067          * TODO after hard reset, update the driver data structures
14068          * 1. update port/phymask mapping table mpt->m_phy_info
14069          * 2. invalid all the entries in hash table
14070          *    m_devhdl = 0xffff and m_deviceinfo = 0
14071          * 3. call sas_device_page/expander_page to update hash table
14072          */
14073         mptsas_update_phymask(mpt);
14074         /*
14075          * Invalid the existing entries
14076          */
14077         mptsas_invalid_hashtab(&mpt->m_active->m_tgttbl);
14078         mptsas_invalid_hashtab(&mpt->m_active->m_smptbl);
14079         mpt->m_done_traverse_dev = 0;
14080         mpt->m_done_traverse_smp = 0;
14081         mpt->m_dev_handle = mpt->m_smp_devhdl = MPTSAS_INVALID_DEVHDL;
14082         mptsas_update_hashtab(mpt);
14083 }
14084 
14085 static void
14086 mptsas_config_all(dev_info_t *pdip)
14087 {
14088         dev_info_t      *smpdip = NULL;
14089         mptsas_t        *mpt = DIP2MPT(pdip);
14090         int             phymask = 0;
14091         mptsas_phymask_t phy_mask;
14092         mptsas_target_t *ptgt = NULL;
14093         mptsas_smp_t    *psmp;
14094 
14095         /*
14096          * Get the phymask associated to the iport
14097          */
14098         phymask = ddi_prop_get_int(DDI_DEV_T_ANY, pdip, 0,
14099             "phymask", 0);
14100 
14101         /*
14102          * Enumerate RAID volumes here (phymask == 0).
14103          */
14104         if (phymask == 0) {
14105                 mptsas_config_all_viport(pdip);
14106                 return;
14107         }
14108 
14109         mutex_enter(&mpt->m_mutex);
14110 
14111         if (!mpt->m_done_traverse_dev || !mpt->m_done_traverse_smp) {
14112                 mptsas_update_hashtab(mpt);
14113         }
14114 
14115         psmp = (mptsas_smp_t *)mptsas_hash_traverse(&mpt->m_active->m_smptbl,
14116             MPTSAS_HASH_FIRST);
14117         while (psmp != NULL) {
14118                 phy_mask = psmp->m_phymask;
14119                 if (phy_mask == phymask) {
14120                         smpdip = NULL;
14121                         mutex_exit(&mpt->m_mutex);
14122                         (void) mptsas_online_smp(pdip, psmp, &smpdip);
14123                         mutex_enter(&mpt->m_mutex);
14124                 }
14125                 psmp = (mptsas_smp_t *)mptsas_hash_traverse(
14126                     &mpt->m_active->m_smptbl, MPTSAS_HASH_NEXT);
14127         }
14128 
14129         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
14130             MPTSAS_HASH_FIRST);
14131         while (ptgt != NULL) {
14132                 phy_mask = ptgt->m_phymask;
14133                 if (phy_mask == phymask) {
14134                         mutex_exit(&mpt->m_mutex);
14135                         (void) mptsas_config_target(pdip, ptgt);
14136                         mutex_enter(&mpt->m_mutex);
14137                 }
14138 
14139                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
14140                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
14141         }
14142         mutex_exit(&mpt->m_mutex);
14143 }
14144 
14145 static int
14146 mptsas_config_target(dev_info_t *pdip, mptsas_target_t *ptgt)
14147 {
14148         int             rval = DDI_FAILURE;
14149         dev_info_t      *tdip;
14150 
14151         rval = mptsas_config_luns(pdip, ptgt);
14152         if (rval != DDI_SUCCESS) {
14153                 /*
14154                  * The return value means the SCMD_REPORT_LUNS
14155                  * did not execute successfully. The target maybe
14156                  * doesn't support such command.
14157                  */
14158                 rval = mptsas_probe_lun(pdip, 0, &tdip, ptgt);
14159         }
14160         return (rval);
14161 }
14162 
14163 /*
14164  * Return fail if not all the childs/paths are freed.
14165  * if there is any path under the HBA, the return value will be always fail
14166  * because we didn't call mdi_pi_free for path
14167  */
14168 static int
14169 mptsas_offline_target(dev_info_t *pdip, char *name)
14170 {
14171         dev_info_t              *child = NULL, *prechild = NULL;
14172         mdi_pathinfo_t          *pip = NULL, *savepip = NULL;
14173         int                     tmp_rval, rval = DDI_SUCCESS;
14174         char                    *addr, *cp;
14175         size_t                  s;
14176         mptsas_t                *mpt = DIP2MPT(pdip);
14177 
14178         child = ddi_get_child(pdip);
14179         while (child) {
14180                 addr = ddi_get_name_addr(child);
14181                 prechild = child;
14182                 child = ddi_get_next_sibling(child);
14183 
14184                 if (addr == NULL) {
14185                         continue;
14186                 }
14187                 if ((cp = strchr(addr, ',')) == NULL) {
14188                         continue;
14189                 }
14190 
14191                 s = (uintptr_t)cp - (uintptr_t)addr;
14192 
14193                 if (strncmp(addr, name, s) != 0) {
14194                         continue;
14195                 }
14196 
14197                 tmp_rval = mptsas_offline_lun(pdip, prechild, NULL,
14198                     NDI_DEVI_REMOVE);
14199                 if (tmp_rval != DDI_SUCCESS) {
14200                         rval = DDI_FAILURE;
14201                         if (ndi_prop_create_boolean(DDI_DEV_T_NONE,
14202                             prechild, MPTSAS_DEV_GONE) !=
14203                             DDI_PROP_SUCCESS) {
14204                                 mptsas_log(mpt, CE_WARN, "mptsas driver "
14205                                     "unable to create property for "
14206                                     "SAS %s (MPTSAS_DEV_GONE)", addr);
14207                         }
14208                 }
14209         }
14210 
14211         pip = mdi_get_next_client_path(pdip, NULL);
14212         while (pip) {
14213                 addr = MDI_PI(pip)->pi_addr;
14214                 savepip = pip;
14215                 pip = mdi_get_next_client_path(pdip, pip);
14216                 if (addr == NULL) {
14217                         continue;
14218                 }
14219 
14220                 if ((cp = strchr(addr, ',')) == NULL) {
14221                         continue;
14222                 }
14223 
14224                 s = (uintptr_t)cp - (uintptr_t)addr;
14225 
14226                 if (strncmp(addr, name, s) != 0) {
14227                         continue;
14228                 }
14229 
14230                 (void) mptsas_offline_lun(pdip, NULL, savepip,
14231                     NDI_DEVI_REMOVE);
14232                 /*
14233                  * driver will not invoke mdi_pi_free, so path will not
14234                  * be freed forever, return DDI_FAILURE.
14235                  */
14236                 rval = DDI_FAILURE;
14237         }
14238         return (rval);
14239 }
14240 
14241 static int
14242 mptsas_offline_lun(dev_info_t *pdip, dev_info_t *rdip,
14243     mdi_pathinfo_t *rpip, uint_t flags)
14244 {
14245         int             rval = DDI_FAILURE;
14246         char            *devname;
14247         dev_info_t      *cdip, *parent;
14248 
14249         if (rpip != NULL) {
14250                 parent = scsi_vhci_dip;
14251                 cdip = mdi_pi_get_client(rpip);
14252         } else if (rdip != NULL) {
14253                 parent = pdip;
14254                 cdip = rdip;
14255         } else {
14256                 return (DDI_FAILURE);
14257         }
14258 
14259         /*
14260          * Make sure node is attached otherwise
14261          * it won't have related cache nodes to
14262          * clean up.  i_ddi_devi_attached is
14263          * similiar to i_ddi_node_state(cdip) >=
14264          * DS_ATTACHED.
14265          */
14266         if (i_ddi_devi_attached(cdip)) {
14267 
14268                 /* Get full devname */
14269                 devname = kmem_alloc(MAXNAMELEN + 1, KM_SLEEP);
14270                 (void) ddi_deviname(cdip, devname);
14271                 /* Clean cache */
14272                 (void) devfs_clean(parent, devname + 1,
14273                     DV_CLEAN_FORCE);
14274                 kmem_free(devname, MAXNAMELEN + 1);
14275         }
14276         if (rpip != NULL) {
14277                 if (MDI_PI_IS_OFFLINE(rpip)) {
14278                         rval = DDI_SUCCESS;
14279                 } else {
14280                         rval = mdi_pi_offline(rpip, 0);
14281                 }
14282         } else {
14283                 rval = ndi_devi_offline(cdip, flags);
14284         }
14285 
14286         return (rval);
14287 }
14288 
14289 static dev_info_t *
14290 mptsas_find_smp_child(dev_info_t *parent, char *str_wwn)
14291 {
14292         dev_info_t      *child = NULL;
14293         char            *smp_wwn = NULL;
14294 
14295         child = ddi_get_child(parent);
14296         while (child) {
14297                 if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
14298                     DDI_PROP_DONTPASS, SMP_WWN, &smp_wwn)
14299                     != DDI_SUCCESS) {
14300                         child = ddi_get_next_sibling(child);
14301                         continue;
14302                 }
14303 
14304                 if (strcmp(smp_wwn, str_wwn) == 0) {
14305                         ddi_prop_free(smp_wwn);
14306                         break;
14307                 }
14308                 child = ddi_get_next_sibling(child);
14309                 ddi_prop_free(smp_wwn);
14310         }
14311         return (child);
14312 }
14313 
14314 static int
14315 mptsas_offline_smp(dev_info_t *pdip, mptsas_smp_t *smp_node, uint_t flags)
14316 {
14317         int             rval = DDI_FAILURE;
14318         char            *devname;
14319         char            wwn_str[MPTSAS_WWN_STRLEN];
14320         dev_info_t      *cdip;
14321 
14322         (void) sprintf(wwn_str, "%"PRIx64, smp_node->m_sasaddr);
14323 
14324         cdip = mptsas_find_smp_child(pdip, wwn_str);
14325 
14326         if (cdip == NULL)
14327                 return (DDI_SUCCESS);
14328 
14329         /*
14330          * Make sure node is attached otherwise
14331          * it won't have related cache nodes to
14332          * clean up.  i_ddi_devi_attached is
14333          * similiar to i_ddi_node_state(cdip) >=
14334          * DS_ATTACHED.
14335          */
14336         if (i_ddi_devi_attached(cdip)) {
14337 
14338                 /* Get full devname */
14339                 devname = kmem_alloc(MAXNAMELEN + 1, KM_SLEEP);
14340                 (void) ddi_deviname(cdip, devname);
14341                 /* Clean cache */
14342                 (void) devfs_clean(pdip, devname + 1,
14343                     DV_CLEAN_FORCE);
14344                 kmem_free(devname, MAXNAMELEN + 1);
14345         }
14346 
14347         rval = ndi_devi_offline(cdip, flags);
14348 
14349         return (rval);
14350 }
14351 
14352 static dev_info_t *
14353 mptsas_find_child(dev_info_t *pdip, char *name)
14354 {
14355         dev_info_t      *child = NULL;
14356         char            *rname = NULL;
14357         int             rval = DDI_FAILURE;
14358 
14359         rname = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
14360 
14361         child = ddi_get_child(pdip);
14362         while (child) {
14363                 rval = mptsas_name_child(child, rname, SCSI_MAXNAMELEN);
14364                 if (rval != DDI_SUCCESS) {
14365                         child = ddi_get_next_sibling(child);
14366                         bzero(rname, SCSI_MAXNAMELEN);
14367                         continue;
14368                 }
14369 
14370                 if (strcmp(rname, name) == 0) {
14371                         break;
14372                 }
14373                 child = ddi_get_next_sibling(child);
14374                 bzero(rname, SCSI_MAXNAMELEN);
14375         }
14376 
14377         kmem_free(rname, SCSI_MAXNAMELEN);
14378 
14379         return (child);
14380 }
14381 
14382 
14383 static dev_info_t *
14384 mptsas_find_child_addr(dev_info_t *pdip, uint64_t sasaddr, int lun)
14385 {
14386         dev_info_t      *child = NULL;
14387         char            *name = NULL;
14388         char            *addr = NULL;
14389 
14390         name = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
14391         addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
14392         (void) sprintf(name, "%016"PRIx64, sasaddr);
14393         (void) sprintf(addr, "w%s,%x", name, lun);
14394         child = mptsas_find_child(pdip, addr);
14395         kmem_free(name, SCSI_MAXNAMELEN);
14396         kmem_free(addr, SCSI_MAXNAMELEN);
14397         return (child);
14398 }
14399 
14400 static dev_info_t *
14401 mptsas_find_child_phy(dev_info_t *pdip, uint8_t phy)
14402 {
14403         dev_info_t      *child;
14404         char            *addr;
14405 
14406         addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
14407         (void) sprintf(addr, "p%x,0", phy);
14408         child = mptsas_find_child(pdip, addr);
14409         kmem_free(addr, SCSI_MAXNAMELEN);
14410         return (child);
14411 }
14412 
14413 static mdi_pathinfo_t *
14414 mptsas_find_path_phy(dev_info_t *pdip, uint8_t phy)
14415 {
14416         mdi_pathinfo_t  *path;
14417         char            *addr = NULL;
14418 
14419         addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
14420         (void) sprintf(addr, "p%x,0", phy);
14421         path = mdi_pi_find(pdip, NULL, addr);
14422         kmem_free(addr, SCSI_MAXNAMELEN);
14423         return (path);
14424 }
14425 
14426 static mdi_pathinfo_t *
14427 mptsas_find_path_addr(dev_info_t *parent, uint64_t sasaddr, int lun)
14428 {
14429         mdi_pathinfo_t  *path;
14430         char            *name = NULL;
14431         char            *addr = NULL;
14432 
14433         name = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
14434         addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
14435         (void) sprintf(name, "%016"PRIx64, sasaddr);
14436         (void) sprintf(addr, "w%s,%x", name, lun);
14437         path = mdi_pi_find(parent, NULL, addr);
14438         kmem_free(name, SCSI_MAXNAMELEN);
14439         kmem_free(addr, SCSI_MAXNAMELEN);
14440 
14441         return (path);
14442 }
14443 
14444 static int
14445 mptsas_create_lun(dev_info_t *pdip, struct scsi_inquiry *sd_inq,
14446     dev_info_t **lun_dip, mptsas_target_t *ptgt, int lun)
14447 {
14448         int                     i = 0;
14449         uchar_t                 *inq83 = NULL;
14450         int                     inq83_len1 = 0xFF;
14451         int                     inq83_len = 0;
14452         int                     rval = DDI_FAILURE;
14453         ddi_devid_t             devid;
14454         char                    *guid = NULL;
14455         int                     target = ptgt->m_devhdl;
14456         mdi_pathinfo_t          *pip = NULL;
14457         mptsas_t                *mpt = DIP2MPT(pdip);
14458 
14459         /*
14460          * For DVD/CD ROM and tape devices and optical
14461          * devices, we won't try to enumerate them under
14462          * scsi_vhci, so no need to try page83
14463          */
14464         if (sd_inq && (sd_inq->inq_dtype == DTYPE_RODIRECT ||
14465             sd_inq->inq_dtype == DTYPE_OPTICAL ||
14466             sd_inq->inq_dtype == DTYPE_ESI))
14467                 goto create_lun;
14468 
14469         /*
14470          * The LCA returns good SCSI status, but corrupt page 83 data the first
14471          * time it is queried. The solution is to keep trying to request page83
14472          * and verify the GUID is not (DDI_NOT_WELL_FORMED) in
14473          * mptsas_inq83_retry_timeout seconds. If the timeout expires, driver
14474          * give up to get VPD page at this stage and fail the enumeration.
14475          */
14476 
14477         inq83   = kmem_zalloc(inq83_len1, KM_SLEEP);
14478 
14479         for (i = 0; i < mptsas_inq83_retry_timeout; i++) {
14480                 rval = mptsas_inquiry(mpt, ptgt, lun, 0x83, inq83,
14481                     inq83_len1, &inq83_len, 1);
14482                 if (rval != 0) {
14483                         mptsas_log(mpt, CE_WARN, "!mptsas request inquiry page "
14484                             "0x83 for target:%x, lun:%x failed!", target, lun);
14485                         if (mptsas_physical_bind_failed_page_83 != B_FALSE)
14486                                 goto create_lun;
14487                         goto out;
14488                 }
14489                 /*
14490                  * create DEVID from inquiry data
14491                  */
14492                 if ((rval = ddi_devid_scsi_encode(
14493                     DEVID_SCSI_ENCODE_VERSION_LATEST, NULL, (uchar_t *)sd_inq,
14494                     sizeof (struct scsi_inquiry), NULL, 0, inq83,
14495                     (size_t)inq83_len, &devid)) == DDI_SUCCESS) {
14496                         /*
14497                          * extract GUID from DEVID
14498                          */
14499                         guid = ddi_devid_to_guid(devid);
14500 
14501                         /*
14502                          * Do not enable MPXIO if the strlen(guid) is greater
14503                          * than MPTSAS_MAX_GUID_LEN, this constrain would be
14504                          * handled by framework later.
14505                          */
14506                         if (guid && (strlen(guid) > MPTSAS_MAX_GUID_LEN)) {
14507                                 ddi_devid_free_guid(guid);
14508                                 guid = NULL;
14509                                 if (mpt->m_mpxio_enable == TRUE) {
14510                                         mptsas_log(mpt, CE_NOTE, "!Target:%x, "
14511                                             "lun:%x doesn't have a valid GUID, "
14512                                             "multipathing for this drive is "
14513                                             "not enabled", target, lun);
14514                                 }
14515                         }
14516 
14517                         /*
14518                          * devid no longer needed
14519                          */
14520                         ddi_devid_free(devid);
14521                         break;
14522                 } else if (rval == DDI_NOT_WELL_FORMED) {
14523                         /*
14524                          * return value of ddi_devid_scsi_encode equal to
14525                          * DDI_NOT_WELL_FORMED means DEVID_RETRY, it worth
14526                          * to retry inquiry page 0x83 and get GUID.
14527                          */
14528                         NDBG20(("Not well formed devid, retry..."));
14529                         delay(1 * drv_usectohz(1000000));
14530                         continue;
14531                 } else {
14532                         mptsas_log(mpt, CE_WARN, "!Encode devid failed for "
14533                             "path target:%x, lun:%x", target, lun);
14534                         rval = DDI_FAILURE;
14535                         goto create_lun;
14536                 }
14537         }
14538 
14539         if (i == mptsas_inq83_retry_timeout) {
14540                 mptsas_log(mpt, CE_WARN, "!Repeated page83 requests timeout "
14541                     "for path target:%x, lun:%x", target, lun);
14542         }
14543 
14544         rval = DDI_FAILURE;
14545 
14546 create_lun:
14547         if ((guid != NULL) && (mpt->m_mpxio_enable == TRUE)) {
14548                 rval = mptsas_create_virt_lun(pdip, sd_inq, guid, lun_dip, &pip,
14549                     ptgt, lun);
14550         }
14551         if (rval != DDI_SUCCESS) {
14552                 rval = mptsas_create_phys_lun(pdip, sd_inq, guid, lun_dip,
14553                     ptgt, lun);
14554 
14555         }
14556 out:
14557         if (guid != NULL) {
14558                 /*
14559                  * guid no longer needed
14560                  */
14561                 ddi_devid_free_guid(guid);
14562         }
14563         if (inq83 != NULL)
14564                 kmem_free(inq83, inq83_len1);
14565         return (rval);
14566 }
14567 
14568 static int
14569 mptsas_create_virt_lun(dev_info_t *pdip, struct scsi_inquiry *inq, char *guid,
14570     dev_info_t **lun_dip, mdi_pathinfo_t **pip, mptsas_target_t *ptgt, int lun)
14571 {
14572         int                     target;
14573         char                    *nodename = NULL;
14574         char                    **compatible = NULL;
14575         int                     ncompatible     = 0;
14576         int                     mdi_rtn = MDI_FAILURE;
14577         int                     rval = DDI_FAILURE;
14578         char                    *old_guid = NULL;
14579         mptsas_t                *mpt = DIP2MPT(pdip);
14580         char                    *lun_addr = NULL;
14581         char                    *wwn_str = NULL;
14582         char                    *attached_wwn_str = NULL;
14583         char                    *component = NULL;
14584         uint8_t                 phy = 0xFF;
14585         uint64_t                sas_wwn;
14586         int64_t                 lun64 = 0;
14587         uint32_t                devinfo;
14588         uint16_t                dev_hdl;
14589         uint16_t                pdev_hdl;
14590         uint64_t                dev_sas_wwn;
14591         uint64_t                pdev_sas_wwn;
14592         uint32_t                pdev_info;
14593         uint8_t                 physport;
14594         uint8_t                 phy_id;
14595         uint32_t                page_address;
14596         uint16_t                bay_num, enclosure;
14597         char                    pdev_wwn_str[MPTSAS_WWN_STRLEN];
14598         uint32_t                dev_info;
14599 
14600         mutex_enter(&mpt->m_mutex);
14601         target = ptgt->m_devhdl;
14602         sas_wwn = ptgt->m_sas_wwn;
14603         devinfo = ptgt->m_deviceinfo;
14604         phy = ptgt->m_phynum;
14605         mutex_exit(&mpt->m_mutex);
14606 
14607         if (sas_wwn) {
14608                 *pip = mptsas_find_path_addr(pdip, sas_wwn, lun);
14609         } else {
14610                 *pip = mptsas_find_path_phy(pdip, phy);
14611         }
14612 
14613         if (*pip != NULL) {
14614                 *lun_dip = MDI_PI(*pip)->pi_client->ct_dip;
14615                 ASSERT(*lun_dip != NULL);
14616                 if (ddi_prop_lookup_string(DDI_DEV_T_ANY, *lun_dip,
14617                     (DDI_PROP_DONTPASS | DDI_PROP_NOTPROM),
14618                     MDI_CLIENT_GUID_PROP, &old_guid) == DDI_SUCCESS) {
14619                         if (strncmp(guid, old_guid, strlen(guid)) == 0) {
14620                                 /*
14621                                  * Same path back online again.
14622                                  */
14623                                 (void) ddi_prop_free(old_guid);
14624                                 if ((!MDI_PI_IS_ONLINE(*pip)) &&
14625                                     (!MDI_PI_IS_STANDBY(*pip)) &&
14626                                     (ptgt->m_tgt_unconfigured == 0)) {
14627                                         rval = mdi_pi_online(*pip, 0);
14628                                         mutex_enter(&mpt->m_mutex);
14629                                         (void) mptsas_set_led_status(mpt, ptgt,
14630                                             0);
14631                                         mutex_exit(&mpt->m_mutex);
14632                                 } else {
14633                                         rval = DDI_SUCCESS;
14634                                 }
14635                                 if (rval != DDI_SUCCESS) {
14636                                         mptsas_log(mpt, CE_WARN, "path:target: "
14637                                             "%x, lun:%x online failed!", target,
14638                                             lun);
14639                                         *pip = NULL;
14640                                         *lun_dip = NULL;
14641                                 }
14642                                 return (rval);
14643                         } else {
14644                                 /*
14645                                  * The GUID of the LUN has changed which maybe
14646                                  * because customer mapped another volume to the
14647                                  * same LUN.
14648                                  */
14649                                 mptsas_log(mpt, CE_WARN, "The GUID of the "
14650                                     "target:%x, lun:%x was changed, maybe "
14651                                     "because someone mapped another volume "
14652                                     "to the same LUN", target, lun);
14653                                 (void) ddi_prop_free(old_guid);
14654                                 if (!MDI_PI_IS_OFFLINE(*pip)) {
14655                                         rval = mdi_pi_offline(*pip, 0);
14656                                         if (rval != MDI_SUCCESS) {
14657                                                 mptsas_log(mpt, CE_WARN, "path:"
14658                                                     "target:%x, lun:%x offline "
14659                                                     "failed!", target, lun);
14660                                                 *pip = NULL;
14661                                                 *lun_dip = NULL;
14662                                                 return (DDI_FAILURE);
14663                                         }
14664                                 }
14665                                 if (mdi_pi_free(*pip, 0) != MDI_SUCCESS) {
14666                                         mptsas_log(mpt, CE_WARN, "path:target:"
14667                                             "%x, lun:%x free failed!", target,
14668                                             lun);
14669                                         *pip = NULL;
14670                                         *lun_dip = NULL;
14671                                         return (DDI_FAILURE);
14672                                 }
14673                         }
14674                 } else {
14675                         mptsas_log(mpt, CE_WARN, "Can't get client-guid "
14676                             "property for path:target:%x, lun:%x", target, lun);
14677                         *pip = NULL;
14678                         *lun_dip = NULL;
14679                         return (DDI_FAILURE);
14680                 }
14681         }
14682         scsi_hba_nodename_compatible_get(inq, NULL,
14683             inq->inq_dtype, NULL, &nodename, &compatible, &ncompatible);
14684 
14685         /*
14686          * if nodename can't be determined then print a message and skip it
14687          */
14688         if (nodename == NULL) {
14689                 mptsas_log(mpt, CE_WARN, "mptsas driver found no compatible "
14690                     "driver for target%d lun %d dtype:0x%02x", target, lun,
14691                     inq->inq_dtype);
14692                 return (DDI_FAILURE);
14693         }
14694 
14695         wwn_str = kmem_zalloc(MPTSAS_WWN_STRLEN, KM_SLEEP);
14696         /* The property is needed by MPAPI */
14697         (void) sprintf(wwn_str, "%016"PRIx64, sas_wwn);
14698 
14699         lun_addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
14700         if (guid) {
14701                 (void) sprintf(lun_addr, "w%s,%x", wwn_str, lun);
14702                 (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
14703         } else {
14704                 (void) sprintf(lun_addr, "p%x,%x", phy, lun);
14705                 (void) sprintf(wwn_str, "p%x", phy);
14706         }
14707 
14708         mdi_rtn = mdi_pi_alloc_compatible(pdip, nodename,
14709             guid, lun_addr, compatible, ncompatible,
14710             0, pip);
14711         if (mdi_rtn == MDI_SUCCESS) {
14712 
14713                 if (mdi_prop_update_string(*pip, MDI_GUID,
14714                     guid) != DDI_SUCCESS) {
14715                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14716                             "create prop for target %d lun %d (MDI_GUID)",
14717                             target, lun);
14718                         mdi_rtn = MDI_FAILURE;
14719                         goto virt_create_done;
14720                 }
14721 
14722                 if (mdi_prop_update_int(*pip, LUN_PROP,
14723                     lun) != DDI_SUCCESS) {
14724                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14725                             "create prop for target %d lun %d (LUN_PROP)",
14726                             target, lun);
14727                         mdi_rtn = MDI_FAILURE;
14728                         goto virt_create_done;
14729                 }
14730                 lun64 = (int64_t)lun;
14731                 if (mdi_prop_update_int64(*pip, LUN64_PROP,
14732                     lun64) != DDI_SUCCESS) {
14733                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14734                             "create prop for target %d (LUN64_PROP)",
14735                             target);
14736                         mdi_rtn = MDI_FAILURE;
14737                         goto virt_create_done;
14738                 }
14739                 if (mdi_prop_update_string_array(*pip, "compatible",
14740                     compatible, ncompatible) !=
14741                     DDI_PROP_SUCCESS) {
14742                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14743                             "create prop for target %d lun %d (COMPATIBLE)",
14744                             target, lun);
14745                         mdi_rtn = MDI_FAILURE;
14746                         goto virt_create_done;
14747                 }
14748                 if (sas_wwn && (mdi_prop_update_string(*pip,
14749                     SCSI_ADDR_PROP_TARGET_PORT, wwn_str) != DDI_PROP_SUCCESS)) {
14750                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14751                             "create prop for target %d lun %d "
14752                             "(target-port)", target, lun);
14753                         mdi_rtn = MDI_FAILURE;
14754                         goto virt_create_done;
14755                 } else if ((sas_wwn == 0) && (mdi_prop_update_int(*pip,
14756                     "sata-phy", phy) != DDI_PROP_SUCCESS)) {
14757                         /*
14758                          * Direct attached SATA device without DeviceName
14759                          */
14760                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14761                             "create prop for SAS target %d lun %d "
14762                             "(sata-phy)", target, lun);
14763                         mdi_rtn = MDI_FAILURE;
14764                         goto virt_create_done;
14765                 }
14766                 mutex_enter(&mpt->m_mutex);
14767 
14768                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
14769                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
14770                     (uint32_t)ptgt->m_devhdl;
14771                 rval = mptsas_get_sas_device_page0(mpt, page_address,
14772                     &dev_hdl, &dev_sas_wwn, &dev_info, &physport,
14773                     &phy_id, &pdev_hdl, &bay_num, &enclosure);
14774                 if (rval != DDI_SUCCESS) {
14775                         mutex_exit(&mpt->m_mutex);
14776                         mptsas_log(mpt, CE_WARN, "mptsas unable to get "
14777                             "parent device for handle %d", page_address);
14778                         mdi_rtn = MDI_FAILURE;
14779                         goto virt_create_done;
14780                 }
14781 
14782                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
14783                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) | (uint32_t)pdev_hdl;
14784                 rval = mptsas_get_sas_device_page0(mpt, page_address,
14785                     &dev_hdl, &pdev_sas_wwn, &pdev_info, &physport,
14786                     &phy_id, &pdev_hdl, &bay_num, &enclosure);
14787                 if (rval != DDI_SUCCESS) {
14788                         mutex_exit(&mpt->m_mutex);
14789                         mptsas_log(mpt, CE_WARN, "mptsas unable to get"
14790                             "device info for handle %d", page_address);
14791                         mdi_rtn = MDI_FAILURE;
14792                         goto virt_create_done;
14793                 }
14794 
14795                 mutex_exit(&mpt->m_mutex);
14796 
14797                 /*
14798                  * If this device direct attached to the controller
14799                  * set the attached-port to the base wwid
14800                  */
14801                 if ((ptgt->m_deviceinfo & DEVINFO_DIRECT_ATTACHED)
14802                     != DEVINFO_DIRECT_ATTACHED) {
14803                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
14804                             pdev_sas_wwn);
14805                 } else {
14806                         /*
14807                          * Update the iport's attached-port to guid
14808                          */
14809                         if (sas_wwn == 0) {
14810                                 (void) sprintf(wwn_str, "p%x", phy);
14811                         } else {
14812                                 (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
14813                         }
14814                         if (ddi_prop_update_string(DDI_DEV_T_NONE,
14815                             pdip, SCSI_ADDR_PROP_ATTACHED_PORT, wwn_str) !=
14816                             DDI_PROP_SUCCESS) {
14817                                 mptsas_log(mpt, CE_WARN,
14818                                     "mptsas unable to create "
14819                                     "property for iport target-port"
14820                                     " %s (sas_wwn)",
14821                                     wwn_str);
14822                                 mdi_rtn = MDI_FAILURE;
14823                                 goto virt_create_done;
14824                         }
14825 
14826                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
14827                             mpt->un.m_base_wwid);
14828                 }
14829 
14830                 if (mdi_prop_update_string(*pip,
14831                     SCSI_ADDR_PROP_ATTACHED_PORT, pdev_wwn_str) !=
14832                     DDI_PROP_SUCCESS) {
14833                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
14834                             "property for iport attached-port %s (sas_wwn)",
14835                             attached_wwn_str);
14836                         mdi_rtn = MDI_FAILURE;
14837                         goto virt_create_done;
14838                 }
14839 
14840 
14841                 if (inq->inq_dtype == 0) {
14842                         component = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
14843                         /*
14844                          * set obp path for pathinfo
14845                          */
14846                         (void) snprintf(component, MAXPATHLEN,
14847                             "disk@%s", lun_addr);
14848 
14849                         if (mdi_pi_pathname_obp_set(*pip, component) !=
14850                             DDI_SUCCESS) {
14851                                 mptsas_log(mpt, CE_WARN, "mpt_sas driver "
14852                                     "unable to set obp-path for object %s",
14853                                     component);
14854                                 mdi_rtn = MDI_FAILURE;
14855                                 goto virt_create_done;
14856                         }
14857                 }
14858 
14859                 *lun_dip = MDI_PI(*pip)->pi_client->ct_dip;
14860                 if (devinfo & (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
14861                     MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
14862                         if ((ndi_prop_update_int(DDI_DEV_T_NONE, *lun_dip,
14863                             "pm-capable", 1)) !=
14864                             DDI_PROP_SUCCESS) {
14865                                 mptsas_log(mpt, CE_WARN, "mptsas driver"
14866                                     "failed to create pm-capable "
14867                                     "property, target %d", target);
14868                                 mdi_rtn = MDI_FAILURE;
14869                                 goto virt_create_done;
14870                         }
14871                 }
14872                 /*
14873                  * Create the phy-num property
14874                  */
14875                 if (mdi_prop_update_int(*pip, "phy-num",
14876                     ptgt->m_phynum) != DDI_SUCCESS) {
14877                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14878                             "create phy-num property for target %d lun %d",
14879                             target, lun);
14880                         mdi_rtn = MDI_FAILURE;
14881                         goto virt_create_done;
14882                 }
14883                 NDBG20(("new path:%s onlining,", MDI_PI(*pip)->pi_addr));
14884                 mdi_rtn = mdi_pi_online(*pip, 0);
14885                 if (mdi_rtn == MDI_SUCCESS) {
14886                         mutex_enter(&mpt->m_mutex);
14887                         if (mptsas_set_led_status(mpt, ptgt, 0) !=
14888                             DDI_SUCCESS) {
14889                                 NDBG14(("mptsas: clear LED for slot %x "
14890                                     "failed", ptgt->m_slot_num));
14891                         }
14892                         mutex_exit(&mpt->m_mutex);
14893                 }
14894                 if (mdi_rtn == MDI_NOT_SUPPORTED) {
14895                         mdi_rtn = MDI_FAILURE;
14896                 }
14897 virt_create_done:
14898                 if (*pip && mdi_rtn != MDI_SUCCESS) {
14899                         (void) mdi_pi_free(*pip, 0);
14900                         *pip = NULL;
14901                         *lun_dip = NULL;
14902                 }
14903         }
14904 
14905         scsi_hba_nodename_compatible_free(nodename, compatible);
14906         if (lun_addr != NULL) {
14907                 kmem_free(lun_addr, SCSI_MAXNAMELEN);
14908         }
14909         if (wwn_str != NULL) {
14910                 kmem_free(wwn_str, MPTSAS_WWN_STRLEN);
14911         }
14912         if (component != NULL) {
14913                 kmem_free(component, MAXPATHLEN);
14914         }
14915 
14916         return ((mdi_rtn == MDI_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
14917 }
14918 
14919 static int
14920 mptsas_create_phys_lun(dev_info_t *pdip, struct scsi_inquiry *inq,
14921     char *guid, dev_info_t **lun_dip, mptsas_target_t *ptgt, int lun)
14922 {
14923         int                     target;
14924         int                     rval;
14925         int                     ndi_rtn = NDI_FAILURE;
14926         uint64_t                be_sas_wwn;
14927         char                    *nodename = NULL;
14928         char                    **compatible = NULL;
14929         int                     ncompatible = 0;
14930         int                     instance = 0;
14931         mptsas_t                *mpt = DIP2MPT(pdip);
14932         char                    *wwn_str = NULL;
14933         char                    *component = NULL;
14934         char                    *attached_wwn_str = NULL;
14935         uint8_t                 phy = 0xFF;
14936         uint64_t                sas_wwn;
14937         uint32_t                devinfo;
14938         uint16_t                dev_hdl;
14939         uint16_t                pdev_hdl;
14940         uint64_t                pdev_sas_wwn;
14941         uint64_t                dev_sas_wwn;
14942         uint32_t                pdev_info;
14943         uint8_t                 physport;
14944         uint8_t                 phy_id;
14945         uint32_t                page_address;
14946         uint16_t                bay_num, enclosure;
14947         char                    pdev_wwn_str[MPTSAS_WWN_STRLEN];
14948         uint32_t                dev_info;
14949         int64_t                 lun64 = 0;
14950 
14951         mutex_enter(&mpt->m_mutex);
14952         target = ptgt->m_devhdl;
14953         sas_wwn = ptgt->m_sas_wwn;
14954         devinfo = ptgt->m_deviceinfo;
14955         phy = ptgt->m_phynum;
14956         mutex_exit(&mpt->m_mutex);
14957 
14958         /*
14959          * generate compatible property with binding-set "mpt"
14960          */
14961         scsi_hba_nodename_compatible_get(inq, NULL, inq->inq_dtype, NULL,
14962             &nodename, &compatible, &ncompatible);
14963 
14964         /*
14965          * if nodename can't be determined then print a message and skip it
14966          */
14967         if (nodename == NULL) {
14968                 mptsas_log(mpt, CE_WARN, "mptsas found no compatible driver "
14969                     "for target %d lun %d", target, lun);
14970                 return (DDI_FAILURE);
14971         }
14972 
14973         ndi_rtn = ndi_devi_alloc(pdip, nodename,
14974             DEVI_SID_NODEID, lun_dip);
14975 
14976         /*
14977          * if lun alloc success, set props
14978          */
14979         if (ndi_rtn == NDI_SUCCESS) {
14980 
14981                 if (ndi_prop_update_int(DDI_DEV_T_NONE,
14982                     *lun_dip, LUN_PROP, lun) !=
14983                     DDI_PROP_SUCCESS) {
14984                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
14985                             "property for target %d lun %d (LUN_PROP)",
14986                             target, lun);
14987                         ndi_rtn = NDI_FAILURE;
14988                         goto phys_create_done;
14989                 }
14990 
14991                 lun64 = (int64_t)lun;
14992                 if (ndi_prop_update_int64(DDI_DEV_T_NONE,
14993                     *lun_dip, LUN64_PROP, lun64) !=
14994                     DDI_PROP_SUCCESS) {
14995                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
14996                             "property for target %d lun64 %d (LUN64_PROP)",
14997                             target, lun);
14998                         ndi_rtn = NDI_FAILURE;
14999                         goto phys_create_done;
15000                 }
15001                 if (ndi_prop_update_string_array(DDI_DEV_T_NONE,
15002                     *lun_dip, "compatible", compatible, ncompatible)
15003                     != DDI_PROP_SUCCESS) {
15004                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
15005                             "property for target %d lun %d (COMPATIBLE)",
15006                             target, lun);
15007                         ndi_rtn = NDI_FAILURE;
15008                         goto phys_create_done;
15009                 }
15010 
15011                 /*
15012                  * We need the SAS WWN for non-multipath devices, so
15013                  * we'll use the same property as that multipathing
15014                  * devices need to present for MPAPI. If we don't have
15015                  * a WWN (e.g. parallel SCSI), don't create the prop.
15016                  */
15017                 wwn_str = kmem_zalloc(MPTSAS_WWN_STRLEN, KM_SLEEP);
15018                 (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
15019                 if (sas_wwn && ndi_prop_update_string(DDI_DEV_T_NONE,
15020                     *lun_dip, SCSI_ADDR_PROP_TARGET_PORT, wwn_str)
15021                     != DDI_PROP_SUCCESS) {
15022                         mptsas_log(mpt, CE_WARN, "mptsas unable to "
15023                             "create property for SAS target %d lun %d "
15024                             "(target-port)", target, lun);
15025                         ndi_rtn = NDI_FAILURE;
15026                         goto phys_create_done;
15027                 }
15028 
15029                 be_sas_wwn = BE_64(sas_wwn);
15030                 if (sas_wwn && ndi_prop_update_byte_array(
15031                     DDI_DEV_T_NONE, *lun_dip, "port-wwn",
15032                     (uchar_t *)&be_sas_wwn, 8) != DDI_PROP_SUCCESS) {
15033                         mptsas_log(mpt, CE_WARN, "mptsas unable to "
15034                             "create property for SAS target %d lun %d "
15035                             "(port-wwn)", target, lun);
15036                         ndi_rtn = NDI_FAILURE;
15037                         goto phys_create_done;
15038                 } else if ((sas_wwn == 0) && (ndi_prop_update_int(
15039                     DDI_DEV_T_NONE, *lun_dip, "sata-phy", phy) !=
15040                     DDI_PROP_SUCCESS)) {
15041                         /*
15042                          * Direct attached SATA device without DeviceName
15043                          */
15044                         mptsas_log(mpt, CE_WARN, "mptsas unable to "
15045                             "create property for SAS target %d lun %d "
15046                             "(sata-phy)", target, lun);
15047                         ndi_rtn = NDI_FAILURE;
15048                         goto phys_create_done;
15049                 }
15050 
15051                 if (ndi_prop_create_boolean(DDI_DEV_T_NONE,
15052                     *lun_dip, SAS_PROP) != DDI_PROP_SUCCESS) {
15053                         mptsas_log(mpt, CE_WARN, "mptsas unable to"
15054                             "create property for SAS target %d lun %d"
15055                             " (SAS_PROP)", target, lun);
15056                         ndi_rtn = NDI_FAILURE;
15057                         goto phys_create_done;
15058                 }
15059                 if (guid && (ndi_prop_update_string(DDI_DEV_T_NONE,
15060                     *lun_dip, NDI_GUID, guid) != DDI_SUCCESS)) {
15061                         mptsas_log(mpt, CE_WARN, "mptsas unable "
15062                             "to create guid property for target %d "
15063                             "lun %d", target, lun);
15064                         ndi_rtn = NDI_FAILURE;
15065                         goto phys_create_done;
15066                 }
15067 
15068                 /*
15069                  * The following code is to set properties for SM-HBA support,
15070                  * it doesn't apply to RAID volumes
15071                  */
15072                 if (ptgt->m_phymask == 0)
15073                         goto phys_raid_lun;
15074 
15075                 mutex_enter(&mpt->m_mutex);
15076 
15077                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
15078                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
15079                     (uint32_t)ptgt->m_devhdl;
15080                 rval = mptsas_get_sas_device_page0(mpt, page_address,
15081                     &dev_hdl, &dev_sas_wwn, &dev_info,
15082                     &physport, &phy_id, &pdev_hdl,
15083                     &bay_num, &enclosure);
15084                 if (rval != DDI_SUCCESS) {
15085                         mutex_exit(&mpt->m_mutex);
15086                         mptsas_log(mpt, CE_WARN, "mptsas unable to get"
15087                             "parent device for handle %d.", page_address);
15088                         ndi_rtn = NDI_FAILURE;
15089                         goto phys_create_done;
15090                 }
15091 
15092                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
15093                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) | (uint32_t)pdev_hdl;
15094                 rval = mptsas_get_sas_device_page0(mpt, page_address,
15095                     &dev_hdl, &pdev_sas_wwn, &pdev_info,
15096                     &physport, &phy_id, &pdev_hdl, &bay_num, &enclosure);
15097                 if (rval != DDI_SUCCESS) {
15098                         mutex_exit(&mpt->m_mutex);
15099                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
15100                             "device for handle %d.", page_address);
15101                         ndi_rtn = NDI_FAILURE;
15102                         goto phys_create_done;
15103                 }
15104 
15105                 mutex_exit(&mpt->m_mutex);
15106 
15107                 /*
15108                  * If this device direct attached to the controller
15109                  * set the attached-port to the base wwid
15110                  */
15111                 if ((ptgt->m_deviceinfo & DEVINFO_DIRECT_ATTACHED)
15112                     != DEVINFO_DIRECT_ATTACHED) {
15113                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
15114                             pdev_sas_wwn);
15115                 } else {
15116                         /*
15117                          * Update the iport's attached-port to guid
15118                          */
15119                         if (sas_wwn == 0) {
15120                                 (void) sprintf(wwn_str, "p%x", phy);
15121                         } else {
15122                                 (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
15123                         }
15124                         if (ddi_prop_update_string(DDI_DEV_T_NONE,
15125                             pdip, SCSI_ADDR_PROP_ATTACHED_PORT, wwn_str) !=
15126                             DDI_PROP_SUCCESS) {
15127                                 mptsas_log(mpt, CE_WARN,
15128                                     "mptsas unable to create "
15129                                     "property for iport target-port"
15130                                     " %s (sas_wwn)",
15131                                     wwn_str);
15132                                 ndi_rtn = NDI_FAILURE;
15133                                 goto phys_create_done;
15134                         }
15135 
15136                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
15137                             mpt->un.m_base_wwid);
15138                 }
15139 
15140                 if (ndi_prop_update_string(DDI_DEV_T_NONE,
15141                     *lun_dip, SCSI_ADDR_PROP_ATTACHED_PORT, pdev_wwn_str) !=
15142                     DDI_PROP_SUCCESS) {
15143                         mptsas_log(mpt, CE_WARN,
15144                             "mptsas unable to create "
15145                             "property for iport attached-port %s (sas_wwn)",
15146                             attached_wwn_str);
15147                         ndi_rtn = NDI_FAILURE;
15148                         goto phys_create_done;
15149                 }
15150 
15151                 if (IS_SATA_DEVICE(dev_info)) {
15152                         if (ndi_prop_update_string(DDI_DEV_T_NONE,
15153                             *lun_dip, MPTSAS_VARIANT, "sata") !=
15154                             DDI_PROP_SUCCESS) {
15155                                 mptsas_log(mpt, CE_WARN,
15156                                     "mptsas unable to create "
15157                                     "property for device variant ");
15158                                 ndi_rtn = NDI_FAILURE;
15159                                 goto phys_create_done;
15160                         }
15161                 }
15162 
15163                 if (IS_ATAPI_DEVICE(dev_info)) {
15164                         if (ndi_prop_update_string(DDI_DEV_T_NONE,
15165                             *lun_dip, MPTSAS_VARIANT, "atapi") !=
15166                             DDI_PROP_SUCCESS) {
15167                                 mptsas_log(mpt, CE_WARN,
15168                                     "mptsas unable to create "
15169                                     "property for device variant ");
15170                                 ndi_rtn = NDI_FAILURE;
15171                                 goto phys_create_done;
15172                         }
15173                 }
15174 
15175 phys_raid_lun:
15176                 /*
15177                  * if this is a SAS controller, and the target is a SATA
15178                  * drive, set the 'pm-capable' property for sd and if on
15179                  * an OPL platform, also check if this is an ATAPI
15180                  * device.
15181                  */
15182                 instance = ddi_get_instance(mpt->m_dip);
15183                 if (devinfo & (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
15184                     MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
15185                         NDBG2(("mptsas%d: creating pm-capable property, "
15186                             "target %d", instance, target));
15187 
15188                         if ((ndi_prop_update_int(DDI_DEV_T_NONE,
15189                             *lun_dip, "pm-capable", 1)) !=
15190                             DDI_PROP_SUCCESS) {
15191                                 mptsas_log(mpt, CE_WARN, "mptsas "
15192                                     "failed to create pm-capable "
15193                                     "property, target %d", target);
15194                                 ndi_rtn = NDI_FAILURE;
15195                                 goto phys_create_done;
15196                         }
15197 
15198                 }
15199 
15200                 if ((inq->inq_dtype == 0) || (inq->inq_dtype == 5)) {
15201                         /*
15202                          * add 'obp-path' properties for devinfo
15203                          */
15204                         bzero(wwn_str, sizeof (wwn_str));
15205                         (void) sprintf(wwn_str, "%016"PRIx64, sas_wwn);
15206                         component = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
15207                         if (guid) {
15208                                 (void) snprintf(component, MAXPATHLEN,
15209                                     "disk@w%s,%x", wwn_str, lun);
15210                         } else {
15211                                 (void) snprintf(component, MAXPATHLEN,
15212                                     "disk@p%x,%x", phy, lun);
15213                         }
15214                         if (ddi_pathname_obp_set(*lun_dip, component)
15215                             != DDI_SUCCESS) {
15216                                 mptsas_log(mpt, CE_WARN, "mpt_sas driver "
15217                                     "unable to set obp-path for SAS "
15218                                     "object %s", component);
15219                                 ndi_rtn = NDI_FAILURE;
15220                                 goto phys_create_done;
15221                         }
15222                 }
15223                 /*
15224                  * Create the phy-num property for non-raid disk
15225                  */
15226                 if (ptgt->m_phymask != 0) {
15227                         if (ndi_prop_update_int(DDI_DEV_T_NONE,
15228                             *lun_dip, "phy-num", ptgt->m_phynum) !=
15229                             DDI_PROP_SUCCESS) {
15230                                 mptsas_log(mpt, CE_WARN, "mptsas driver "
15231                                     "failed to create phy-num property for "
15232                                     "target %d", target);
15233                                 ndi_rtn = NDI_FAILURE;
15234                                 goto phys_create_done;
15235                         }
15236                 }
15237 phys_create_done:
15238                 /*
15239                  * If props were setup ok, online the lun
15240                  */
15241                 if (ndi_rtn == NDI_SUCCESS) {
15242                         /*
15243                          * Try to online the new node
15244                          */
15245                         ndi_rtn = ndi_devi_online(*lun_dip, NDI_ONLINE_ATTACH);
15246                 }
15247                 if (ndi_rtn == NDI_SUCCESS) {
15248                         mutex_enter(&mpt->m_mutex);
15249                         if (mptsas_set_led_status(mpt, ptgt, 0) !=
15250                             DDI_SUCCESS) {
15251                                 NDBG14(("mptsas: clear LED for tgt %x "
15252                                     "failed", ptgt->m_slot_num));
15253                         }
15254                         mutex_exit(&mpt->m_mutex);
15255                 }
15256 
15257                 /*
15258                  * If success set rtn flag, else unwire alloc'd lun
15259                  */
15260                 if (ndi_rtn != NDI_SUCCESS) {
15261                         NDBG12(("mptsas driver unable to online "
15262                             "target %d lun %d", target, lun));
15263                         ndi_prop_remove_all(*lun_dip);
15264                         (void) ndi_devi_free(*lun_dip);
15265                         *lun_dip = NULL;
15266                 }
15267         }
15268 
15269         scsi_hba_nodename_compatible_free(nodename, compatible);
15270 
15271         if (wwn_str != NULL) {
15272                 kmem_free(wwn_str, MPTSAS_WWN_STRLEN);
15273         }
15274         if (component != NULL) {
15275                 kmem_free(component, MAXPATHLEN);
15276         }
15277 
15278 
15279         return ((ndi_rtn == NDI_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
15280 }
15281 
15282 static int
15283 mptsas_probe_smp(dev_info_t *pdip, uint64_t wwn)
15284 {
15285         mptsas_t        *mpt = DIP2MPT(pdip);
15286         struct smp_device smp_sd;
15287 
15288         /* XXX An HBA driver should not be allocating an smp_device. */
15289         bzero(&smp_sd, sizeof (struct smp_device));
15290         smp_sd.smp_sd_address.smp_a_hba_tran = mpt->m_smptran;
15291         bcopy(&wwn, smp_sd.smp_sd_address.smp_a_wwn, SAS_WWN_BYTE_SIZE);
15292 
15293         if (smp_probe(&smp_sd) != DDI_PROBE_SUCCESS)
15294                 return (NDI_FAILURE);
15295         return (NDI_SUCCESS);
15296 }
15297 
15298 static int
15299 mptsas_config_smp(dev_info_t *pdip, uint64_t sas_wwn, dev_info_t **smp_dip)
15300 {
15301         mptsas_t        *mpt = DIP2MPT(pdip);
15302         mptsas_smp_t    *psmp = NULL;
15303         int             rval;
15304         int             phymask;
15305 
15306         /*
15307          * Get the physical port associated to the iport
15308          * PHYMASK TODO
15309          */
15310         phymask = ddi_prop_get_int(DDI_DEV_T_ANY, pdip, 0,
15311             "phymask", 0);
15312         /*
15313          * Find the smp node in hash table with specified sas address and
15314          * physical port
15315          */
15316         psmp = mptsas_wwid_to_psmp(mpt, phymask, sas_wwn);
15317         if (psmp == NULL) {
15318                 return (DDI_FAILURE);
15319         }
15320 
15321         rval = mptsas_online_smp(pdip, psmp, smp_dip);
15322 
15323         return (rval);
15324 }
15325 
15326 static int
15327 mptsas_online_smp(dev_info_t *pdip, mptsas_smp_t *smp_node,
15328     dev_info_t **smp_dip)
15329 {
15330         char            wwn_str[MPTSAS_WWN_STRLEN];
15331         char            attached_wwn_str[MPTSAS_WWN_STRLEN];
15332         int             ndi_rtn = NDI_FAILURE;
15333         int             rval = 0;
15334         mptsas_smp_t    dev_info;
15335         uint32_t        page_address;
15336         mptsas_t        *mpt = DIP2MPT(pdip);
15337         uint16_t        dev_hdl;
15338         uint64_t        sas_wwn;
15339         uint64_t        smp_sas_wwn;
15340         uint8_t         physport;
15341         uint8_t         phy_id;
15342         uint16_t        pdev_hdl;
15343         uint8_t         numphys = 0;
15344         uint16_t        i = 0;
15345         char            phymask[MPTSAS_MAX_PHYS];
15346         char            *iport = NULL;
15347         mptsas_phymask_t        phy_mask = 0;
15348         uint16_t        attached_devhdl;
15349         uint16_t        bay_num, enclosure;
15350 
15351         (void) sprintf(wwn_str, "%"PRIx64, smp_node->m_sasaddr);
15352 
15353         /*
15354          * Probe smp device, prevent the node of removed device from being
15355          * configured succesfully
15356          */
15357         if (mptsas_probe_smp(pdip, smp_node->m_sasaddr) != NDI_SUCCESS) {
15358                 return (DDI_FAILURE);
15359         }
15360 
15361         if ((*smp_dip = mptsas_find_smp_child(pdip, wwn_str)) != NULL) {
15362                 return (DDI_SUCCESS);
15363         }
15364 
15365         ndi_rtn = ndi_devi_alloc(pdip, "smp", DEVI_SID_NODEID, smp_dip);
15366 
15367         /*
15368          * if lun alloc success, set props
15369          */
15370         if (ndi_rtn == NDI_SUCCESS) {
15371                 /*
15372                  * Set the flavor of the child to be SMP flavored
15373                  */
15374                 ndi_flavor_set(*smp_dip, SCSA_FLAVOR_SMP);
15375 
15376                 if (ndi_prop_update_string(DDI_DEV_T_NONE,
15377                     *smp_dip, SMP_WWN, wwn_str) !=
15378                     DDI_PROP_SUCCESS) {
15379                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
15380                             "property for smp device %s (sas_wwn)",
15381                             wwn_str);
15382                         ndi_rtn = NDI_FAILURE;
15383                         goto smp_create_done;
15384                 }
15385                 (void) sprintf(wwn_str, "w%"PRIx64, smp_node->m_sasaddr);
15386                 if (ndi_prop_update_string(DDI_DEV_T_NONE,
15387                     *smp_dip, SCSI_ADDR_PROP_TARGET_PORT, wwn_str) !=
15388                     DDI_PROP_SUCCESS) {
15389                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
15390                             "property for iport target-port %s (sas_wwn)",
15391                             wwn_str);
15392                         ndi_rtn = NDI_FAILURE;
15393                         goto smp_create_done;
15394                 }
15395 
15396                 mutex_enter(&mpt->m_mutex);
15397 
15398                 page_address = (MPI2_SAS_EXPAND_PGAD_FORM_HNDL &
15399                     MPI2_SAS_EXPAND_PGAD_FORM_MASK) | smp_node->m_devhdl;
15400                 rval = mptsas_get_sas_expander_page0(mpt, page_address,
15401                     &dev_info);
15402                 if (rval != DDI_SUCCESS) {
15403                         mutex_exit(&mpt->m_mutex);
15404                         mptsas_log(mpt, CE_WARN,
15405                             "mptsas unable to get expander "
15406                             "parent device info for %x", page_address);
15407                         ndi_rtn = NDI_FAILURE;
15408                         goto smp_create_done;
15409                 }
15410 
15411                 smp_node->m_pdevhdl = dev_info.m_pdevhdl;
15412                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
15413                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
15414                     (uint32_t)dev_info.m_pdevhdl;
15415                 rval = mptsas_get_sas_device_page0(mpt, page_address,
15416                     &dev_hdl, &sas_wwn, &smp_node->m_pdevinfo,
15417                     &physport, &phy_id, &pdev_hdl, &bay_num, &enclosure);
15418                 if (rval != DDI_SUCCESS) {
15419                         mutex_exit(&mpt->m_mutex);
15420                         mptsas_log(mpt, CE_WARN, "mptsas unable to get "
15421                             "device info for %x", page_address);
15422                         ndi_rtn = NDI_FAILURE;
15423                         goto smp_create_done;
15424                 }
15425 
15426                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
15427                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
15428                     (uint32_t)dev_info.m_devhdl;
15429                 rval = mptsas_get_sas_device_page0(mpt, page_address,
15430                     &dev_hdl, &smp_sas_wwn, &smp_node->m_deviceinfo,
15431                     &physport, &phy_id, &pdev_hdl, &bay_num, &enclosure);
15432                 if (rval != DDI_SUCCESS) {
15433                         mutex_exit(&mpt->m_mutex);
15434                         mptsas_log(mpt, CE_WARN, "mptsas unable to get "
15435                             "device info for %x", page_address);
15436                         ndi_rtn = NDI_FAILURE;
15437                         goto smp_create_done;
15438                 }
15439                 mutex_exit(&mpt->m_mutex);
15440 
15441                 /*
15442                  * If this smp direct attached to the controller
15443                  * set the attached-port to the base wwid
15444                  */
15445                 if ((smp_node->m_deviceinfo & DEVINFO_DIRECT_ATTACHED)
15446                     != DEVINFO_DIRECT_ATTACHED) {
15447                         (void) sprintf(attached_wwn_str, "w%016"PRIx64,
15448                             sas_wwn);
15449                 } else {
15450                         (void) sprintf(attached_wwn_str, "w%016"PRIx64,
15451                             mpt->un.m_base_wwid);
15452                 }
15453 
15454                 if (ndi_prop_update_string(DDI_DEV_T_NONE,
15455                     *smp_dip, SCSI_ADDR_PROP_ATTACHED_PORT, attached_wwn_str) !=
15456                     DDI_PROP_SUCCESS) {
15457                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
15458                             "property for smp attached-port %s (sas_wwn)",
15459                             attached_wwn_str);
15460                         ndi_rtn = NDI_FAILURE;
15461                         goto smp_create_done;
15462                 }
15463 
15464                 if (ndi_prop_create_boolean(DDI_DEV_T_NONE,
15465                     *smp_dip, SMP_PROP) != DDI_PROP_SUCCESS) {
15466                         mptsas_log(mpt, CE_WARN, "mptsas unable to "
15467                             "create property for SMP %s (SMP_PROP) ",
15468                             wwn_str);
15469                         ndi_rtn = NDI_FAILURE;
15470                         goto smp_create_done;
15471                 }
15472 
15473                 /*
15474                  * check the smp to see whether it direct
15475                  * attached to the controller
15476                  */
15477                 if ((smp_node->m_deviceinfo & DEVINFO_DIRECT_ATTACHED)
15478                     != DEVINFO_DIRECT_ATTACHED) {
15479                         goto smp_create_done;
15480                 }
15481                 numphys = ddi_prop_get_int(DDI_DEV_T_ANY, pdip,
15482                     DDI_PROP_DONTPASS, MPTSAS_NUM_PHYS, -1);
15483                 if (numphys > 0) {
15484                         goto smp_create_done;
15485                 }
15486                 /*
15487                  * this iport is an old iport, we need to
15488                  * reconfig the props for it.
15489                  */
15490                 if (ddi_prop_update_int(DDI_DEV_T_NONE, pdip,
15491                     MPTSAS_VIRTUAL_PORT, 0) !=
15492                     DDI_PROP_SUCCESS) {
15493                         (void) ddi_prop_remove(DDI_DEV_T_NONE, pdip,
15494                             MPTSAS_VIRTUAL_PORT);
15495                         mptsas_log(mpt, CE_WARN, "mptsas virtual port "
15496                             "prop update failed");
15497                         goto smp_create_done;
15498                 }
15499 
15500                 mutex_enter(&mpt->m_mutex);
15501                 numphys = 0;
15502                 iport = ddi_get_name_addr(pdip);
15503                 for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
15504                         bzero(phymask, sizeof (phymask));
15505                         (void) sprintf(phymask,
15506                             "%x", mpt->m_phy_info[i].phy_mask);
15507                         if (strcmp(phymask, iport) == 0) {
15508                                 phy_mask = mpt->m_phy_info[i].phy_mask;
15509                                 break;
15510                         }
15511                 }
15512 
15513                 for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
15514                         if ((phy_mask >> i) & 0x01) {
15515                                 numphys++;
15516                         }
15517                 }
15518                 /*
15519                  * Update PHY info for smhba
15520                  */
15521                 if (mptsas_smhba_phy_init(mpt)) {
15522                         mutex_exit(&mpt->m_mutex);
15523                         mptsas_log(mpt, CE_WARN, "mptsas phy update "
15524                             "failed");
15525                         goto smp_create_done;
15526                 }
15527                 mutex_exit(&mpt->m_mutex);
15528 
15529                 mptsas_smhba_set_phy_props(mpt, iport, pdip,
15530                     numphys, &attached_devhdl);
15531 
15532                 if (ddi_prop_update_int(DDI_DEV_T_NONE, pdip,
15533                     MPTSAS_NUM_PHYS, numphys) !=
15534                     DDI_PROP_SUCCESS) {
15535                         (void) ddi_prop_remove(DDI_DEV_T_NONE, pdip,
15536                             MPTSAS_NUM_PHYS);
15537                         mptsas_log(mpt, CE_WARN, "mptsas update "
15538                             "num phys props failed");
15539                         goto smp_create_done;
15540                 }
15541                 /*
15542                  * Add parent's props for SMHBA support
15543                  */
15544                 if (ddi_prop_update_string(DDI_DEV_T_NONE, pdip,
15545                     SCSI_ADDR_PROP_ATTACHED_PORT, wwn_str) !=
15546                     DDI_PROP_SUCCESS) {
15547                         (void) ddi_prop_remove(DDI_DEV_T_NONE, pdip,
15548                             SCSI_ADDR_PROP_ATTACHED_PORT);
15549                         mptsas_log(mpt, CE_WARN, "mptsas update iport"
15550                             "attached-port failed");
15551                         goto smp_create_done;
15552                 }
15553 
15554 smp_create_done:
15555                 /*
15556                  * If props were setup ok, online the lun
15557                  */
15558                 if (ndi_rtn == NDI_SUCCESS) {
15559                         /*
15560                          * Try to online the new node
15561                          */
15562                         ndi_rtn = ndi_devi_online(*smp_dip, NDI_ONLINE_ATTACH);
15563                 }
15564 
15565                 /*
15566                  * If success set rtn flag, else unwire alloc'd lun
15567                  */
15568                 if (ndi_rtn != NDI_SUCCESS) {
15569                         NDBG12(("mptsas unable to online "
15570                             "SMP target %s", wwn_str));
15571                         ndi_prop_remove_all(*smp_dip);
15572                         (void) ndi_devi_free(*smp_dip);
15573                 }
15574         }
15575 
15576         return ((ndi_rtn == NDI_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
15577 }
15578 
15579 /* smp transport routine */
15580 static int mptsas_smp_start(struct smp_pkt *smp_pkt)
15581 {
15582         uint64_t                        wwn;
15583         Mpi2SmpPassthroughRequest_t     req;
15584         Mpi2SmpPassthroughReply_t       rep;
15585         uint32_t                        direction = 0;
15586         mptsas_t                        *mpt;
15587         int                             ret;
15588         uint64_t                        tmp64;
15589 
15590         mpt = (mptsas_t *)smp_pkt->smp_pkt_address->
15591             smp_a_hba_tran->smp_tran_hba_private;
15592 
15593         bcopy(smp_pkt->smp_pkt_address->smp_a_wwn, &wwn, SAS_WWN_BYTE_SIZE);
15594         /*
15595          * Need to compose a SMP request message
15596          * and call mptsas_do_passthru() function
15597          */
15598         bzero(&req, sizeof (req));
15599         bzero(&rep, sizeof (rep));
15600         req.PassthroughFlags = 0;
15601         req.PhysicalPort = 0xff;
15602         req.ChainOffset = 0;
15603         req.Function = MPI2_FUNCTION_SMP_PASSTHROUGH;
15604 
15605         if ((smp_pkt->smp_pkt_reqsize & 0xffff0000ul) != 0) {
15606                 smp_pkt->smp_pkt_reason = ERANGE;
15607                 return (DDI_FAILURE);
15608         }
15609         req.RequestDataLength = LE_16((uint16_t)(smp_pkt->smp_pkt_reqsize - 4));
15610 
15611         req.MsgFlags = 0;
15612         tmp64 = LE_64(wwn);
15613         bcopy(&tmp64, &req.SASAddress, SAS_WWN_BYTE_SIZE);
15614         if (smp_pkt->smp_pkt_rspsize > 0) {
15615                 direction |= MPTSAS_PASS_THRU_DIRECTION_READ;
15616         }
15617         if (smp_pkt->smp_pkt_reqsize > 0) {
15618                 direction |= MPTSAS_PASS_THRU_DIRECTION_WRITE;
15619         }
15620 
15621         mutex_enter(&mpt->m_mutex);
15622         ret = mptsas_do_passthru(mpt, (uint8_t *)&req, (uint8_t *)&rep,
15623             (uint8_t *)smp_pkt->smp_pkt_rsp,
15624             offsetof(Mpi2SmpPassthroughRequest_t, SGL), sizeof (rep),
15625             smp_pkt->smp_pkt_rspsize - 4, direction,
15626             (uint8_t *)smp_pkt->smp_pkt_req, smp_pkt->smp_pkt_reqsize - 4,
15627             smp_pkt->smp_pkt_timeout, FKIOCTL);
15628         mutex_exit(&mpt->m_mutex);
15629         if (ret != 0) {
15630                 cmn_err(CE_WARN, "smp_start do passthru error %d", ret);
15631                 smp_pkt->smp_pkt_reason = (uchar_t)(ret);
15632                 return (DDI_FAILURE);
15633         }
15634         /* do passthrough success, check the smp status */
15635         if (LE_16(rep.IOCStatus) != MPI2_IOCSTATUS_SUCCESS) {
15636                 switch (LE_16(rep.IOCStatus)) {
15637                 case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
15638                         smp_pkt->smp_pkt_reason = ENODEV;
15639                         break;
15640                 case MPI2_IOCSTATUS_SAS_SMP_DATA_OVERRUN:
15641                         smp_pkt->smp_pkt_reason = EOVERFLOW;
15642                         break;
15643                 case MPI2_IOCSTATUS_SAS_SMP_REQUEST_FAILED:
15644                         smp_pkt->smp_pkt_reason = EIO;
15645                         break;
15646                 default:
15647                         mptsas_log(mpt, CE_NOTE, "smp_start: get unknown ioc"
15648                             "status:%x", LE_16(rep.IOCStatus));
15649                         smp_pkt->smp_pkt_reason = EIO;
15650                         break;
15651                 }
15652                 return (DDI_FAILURE);
15653         }
15654         if (rep.SASStatus != MPI2_SASSTATUS_SUCCESS) {
15655                 mptsas_log(mpt, CE_NOTE, "smp_start: get error SAS status:%x",
15656                     rep.SASStatus);
15657                 smp_pkt->smp_pkt_reason = EIO;
15658                 return (DDI_FAILURE);
15659         }
15660 
15661         return (DDI_SUCCESS);
15662 }
15663 
15664 /*
15665  * If we didn't get a match, we need to get sas page0 for each device, and
15666  * untill we get a match. If failed, return NULL
15667  */
15668 static mptsas_target_t *
15669 mptsas_phy_to_tgt(mptsas_t *mpt, int phymask, uint8_t phy)
15670 {
15671         int             i, j = 0;
15672         int             rval = 0;
15673         uint16_t        cur_handle;
15674         uint32_t        page_address;
15675         mptsas_target_t *ptgt = NULL;
15676 
15677         /*
15678          * PHY named device must be direct attached and attaches to
15679          * narrow port, if the iport is not parent of the device which
15680          * we are looking for.
15681          */
15682         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
15683                 if ((1 << i) & phymask)
15684                         j++;
15685         }
15686 
15687         if (j > 1)
15688                 return (NULL);
15689 
15690         /*
15691          * Must be a narrow port and single device attached to the narrow port
15692          * So the physical port num of device  which is equal to the iport's
15693          * port num is the device what we are looking for.
15694          */
15695 
15696         if (mpt->m_phy_info[phy].phy_mask != phymask)
15697                 return (NULL);
15698 
15699         mutex_enter(&mpt->m_mutex);
15700 
15701         ptgt = (mptsas_target_t *)mptsas_hash_traverse(&mpt->m_active->m_tgttbl,
15702             MPTSAS_HASH_FIRST);
15703         while (ptgt != NULL) {
15704                         if ((ptgt->m_sas_wwn == 0) && (ptgt->m_phynum == phy)) {
15705                         mutex_exit(&mpt->m_mutex);
15706                         return (ptgt);
15707                 }
15708 
15709                 ptgt = (mptsas_target_t *)mptsas_hash_traverse(
15710                     &mpt->m_active->m_tgttbl, MPTSAS_HASH_NEXT);
15711         }
15712 
15713         if (mpt->m_done_traverse_dev) {
15714                 mutex_exit(&mpt->m_mutex);
15715                 return (NULL);
15716         }
15717 
15718         /* If didn't get a match, come here */
15719         cur_handle = mpt->m_dev_handle;
15720         for (; ; ) {
15721                 ptgt = NULL;
15722                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_GET_NEXT_HANDLE &
15723                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) | (uint32_t)cur_handle;
15724                 rval = mptsas_get_target_device_info(mpt, page_address,
15725                     &cur_handle, &ptgt);
15726                 if ((rval == DEV_INFO_FAIL_PAGE0) ||
15727                     (rval == DEV_INFO_FAIL_ALLOC)) {
15728                         break;
15729                 }
15730                 if ((rval == DEV_INFO_WRONG_DEVICE_TYPE) ||
15731                     (rval == DEV_INFO_PHYS_DISK)) {
15732                         continue;
15733                 }
15734                 mpt->m_dev_handle = cur_handle;
15735 
15736                 if ((ptgt->m_sas_wwn == 0) && (ptgt->m_phynum == phy)) {
15737                         break;
15738                 }
15739         }
15740 
15741         mutex_exit(&mpt->m_mutex);
15742         return (ptgt);
15743 }
15744 
15745 /*
15746  * The ptgt->m_sas_wwn contains the wwid for each disk.
15747  * For Raid volumes, we need to check m_raidvol[x].m_raidwwid
15748  * If we didn't get a match, we need to get sas page0 for each device, and
15749  * untill we get a match
15750  * If failed, return NULL
15751  */
15752 static mptsas_target_t *
15753 mptsas_wwid_to_ptgt(mptsas_t *mpt, int phymask, uint64_t wwid)
15754 {
15755         int             rval = 0;
15756         uint16_t        cur_handle;
15757         uint32_t        page_address;
15758         mptsas_target_t *tmp_tgt = NULL;
15759 
15760         mutex_enter(&mpt->m_mutex);
15761         tmp_tgt = (struct mptsas_target *)mptsas_hash_search(
15762             &mpt->m_active->m_tgttbl, wwid, phymask);
15763         if (tmp_tgt != NULL) {
15764                 mutex_exit(&mpt->m_mutex);
15765                 return (tmp_tgt);
15766         }
15767 
15768         if (phymask == 0) {
15769                 /*
15770                  * It's IR volume
15771                  */
15772                 rval = mptsas_get_raid_info(mpt);
15773                 if (rval) {
15774                         tmp_tgt = (struct mptsas_target *)mptsas_hash_search(
15775                             &mpt->m_active->m_tgttbl, wwid, phymask);
15776                 }
15777                 mutex_exit(&mpt->m_mutex);
15778                 return (tmp_tgt);
15779         }
15780 
15781         if (mpt->m_done_traverse_dev) {
15782                 mutex_exit(&mpt->m_mutex);
15783                 return (NULL);
15784         }
15785 
15786         /* If didn't get a match, come here */
15787         cur_handle = mpt->m_dev_handle;
15788         for (; ; ) {
15789                 tmp_tgt = NULL;
15790                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_GET_NEXT_HANDLE &
15791                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) | cur_handle;
15792                 rval = mptsas_get_target_device_info(mpt, page_address,
15793                     &cur_handle, &tmp_tgt);
15794                 if ((rval == DEV_INFO_FAIL_PAGE0) ||
15795                     (rval == DEV_INFO_FAIL_ALLOC)) {
15796                         tmp_tgt = NULL;
15797                         break;
15798                 }
15799                 if ((rval == DEV_INFO_WRONG_DEVICE_TYPE) ||
15800                     (rval == DEV_INFO_PHYS_DISK)) {
15801                         continue;
15802                 }
15803                 mpt->m_dev_handle = cur_handle;
15804                 if ((tmp_tgt->m_sas_wwn) && (tmp_tgt->m_sas_wwn == wwid) &&
15805                     (tmp_tgt->m_phymask == phymask)) {
15806                         break;
15807                 }
15808         }
15809 
15810         mutex_exit(&mpt->m_mutex);
15811         return (tmp_tgt);
15812 }
15813 
15814 static mptsas_smp_t *
15815 mptsas_wwid_to_psmp(mptsas_t *mpt, int phymask, uint64_t wwid)
15816 {
15817         int             rval = 0;
15818         uint16_t        cur_handle;
15819         uint32_t        page_address;
15820         mptsas_smp_t    smp_node, *psmp = NULL;
15821 
15822         mutex_enter(&mpt->m_mutex);
15823         psmp = (struct mptsas_smp *)mptsas_hash_search(&mpt->m_active->m_smptbl,
15824             wwid, phymask);
15825         if (psmp != NULL) {
15826                 mutex_exit(&mpt->m_mutex);
15827                 return (psmp);
15828         }
15829 
15830         if (mpt->m_done_traverse_smp) {
15831                 mutex_exit(&mpt->m_mutex);
15832                 return (NULL);
15833         }
15834 
15835         /* If didn't get a match, come here */
15836         cur_handle = mpt->m_smp_devhdl;
15837         for (; ; ) {
15838                 psmp = NULL;
15839                 page_address = (MPI2_SAS_EXPAND_PGAD_FORM_GET_NEXT_HNDL &
15840                     MPI2_SAS_EXPAND_PGAD_FORM_MASK) | (uint32_t)cur_handle;
15841                 rval = mptsas_get_sas_expander_page0(mpt, page_address,
15842                     &smp_node);
15843                 if (rval != DDI_SUCCESS) {
15844                         break;
15845                 }
15846                 mpt->m_smp_devhdl = cur_handle = smp_node.m_devhdl;
15847                 psmp = mptsas_smp_alloc(&mpt->m_active->m_smptbl, &smp_node);
15848                 ASSERT(psmp);
15849                 if ((psmp->m_sasaddr) && (psmp->m_sasaddr == wwid) &&
15850                     (psmp->m_phymask == phymask)) {
15851                         break;
15852                 }
15853         }
15854 
15855         mutex_exit(&mpt->m_mutex);
15856         return (psmp);
15857 }
15858 
15859 /* helper functions using hash */
15860 
15861 /*
15862  * Can't have duplicate entries for same devhdl,
15863  * if there are invalid entries, the devhdl should be set to 0xffff
15864  */
15865 static void *
15866 mptsas_search_by_devhdl(mptsas_hash_table_t *hashtab, uint16_t devhdl)
15867 {
15868         mptsas_hash_data_t *data;
15869 
15870         data = mptsas_hash_traverse(hashtab, MPTSAS_HASH_FIRST);
15871         while (data != NULL) {
15872                 if (data->devhdl == devhdl) {
15873                         break;
15874                 }
15875                 data = mptsas_hash_traverse(hashtab, MPTSAS_HASH_NEXT);
15876         }
15877         return (data);
15878 }
15879 
15880 mptsas_target_t *
15881 mptsas_tgt_alloc(mptsas_hash_table_t *hashtab, uint16_t devhdl, uint64_t wwid,
15882     uint32_t devinfo, mptsas_phymask_t phymask, uint8_t phynum, mptsas_t *mpt)
15883 {
15884         mptsas_target_t *tmp_tgt = NULL;
15885 
15886         tmp_tgt = mptsas_hash_search(hashtab, wwid, phymask);
15887         if (tmp_tgt != NULL) {
15888                 NDBG20(("Hash item already exist"));
15889                 tmp_tgt->m_deviceinfo = devinfo;
15890                 tmp_tgt->m_devhdl = devhdl;
15891                 return (tmp_tgt);
15892         }
15893         tmp_tgt = kmem_zalloc(sizeof (struct mptsas_target), KM_SLEEP);
15894         if (tmp_tgt == NULL) {
15895                 cmn_err(CE_WARN, "Fatal, allocated tgt failed");
15896                 return (NULL);
15897         }
15898         tmp_tgt->m_devhdl = devhdl;
15899         tmp_tgt->m_sas_wwn = wwid;
15900         tmp_tgt->m_deviceinfo = devinfo;
15901         tmp_tgt->m_phymask = phymask;
15902         tmp_tgt->m_phynum = phynum;
15903         /* Initialized the tgt structure */
15904         tmp_tgt->m_qfull_retries = QFULL_RETRIES;
15905         tmp_tgt->m_qfull_retry_interval =
15906             drv_usectohz(QFULL_RETRY_INTERVAL * 1000);
15907         tmp_tgt->m_t_throttle = MAX_THROTTLE;
15908         mutex_init(&tmp_tgt->m_tgt_intr_mutex, NULL, MUTEX_DRIVER,
15909             DDI_INTR_PRI(mpt->m_intr_pri));
15910 
15911         mptsas_hash_add(hashtab, tmp_tgt);
15912 
15913         return (tmp_tgt);
15914 }
15915 
15916 static void
15917 mptsas_tgt_free(mptsas_hash_table_t *hashtab, uint64_t wwid,
15918     mptsas_phymask_t phymask)
15919 {
15920         mptsas_target_t *tmp_tgt;
15921         tmp_tgt = mptsas_hash_rem(hashtab, wwid, phymask);
15922         if (tmp_tgt == NULL) {
15923                 cmn_err(CE_WARN, "Tgt not found, nothing to free");
15924         } else {
15925                 mutex_destroy(&tmp_tgt->m_tgt_intr_mutex);
15926                 kmem_free(tmp_tgt, sizeof (struct mptsas_target));
15927         }
15928 }
15929 
15930 /*
15931  * Return the entry in the hash table
15932  */
15933 static mptsas_smp_t *
15934 mptsas_smp_alloc(mptsas_hash_table_t *hashtab, mptsas_smp_t *data)
15935 {
15936         uint64_t key1 = data->m_sasaddr;
15937         mptsas_phymask_t key2 = data->m_phymask;
15938         mptsas_smp_t *ret_data;
15939 
15940         ret_data = mptsas_hash_search(hashtab, key1, key2);
15941         if (ret_data != NULL) {
15942                 bcopy(data, ret_data, sizeof (mptsas_smp_t));
15943                 return (ret_data);
15944         }
15945 
15946         ret_data = kmem_alloc(sizeof (mptsas_smp_t), KM_SLEEP);
15947         bcopy(data, ret_data, sizeof (mptsas_smp_t));
15948         mptsas_hash_add(hashtab, ret_data);
15949         return (ret_data);
15950 }
15951 
15952 static void
15953 mptsas_smp_free(mptsas_hash_table_t *hashtab, uint64_t wwid,
15954     mptsas_phymask_t phymask)
15955 {
15956         mptsas_smp_t *tmp_smp;
15957         tmp_smp = mptsas_hash_rem(hashtab, wwid, phymask);
15958         if (tmp_smp == NULL) {
15959                 cmn_err(CE_WARN, "Smp element not found, nothing to free");
15960         } else {
15961                 kmem_free(tmp_smp, sizeof (struct mptsas_smp));
15962         }
15963 }
15964 
15965 /*
15966  * Hash operation functions
15967  * key1 is the sas_wwn, key2 is the phymask
15968  */
15969 static void
15970 mptsas_hash_init(mptsas_hash_table_t *hashtab)
15971 {
15972         if (hashtab == NULL) {
15973                 return;
15974         }
15975         bzero(hashtab->head, sizeof (mptsas_hash_node_t) *
15976             MPTSAS_HASH_ARRAY_SIZE);
15977         hashtab->cur = NULL;
15978         hashtab->line = 0;
15979 }
15980 
15981 static void
15982 mptsas_hash_uninit(mptsas_hash_table_t *hashtab, size_t datalen)
15983 {
15984         uint16_t line = 0;
15985         mptsas_hash_node_t *cur = NULL, *last = NULL;
15986 
15987         if (hashtab == NULL) {
15988                 return;
15989         }
15990         for (line = 0; line < MPTSAS_HASH_ARRAY_SIZE; line++) {
15991                 cur = hashtab->head[line];
15992                 while (cur != NULL) {
15993                         last = cur;
15994                         cur = cur->next;
15995                         kmem_free(last->data, datalen);
15996                         kmem_free(last, sizeof (mptsas_hash_node_t));
15997                 }
15998         }
15999 }
16000 
16001 /*
16002  * You must guarantee the element doesn't exist in the hash table
16003  * before you call mptsas_hash_add()
16004  */
16005 static void
16006 mptsas_hash_add(mptsas_hash_table_t *hashtab, void *data)
16007 {
16008         uint64_t key1 = ((mptsas_hash_data_t *)data)->key1;
16009         mptsas_phymask_t key2 = ((mptsas_hash_data_t *)data)->key2;
16010         mptsas_hash_node_t **head = NULL;
16011         mptsas_hash_node_t *node = NULL;
16012 
16013         if (hashtab == NULL) {
16014                 return;
16015         }
16016         ASSERT(mptsas_hash_search(hashtab, key1, key2) == NULL);
16017         node = kmem_zalloc(sizeof (mptsas_hash_node_t), KM_NOSLEEP);
16018         node->data = data;
16019 
16020         head = &(hashtab->head[key1 % MPTSAS_HASH_ARRAY_SIZE]);
16021         if (*head == NULL) {
16022                 *head = node;
16023         } else {
16024                 node->next = *head;
16025                 *head = node;
16026         }
16027 }
16028 
16029 static void *
16030 mptsas_hash_rem(mptsas_hash_table_t *hashtab, uint64_t key1,
16031     mptsas_phymask_t key2)
16032 {
16033         mptsas_hash_node_t **head = NULL;
16034         mptsas_hash_node_t *last = NULL, *cur = NULL;
16035         mptsas_hash_data_t *data;
16036         if (hashtab == NULL) {
16037                 return (NULL);
16038         }
16039         head = &(hashtab->head[key1 % MPTSAS_HASH_ARRAY_SIZE]);
16040         cur = *head;
16041         while (cur != NULL) {
16042                 data = cur->data;
16043                 if ((data->key1 == key1) && (data->key2 == key2)) {
16044                         if (last == NULL) {
16045                                 (*head) = cur->next;
16046                         } else {
16047                                 last->next = cur->next;
16048                         }
16049                         kmem_free(cur, sizeof (mptsas_hash_node_t));
16050                         return (data);
16051                 } else {
16052                         last = cur;
16053                         cur = cur->next;
16054                 }
16055         }
16056         return (NULL);
16057 }
16058 
16059 static void *
16060 mptsas_hash_search(mptsas_hash_table_t *hashtab, uint64_t key1,
16061     mptsas_phymask_t key2)
16062 {
16063         mptsas_hash_node_t *cur = NULL;
16064         mptsas_hash_data_t *data;
16065         if (hashtab == NULL) {
16066                 return (NULL);
16067         }
16068         cur = hashtab->head[key1 % MPTSAS_HASH_ARRAY_SIZE];
16069         while (cur != NULL) {
16070                 data = cur->data;
16071                 if ((data->key1 == key1) && (data->key2 == key2)) {
16072                         return (data);
16073                 } else {
16074                         cur = cur->next;
16075                 }
16076         }
16077         return (NULL);
16078 }
16079 
16080 static void *
16081 mptsas_hash_traverse(mptsas_hash_table_t *hashtab, int pos)
16082 {
16083         mptsas_hash_node_t *this = NULL;
16084 
16085         if (hashtab == NULL) {
16086                 return (NULL);
16087         }
16088 
16089         if (pos == MPTSAS_HASH_FIRST) {
16090                 hashtab->line = 0;
16091                 hashtab->cur = NULL;
16092                 this = hashtab->head[0];
16093         } else {
16094                 if (hashtab->cur == NULL) {
16095                         return (NULL);
16096                 } else {
16097                         this = hashtab->cur->next;
16098                 }
16099         }
16100 
16101         while (this == NULL) {
16102                 hashtab->line++;
16103                 if (hashtab->line >= MPTSAS_HASH_ARRAY_SIZE) {
16104                         /* the traverse reaches the end */
16105                         hashtab->cur = NULL;
16106                         return (NULL);
16107                 } else {
16108                         this = hashtab->head[hashtab->line];
16109                 }
16110         }
16111         hashtab->cur = this;
16112         return (this->data);
16113 }
16114 
16115 /*
16116  * Functions for SGPIO LED support
16117  */
16118 static dev_info_t *
16119 mptsas_get_dip_from_dev(dev_t dev, mptsas_phymask_t *phymask)
16120 {
16121         dev_info_t      *dip;
16122         int             prop;
16123         dip = e_ddi_hold_devi_by_dev(dev, 0);
16124         if (dip == NULL)
16125                 return (dip);
16126         prop = ddi_prop_get_int(DDI_DEV_T_ANY, dip, 0,
16127             "phymask", 0);
16128         *phymask = (mptsas_phymask_t)prop;
16129         ddi_release_devi(dip);
16130         return (dip);
16131 }
16132 static mptsas_target_t *
16133 mptsas_addr_to_ptgt(mptsas_t *mpt, char *addr, mptsas_phymask_t phymask)
16134 {
16135         uint8_t                 phynum;
16136         uint64_t                wwn;
16137         int                     lun;
16138         mptsas_target_t         *ptgt = NULL;
16139 
16140         if (mptsas_parse_address(addr, &wwn, &phynum, &lun) != DDI_SUCCESS) {
16141                 return (NULL);
16142         }
16143         if (addr[0] == 'w') {
16144                 ptgt = mptsas_wwid_to_ptgt(mpt, (int)phymask, wwn);
16145         } else {
16146                 ptgt = mptsas_phy_to_tgt(mpt, (int)phymask, phynum);
16147         }
16148         return (ptgt);
16149 }
16150 
16151 #ifdef MPTSAS_GET_LED
16152 static int
16153 mptsas_get_led_status(mptsas_t *mpt, mptsas_target_t *ptgt,
16154     uint32_t *slotstatus)
16155 {
16156         return (mptsas_send_sep(mpt, ptgt, slotstatus,
16157             MPI2_SEP_REQ_ACTION_READ_STATUS));
16158 }
16159 #endif
16160 static int
16161 mptsas_set_led_status(mptsas_t *mpt, mptsas_target_t *ptgt, uint32_t slotstatus)
16162 {
16163         NDBG14(("mptsas_ioctl: set LED status %x for slot %x",
16164             slotstatus, ptgt->m_slot_num));
16165         return (mptsas_send_sep(mpt, ptgt, &slotstatus,
16166             MPI2_SEP_REQ_ACTION_WRITE_STATUS));
16167 }
16168 /*
16169  *  send sep request, use enclosure/slot addressing
16170  */
16171 static int mptsas_send_sep(mptsas_t *mpt, mptsas_target_t *ptgt,
16172     uint32_t *status, uint8_t act)
16173 {
16174         Mpi2SepRequest_t        req;
16175         Mpi2SepReply_t          rep;
16176         int                     ret;
16177 
16178         ASSERT(mutex_owned(&mpt->m_mutex));
16179 
16180         bzero(&req, sizeof (req));
16181         bzero(&rep, sizeof (rep));
16182 
16183         /* Do nothing for RAID volumes */
16184         if (ptgt->m_phymask == 0) {
16185                 NDBG14(("mptsas_send_sep: Skip RAID volumes"));
16186                 return (DDI_FAILURE);
16187         }
16188 
16189         req.Function = MPI2_FUNCTION_SCSI_ENCLOSURE_PROCESSOR;
16190         req.Action = act;
16191         req.Flags = MPI2_SEP_REQ_FLAGS_ENCLOSURE_SLOT_ADDRESS;
16192         req.EnclosureHandle = LE_16(ptgt->m_enclosure);
16193         req.Slot = LE_16(ptgt->m_slot_num);
16194         if (act == MPI2_SEP_REQ_ACTION_WRITE_STATUS) {
16195                 req.SlotStatus = LE_32(*status);
16196         }
16197         ret = mptsas_do_passthru(mpt, (uint8_t *)&req, (uint8_t *)&rep, NULL,
16198             sizeof (req), sizeof (rep), NULL, 0, NULL, 0, 60, FKIOCTL);
16199         if (ret != 0) {
16200                 mptsas_log(mpt, CE_NOTE, "mptsas_send_sep: passthru SEP "
16201                     "Processor Request message error %d", ret);
16202                 return (DDI_FAILURE);
16203         }
16204         /* do passthrough success, check the ioc status */
16205         if (LE_16(rep.IOCStatus) != MPI2_IOCSTATUS_SUCCESS) {
16206                 if ((LE_16(rep.IOCStatus) & MPI2_IOCSTATUS_MASK) ==
16207                     MPI2_IOCSTATUS_INVALID_FIELD) {
16208                         mptsas_log(mpt, CE_NOTE, "send sep act %x: Not "
16209                             "supported action, loginfo %x", act,
16210                             LE_32(rep.IOCLogInfo));
16211                         return (DDI_FAILURE);
16212                 }
16213                 mptsas_log(mpt, CE_NOTE, "send_sep act %x: ioc "
16214                     "status:%x", act, LE_16(rep.IOCStatus));
16215                 return (DDI_FAILURE);
16216         }
16217         if (act != MPI2_SEP_REQ_ACTION_WRITE_STATUS) {
16218                 *status = LE_32(rep.SlotStatus);
16219         }
16220 
16221         return (DDI_SUCCESS);
16222 }
16223 
16224 int
16225 mptsas_dma_addr_create(mptsas_t *mpt, ddi_dma_attr_t dma_attr,
16226     ddi_dma_handle_t *dma_hdp, ddi_acc_handle_t *acc_hdp, caddr_t *dma_memp,
16227     uint32_t alloc_size, ddi_dma_cookie_t *cookiep)
16228 {
16229         ddi_dma_cookie_t        new_cookie;
16230         size_t                  alloc_len;
16231         uint_t                  ncookie;
16232 
16233         if (cookiep == NULL)
16234                 cookiep = &new_cookie;
16235 
16236         if (ddi_dma_alloc_handle(mpt->m_dip, &dma_attr, DDI_DMA_SLEEP,
16237             NULL, dma_hdp) != DDI_SUCCESS) {
16238                 dma_hdp = NULL;
16239                 return (FALSE);
16240         }
16241 
16242         if (ddi_dma_mem_alloc(*dma_hdp, alloc_size, &mpt->m_dev_acc_attr,
16243             DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL, dma_memp, &alloc_len,
16244             acc_hdp) != DDI_SUCCESS) {
16245                 ddi_dma_free_handle(dma_hdp);
16246                 dma_hdp = NULL;
16247                 return (FALSE);
16248         }
16249 
16250         if (ddi_dma_addr_bind_handle(*dma_hdp, NULL, *dma_memp, alloc_len,
16251             (DDI_DMA_RDWR | DDI_DMA_CONSISTENT), DDI_DMA_SLEEP, NULL,
16252             cookiep, &ncookie) != DDI_DMA_MAPPED) {
16253                 (void) ddi_dma_mem_free(acc_hdp);
16254                 ddi_dma_free_handle(dma_hdp);
16255                 dma_hdp = NULL;
16256                 return (FALSE);
16257         }
16258 
16259         return (TRUE);
16260 }
16261 
16262 void
16263 mptsas_dma_addr_destroy(ddi_dma_handle_t *dma_hdp, ddi_acc_handle_t *acc_hdp)
16264 {
16265         if (*dma_hdp == NULL)
16266                 return;
16267 
16268         (void) ddi_dma_unbind_handle(*dma_hdp);
16269         (void) ddi_dma_mem_free(acc_hdp);
16270         ddi_dma_free_handle(dma_hdp);
16271         dma_hdp = NULL;
16272 }
16273 
16274 static int
16275 mptsas_outstanding_cmds_n(mptsas_t *mpt)
16276 {
16277         int n = 0, i;
16278         for (i = 0; i < mpt->m_slot_freeq_pair_n; i++) {
16279                 mutex_enter(&mpt->m_slot_freeq_pairp[i].
16280                     m_slot_allocq.s.m_fq_mutex);
16281                 mutex_enter(&mpt->m_slot_freeq_pairp[i].
16282                     m_slot_releq.s.m_fq_mutex);
16283                 n += (mpt->m_slot_freeq_pairp[i].m_slot_allocq.s.m_fq_n_init -
16284                     mpt->m_slot_freeq_pairp[i].m_slot_allocq.s.m_fq_n -
16285                     mpt->m_slot_freeq_pairp[i].m_slot_releq.s.m_fq_n);
16286                 mutex_exit(&mpt->m_slot_freeq_pairp[i].
16287                     m_slot_releq.s.m_fq_mutex);
16288                 mutex_exit(&mpt->m_slot_freeq_pairp[i].
16289                     m_slot_allocq.s.m_fq_mutex);
16290         }
16291         if (mpt->m_max_requests - 2 < n)
16292                 panic("mptsas: free slot allocq and releq crazy");
16293         return (n);
16294 }