ciss.c revision 281826
1/*-
2 * Copyright (c) 2001 Michael Smith
3 * Copyright (c) 2004 Paul Saab
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 *
27 *	$FreeBSD: stable/10/sys/dev/ciss/ciss.c 281826 2015-04-21 11:27:50Z mav $
28 */
29
30/*
31 * Common Interface for SCSI-3 Support driver.
32 *
33 * CISS claims to provide a common interface between a generic SCSI
34 * transport and an intelligent host adapter.
35 *
36 * This driver supports CISS as defined in the document "CISS Command
37 * Interface for SCSI-3 Support Open Specification", Version 1.04,
38 * Valence Number 1, dated 20001127, produced by Compaq Computer
39 * Corporation.  This document appears to be a hastily and somewhat
40 * arbitrarlily cut-down version of a larger (and probably even more
41 * chaotic and inconsistent) Compaq internal document.  Various
42 * details were also gleaned from Compaq's "cciss" driver for Linux.
43 *
44 * We provide a shim layer between the CISS interface and CAM,
45 * offloading most of the queueing and being-a-disk chores onto CAM.
46 * Entry to the driver is via the PCI bus attachment (ciss_probe,
47 * ciss_attach, etc) and via the CAM interface (ciss_cam_action,
48 * ciss_cam_poll).  The Compaq CISS adapters are, however, poor SCSI
49 * citizens and we have to fake up some responses to get reasonable
50 * behaviour out of them.  In addition, the CISS command set is by no
51 * means adequate to support the functionality of a RAID controller,
52 * and thus the supported Compaq adapters utilise portions of the
53 * control protocol from earlier Compaq adapter families.
54 *
55 * Note that we only support the "simple" transport layer over PCI.
56 * This interface (ab)uses the I2O register set (specifically the post
57 * queues) to exchange commands with the adapter.  Other interfaces
58 * are available, but we aren't supposed to know about them, and it is
59 * dubious whether they would provide major performance improvements
60 * except under extreme load.
61 *
62 * Currently the only supported CISS adapters are the Compaq Smart
63 * Array 5* series (5300, 5i, 532).  Even with only three adapters,
64 * Compaq still manage to have interface variations.
65 *
66 *
67 * Thanks must go to Fred Harris and Darryl DeVinney at Compaq, as
68 * well as Paul Saab at Yahoo! for their assistance in making this
69 * driver happen.
70 *
71 * More thanks must go to John Cagle at HP for the countless hours
72 * spent making this driver "work" with the MSA* series storage
73 * enclosures.  Without his help (and nagging), this driver could not
74 * be used with these enclosures.
75 */
76
77#include <sys/param.h>
78#include <sys/systm.h>
79#include <sys/malloc.h>
80#include <sys/kernel.h>
81#include <sys/bus.h>
82#include <sys/conf.h>
83#include <sys/stat.h>
84#include <sys/kthread.h>
85#include <sys/queue.h>
86#include <sys/sysctl.h>
87
88#include <cam/cam.h>
89#include <cam/cam_ccb.h>
90#include <cam/cam_periph.h>
91#include <cam/cam_sim.h>
92#include <cam/cam_xpt_sim.h>
93#include <cam/scsi/scsi_all.h>
94#include <cam/scsi/scsi_message.h>
95
96#include <machine/bus.h>
97#include <machine/endian.h>
98#include <machine/resource.h>
99#include <sys/rman.h>
100
101#include <dev/pci/pcireg.h>
102#include <dev/pci/pcivar.h>
103
104#include <dev/ciss/cissreg.h>
105#include <dev/ciss/cissio.h>
106#include <dev/ciss/cissvar.h>
107
108static MALLOC_DEFINE(CISS_MALLOC_CLASS, "ciss_data",
109    "ciss internal data buffers");
110
111/* pci interface */
112static int	ciss_lookup(device_t dev);
113static int	ciss_probe(device_t dev);
114static int	ciss_attach(device_t dev);
115static int	ciss_detach(device_t dev);
116static int	ciss_shutdown(device_t dev);
117
118/* (de)initialisation functions, control wrappers */
119static int	ciss_init_pci(struct ciss_softc *sc);
120static int	ciss_setup_msix(struct ciss_softc *sc);
121static int	ciss_init_perf(struct ciss_softc *sc);
122static int	ciss_wait_adapter(struct ciss_softc *sc);
123static int	ciss_flush_adapter(struct ciss_softc *sc);
124static int	ciss_init_requests(struct ciss_softc *sc);
125static void	ciss_command_map_helper(void *arg, bus_dma_segment_t *segs,
126					int nseg, int error);
127static int	ciss_identify_adapter(struct ciss_softc *sc);
128static int	ciss_init_logical(struct ciss_softc *sc);
129static int	ciss_init_physical(struct ciss_softc *sc);
130static int	ciss_filter_physical(struct ciss_softc *sc, struct ciss_lun_report *cll);
131static int	ciss_identify_logical(struct ciss_softc *sc, struct ciss_ldrive *ld);
132static int	ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld);
133static int	ciss_update_config(struct ciss_softc *sc);
134static int	ciss_accept_media(struct ciss_softc *sc, struct ciss_ldrive *ld);
135static void	ciss_init_sysctl(struct ciss_softc *sc);
136static void	ciss_soft_reset(struct ciss_softc *sc);
137static void	ciss_free(struct ciss_softc *sc);
138static void	ciss_spawn_notify_thread(struct ciss_softc *sc);
139static void	ciss_kill_notify_thread(struct ciss_softc *sc);
140
141/* request submission/completion */
142static int	ciss_start(struct ciss_request *cr);
143static void	ciss_done(struct ciss_softc *sc, cr_qhead_t *qh);
144static void	ciss_perf_done(struct ciss_softc *sc, cr_qhead_t *qh);
145static void	ciss_intr(void *arg);
146static void	ciss_perf_intr(void *arg);
147static void	ciss_perf_msi_intr(void *arg);
148static void	ciss_complete(struct ciss_softc *sc, cr_qhead_t *qh);
149static int	_ciss_report_request(struct ciss_request *cr, int *command_status, int *scsi_status, const char *func);
150static int	ciss_synch_request(struct ciss_request *cr, int timeout);
151static int	ciss_poll_request(struct ciss_request *cr, int timeout);
152static int	ciss_wait_request(struct ciss_request *cr, int timeout);
153#if 0
154static int	ciss_abort_request(struct ciss_request *cr);
155#endif
156
157/* request queueing */
158static int	ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp);
159static void	ciss_preen_command(struct ciss_request *cr);
160static void 	ciss_release_request(struct ciss_request *cr);
161
162/* request helpers */
163static int	ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
164				      int opcode, void **bufp, size_t bufsize);
165static int	ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc);
166
167/* DMA map/unmap */
168static int	ciss_map_request(struct ciss_request *cr);
169static void	ciss_request_map_helper(void *arg, bus_dma_segment_t *segs,
170					int nseg, int error);
171static void	ciss_unmap_request(struct ciss_request *cr);
172
173/* CAM interface */
174static int	ciss_cam_init(struct ciss_softc *sc);
175static void	ciss_cam_rescan_target(struct ciss_softc *sc,
176				       int bus, int target);
177static void	ciss_cam_action(struct cam_sim *sim, union ccb *ccb);
178static int	ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio);
179static int	ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio);
180static void	ciss_cam_poll(struct cam_sim *sim);
181static void	ciss_cam_complete(struct ciss_request *cr);
182static void	ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio);
183static int	ciss_name_device(struct ciss_softc *sc, int bus, int target);
184
185/* periodic status monitoring */
186static void	ciss_periodic(void *arg);
187static void	ciss_nop_complete(struct ciss_request *cr);
188static void	ciss_disable_adapter(struct ciss_softc *sc);
189static void	ciss_notify_event(struct ciss_softc *sc);
190static void	ciss_notify_complete(struct ciss_request *cr);
191static int	ciss_notify_abort(struct ciss_softc *sc);
192static int	ciss_notify_abort_bmic(struct ciss_softc *sc);
193static void	ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn);
194static void	ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn);
195static void	ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn);
196
197/* debugging output */
198static void	ciss_print_request(struct ciss_request *cr);
199static void	ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld);
200static const char *ciss_name_ldrive_status(int status);
201static int	ciss_decode_ldrive_status(int status);
202static const char *ciss_name_ldrive_org(int org);
203static const char *ciss_name_command_status(int status);
204
205/*
206 * PCI bus interface.
207 */
208static device_method_t ciss_methods[] = {
209    /* Device interface */
210    DEVMETHOD(device_probe,	ciss_probe),
211    DEVMETHOD(device_attach,	ciss_attach),
212    DEVMETHOD(device_detach,	ciss_detach),
213    DEVMETHOD(device_shutdown,	ciss_shutdown),
214    { 0, 0 }
215};
216
217static driver_t ciss_pci_driver = {
218    "ciss",
219    ciss_methods,
220    sizeof(struct ciss_softc)
221};
222
223static devclass_t	ciss_devclass;
224DRIVER_MODULE(ciss, pci, ciss_pci_driver, ciss_devclass, 0, 0);
225MODULE_DEPEND(ciss, cam, 1, 1, 1);
226MODULE_DEPEND(ciss, pci, 1, 1, 1);
227
228/*
229 * Control device interface.
230 */
231static d_open_t		ciss_open;
232static d_close_t	ciss_close;
233static d_ioctl_t	ciss_ioctl;
234
235static struct cdevsw ciss_cdevsw = {
236	.d_version =	D_VERSION,
237	.d_flags =	0,
238	.d_open =	ciss_open,
239	.d_close =	ciss_close,
240	.d_ioctl =	ciss_ioctl,
241	.d_name =	"ciss",
242};
243
244/*
245 * This tunable can be set at boot time and controls whether physical devices
246 * that are marked hidden by the firmware should be exposed anyways.
247 */
248static unsigned int ciss_expose_hidden_physical = 0;
249TUNABLE_INT("hw.ciss.expose_hidden_physical", &ciss_expose_hidden_physical);
250
251static unsigned int ciss_nop_message_heartbeat = 0;
252TUNABLE_INT("hw.ciss.nop_message_heartbeat", &ciss_nop_message_heartbeat);
253
254/*
255 * This tunable can force a particular transport to be used:
256 * <= 0 : use default
257 *    1 : force simple
258 *    2 : force performant
259 */
260static int ciss_force_transport = 0;
261TUNABLE_INT("hw.ciss.force_transport", &ciss_force_transport);
262
263/*
264 * This tunable can force a particular interrupt delivery method to be used:
265 * <= 0 : use default
266 *    1 : force INTx
267 *    2 : force MSIX
268 */
269static int ciss_force_interrupt = 0;
270TUNABLE_INT("hw.ciss.force_interrupt", &ciss_force_interrupt);
271
272/************************************************************************
273 * CISS adapters amazingly don't have a defined programming interface
274 * value.  (One could say some very despairing things about PCI and
275 * people just not getting the general idea.)  So we are forced to
276 * stick with matching against subvendor/subdevice, and thus have to
277 * be updated for every new CISS adapter that appears.
278 */
279#define CISS_BOARD_UNKNWON	0
280#define CISS_BOARD_SA5		1
281#define CISS_BOARD_SA5B		2
282#define CISS_BOARD_NOMSI	(1<<4)
283#define CISS_BOARD_SIMPLE       (1<<5)
284
285static struct
286{
287    u_int16_t	subvendor;
288    u_int16_t	subdevice;
289    int		flags;
290    char	*desc;
291} ciss_vendor_data[] = {
292    { 0x0e11, 0x4070, CISS_BOARD_SA5|CISS_BOARD_NOMSI|CISS_BOARD_SIMPLE,
293                                                        "Compaq Smart Array 5300" },
294    { 0x0e11, 0x4080, CISS_BOARD_SA5B|CISS_BOARD_NOMSI,	"Compaq Smart Array 5i" },
295    { 0x0e11, 0x4082, CISS_BOARD_SA5B|CISS_BOARD_NOMSI,	"Compaq Smart Array 532" },
296    { 0x0e11, 0x4083, CISS_BOARD_SA5B|CISS_BOARD_NOMSI,	"HP Smart Array 5312" },
297    { 0x0e11, 0x4091, CISS_BOARD_SA5,	"HP Smart Array 6i" },
298    { 0x0e11, 0x409A, CISS_BOARD_SA5,	"HP Smart Array 641" },
299    { 0x0e11, 0x409B, CISS_BOARD_SA5,	"HP Smart Array 642" },
300    { 0x0e11, 0x409C, CISS_BOARD_SA5,	"HP Smart Array 6400" },
301    { 0x0e11, 0x409D, CISS_BOARD_SA5,	"HP Smart Array 6400 EM" },
302    { 0x103C, 0x3211, CISS_BOARD_SA5,	"HP Smart Array E200i" },
303    { 0x103C, 0x3212, CISS_BOARD_SA5,	"HP Smart Array E200" },
304    { 0x103C, 0x3213, CISS_BOARD_SA5,	"HP Smart Array E200i" },
305    { 0x103C, 0x3214, CISS_BOARD_SA5,	"HP Smart Array E200i" },
306    { 0x103C, 0x3215, CISS_BOARD_SA5,	"HP Smart Array E200i" },
307    { 0x103C, 0x3220, CISS_BOARD_SA5,	"HP Smart Array" },
308    { 0x103C, 0x3222, CISS_BOARD_SA5,	"HP Smart Array" },
309    { 0x103C, 0x3223, CISS_BOARD_SA5,	"HP Smart Array P800" },
310    { 0x103C, 0x3225, CISS_BOARD_SA5,	"HP Smart Array P600" },
311    { 0x103C, 0x3230, CISS_BOARD_SA5,	"HP Smart Array" },
312    { 0x103C, 0x3231, CISS_BOARD_SA5,	"HP Smart Array" },
313    { 0x103C, 0x3232, CISS_BOARD_SA5,	"HP Smart Array" },
314    { 0x103C, 0x3233, CISS_BOARD_SA5,	"HP Smart Array" },
315    { 0x103C, 0x3234, CISS_BOARD_SA5,	"HP Smart Array P400" },
316    { 0x103C, 0x3235, CISS_BOARD_SA5,	"HP Smart Array P400i" },
317    { 0x103C, 0x3236, CISS_BOARD_SA5,	"HP Smart Array" },
318    { 0x103C, 0x3237, CISS_BOARD_SA5,	"HP Smart Array E500" },
319    { 0x103C, 0x3238, CISS_BOARD_SA5,	"HP Smart Array" },
320    { 0x103C, 0x3239, CISS_BOARD_SA5,	"HP Smart Array" },
321    { 0x103C, 0x323A, CISS_BOARD_SA5,	"HP Smart Array" },
322    { 0x103C, 0x323B, CISS_BOARD_SA5,	"HP Smart Array" },
323    { 0x103C, 0x323C, CISS_BOARD_SA5,	"HP Smart Array" },
324    { 0x103C, 0x323D, CISS_BOARD_SA5,	"HP Smart Array P700m" },
325    { 0x103C, 0x3241, CISS_BOARD_SA5,	"HP Smart Array P212" },
326    { 0x103C, 0x3243, CISS_BOARD_SA5,	"HP Smart Array P410" },
327    { 0x103C, 0x3245, CISS_BOARD_SA5,	"HP Smart Array P410i" },
328    { 0x103C, 0x3247, CISS_BOARD_SA5,	"HP Smart Array P411" },
329    { 0x103C, 0x3249, CISS_BOARD_SA5,	"HP Smart Array P812" },
330    { 0x103C, 0x324A, CISS_BOARD_SA5,	"HP Smart Array P712m" },
331    { 0x103C, 0x324B, CISS_BOARD_SA5,	"HP Smart Array" },
332    { 0x103C, 0x3350, CISS_BOARD_SA5,   "HP Smart Array P222" },
333    { 0x103C, 0x3351, CISS_BOARD_SA5,   "HP Smart Array P420" },
334    { 0x103C, 0x3352, CISS_BOARD_SA5,   "HP Smart Array P421" },
335    { 0x103C, 0x3353, CISS_BOARD_SA5,   "HP Smart Array P822" },
336    { 0x103C, 0x3354, CISS_BOARD_SA5,   "HP Smart Array P420i" },
337    { 0x103C, 0x3355, CISS_BOARD_SA5,   "HP Smart Array P220i" },
338    { 0x103C, 0x3356, CISS_BOARD_SA5,   "HP Smart Array P721m" },
339    { 0x103C, 0x1920, CISS_BOARD_SA5,   "HP Smart Array P430i" },
340    { 0x103C, 0x1921, CISS_BOARD_SA5,   "HP Smart Array P830i" },
341    { 0x103C, 0x1922, CISS_BOARD_SA5,   "HP Smart Array P430" },
342    { 0x103C, 0x1923, CISS_BOARD_SA5,   "HP Smart Array P431" },
343    { 0x103C, 0x1924, CISS_BOARD_SA5,   "HP Smart Array P830" },
344    { 0x103C, 0x1926, CISS_BOARD_SA5,   "HP Smart Array P731m" },
345    { 0x103C, 0x1928, CISS_BOARD_SA5,   "HP Smart Array P230i" },
346    { 0x103C, 0x1929, CISS_BOARD_SA5,   "HP Smart Array P530" },
347    { 0x103C, 0x192A, CISS_BOARD_SA5,   "HP Smart Array P531" },
348    { 0x103C, 0x21BD, CISS_BOARD_SA5,   "HP Smart Array TBD" },
349    { 0x103C, 0x21BE, CISS_BOARD_SA5,   "HP Smart Array TBD" },
350    { 0x103C, 0x21BF, CISS_BOARD_SA5,   "HP Smart Array TBD" },
351    { 0x103C, 0x21C0, CISS_BOARD_SA5,   "HP Smart Array TBD" },
352    { 0x103C, 0x21C2, CISS_BOARD_SA5,   "HP Smart Array TBD" },
353    { 0x103C, 0x21C3, CISS_BOARD_SA5,   "HP Smart Array TBD" },
354    { 0x103C, 0x21C5, CISS_BOARD_SA5,   "HP Smart Array TBD" },
355    { 0x103C, 0x21C6, CISS_BOARD_SA5,   "HP Smart Array TBD" },
356    { 0x103C, 0x21C7, CISS_BOARD_SA5,   "HP Smart Array TBD" },
357    { 0x103C, 0x21C8, CISS_BOARD_SA5,   "HP Smart Array TBD" },
358    { 0x103C, 0x21CA, CISS_BOARD_SA5,   "HP Smart Array TBD" },
359    { 0x103C, 0x21CB, CISS_BOARD_SA5,   "HP Smart Array TBD" },
360    { 0x103C, 0x21CC, CISS_BOARD_SA5,   "HP Smart Array TBD" },
361    { 0x103C, 0x21CD, CISS_BOARD_SA5,   "HP Smart Array TBD" },
362    { 0x103C, 0x21CE, CISS_BOARD_SA5,   "HP Smart Array TBD" },
363    { 0, 0, 0, NULL }
364};
365
366/************************************************************************
367 * Find a match for the device in our list of known adapters.
368 */
369static int
370ciss_lookup(device_t dev)
371{
372    int 	i;
373
374    for (i = 0; ciss_vendor_data[i].desc != NULL; i++)
375	if ((pci_get_subvendor(dev) == ciss_vendor_data[i].subvendor) &&
376	    (pci_get_subdevice(dev) == ciss_vendor_data[i].subdevice)) {
377	    return(i);
378	}
379    return(-1);
380}
381
382/************************************************************************
383 * Match a known CISS adapter.
384 */
385static int
386ciss_probe(device_t dev)
387{
388    int		i;
389
390    i = ciss_lookup(dev);
391    if (i != -1) {
392	device_set_desc(dev, ciss_vendor_data[i].desc);
393	return(BUS_PROBE_DEFAULT);
394    }
395    return(ENOENT);
396}
397
398/************************************************************************
399 * Attach the driver to this adapter.
400 */
401static int
402ciss_attach(device_t dev)
403{
404    struct ciss_softc	*sc;
405    int			error;
406
407    debug_called(1);
408
409#ifdef CISS_DEBUG
410    /* print structure/union sizes */
411    debug_struct(ciss_command);
412    debug_struct(ciss_header);
413    debug_union(ciss_device_address);
414    debug_struct(ciss_cdb);
415    debug_struct(ciss_report_cdb);
416    debug_struct(ciss_notify_cdb);
417    debug_struct(ciss_notify);
418    debug_struct(ciss_message_cdb);
419    debug_struct(ciss_error_info_pointer);
420    debug_struct(ciss_error_info);
421    debug_struct(ciss_sg_entry);
422    debug_struct(ciss_config_table);
423    debug_struct(ciss_bmic_cdb);
424    debug_struct(ciss_bmic_id_ldrive);
425    debug_struct(ciss_bmic_id_lstatus);
426    debug_struct(ciss_bmic_id_table);
427    debug_struct(ciss_bmic_id_pdrive);
428    debug_struct(ciss_bmic_blink_pdrive);
429    debug_struct(ciss_bmic_flush_cache);
430    debug_const(CISS_MAX_REQUESTS);
431    debug_const(CISS_MAX_LOGICAL);
432    debug_const(CISS_INTERRUPT_COALESCE_DELAY);
433    debug_const(CISS_INTERRUPT_COALESCE_COUNT);
434    debug_const(CISS_COMMAND_ALLOC_SIZE);
435    debug_const(CISS_COMMAND_SG_LENGTH);
436
437    debug_type(cciss_pci_info_struct);
438    debug_type(cciss_coalint_struct);
439    debug_type(cciss_coalint_struct);
440    debug_type(NodeName_type);
441    debug_type(NodeName_type);
442    debug_type(Heartbeat_type);
443    debug_type(BusTypes_type);
444    debug_type(FirmwareVer_type);
445    debug_type(DriverVer_type);
446    debug_type(IOCTL_Command_struct);
447#endif
448
449    sc = device_get_softc(dev);
450    sc->ciss_dev = dev;
451    mtx_init(&sc->ciss_mtx, "cissmtx", NULL, MTX_DEF);
452    callout_init_mtx(&sc->ciss_periodic, &sc->ciss_mtx, 0);
453
454    /*
455     * Do PCI-specific init.
456     */
457    if ((error = ciss_init_pci(sc)) != 0)
458	goto out;
459
460    /*
461     * Initialise driver queues.
462     */
463    ciss_initq_free(sc);
464    ciss_initq_notify(sc);
465
466    /*
467     * Initalize device sysctls.
468     */
469    ciss_init_sysctl(sc);
470
471    /*
472     * Initialise command/request pool.
473     */
474    if ((error = ciss_init_requests(sc)) != 0)
475	goto out;
476
477    /*
478     * Get adapter information.
479     */
480    if ((error = ciss_identify_adapter(sc)) != 0)
481	goto out;
482
483    /*
484     * Find all the physical devices.
485     */
486    if ((error = ciss_init_physical(sc)) != 0)
487	goto out;
488
489    /*
490     * Build our private table of logical devices.
491     */
492    if ((error = ciss_init_logical(sc)) != 0)
493	goto out;
494
495    /*
496     * Enable interrupts so that the CAM scan can complete.
497     */
498    CISS_TL_SIMPLE_ENABLE_INTERRUPTS(sc);
499
500    /*
501     * Initialise the CAM interface.
502     */
503    if ((error = ciss_cam_init(sc)) != 0)
504	goto out;
505
506    /*
507     * Start the heartbeat routine and event chain.
508     */
509    ciss_periodic(sc);
510
511   /*
512     * Create the control device.
513     */
514    sc->ciss_dev_t = make_dev(&ciss_cdevsw, device_get_unit(sc->ciss_dev),
515			      UID_ROOT, GID_OPERATOR, S_IRUSR | S_IWUSR,
516			      "ciss%d", device_get_unit(sc->ciss_dev));
517    sc->ciss_dev_t->si_drv1 = sc;
518
519    /*
520     * The adapter is running; synchronous commands can now sleep
521     * waiting for an interrupt to signal completion.
522     */
523    sc->ciss_flags |= CISS_FLAG_RUNNING;
524
525    ciss_spawn_notify_thread(sc);
526
527    error = 0;
528 out:
529    if (error != 0) {
530	/* ciss_free() expects the mutex to be held */
531	mtx_lock(&sc->ciss_mtx);
532	ciss_free(sc);
533    }
534    return(error);
535}
536
537/************************************************************************
538 * Detach the driver from this adapter.
539 */
540static int
541ciss_detach(device_t dev)
542{
543    struct ciss_softc	*sc = device_get_softc(dev);
544
545    debug_called(1);
546
547    mtx_lock(&sc->ciss_mtx);
548    if (sc->ciss_flags & CISS_FLAG_CONTROL_OPEN) {
549	mtx_unlock(&sc->ciss_mtx);
550	return (EBUSY);
551    }
552
553    /* flush adapter cache */
554    ciss_flush_adapter(sc);
555
556    /* release all resources.  The mutex is released and freed here too. */
557    ciss_free(sc);
558
559    return(0);
560}
561
562/************************************************************************
563 * Prepare adapter for system shutdown.
564 */
565static int
566ciss_shutdown(device_t dev)
567{
568    struct ciss_softc	*sc = device_get_softc(dev);
569
570    debug_called(1);
571
572    mtx_lock(&sc->ciss_mtx);
573    /* flush adapter cache */
574    ciss_flush_adapter(sc);
575
576    if (sc->ciss_soft_reset)
577	ciss_soft_reset(sc);
578    mtx_unlock(&sc->ciss_mtx);
579
580    return(0);
581}
582
583static void
584ciss_init_sysctl(struct ciss_softc *sc)
585{
586
587    SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->ciss_dev),
588	SYSCTL_CHILDREN(device_get_sysctl_tree(sc->ciss_dev)),
589	OID_AUTO, "soft_reset", CTLFLAG_RW, &sc->ciss_soft_reset, 0, "");
590}
591
592/************************************************************************
593 * Perform PCI-specific attachment actions.
594 */
595static int
596ciss_init_pci(struct ciss_softc *sc)
597{
598    uintptr_t		cbase, csize, cofs;
599    uint32_t		method, supported_methods;
600    int			error, sqmask, i;
601    void		*intr;
602
603    debug_called(1);
604
605    /*
606     * Work out adapter type.
607     */
608    i = ciss_lookup(sc->ciss_dev);
609    if (i < 0) {
610	ciss_printf(sc, "unknown adapter type\n");
611	return (ENXIO);
612    }
613
614    if (ciss_vendor_data[i].flags & CISS_BOARD_SA5) {
615	sqmask = CISS_TL_SIMPLE_INTR_OPQ_SA5;
616    } else if (ciss_vendor_data[i].flags & CISS_BOARD_SA5B) {
617	sqmask = CISS_TL_SIMPLE_INTR_OPQ_SA5B;
618    } else {
619	/*
620	 * XXX Big hammer, masks/unmasks all possible interrupts.  This should
621	 * work on all hardware variants.  Need to add code to handle the
622	 * "controller crashed" interupt bit that this unmasks.
623	 */
624	sqmask = ~0;
625    }
626
627    /*
628     * Allocate register window first (we need this to find the config
629     * struct).
630     */
631    error = ENXIO;
632    sc->ciss_regs_rid = CISS_TL_SIMPLE_BAR_REGS;
633    if ((sc->ciss_regs_resource =
634	 bus_alloc_resource_any(sc->ciss_dev, SYS_RES_MEMORY,
635				&sc->ciss_regs_rid, RF_ACTIVE)) == NULL) {
636	ciss_printf(sc, "can't allocate register window\n");
637	return(ENXIO);
638    }
639    sc->ciss_regs_bhandle = rman_get_bushandle(sc->ciss_regs_resource);
640    sc->ciss_regs_btag = rman_get_bustag(sc->ciss_regs_resource);
641
642    /*
643     * Find the BAR holding the config structure.  If it's not the one
644     * we already mapped for registers, map it too.
645     */
646    sc->ciss_cfg_rid = CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_CFG_BAR) & 0xffff;
647    if (sc->ciss_cfg_rid != sc->ciss_regs_rid) {
648	if ((sc->ciss_cfg_resource =
649	     bus_alloc_resource_any(sc->ciss_dev, SYS_RES_MEMORY,
650				    &sc->ciss_cfg_rid, RF_ACTIVE)) == NULL) {
651	    ciss_printf(sc, "can't allocate config window\n");
652	    return(ENXIO);
653	}
654	cbase = (uintptr_t)rman_get_virtual(sc->ciss_cfg_resource);
655	csize = rman_get_end(sc->ciss_cfg_resource) -
656	    rman_get_start(sc->ciss_cfg_resource) + 1;
657    } else {
658	cbase = (uintptr_t)rman_get_virtual(sc->ciss_regs_resource);
659	csize = rman_get_end(sc->ciss_regs_resource) -
660	    rman_get_start(sc->ciss_regs_resource) + 1;
661    }
662    cofs = CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_CFG_OFF);
663
664    /*
665     * Use the base/size/offset values we just calculated to
666     * sanity-check the config structure.  If it's OK, point to it.
667     */
668    if ((cofs + sizeof(struct ciss_config_table)) > csize) {
669	ciss_printf(sc, "config table outside window\n");
670	return(ENXIO);
671    }
672    sc->ciss_cfg = (struct ciss_config_table *)(cbase + cofs);
673    debug(1, "config struct at %p", sc->ciss_cfg);
674
675    /*
676     * Calculate the number of request structures/commands we are
677     * going to provide for this adapter.
678     */
679    sc->ciss_max_requests = min(CISS_MAX_REQUESTS, sc->ciss_cfg->max_outstanding_commands);
680
681    /*
682     * Validate the config structure.  If we supported other transport
683     * methods, we could select amongst them at this point in time.
684     */
685    if (strncmp(sc->ciss_cfg->signature, "CISS", 4)) {
686	ciss_printf(sc, "config signature mismatch (got '%c%c%c%c')\n",
687		    sc->ciss_cfg->signature[0], sc->ciss_cfg->signature[1],
688		    sc->ciss_cfg->signature[2], sc->ciss_cfg->signature[3]);
689	return(ENXIO);
690    }
691
692    /*
693     * Select the mode of operation, prefer Performant.
694     */
695    if (!(sc->ciss_cfg->supported_methods &
696	(CISS_TRANSPORT_METHOD_SIMPLE | CISS_TRANSPORT_METHOD_PERF))) {
697	ciss_printf(sc, "No supported transport layers: 0x%x\n",
698	    sc->ciss_cfg->supported_methods);
699    }
700
701    switch (ciss_force_transport) {
702    case 1:
703	supported_methods = CISS_TRANSPORT_METHOD_SIMPLE;
704	break;
705    case 2:
706	supported_methods = CISS_TRANSPORT_METHOD_PERF;
707	break;
708    default:
709        /*
710         * Override the capabilities of the BOARD and specify SIMPLE
711         * MODE
712         */
713        if (ciss_vendor_data[i].flags & CISS_BOARD_SIMPLE)
714                supported_methods = CISS_TRANSPORT_METHOD_SIMPLE;
715        else
716                supported_methods = sc->ciss_cfg->supported_methods;
717        break;
718    }
719
720setup:
721    if ((supported_methods & CISS_TRANSPORT_METHOD_PERF) != 0) {
722	method = CISS_TRANSPORT_METHOD_PERF;
723	sc->ciss_perf = (struct ciss_perf_config *)(cbase + cofs +
724	    sc->ciss_cfg->transport_offset);
725	if (ciss_init_perf(sc)) {
726	    supported_methods &= ~method;
727	    goto setup;
728	}
729    } else if (supported_methods & CISS_TRANSPORT_METHOD_SIMPLE) {
730	method = CISS_TRANSPORT_METHOD_SIMPLE;
731    } else {
732	ciss_printf(sc, "No supported transport methods: 0x%x\n",
733	    sc->ciss_cfg->supported_methods);
734	return(ENXIO);
735    }
736
737    /*
738     * Tell it we're using the low 4GB of RAM.  Set the default interrupt
739     * coalescing options.
740     */
741    sc->ciss_cfg->requested_method = method;
742    sc->ciss_cfg->command_physlimit = 0;
743    sc->ciss_cfg->interrupt_coalesce_delay = CISS_INTERRUPT_COALESCE_DELAY;
744    sc->ciss_cfg->interrupt_coalesce_count = CISS_INTERRUPT_COALESCE_COUNT;
745
746#ifdef __i386__
747    sc->ciss_cfg->host_driver |= CISS_DRIVER_SCSI_PREFETCH;
748#endif
749
750    if (ciss_update_config(sc)) {
751	ciss_printf(sc, "adapter refuses to accept config update (IDBR 0x%x)\n",
752		    CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_IDBR));
753	return(ENXIO);
754    }
755    if ((sc->ciss_cfg->active_method & method) == 0) {
756	supported_methods &= ~method;
757	if (supported_methods == 0) {
758	    ciss_printf(sc, "adapter refuses to go into available transports "
759		"mode (0x%x, 0x%x)\n", supported_methods,
760		sc->ciss_cfg->active_method);
761	    return(ENXIO);
762	} else
763	    goto setup;
764    }
765
766    /*
767     * Wait for the adapter to come ready.
768     */
769    if ((error = ciss_wait_adapter(sc)) != 0)
770	return(error);
771
772    /* Prepare to possibly use MSIX and/or PERFORMANT interrupts.  Normal
773     * interrupts have a rid of 0, this will be overridden if MSIX is used.
774     */
775    sc->ciss_irq_rid[0] = 0;
776    if (method == CISS_TRANSPORT_METHOD_PERF) {
777	ciss_printf(sc, "PERFORMANT Transport\n");
778	if ((ciss_force_interrupt != 1) && (ciss_setup_msix(sc) == 0)) {
779	    intr = ciss_perf_msi_intr;
780	} else {
781	    intr = ciss_perf_intr;
782	}
783	/* XXX The docs say that the 0x01 bit is only for SAS controllers.
784	 * Unfortunately, there is no good way to know if this is a SAS
785	 * controller.  Hopefully enabling this bit universally will work OK.
786	 * It seems to work fine for SA6i controllers.
787	 */
788	sc->ciss_interrupt_mask = CISS_TL_PERF_INTR_OPQ | CISS_TL_PERF_INTR_MSI;
789
790    } else {
791	ciss_printf(sc, "SIMPLE Transport\n");
792	/* MSIX doesn't seem to work in SIMPLE mode, only enable if it forced */
793	if (ciss_force_interrupt == 2)
794	    /* If this fails, we automatically revert to INTx */
795	    ciss_setup_msix(sc);
796	sc->ciss_perf = NULL;
797	intr = ciss_intr;
798	sc->ciss_interrupt_mask = sqmask;
799    }
800
801    /*
802     * Turn off interrupts before we go routing anything.
803     */
804    CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
805
806    /*
807     * Allocate and set up our interrupt.
808     */
809    if ((sc->ciss_irq_resource =
810	 bus_alloc_resource_any(sc->ciss_dev, SYS_RES_IRQ, &sc->ciss_irq_rid[0],
811				RF_ACTIVE | RF_SHAREABLE)) == NULL) {
812	ciss_printf(sc, "can't allocate interrupt\n");
813	return(ENXIO);
814    }
815
816    if (bus_setup_intr(sc->ciss_dev, sc->ciss_irq_resource,
817		       INTR_TYPE_CAM|INTR_MPSAFE, NULL, intr, sc,
818		       &sc->ciss_intr)) {
819	ciss_printf(sc, "can't set up interrupt\n");
820	return(ENXIO);
821    }
822
823    /*
824     * Allocate the parent bus DMA tag appropriate for our PCI
825     * interface.
826     *
827     * Note that "simple" adapters can only address within a 32-bit
828     * span.
829     */
830    if (bus_dma_tag_create(bus_get_dma_tag(sc->ciss_dev),/* PCI parent */
831			   1, 0, 			/* alignment, boundary */
832			   BUS_SPACE_MAXADDR,		/* lowaddr */
833			   BUS_SPACE_MAXADDR, 		/* highaddr */
834			   NULL, NULL, 			/* filter, filterarg */
835			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsize */
836			   BUS_SPACE_UNRESTRICTED,	/* nsegments */
837			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
838			   0,				/* flags */
839			   NULL, NULL,			/* lockfunc, lockarg */
840			   &sc->ciss_parent_dmat)) {
841	ciss_printf(sc, "can't allocate parent DMA tag\n");
842	return(ENOMEM);
843    }
844
845    /*
846     * Create DMA tag for mapping buffers into adapter-addressable
847     * space.
848     */
849    if (bus_dma_tag_create(sc->ciss_parent_dmat, 	/* parent */
850			   1, 0, 			/* alignment, boundary */
851			   BUS_SPACE_MAXADDR,		/* lowaddr */
852			   BUS_SPACE_MAXADDR, 		/* highaddr */
853			   NULL, NULL, 			/* filter, filterarg */
854			   (CISS_MAX_SG_ELEMENTS - 1) * PAGE_SIZE, /* maxsize */
855			   CISS_MAX_SG_ELEMENTS,	/* nsegments */
856			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
857			   BUS_DMA_ALLOCNOW,		/* flags */
858			   busdma_lock_mutex, &sc->ciss_mtx,	/* lockfunc, lockarg */
859			   &sc->ciss_buffer_dmat)) {
860	ciss_printf(sc, "can't allocate buffer DMA tag\n");
861	return(ENOMEM);
862    }
863    return(0);
864}
865
866/************************************************************************
867 * Setup MSI/MSIX operation (Performant only)
868 * Four interrupts are available, but we only use 1 right now.  If MSI-X
869 * isn't avaialble, try using MSI instead.
870 */
871static int
872ciss_setup_msix(struct ciss_softc *sc)
873{
874    int val, i;
875
876    /* Weed out devices that don't actually support MSI */
877    i = ciss_lookup(sc->ciss_dev);
878    if (ciss_vendor_data[i].flags & CISS_BOARD_NOMSI)
879	return (EINVAL);
880
881    /*
882     * Only need to use the minimum number of MSI vectors, as the driver
883     * doesn't support directed MSIX interrupts.
884     */
885    val = pci_msix_count(sc->ciss_dev);
886    if (val < CISS_MSI_COUNT) {
887	val = pci_msi_count(sc->ciss_dev);
888	device_printf(sc->ciss_dev, "got %d MSI messages]\n", val);
889	if (val < CISS_MSI_COUNT)
890	    return (EINVAL);
891    }
892    val = MIN(val, CISS_MSI_COUNT);
893    if (pci_alloc_msix(sc->ciss_dev, &val) != 0) {
894	if (pci_alloc_msi(sc->ciss_dev, &val) != 0)
895	    return (EINVAL);
896    }
897
898    sc->ciss_msi = val;
899    if (bootverbose)
900	ciss_printf(sc, "Using %d MSIX interrupt%s\n", val,
901	    (val != 1) ? "s" : "");
902
903    for (i = 0; i < val; i++)
904	sc->ciss_irq_rid[i] = i + 1;
905
906    return (0);
907
908}
909
910/************************************************************************
911 * Setup the Performant structures.
912 */
913static int
914ciss_init_perf(struct ciss_softc *sc)
915{
916    struct ciss_perf_config *pc = sc->ciss_perf;
917    int reply_size;
918
919    /*
920     * Create the DMA tag for the reply queue.
921     */
922    reply_size = sizeof(uint64_t) * sc->ciss_max_requests;
923    if (bus_dma_tag_create(sc->ciss_parent_dmat,	/* parent */
924			   1, 0, 			/* alignment, boundary */
925			   BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
926			   BUS_SPACE_MAXADDR, 		/* highaddr */
927			   NULL, NULL, 			/* filter, filterarg */
928			   reply_size, 1,		/* maxsize, nsegments */
929			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
930			   0,				/* flags */
931			   NULL, NULL,			/* lockfunc, lockarg */
932			   &sc->ciss_reply_dmat)) {
933	ciss_printf(sc, "can't allocate reply DMA tag\n");
934	return(ENOMEM);
935    }
936    /*
937     * Allocate memory and make it available for DMA.
938     */
939    if (bus_dmamem_alloc(sc->ciss_reply_dmat, (void **)&sc->ciss_reply,
940			 BUS_DMA_NOWAIT, &sc->ciss_reply_map)) {
941	ciss_printf(sc, "can't allocate reply memory\n");
942	return(ENOMEM);
943    }
944    bus_dmamap_load(sc->ciss_reply_dmat, sc->ciss_reply_map, sc->ciss_reply,
945		    reply_size, ciss_command_map_helper, &sc->ciss_reply_phys, 0);
946    bzero(sc->ciss_reply, reply_size);
947
948    sc->ciss_cycle = 0x1;
949    sc->ciss_rqidx = 0;
950
951    /*
952     * Preload the fetch table with common command sizes.  This allows the
953     * hardware to not waste bus cycles for typical i/o commands, but also not
954     * tax the driver to be too exact in choosing sizes.  The table is optimized
955     * for page-aligned i/o's, but since most i/o comes from the various pagers,
956     * it's a reasonable assumption to make.
957     */
958    pc->fetch_count[CISS_SG_FETCH_NONE] = (sizeof(struct ciss_command) + 15) / 16;
959    pc->fetch_count[CISS_SG_FETCH_1] =
960	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 1 + 15) / 16;
961    pc->fetch_count[CISS_SG_FETCH_2] =
962	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 2 + 15) / 16;
963    pc->fetch_count[CISS_SG_FETCH_4] =
964	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 4 + 15) / 16;
965    pc->fetch_count[CISS_SG_FETCH_8] =
966	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 8 + 15) / 16;
967    pc->fetch_count[CISS_SG_FETCH_16] =
968	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 16 + 15) / 16;
969    pc->fetch_count[CISS_SG_FETCH_32] =
970	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 32 + 15) / 16;
971    pc->fetch_count[CISS_SG_FETCH_MAX] = (CISS_COMMAND_ALLOC_SIZE + 15) / 16;
972
973    pc->rq_size = sc->ciss_max_requests; /* XXX less than the card supports? */
974    pc->rq_count = 1;	/* XXX Hardcode for a single queue */
975    pc->rq_bank_hi = 0;
976    pc->rq_bank_lo = 0;
977    pc->rq[0].rq_addr_hi = 0x0;
978    pc->rq[0].rq_addr_lo = sc->ciss_reply_phys;
979
980    return(0);
981}
982
983/************************************************************************
984 * Wait for the adapter to come ready.
985 */
986static int
987ciss_wait_adapter(struct ciss_softc *sc)
988{
989    int		i;
990
991    debug_called(1);
992
993    /*
994     * Wait for the adapter to come ready.
995     */
996    if (!(sc->ciss_cfg->active_method & CISS_TRANSPORT_METHOD_READY)) {
997	ciss_printf(sc, "waiting for adapter to come ready...\n");
998	for (i = 0; !(sc->ciss_cfg->active_method & CISS_TRANSPORT_METHOD_READY); i++) {
999	    DELAY(1000000);	/* one second */
1000	    if (i > 30) {
1001		ciss_printf(sc, "timed out waiting for adapter to come ready\n");
1002		return(EIO);
1003	    }
1004	}
1005    }
1006    return(0);
1007}
1008
1009/************************************************************************
1010 * Flush the adapter cache.
1011 */
1012static int
1013ciss_flush_adapter(struct ciss_softc *sc)
1014{
1015    struct ciss_request			*cr;
1016    struct ciss_bmic_flush_cache	*cbfc;
1017    int					error, command_status;
1018
1019    debug_called(1);
1020
1021    cr = NULL;
1022    cbfc = NULL;
1023
1024    /*
1025     * Build a BMIC request to flush the cache.  We don't disable
1026     * it, as we may be going to do more I/O (eg. we are emulating
1027     * the Synchronise Cache command).
1028     */
1029    if ((cbfc = malloc(sizeof(*cbfc), CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
1030	error = ENOMEM;
1031	goto out;
1032    }
1033    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_FLUSH_CACHE,
1034				       (void **)&cbfc, sizeof(*cbfc))) != 0)
1035	goto out;
1036
1037    /*
1038     * Submit the request and wait for it to complete.
1039     */
1040    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1041	ciss_printf(sc, "error sending BMIC FLUSH_CACHE command (%d)\n", error);
1042	goto out;
1043    }
1044
1045    /*
1046     * Check response.
1047     */
1048    ciss_report_request(cr, &command_status, NULL);
1049    switch(command_status) {
1050    case CISS_CMD_STATUS_SUCCESS:
1051	break;
1052    default:
1053	ciss_printf(sc, "error flushing cache (%s)\n",
1054		    ciss_name_command_status(command_status));
1055	error = EIO;
1056	goto out;
1057    }
1058
1059out:
1060    if (cbfc != NULL)
1061	free(cbfc, CISS_MALLOC_CLASS);
1062    if (cr != NULL)
1063	ciss_release_request(cr);
1064    return(error);
1065}
1066
1067static void
1068ciss_soft_reset(struct ciss_softc *sc)
1069{
1070    struct ciss_request		*cr = NULL;
1071    struct ciss_command		*cc;
1072    int				i, error = 0;
1073
1074    for (i = 0; i < sc->ciss_max_logical_bus; i++) {
1075	/* only reset proxy controllers */
1076	if (sc->ciss_controllers[i].physical.bus == 0)
1077	    continue;
1078
1079	if ((error = ciss_get_request(sc, &cr)) != 0)
1080	    break;
1081
1082	if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_SOFT_RESET,
1083					   NULL, 0)) != 0)
1084	    break;
1085
1086	cc = cr->cr_cc;
1087	cc->header.address = sc->ciss_controllers[i];
1088
1089	if ((error = ciss_synch_request(cr, 60 * 1000)) != 0)
1090	    break;
1091
1092	ciss_release_request(cr);
1093    }
1094
1095    if (error)
1096	ciss_printf(sc, "error resetting controller (%d)\n", error);
1097
1098    if (cr != NULL)
1099	ciss_release_request(cr);
1100}
1101
1102/************************************************************************
1103 * Allocate memory for the adapter command structures, initialise
1104 * the request structures.
1105 *
1106 * Note that the entire set of commands are allocated in a single
1107 * contiguous slab.
1108 */
1109static int
1110ciss_init_requests(struct ciss_softc *sc)
1111{
1112    struct ciss_request	*cr;
1113    int			i;
1114
1115    debug_called(1);
1116
1117    if (bootverbose)
1118	ciss_printf(sc, "using %d of %d available commands\n",
1119		    sc->ciss_max_requests, sc->ciss_cfg->max_outstanding_commands);
1120
1121    /*
1122     * Create the DMA tag for commands.
1123     */
1124    if (bus_dma_tag_create(sc->ciss_parent_dmat,	/* parent */
1125			   32, 0, 			/* alignment, boundary */
1126			   BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1127			   BUS_SPACE_MAXADDR, 		/* highaddr */
1128			   NULL, NULL, 			/* filter, filterarg */
1129			   CISS_COMMAND_ALLOC_SIZE *
1130			   sc->ciss_max_requests, 1,	/* maxsize, nsegments */
1131			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
1132			   0,				/* flags */
1133			   NULL, NULL,			/* lockfunc, lockarg */
1134			   &sc->ciss_command_dmat)) {
1135	ciss_printf(sc, "can't allocate command DMA tag\n");
1136	return(ENOMEM);
1137    }
1138    /*
1139     * Allocate memory and make it available for DMA.
1140     */
1141    if (bus_dmamem_alloc(sc->ciss_command_dmat, (void **)&sc->ciss_command,
1142			 BUS_DMA_NOWAIT, &sc->ciss_command_map)) {
1143	ciss_printf(sc, "can't allocate command memory\n");
1144	return(ENOMEM);
1145    }
1146    bus_dmamap_load(sc->ciss_command_dmat, sc->ciss_command_map,sc->ciss_command,
1147		    CISS_COMMAND_ALLOC_SIZE * sc->ciss_max_requests,
1148		    ciss_command_map_helper, &sc->ciss_command_phys, 0);
1149    bzero(sc->ciss_command, CISS_COMMAND_ALLOC_SIZE * sc->ciss_max_requests);
1150
1151    /*
1152     * Set up the request and command structures, push requests onto
1153     * the free queue.
1154     */
1155    for (i = 1; i < sc->ciss_max_requests; i++) {
1156	cr = &sc->ciss_request[i];
1157	cr->cr_sc = sc;
1158	cr->cr_tag = i;
1159	cr->cr_cc = (struct ciss_command *)((uintptr_t)sc->ciss_command +
1160	    CISS_COMMAND_ALLOC_SIZE * i);
1161	cr->cr_ccphys = sc->ciss_command_phys + CISS_COMMAND_ALLOC_SIZE * i;
1162	bus_dmamap_create(sc->ciss_buffer_dmat, 0, &cr->cr_datamap);
1163	ciss_enqueue_free(cr);
1164    }
1165    return(0);
1166}
1167
1168static void
1169ciss_command_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1170{
1171    uint32_t *addr;
1172
1173    addr = arg;
1174    *addr = segs[0].ds_addr;
1175}
1176
1177/************************************************************************
1178 * Identify the adapter, print some information about it.
1179 */
1180static int
1181ciss_identify_adapter(struct ciss_softc *sc)
1182{
1183    struct ciss_request	*cr;
1184    int			error, command_status;
1185
1186    debug_called(1);
1187
1188    cr = NULL;
1189
1190    /*
1191     * Get a request, allocate storage for the adapter data.
1192     */
1193    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_CTLR,
1194				       (void **)&sc->ciss_id,
1195				       sizeof(*sc->ciss_id))) != 0)
1196	goto out;
1197
1198    /*
1199     * Submit the request and wait for it to complete.
1200     */
1201    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1202	ciss_printf(sc, "error sending BMIC ID_CTLR command (%d)\n", error);
1203	goto out;
1204    }
1205
1206    /*
1207     * Check response.
1208     */
1209    ciss_report_request(cr, &command_status, NULL);
1210    switch(command_status) {
1211    case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1212	break;
1213    case CISS_CMD_STATUS_DATA_UNDERRUN:
1214    case CISS_CMD_STATUS_DATA_OVERRUN:
1215	ciss_printf(sc, "data over/underrun reading adapter information\n");
1216    default:
1217	ciss_printf(sc, "error reading adapter information (%s)\n",
1218		    ciss_name_command_status(command_status));
1219	error = EIO;
1220	goto out;
1221    }
1222
1223    /* sanity-check reply */
1224    if (!(sc->ciss_id->controller_flags & CONTROLLER_FLAGS_BIG_MAP_SUPPORT)) {
1225	ciss_printf(sc, "adapter does not support BIG_MAP\n");
1226	error = ENXIO;
1227	goto out;
1228    }
1229
1230#if 0
1231    /* XXX later revisions may not need this */
1232    sc->ciss_flags |= CISS_FLAG_FAKE_SYNCH;
1233#endif
1234
1235    /* XXX only really required for old 5300 adapters? */
1236    sc->ciss_flags |= CISS_FLAG_BMIC_ABORT;
1237
1238    /*
1239     * Earlier controller specs do not contain these config
1240     * entries, so assume that a 0 means its old and assign
1241     * these values to the defaults that were established
1242     * when this driver was developed for them
1243     */
1244    if (sc->ciss_cfg->max_logical_supported == 0)
1245        sc->ciss_cfg->max_logical_supported = CISS_MAX_LOGICAL;
1246    if (sc->ciss_cfg->max_physical_supported == 0)
1247	sc->ciss_cfg->max_physical_supported = CISS_MAX_PHYSICAL;
1248    /* print information */
1249    if (bootverbose) {
1250	ciss_printf(sc, "  %d logical drive%s configured\n",
1251		    sc->ciss_id->configured_logical_drives,
1252		    (sc->ciss_id->configured_logical_drives == 1) ? "" : "s");
1253	ciss_printf(sc, "  firmware %4.4s\n", sc->ciss_id->running_firmware_revision);
1254	ciss_printf(sc, "  %d SCSI channels\n", sc->ciss_id->scsi_chip_count);
1255
1256	ciss_printf(sc, "  signature '%.4s'\n", sc->ciss_cfg->signature);
1257	ciss_printf(sc, "  valence %d\n", sc->ciss_cfg->valence);
1258	ciss_printf(sc, "  supported I/O methods 0x%b\n",
1259		    sc->ciss_cfg->supported_methods,
1260		    "\20\1READY\2simple\3performant\4MEMQ\n");
1261	ciss_printf(sc, "  active I/O method 0x%b\n",
1262		    sc->ciss_cfg->active_method, "\20\2simple\3performant\4MEMQ\n");
1263	ciss_printf(sc, "  4G page base 0x%08x\n",
1264		    sc->ciss_cfg->command_physlimit);
1265	ciss_printf(sc, "  interrupt coalesce delay %dus\n",
1266		    sc->ciss_cfg->interrupt_coalesce_delay);
1267	ciss_printf(sc, "  interrupt coalesce count %d\n",
1268		    sc->ciss_cfg->interrupt_coalesce_count);
1269	ciss_printf(sc, "  max outstanding commands %d\n",
1270		    sc->ciss_cfg->max_outstanding_commands);
1271	ciss_printf(sc, "  bus types 0x%b\n", sc->ciss_cfg->bus_types,
1272		    "\20\1ultra2\2ultra3\10fibre1\11fibre2\n");
1273	ciss_printf(sc, "  server name '%.16s'\n", sc->ciss_cfg->server_name);
1274	ciss_printf(sc, "  heartbeat 0x%x\n", sc->ciss_cfg->heartbeat);
1275    	ciss_printf(sc, "  max logical logical volumes: %d\n", sc->ciss_cfg->max_logical_supported);
1276    	ciss_printf(sc, "  max physical disks supported: %d\n", sc->ciss_cfg->max_physical_supported);
1277    	ciss_printf(sc, "  max physical disks per logical volume: %d\n", sc->ciss_cfg->max_physical_per_logical);
1278	ciss_printf(sc, "  JBOD Support is %s\n", (sc->ciss_id->uiYetMoreControllerFlags & YMORE_CONTROLLER_FLAGS_JBOD_SUPPORTED) ?
1279			"Available" : "Unavailable");
1280	ciss_printf(sc, "  JBOD Mode is %s\n", (sc->ciss_id->PowerUPNvramFlags & PWR_UP_FLAG_JBOD_ENABLED) ?
1281			"Enabled" : "Disabled");
1282    }
1283
1284out:
1285    if (error) {
1286	if (sc->ciss_id != NULL) {
1287	    free(sc->ciss_id, CISS_MALLOC_CLASS);
1288	    sc->ciss_id = NULL;
1289	}
1290    }
1291    if (cr != NULL)
1292	ciss_release_request(cr);
1293    return(error);
1294}
1295
1296/************************************************************************
1297 * Helper routine for generating a list of logical and physical luns.
1298 */
1299static struct ciss_lun_report *
1300ciss_report_luns(struct ciss_softc *sc, int opcode, int nunits)
1301{
1302    struct ciss_request		*cr;
1303    struct ciss_command		*cc;
1304    struct ciss_report_cdb	*crc;
1305    struct ciss_lun_report	*cll;
1306    int				command_status;
1307    int				report_size;
1308    int				error = 0;
1309
1310    debug_called(1);
1311
1312    cr = NULL;
1313    cll = NULL;
1314
1315    /*
1316     * Get a request, allocate storage for the address list.
1317     */
1318    if ((error = ciss_get_request(sc, &cr)) != 0)
1319	goto out;
1320    report_size = sizeof(*cll) + nunits * sizeof(union ciss_device_address);
1321    if ((cll = malloc(report_size, CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
1322	ciss_printf(sc, "can't allocate memory for lun report\n");
1323	error = ENOMEM;
1324	goto out;
1325    }
1326
1327    /*
1328     * Build the Report Logical/Physical LUNs command.
1329     */
1330    cc = cr->cr_cc;
1331    cr->cr_data = cll;
1332    cr->cr_length = report_size;
1333    cr->cr_flags = CISS_REQ_DATAIN;
1334
1335    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
1336    cc->header.address.physical.bus = 0;
1337    cc->header.address.physical.target = 0;
1338    cc->cdb.cdb_length = sizeof(*crc);
1339    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
1340    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
1341    cc->cdb.direction = CISS_CDB_DIRECTION_READ;
1342    cc->cdb.timeout = 30;	/* XXX better suggestions? */
1343
1344    crc = (struct ciss_report_cdb *)&(cc->cdb.cdb[0]);
1345    bzero(crc, sizeof(*crc));
1346    crc->opcode = opcode;
1347    crc->length = htonl(report_size);			/* big-endian field */
1348    cll->list_size = htonl(report_size - sizeof(*cll));	/* big-endian field */
1349
1350    /*
1351     * Submit the request and wait for it to complete.  (timeout
1352     * here should be much greater than above)
1353     */
1354    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1355	ciss_printf(sc, "error sending %d LUN command (%d)\n", opcode, error);
1356	goto out;
1357    }
1358
1359    /*
1360     * Check response.  Note that data over/underrun is OK.
1361     */
1362    ciss_report_request(cr, &command_status, NULL);
1363    switch(command_status) {
1364    case CISS_CMD_STATUS_SUCCESS:	/* buffer right size */
1365    case CISS_CMD_STATUS_DATA_UNDERRUN:	/* buffer too large, not bad */
1366	break;
1367    case CISS_CMD_STATUS_DATA_OVERRUN:
1368	ciss_printf(sc, "WARNING: more units than driver limit (%d)\n",
1369		    sc->ciss_cfg->max_logical_supported);
1370	break;
1371    default:
1372	ciss_printf(sc, "error detecting logical drive configuration (%s)\n",
1373		    ciss_name_command_status(command_status));
1374	error = EIO;
1375	goto out;
1376    }
1377    ciss_release_request(cr);
1378    cr = NULL;
1379
1380out:
1381    if (cr != NULL)
1382	ciss_release_request(cr);
1383    if (error && cll != NULL) {
1384	free(cll, CISS_MALLOC_CLASS);
1385	cll = NULL;
1386    }
1387    return(cll);
1388}
1389
1390/************************************************************************
1391 * Find logical drives on the adapter.
1392 */
1393static int
1394ciss_init_logical(struct ciss_softc *sc)
1395{
1396    struct ciss_lun_report	*cll;
1397    int				error = 0, i, j;
1398    int				ndrives;
1399
1400    debug_called(1);
1401
1402    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
1403			   sc->ciss_cfg->max_logical_supported);
1404    if (cll == NULL) {
1405	error = ENXIO;
1406	goto out;
1407    }
1408
1409    /* sanity-check reply */
1410    ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
1411    if ((ndrives < 0) || (ndrives > sc->ciss_cfg->max_logical_supported)) {
1412	ciss_printf(sc, "adapter claims to report absurd number of logical drives (%d > %d)\n",
1413	    	ndrives, sc->ciss_cfg->max_logical_supported);
1414	error = ENXIO;
1415	goto out;
1416    }
1417
1418    /*
1419     * Save logical drive information.
1420     */
1421    if (bootverbose) {
1422	ciss_printf(sc, "%d logical drive%s\n",
1423	    ndrives, (ndrives > 1 || ndrives == 0) ? "s" : "");
1424    }
1425
1426    sc->ciss_logical =
1427	malloc(sc->ciss_max_logical_bus * sizeof(struct ciss_ldrive *),
1428	       CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
1429    if (sc->ciss_logical == NULL) {
1430	error = ENXIO;
1431	goto out;
1432    }
1433
1434    for (i = 0; i <= sc->ciss_max_logical_bus; i++) {
1435	sc->ciss_logical[i] =
1436	    malloc(sc->ciss_cfg->max_logical_supported *
1437		   sizeof(struct ciss_ldrive),
1438		   CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
1439	if (sc->ciss_logical[i] == NULL) {
1440	    error = ENXIO;
1441	    goto out;
1442	}
1443
1444	for (j = 0; j < sc->ciss_cfg->max_logical_supported; j++)
1445	    sc->ciss_logical[i][j].cl_status = CISS_LD_NONEXISTENT;
1446    }
1447
1448
1449    for (i = 0; i < sc->ciss_cfg->max_logical_supported; i++) {
1450	if (i < ndrives) {
1451	    struct ciss_ldrive	*ld;
1452	    int			bus, target;
1453
1454	    bus		= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
1455	    target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
1456	    ld		= &sc->ciss_logical[bus][target];
1457
1458	    ld->cl_address	= cll->lun[i];
1459	    ld->cl_controller	= &sc->ciss_controllers[bus];
1460	    if (ciss_identify_logical(sc, ld) != 0)
1461		continue;
1462	    /*
1463	     * If the drive has had media exchanged, we should bring it online.
1464	     */
1465	    if (ld->cl_lstatus->media_exchanged)
1466		ciss_accept_media(sc, ld);
1467
1468	}
1469    }
1470
1471 out:
1472    if (cll != NULL)
1473	free(cll, CISS_MALLOC_CLASS);
1474    return(error);
1475}
1476
1477static int
1478ciss_init_physical(struct ciss_softc *sc)
1479{
1480    struct ciss_lun_report	*cll;
1481    int				error = 0, i;
1482    int				nphys;
1483    int				bus, target;
1484
1485    debug_called(1);
1486
1487    bus = 0;
1488    target = 0;
1489
1490    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
1491			   sc->ciss_cfg->max_physical_supported);
1492    if (cll == NULL) {
1493	error = ENXIO;
1494	goto out;
1495    }
1496
1497    nphys = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
1498
1499    if (bootverbose) {
1500	ciss_printf(sc, "%d physical device%s\n",
1501	    nphys, (nphys > 1 || nphys == 0) ? "s" : "");
1502    }
1503
1504    /*
1505     * Figure out the bus mapping.
1506     * Logical buses include both the local logical bus for local arrays and
1507     * proxy buses for remote arrays.  Physical buses are numbered by the
1508     * controller and represent physical buses that hold physical devices.
1509     * We shift these bus numbers so that everything fits into a single flat
1510     * numbering space for CAM.  Logical buses occupy the first 32 CAM bus
1511     * numbers, and the physical bus numbers are shifted to be above that.
1512     * This results in the various driver arrays being indexed as follows:
1513     *
1514     * ciss_controllers[] - indexed by logical bus
1515     * ciss_cam_sim[]     - indexed by both logical and physical, with physical
1516     *                      being shifted by 32.
1517     * ciss_logical[][]   - indexed by logical bus
1518     * ciss_physical[][]  - indexed by physical bus
1519     *
1520     * XXX This is getting more and more hackish.  CISS really doesn't play
1521     *     well with a standard SCSI model; devices are addressed via magic
1522     *     cookies, not via b/t/l addresses.  Since there is no way to store
1523     *     the cookie in the CAM device object, we have to keep these lookup
1524     *     tables handy so that the devices can be found quickly at the cost
1525     *     of wasting memory and having a convoluted lookup scheme.  This
1526     *     driver should probably be converted to block interface.
1527     */
1528    /*
1529     * If the L2 and L3 SCSI addresses are 0, this signifies a proxy
1530     * controller. A proxy controller is another physical controller
1531     * behind the primary PCI controller. We need to know about this
1532     * so that BMIC commands can be properly targeted.  There can be
1533     * proxy controllers attached to a single PCI controller, so
1534     * find the highest numbered one so the array can be properly
1535     * sized.
1536     */
1537    sc->ciss_max_logical_bus = 1;
1538    for (i = 0; i < nphys; i++) {
1539	if (cll->lun[i].physical.extra_address == 0) {
1540	    bus = cll->lun[i].physical.bus;
1541	    sc->ciss_max_logical_bus = max(sc->ciss_max_logical_bus, bus) + 1;
1542	} else {
1543	    bus = CISS_EXTRA_BUS2(cll->lun[i].physical.extra_address);
1544	    sc->ciss_max_physical_bus = max(sc->ciss_max_physical_bus, bus);
1545	}
1546    }
1547
1548    sc->ciss_controllers =
1549	malloc(sc->ciss_max_logical_bus * sizeof (union ciss_device_address),
1550	       CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
1551
1552    if (sc->ciss_controllers == NULL) {
1553	ciss_printf(sc, "Could not allocate memory for controller map\n");
1554	error = ENOMEM;
1555	goto out;
1556    }
1557
1558    /* setup a map of controller addresses */
1559    for (i = 0; i < nphys; i++) {
1560	if (cll->lun[i].physical.extra_address == 0) {
1561	    sc->ciss_controllers[cll->lun[i].physical.bus] = cll->lun[i];
1562	}
1563    }
1564
1565    sc->ciss_physical =
1566	malloc(sc->ciss_max_physical_bus * sizeof(struct ciss_pdrive *),
1567	       CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
1568    if (sc->ciss_physical == NULL) {
1569	ciss_printf(sc, "Could not allocate memory for physical device map\n");
1570	error = ENOMEM;
1571	goto out;
1572    }
1573
1574    for (i = 0; i < sc->ciss_max_physical_bus; i++) {
1575	sc->ciss_physical[i] =
1576	    malloc(sizeof(struct ciss_pdrive) * CISS_MAX_PHYSTGT,
1577		   CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
1578	if (sc->ciss_physical[i] == NULL) {
1579	    ciss_printf(sc, "Could not allocate memory for target map\n");
1580	    error = ENOMEM;
1581	    goto out;
1582	}
1583    }
1584
1585    ciss_filter_physical(sc, cll);
1586
1587out:
1588    if (cll != NULL)
1589	free(cll, CISS_MALLOC_CLASS);
1590
1591    return(error);
1592}
1593
1594static int
1595ciss_filter_physical(struct ciss_softc *sc, struct ciss_lun_report *cll)
1596{
1597    u_int32_t ea;
1598    int i, nphys;
1599    int	bus, target;
1600
1601    nphys = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
1602    for (i = 0; i < nphys; i++) {
1603	if (cll->lun[i].physical.extra_address == 0)
1604	    continue;
1605
1606	/*
1607	 * Filter out devices that we don't want.  Level 3 LUNs could
1608	 * probably be supported, but the docs don't give enough of a
1609	 * hint to know how.
1610	 *
1611	 * The mode field of the physical address is likely set to have
1612	 * hard disks masked out.  Honor it unless the user has overridden
1613	 * us with the tunable.  We also munge the inquiry data for these
1614	 * disks so that they only show up as passthrough devices.  Keeping
1615	 * them visible in this fashion is useful for doing things like
1616	 * flashing firmware.
1617	 */
1618	ea = cll->lun[i].physical.extra_address;
1619	if ((CISS_EXTRA_BUS3(ea) != 0) || (CISS_EXTRA_TARGET3(ea) != 0) ||
1620	    (CISS_EXTRA_MODE2(ea) == 0x3))
1621	    continue;
1622	if ((ciss_expose_hidden_physical == 0) &&
1623	   (cll->lun[i].physical.mode == CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL))
1624	    continue;
1625
1626	/*
1627	 * Note: CISS firmware numbers physical busses starting at '1', not
1628	 *       '0'.  This numbering is internal to the firmware and is only
1629	 *       used as a hint here.
1630	 */
1631	bus = CISS_EXTRA_BUS2(ea) - 1;
1632	target = CISS_EXTRA_TARGET2(ea);
1633	sc->ciss_physical[bus][target].cp_address = cll->lun[i];
1634	sc->ciss_physical[bus][target].cp_online = 1;
1635    }
1636
1637    return (0);
1638}
1639
1640static int
1641ciss_inquiry_logical(struct ciss_softc *sc, struct ciss_ldrive *ld)
1642{
1643    struct ciss_request			*cr;
1644    struct ciss_command			*cc;
1645    struct scsi_inquiry			*inq;
1646    int					error;
1647    int					command_status;
1648
1649    cr = NULL;
1650
1651    bzero(&ld->cl_geometry, sizeof(ld->cl_geometry));
1652
1653    if ((error = ciss_get_request(sc, &cr)) != 0)
1654	goto out;
1655
1656    cc = cr->cr_cc;
1657    cr->cr_data = &ld->cl_geometry;
1658    cr->cr_length = sizeof(ld->cl_geometry);
1659    cr->cr_flags = CISS_REQ_DATAIN;
1660
1661    cc->header.address = ld->cl_address;
1662    cc->cdb.cdb_length = 6;
1663    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
1664    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
1665    cc->cdb.direction = CISS_CDB_DIRECTION_READ;
1666    cc->cdb.timeout = 30;
1667
1668    inq = (struct scsi_inquiry *)&(cc->cdb.cdb[0]);
1669    inq->opcode = INQUIRY;
1670    inq->byte2 = SI_EVPD;
1671    inq->page_code = CISS_VPD_LOGICAL_DRIVE_GEOMETRY;
1672    scsi_ulto2b(sizeof(ld->cl_geometry), inq->length);
1673
1674    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1675	ciss_printf(sc, "error getting geometry (%d)\n", error);
1676	goto out;
1677    }
1678
1679    ciss_report_request(cr, &command_status, NULL);
1680    switch(command_status) {
1681    case CISS_CMD_STATUS_SUCCESS:
1682    case CISS_CMD_STATUS_DATA_UNDERRUN:
1683	break;
1684    case CISS_CMD_STATUS_DATA_OVERRUN:
1685	ciss_printf(sc, "WARNING: Data overrun\n");
1686	break;
1687    default:
1688	ciss_printf(sc, "Error detecting logical drive geometry (%s)\n",
1689		    ciss_name_command_status(command_status));
1690	break;
1691    }
1692
1693out:
1694    if (cr != NULL)
1695	ciss_release_request(cr);
1696    return(error);
1697}
1698/************************************************************************
1699 * Identify a logical drive, initialise state related to it.
1700 */
1701static int
1702ciss_identify_logical(struct ciss_softc *sc, struct ciss_ldrive *ld)
1703{
1704    struct ciss_request		*cr;
1705    struct ciss_command		*cc;
1706    struct ciss_bmic_cdb	*cbc;
1707    int				error, command_status;
1708
1709    debug_called(1);
1710
1711    cr = NULL;
1712
1713    /*
1714     * Build a BMIC request to fetch the drive ID.
1715     */
1716    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_LDRIVE,
1717				       (void **)&ld->cl_ldrive,
1718				       sizeof(*ld->cl_ldrive))) != 0)
1719	goto out;
1720    cc = cr->cr_cc;
1721    cc->header.address = *ld->cl_controller;	/* target controller */
1722    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1723    cbc->log_drive = CISS_LUN_TO_TARGET(ld->cl_address.logical.lun);
1724
1725    /*
1726     * Submit the request and wait for it to complete.
1727     */
1728    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1729	ciss_printf(sc, "error sending BMIC LDRIVE command (%d)\n", error);
1730	goto out;
1731    }
1732
1733    /*
1734     * Check response.
1735     */
1736    ciss_report_request(cr, &command_status, NULL);
1737    switch(command_status) {
1738    case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1739	break;
1740    case CISS_CMD_STATUS_DATA_UNDERRUN:
1741    case CISS_CMD_STATUS_DATA_OVERRUN:
1742	ciss_printf(sc, "data over/underrun reading logical drive ID\n");
1743    default:
1744	ciss_printf(sc, "error reading logical drive ID (%s)\n",
1745		    ciss_name_command_status(command_status));
1746	error = EIO;
1747	goto out;
1748    }
1749    ciss_release_request(cr);
1750    cr = NULL;
1751
1752    /*
1753     * Build a CISS BMIC command to get the logical drive status.
1754     */
1755    if ((error = ciss_get_ldrive_status(sc, ld)) != 0)
1756	goto out;
1757
1758    /*
1759     * Get the logical drive geometry.
1760     */
1761    if ((error = ciss_inquiry_logical(sc, ld)) != 0)
1762	goto out;
1763
1764    /*
1765     * Print the drive's basic characteristics.
1766     */
1767    if (bootverbose) {
1768	ciss_printf(sc, "logical drive (b%dt%d): %s, %dMB ",
1769		    CISS_LUN_TO_BUS(ld->cl_address.logical.lun),
1770		    CISS_LUN_TO_TARGET(ld->cl_address.logical.lun),
1771		    ciss_name_ldrive_org(ld->cl_ldrive->fault_tolerance),
1772		    ((ld->cl_ldrive->blocks_available / (1024 * 1024)) *
1773		     ld->cl_ldrive->block_size));
1774
1775	ciss_print_ldrive(sc, ld);
1776    }
1777out:
1778    if (error != 0) {
1779	/* make the drive not-exist */
1780	ld->cl_status = CISS_LD_NONEXISTENT;
1781	if (ld->cl_ldrive != NULL) {
1782	    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
1783	    ld->cl_ldrive = NULL;
1784	}
1785	if (ld->cl_lstatus != NULL) {
1786	    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
1787	    ld->cl_lstatus = NULL;
1788	}
1789    }
1790    if (cr != NULL)
1791	ciss_release_request(cr);
1792
1793    return(error);
1794}
1795
1796/************************************************************************
1797 * Get status for a logical drive.
1798 *
1799 * XXX should we also do this in response to Test Unit Ready?
1800 */
1801static int
1802ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld)
1803{
1804    struct ciss_request		*cr;
1805    struct ciss_command		*cc;
1806    struct ciss_bmic_cdb	*cbc;
1807    int				error, command_status;
1808
1809    /*
1810     * Build a CISS BMIC command to get the logical drive status.
1811     */
1812    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_LSTATUS,
1813				       (void **)&ld->cl_lstatus,
1814				       sizeof(*ld->cl_lstatus))) != 0)
1815	goto out;
1816    cc = cr->cr_cc;
1817    cc->header.address = *ld->cl_controller;	/* target controller */
1818    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1819    cbc->log_drive = CISS_LUN_TO_TARGET(ld->cl_address.logical.lun);
1820
1821    /*
1822     * Submit the request and wait for it to complete.
1823     */
1824    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1825	ciss_printf(sc, "error sending BMIC LSTATUS command (%d)\n", error);
1826	goto out;
1827    }
1828
1829    /*
1830     * Check response.
1831     */
1832    ciss_report_request(cr, &command_status, NULL);
1833    switch(command_status) {
1834    case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1835	break;
1836    case CISS_CMD_STATUS_DATA_UNDERRUN:
1837    case CISS_CMD_STATUS_DATA_OVERRUN:
1838	ciss_printf(sc, "data over/underrun reading logical drive status\n");
1839    default:
1840	ciss_printf(sc, "error reading logical drive status (%s)\n",
1841		    ciss_name_command_status(command_status));
1842	error = EIO;
1843	goto out;
1844    }
1845
1846    /*
1847     * Set the drive's summary status based on the returned status.
1848     *
1849     * XXX testing shows that a failed JBOD drive comes back at next
1850     * boot in "queued for expansion" mode.  WTF?
1851     */
1852    ld->cl_status = ciss_decode_ldrive_status(ld->cl_lstatus->status);
1853
1854out:
1855    if (cr != NULL)
1856	ciss_release_request(cr);
1857    return(error);
1858}
1859
1860/************************************************************************
1861 * Notify the adapter of a config update.
1862 */
1863static int
1864ciss_update_config(struct ciss_softc *sc)
1865{
1866    int		i;
1867
1868    debug_called(1);
1869
1870    CISS_TL_SIMPLE_WRITE(sc, CISS_TL_SIMPLE_IDBR, CISS_TL_SIMPLE_IDBR_CFG_TABLE);
1871    for (i = 0; i < 1000; i++) {
1872	if (!(CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_IDBR) &
1873	      CISS_TL_SIMPLE_IDBR_CFG_TABLE)) {
1874	    return(0);
1875	}
1876	DELAY(1000);
1877    }
1878    return(1);
1879}
1880
1881/************************************************************************
1882 * Accept new media into a logical drive.
1883 *
1884 * XXX The drive has previously been offline; it would be good if we
1885 *     could make sure it's not open right now.
1886 */
1887static int
1888ciss_accept_media(struct ciss_softc *sc, struct ciss_ldrive *ld)
1889{
1890    struct ciss_request		*cr;
1891    struct ciss_command		*cc;
1892    struct ciss_bmic_cdb	*cbc;
1893    int				command_status;
1894    int				error = 0, ldrive;
1895
1896    ldrive = CISS_LUN_TO_TARGET(ld->cl_address.logical.lun);
1897
1898    debug(0, "bringing logical drive %d back online", ldrive);
1899
1900    /*
1901     * Build a CISS BMIC command to bring the drive back online.
1902     */
1903    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ACCEPT_MEDIA,
1904				       NULL, 0)) != 0)
1905	goto out;
1906    cc = cr->cr_cc;
1907    cc->header.address = *ld->cl_controller;	/* target controller */
1908    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1909    cbc->log_drive = ldrive;
1910
1911    /*
1912     * Submit the request and wait for it to complete.
1913     */
1914    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1915	ciss_printf(sc, "error sending BMIC ACCEPT MEDIA command (%d)\n", error);
1916	goto out;
1917    }
1918
1919    /*
1920     * Check response.
1921     */
1922    ciss_report_request(cr, &command_status, NULL);
1923    switch(command_status) {
1924    case CISS_CMD_STATUS_SUCCESS:		/* all OK */
1925	/* we should get a logical drive status changed event here */
1926	break;
1927    default:
1928	ciss_printf(cr->cr_sc, "error accepting media into failed logical drive (%s)\n",
1929		    ciss_name_command_status(command_status));
1930	break;
1931    }
1932
1933out:
1934    if (cr != NULL)
1935	ciss_release_request(cr);
1936    return(error);
1937}
1938
1939/************************************************************************
1940 * Release adapter resources.
1941 */
1942static void
1943ciss_free(struct ciss_softc *sc)
1944{
1945    struct ciss_request *cr;
1946    int			i, j;
1947
1948    debug_called(1);
1949
1950    /* we're going away */
1951    sc->ciss_flags |= CISS_FLAG_ABORTING;
1952
1953    /* terminate the periodic heartbeat routine */
1954    callout_stop(&sc->ciss_periodic);
1955
1956    /* cancel the Event Notify chain */
1957    ciss_notify_abort(sc);
1958
1959    ciss_kill_notify_thread(sc);
1960
1961    /* disconnect from CAM */
1962    if (sc->ciss_cam_sim) {
1963	for (i = 0; i < sc->ciss_max_logical_bus; i++) {
1964	    if (sc->ciss_cam_sim[i]) {
1965		xpt_bus_deregister(cam_sim_path(sc->ciss_cam_sim[i]));
1966		cam_sim_free(sc->ciss_cam_sim[i], 0);
1967	    }
1968	}
1969	for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
1970	     CISS_PHYSICAL_BASE; i++) {
1971	    if (sc->ciss_cam_sim[i]) {
1972		xpt_bus_deregister(cam_sim_path(sc->ciss_cam_sim[i]));
1973		cam_sim_free(sc->ciss_cam_sim[i], 0);
1974	    }
1975	}
1976	free(sc->ciss_cam_sim, CISS_MALLOC_CLASS);
1977    }
1978    if (sc->ciss_cam_devq)
1979	cam_simq_free(sc->ciss_cam_devq);
1980
1981    /* remove the control device */
1982    mtx_unlock(&sc->ciss_mtx);
1983    if (sc->ciss_dev_t != NULL)
1984	destroy_dev(sc->ciss_dev_t);
1985
1986    /* Final cleanup of the callout. */
1987    callout_drain(&sc->ciss_periodic);
1988    mtx_destroy(&sc->ciss_mtx);
1989
1990    /* free the controller data */
1991    if (sc->ciss_id != NULL)
1992	free(sc->ciss_id, CISS_MALLOC_CLASS);
1993
1994    /* release I/O resources */
1995    if (sc->ciss_regs_resource != NULL)
1996	bus_release_resource(sc->ciss_dev, SYS_RES_MEMORY,
1997			     sc->ciss_regs_rid, sc->ciss_regs_resource);
1998    if (sc->ciss_cfg_resource != NULL)
1999	bus_release_resource(sc->ciss_dev, SYS_RES_MEMORY,
2000			     sc->ciss_cfg_rid, sc->ciss_cfg_resource);
2001    if (sc->ciss_intr != NULL)
2002	bus_teardown_intr(sc->ciss_dev, sc->ciss_irq_resource, sc->ciss_intr);
2003    if (sc->ciss_irq_resource != NULL)
2004	bus_release_resource(sc->ciss_dev, SYS_RES_IRQ,
2005			     sc->ciss_irq_rid[0], sc->ciss_irq_resource);
2006    if (sc->ciss_msi)
2007	pci_release_msi(sc->ciss_dev);
2008
2009    while ((cr = ciss_dequeue_free(sc)) != NULL)
2010	bus_dmamap_destroy(sc->ciss_buffer_dmat, cr->cr_datamap);
2011    if (sc->ciss_buffer_dmat)
2012	bus_dma_tag_destroy(sc->ciss_buffer_dmat);
2013
2014    /* destroy command memory and DMA tag */
2015    if (sc->ciss_command != NULL) {
2016	bus_dmamap_unload(sc->ciss_command_dmat, sc->ciss_command_map);
2017	bus_dmamem_free(sc->ciss_command_dmat, sc->ciss_command, sc->ciss_command_map);
2018    }
2019    if (sc->ciss_command_dmat)
2020	bus_dma_tag_destroy(sc->ciss_command_dmat);
2021
2022    if (sc->ciss_reply) {
2023	bus_dmamap_unload(sc->ciss_reply_dmat, sc->ciss_reply_map);
2024	bus_dmamem_free(sc->ciss_reply_dmat, sc->ciss_reply, sc->ciss_reply_map);
2025    }
2026    if (sc->ciss_reply_dmat)
2027	bus_dma_tag_destroy(sc->ciss_reply_dmat);
2028
2029    /* destroy DMA tags */
2030    if (sc->ciss_parent_dmat)
2031	bus_dma_tag_destroy(sc->ciss_parent_dmat);
2032    if (sc->ciss_logical) {
2033	for (i = 0; i <= sc->ciss_max_logical_bus; i++) {
2034	    for (j = 0; j < sc->ciss_cfg->max_logical_supported; j++) {
2035		if (sc->ciss_logical[i][j].cl_ldrive)
2036		    free(sc->ciss_logical[i][j].cl_ldrive, CISS_MALLOC_CLASS);
2037		if (sc->ciss_logical[i][j].cl_lstatus)
2038		    free(sc->ciss_logical[i][j].cl_lstatus, CISS_MALLOC_CLASS);
2039	    }
2040	    free(sc->ciss_logical[i], CISS_MALLOC_CLASS);
2041	}
2042	free(sc->ciss_logical, CISS_MALLOC_CLASS);
2043    }
2044
2045    if (sc->ciss_physical) {
2046	for (i = 0; i < sc->ciss_max_physical_bus; i++)
2047	    free(sc->ciss_physical[i], CISS_MALLOC_CLASS);
2048	free(sc->ciss_physical, CISS_MALLOC_CLASS);
2049    }
2050
2051    if (sc->ciss_controllers)
2052	free(sc->ciss_controllers, CISS_MALLOC_CLASS);
2053
2054}
2055
2056/************************************************************************
2057 * Give a command to the adapter.
2058 *
2059 * Note that this uses the simple transport layer directly.  If we
2060 * want to add support for other layers, we'll need a switch of some
2061 * sort.
2062 *
2063 * Note that the simple transport layer has no way of refusing a
2064 * command; we only have as many request structures as the adapter
2065 * supports commands, so we don't have to check (this presumes that
2066 * the adapter can handle commands as fast as we throw them at it).
2067 */
2068static int
2069ciss_start(struct ciss_request *cr)
2070{
2071    struct ciss_command	*cc;	/* XXX debugging only */
2072    int			error;
2073
2074    cc = cr->cr_cc;
2075    debug(2, "post command %d tag %d ", cr->cr_tag, cc->header.host_tag);
2076
2077    /*
2078     * Map the request's data.
2079     */
2080    if ((error = ciss_map_request(cr)))
2081	return(error);
2082
2083#if 0
2084    ciss_print_request(cr);
2085#endif
2086
2087    return(0);
2088}
2089
2090/************************************************************************
2091 * Fetch completed request(s) from the adapter, queue them for
2092 * completion handling.
2093 *
2094 * Note that this uses the simple transport layer directly.  If we
2095 * want to add support for other layers, we'll need a switch of some
2096 * sort.
2097 *
2098 * Note that the simple transport mechanism does not require any
2099 * reentrancy protection; the OPQ read is atomic.  If there is a
2100 * chance of a race with something else that might move the request
2101 * off the busy list, then we will have to lock against that
2102 * (eg. timeouts, etc.)
2103 */
2104static void
2105ciss_done(struct ciss_softc *sc, cr_qhead_t *qh)
2106{
2107    struct ciss_request	*cr;
2108    struct ciss_command	*cc;
2109    u_int32_t		tag, index;
2110
2111    debug_called(3);
2112
2113    /*
2114     * Loop quickly taking requests from the adapter and moving them
2115     * to the completed queue.
2116     */
2117    for (;;) {
2118
2119	tag = CISS_TL_SIMPLE_FETCH_CMD(sc);
2120	if (tag == CISS_TL_SIMPLE_OPQ_EMPTY)
2121	    break;
2122	index = tag >> 2;
2123	debug(2, "completed command %d%s", index,
2124	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
2125	if (index >= sc->ciss_max_requests) {
2126	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
2127	    continue;
2128	}
2129	cr = &(sc->ciss_request[index]);
2130	cc = cr->cr_cc;
2131	cc->header.host_tag = tag;	/* not updated by adapter */
2132	ciss_enqueue_complete(cr, qh);
2133    }
2134
2135}
2136
2137static void
2138ciss_perf_done(struct ciss_softc *sc, cr_qhead_t *qh)
2139{
2140    struct ciss_request	*cr;
2141    struct ciss_command	*cc;
2142    u_int32_t		tag, index;
2143
2144    debug_called(3);
2145
2146    /*
2147     * Loop quickly taking requests from the adapter and moving them
2148     * to the completed queue.
2149     */
2150    for (;;) {
2151	tag = sc->ciss_reply[sc->ciss_rqidx];
2152	if ((tag & CISS_CYCLE_MASK) != sc->ciss_cycle)
2153	    break;
2154	index = tag >> 2;
2155	debug(2, "completed command %d%s\n", index,
2156	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
2157	if (index < sc->ciss_max_requests) {
2158	    cr = &(sc->ciss_request[index]);
2159	    cc = cr->cr_cc;
2160	    cc->header.host_tag = tag;	/* not updated by adapter */
2161	    ciss_enqueue_complete(cr, qh);
2162	} else {
2163	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
2164	}
2165	if (++sc->ciss_rqidx == sc->ciss_max_requests) {
2166	    sc->ciss_rqidx = 0;
2167	    sc->ciss_cycle ^= 1;
2168	}
2169    }
2170
2171}
2172
2173/************************************************************************
2174 * Take an interrupt from the adapter.
2175 */
2176static void
2177ciss_intr(void *arg)
2178{
2179    cr_qhead_t qh;
2180    struct ciss_softc	*sc = (struct ciss_softc *)arg;
2181
2182    /*
2183     * The only interrupt we recognise indicates that there are
2184     * entries in the outbound post queue.
2185     */
2186    STAILQ_INIT(&qh);
2187    ciss_done(sc, &qh);
2188    mtx_lock(&sc->ciss_mtx);
2189    ciss_complete(sc, &qh);
2190    mtx_unlock(&sc->ciss_mtx);
2191}
2192
2193static void
2194ciss_perf_intr(void *arg)
2195{
2196    struct ciss_softc	*sc = (struct ciss_softc *)arg;
2197
2198    /* Clear the interrupt and flush the bridges.  Docs say that the flush
2199     * needs to be done twice, which doesn't seem right.
2200     */
2201    CISS_TL_PERF_CLEAR_INT(sc);
2202    CISS_TL_PERF_FLUSH_INT(sc);
2203
2204    ciss_perf_msi_intr(sc);
2205}
2206
2207static void
2208ciss_perf_msi_intr(void *arg)
2209{
2210    cr_qhead_t qh;
2211    struct ciss_softc	*sc = (struct ciss_softc *)arg;
2212
2213    STAILQ_INIT(&qh);
2214    ciss_perf_done(sc, &qh);
2215    mtx_lock(&sc->ciss_mtx);
2216    ciss_complete(sc, &qh);
2217    mtx_unlock(&sc->ciss_mtx);
2218}
2219
2220
2221/************************************************************************
2222 * Process completed requests.
2223 *
2224 * Requests can be completed in three fashions:
2225 *
2226 * - by invoking a callback function (cr_complete is non-null)
2227 * - by waking up a sleeper (cr_flags has CISS_REQ_SLEEP set)
2228 * - by clearing the CISS_REQ_POLL flag in interrupt/timeout context
2229 */
2230static void
2231ciss_complete(struct ciss_softc *sc, cr_qhead_t *qh)
2232{
2233    struct ciss_request	*cr;
2234
2235    debug_called(2);
2236
2237    /*
2238     * Loop taking requests off the completed queue and performing
2239     * completion processing on them.
2240     */
2241    for (;;) {
2242	if ((cr = ciss_dequeue_complete(sc, qh)) == NULL)
2243	    break;
2244	ciss_unmap_request(cr);
2245
2246	if ((cr->cr_flags & CISS_REQ_BUSY) == 0)
2247	    ciss_printf(sc, "WARNING: completing non-busy request\n");
2248	cr->cr_flags &= ~CISS_REQ_BUSY;
2249
2250	/*
2251	 * If the request has a callback, invoke it.
2252	 */
2253	if (cr->cr_complete != NULL) {
2254	    cr->cr_complete(cr);
2255	    continue;
2256	}
2257
2258	/*
2259	 * If someone is sleeping on this request, wake them up.
2260	 */
2261	if (cr->cr_flags & CISS_REQ_SLEEP) {
2262	    cr->cr_flags &= ~CISS_REQ_SLEEP;
2263	    wakeup(cr);
2264	    continue;
2265	}
2266
2267	/*
2268	 * If someone is polling this request for completion, signal.
2269	 */
2270	if (cr->cr_flags & CISS_REQ_POLL) {
2271	    cr->cr_flags &= ~CISS_REQ_POLL;
2272	    continue;
2273	}
2274
2275	/*
2276	 * Give up and throw the request back on the free queue.  This
2277	 * should never happen; resources will probably be lost.
2278	 */
2279	ciss_printf(sc, "WARNING: completed command with no submitter\n");
2280	ciss_enqueue_free(cr);
2281    }
2282}
2283
2284/************************************************************************
2285 * Report on the completion status of a request, and pass back SCSI
2286 * and command status values.
2287 */
2288static int
2289_ciss_report_request(struct ciss_request *cr, int *command_status, int *scsi_status, const char *func)
2290{
2291    struct ciss_command		*cc;
2292    struct ciss_error_info	*ce;
2293
2294    debug_called(2);
2295
2296    cc = cr->cr_cc;
2297    ce = (struct ciss_error_info *)&(cc->sg[0]);
2298
2299    /*
2300     * We don't consider data under/overrun an error for the Report
2301     * Logical/Physical LUNs commands.
2302     */
2303    if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) &&
2304	((ce->command_status == CISS_CMD_STATUS_DATA_OVERRUN) ||
2305	 (ce->command_status == CISS_CMD_STATUS_DATA_UNDERRUN)) &&
2306	((cc->cdb.cdb[0] == CISS_OPCODE_REPORT_LOGICAL_LUNS) ||
2307	 (cc->cdb.cdb[0] == CISS_OPCODE_REPORT_PHYSICAL_LUNS) ||
2308	 (cc->cdb.cdb[0] == INQUIRY))) {
2309	cc->header.host_tag &= ~CISS_HDR_HOST_TAG_ERROR;
2310	debug(2, "ignoring irrelevant under/overrun error");
2311    }
2312
2313    /*
2314     * Check the command's error bit, if clear, there's no status and
2315     * everything is OK.
2316     */
2317    if (!(cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR)) {
2318	if (scsi_status != NULL)
2319	    *scsi_status = SCSI_STATUS_OK;
2320	if (command_status != NULL)
2321	    *command_status = CISS_CMD_STATUS_SUCCESS;
2322	return(0);
2323    } else {
2324	if (command_status != NULL)
2325	    *command_status = ce->command_status;
2326	if (scsi_status != NULL) {
2327	    if (ce->command_status == CISS_CMD_STATUS_TARGET_STATUS) {
2328		*scsi_status = ce->scsi_status;
2329	    } else {
2330		*scsi_status = -1;
2331	    }
2332	}
2333	if (bootverbose)
2334	    ciss_printf(cr->cr_sc, "command status 0x%x (%s) scsi status 0x%x\n",
2335			ce->command_status, ciss_name_command_status(ce->command_status),
2336			ce->scsi_status);
2337	if (ce->command_status == CISS_CMD_STATUS_INVALID_COMMAND) {
2338	    ciss_printf(cr->cr_sc, "invalid command, offense size %d at %d, value 0x%x, function %s\n",
2339			ce->additional_error_info.invalid_command.offense_size,
2340			ce->additional_error_info.invalid_command.offense_offset,
2341			ce->additional_error_info.invalid_command.offense_value,
2342			func);
2343	}
2344    }
2345#if 0
2346    ciss_print_request(cr);
2347#endif
2348    return(1);
2349}
2350
2351/************************************************************************
2352 * Issue a request and don't return until it's completed.
2353 *
2354 * Depending on adapter status, we may poll or sleep waiting for
2355 * completion.
2356 */
2357static int
2358ciss_synch_request(struct ciss_request *cr, int timeout)
2359{
2360    if (cr->cr_sc->ciss_flags & CISS_FLAG_RUNNING) {
2361	return(ciss_wait_request(cr, timeout));
2362    } else {
2363	return(ciss_poll_request(cr, timeout));
2364    }
2365}
2366
2367/************************************************************************
2368 * Issue a request and poll for completion.
2369 *
2370 * Timeout in milliseconds.
2371 */
2372static int
2373ciss_poll_request(struct ciss_request *cr, int timeout)
2374{
2375    cr_qhead_t qh;
2376    struct ciss_softc *sc;
2377    int		error;
2378
2379    debug_called(2);
2380
2381    STAILQ_INIT(&qh);
2382    sc = cr->cr_sc;
2383    cr->cr_flags |= CISS_REQ_POLL;
2384    if ((error = ciss_start(cr)) != 0)
2385	return(error);
2386
2387    do {
2388	if (sc->ciss_perf)
2389	    ciss_perf_done(sc, &qh);
2390	else
2391	    ciss_done(sc, &qh);
2392	ciss_complete(sc, &qh);
2393	if (!(cr->cr_flags & CISS_REQ_POLL))
2394	    return(0);
2395	DELAY(1000);
2396    } while (timeout-- >= 0);
2397    return(EWOULDBLOCK);
2398}
2399
2400/************************************************************************
2401 * Issue a request and sleep waiting for completion.
2402 *
2403 * Timeout in milliseconds.  Note that a spurious wakeup will reset
2404 * the timeout.
2405 */
2406static int
2407ciss_wait_request(struct ciss_request *cr, int timeout)
2408{
2409    int		error;
2410
2411    debug_called(2);
2412
2413    cr->cr_flags |= CISS_REQ_SLEEP;
2414    if ((error = ciss_start(cr)) != 0)
2415	return(error);
2416
2417    while ((cr->cr_flags & CISS_REQ_SLEEP) && (error != EWOULDBLOCK)) {
2418	error = msleep_sbt(cr, &cr->cr_sc->ciss_mtx, PRIBIO, "cissREQ",
2419	    SBT_1MS * timeout, 0, 0);
2420    }
2421    return(error);
2422}
2423
2424#if 0
2425/************************************************************************
2426 * Abort a request.  Note that a potential exists here to race the
2427 * request being completed; the caller must deal with this.
2428 */
2429static int
2430ciss_abort_request(struct ciss_request *ar)
2431{
2432    struct ciss_request		*cr;
2433    struct ciss_command		*cc;
2434    struct ciss_message_cdb	*cmc;
2435    int				error;
2436
2437    debug_called(1);
2438
2439    /* get a request */
2440    if ((error = ciss_get_request(ar->cr_sc, &cr)) != 0)
2441	return(error);
2442
2443    /* build the abort command */
2444    cc = cr->cr_cc;
2445    cc->header.address.mode.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;	/* addressing? */
2446    cc->header.address.physical.target = 0;
2447    cc->header.address.physical.bus = 0;
2448    cc->cdb.cdb_length = sizeof(*cmc);
2449    cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
2450    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2451    cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
2452    cc->cdb.timeout = 30;
2453
2454    cmc = (struct ciss_message_cdb *)&(cc->cdb.cdb[0]);
2455    cmc->opcode = CISS_OPCODE_MESSAGE_ABORT;
2456    cmc->type = CISS_MESSAGE_ABORT_TASK;
2457    cmc->abort_tag = ar->cr_tag;	/* endianness?? */
2458
2459    /*
2460     * Send the request and wait for a response.  If we believe we
2461     * aborted the request OK, clear the flag that indicates it's
2462     * running.
2463     */
2464    error = ciss_synch_request(cr, 35 * 1000);
2465    if (!error)
2466	error = ciss_report_request(cr, NULL, NULL);
2467    ciss_release_request(cr);
2468
2469    return(error);
2470}
2471#endif
2472
2473
2474/************************************************************************
2475 * Fetch and initialise a request
2476 */
2477static int
2478ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp)
2479{
2480    struct ciss_request *cr;
2481
2482    debug_called(2);
2483
2484    /*
2485     * Get a request and clean it up.
2486     */
2487    if ((cr = ciss_dequeue_free(sc)) == NULL)
2488	return(ENOMEM);
2489
2490    cr->cr_data = NULL;
2491    cr->cr_flags = 0;
2492    cr->cr_complete = NULL;
2493    cr->cr_private = NULL;
2494    cr->cr_sg_tag = CISS_SG_MAX;	/* Backstop to prevent accidents */
2495
2496    ciss_preen_command(cr);
2497    *crp = cr;
2498    return(0);
2499}
2500
2501static void
2502ciss_preen_command(struct ciss_request *cr)
2503{
2504    struct ciss_command	*cc;
2505    u_int32_t		cmdphys;
2506
2507    /*
2508     * Clean up the command structure.
2509     *
2510     * Note that we set up the error_info structure here, since the
2511     * length can be overwritten by any command.
2512     */
2513    cc = cr->cr_cc;
2514    cc->header.sg_in_list = 0;		/* kinda inefficient this way */
2515    cc->header.sg_total = 0;
2516    cc->header.host_tag = cr->cr_tag << 2;
2517    cc->header.host_tag_zeroes = 0;
2518    bzero(&(cc->sg[0]), CISS_COMMAND_ALLOC_SIZE - sizeof(struct ciss_command));
2519    cmdphys = cr->cr_ccphys;
2520    cc->error_info.error_info_address = cmdphys + sizeof(struct ciss_command);
2521    cc->error_info.error_info_length = CISS_COMMAND_ALLOC_SIZE - sizeof(struct ciss_command);
2522}
2523
2524/************************************************************************
2525 * Release a request to the free list.
2526 */
2527static void
2528ciss_release_request(struct ciss_request *cr)
2529{
2530    struct ciss_softc	*sc;
2531
2532    debug_called(2);
2533
2534    sc = cr->cr_sc;
2535
2536    /* release the request to the free queue */
2537    ciss_requeue_free(cr);
2538}
2539
2540/************************************************************************
2541 * Allocate a request that will be used to send a BMIC command.  Do some
2542 * of the common setup here to avoid duplicating it everywhere else.
2543 */
2544static int
2545ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
2546		      int opcode, void **bufp, size_t bufsize)
2547{
2548    struct ciss_request		*cr;
2549    struct ciss_command		*cc;
2550    struct ciss_bmic_cdb	*cbc;
2551    void			*buf;
2552    int				error;
2553    int				dataout;
2554
2555    debug_called(2);
2556
2557    cr = NULL;
2558    buf = NULL;
2559
2560    /*
2561     * Get a request.
2562     */
2563    if ((error = ciss_get_request(sc, &cr)) != 0)
2564	goto out;
2565
2566    /*
2567     * Allocate data storage if requested, determine the data direction.
2568     */
2569    dataout = 0;
2570    if ((bufsize > 0) && (bufp != NULL)) {
2571	if (*bufp == NULL) {
2572	    if ((buf = malloc(bufsize, CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
2573		error = ENOMEM;
2574		goto out;
2575	    }
2576	} else {
2577	    buf = *bufp;
2578	    dataout = 1;	/* we are given a buffer, so we are writing */
2579	}
2580    }
2581
2582    /*
2583     * Build a CISS BMIC command to get the logical drive ID.
2584     */
2585    cr->cr_data = buf;
2586    cr->cr_length = bufsize;
2587    if (!dataout)
2588	cr->cr_flags = CISS_REQ_DATAIN;
2589
2590    cc = cr->cr_cc;
2591    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2592    cc->header.address.physical.bus = 0;
2593    cc->header.address.physical.target = 0;
2594    cc->cdb.cdb_length = sizeof(*cbc);
2595    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2596    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2597    cc->cdb.direction = dataout ? CISS_CDB_DIRECTION_WRITE : CISS_CDB_DIRECTION_READ;
2598    cc->cdb.timeout = 0;
2599
2600    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
2601    bzero(cbc, sizeof(*cbc));
2602    cbc->opcode = dataout ? CISS_ARRAY_CONTROLLER_WRITE : CISS_ARRAY_CONTROLLER_READ;
2603    cbc->bmic_opcode = opcode;
2604    cbc->size = htons((u_int16_t)bufsize);
2605
2606out:
2607    if (error) {
2608	if (cr != NULL)
2609	    ciss_release_request(cr);
2610    } else {
2611	*crp = cr;
2612	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
2613	    *bufp = buf;
2614    }
2615    return(error);
2616}
2617
2618/************************************************************************
2619 * Handle a command passed in from userspace.
2620 */
2621static int
2622ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc)
2623{
2624    struct ciss_request		*cr;
2625    struct ciss_command		*cc;
2626    struct ciss_error_info	*ce;
2627    int				error = 0;
2628
2629    debug_called(1);
2630
2631    cr = NULL;
2632
2633    /*
2634     * Get a request.
2635     */
2636    while (ciss_get_request(sc, &cr) != 0)
2637	msleep(sc, &sc->ciss_mtx, PPAUSE, "cissREQ", hz);
2638    cc = cr->cr_cc;
2639
2640    /*
2641     * Allocate an in-kernel databuffer if required, copy in user data.
2642     */
2643    mtx_unlock(&sc->ciss_mtx);
2644    cr->cr_length = ioc->buf_size;
2645    if (ioc->buf_size > 0) {
2646	if ((cr->cr_data = malloc(ioc->buf_size, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
2647	    error = ENOMEM;
2648	    goto out_unlocked;
2649	}
2650	if ((error = copyin(ioc->buf, cr->cr_data, ioc->buf_size))) {
2651	    debug(0, "copyin: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2652	    goto out_unlocked;
2653	}
2654    }
2655
2656    /*
2657     * Build the request based on the user command.
2658     */
2659    bcopy(&ioc->LUN_info, &cc->header.address, sizeof(cc->header.address));
2660    bcopy(&ioc->Request, &cc->cdb, sizeof(cc->cdb));
2661
2662    /* XXX anything else to populate here? */
2663    mtx_lock(&sc->ciss_mtx);
2664
2665    /*
2666     * Run the command.
2667     */
2668    if ((error = ciss_synch_request(cr, 60 * 1000))) {
2669	debug(0, "request failed - %d", error);
2670	goto out;
2671    }
2672
2673    /*
2674     * Check to see if the command succeeded.
2675     */
2676    ce = (struct ciss_error_info *)&(cc->sg[0]);
2677    if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) == 0)
2678	bzero(ce, sizeof(*ce));
2679
2680    /*
2681     * Copy the results back to the user.
2682     */
2683    bcopy(ce, &ioc->error_info, sizeof(*ce));
2684    mtx_unlock(&sc->ciss_mtx);
2685    if ((ioc->buf_size > 0) &&
2686	(error = copyout(cr->cr_data, ioc->buf, ioc->buf_size))) {
2687	debug(0, "copyout: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2688	goto out_unlocked;
2689    }
2690
2691    /* done OK */
2692    error = 0;
2693
2694out_unlocked:
2695    mtx_lock(&sc->ciss_mtx);
2696
2697out:
2698    if ((cr != NULL) && (cr->cr_data != NULL))
2699	free(cr->cr_data, CISS_MALLOC_CLASS);
2700    if (cr != NULL)
2701	ciss_release_request(cr);
2702    return(error);
2703}
2704
2705/************************************************************************
2706 * Map a request into bus-visible space, initialise the scatter/gather
2707 * list.
2708 */
2709static int
2710ciss_map_request(struct ciss_request *cr)
2711{
2712    struct ciss_softc	*sc;
2713    int			error = 0;
2714
2715    debug_called(2);
2716
2717    sc = cr->cr_sc;
2718
2719    /* check that mapping is necessary */
2720    if (cr->cr_flags & CISS_REQ_MAPPED)
2721	return(0);
2722
2723    cr->cr_flags |= CISS_REQ_MAPPED;
2724
2725    bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2726		    BUS_DMASYNC_PREWRITE);
2727
2728    if (cr->cr_data != NULL) {
2729	if (cr->cr_flags & CISS_REQ_CCB)
2730		error = bus_dmamap_load_ccb(sc->ciss_buffer_dmat,
2731					cr->cr_datamap, cr->cr_data,
2732					ciss_request_map_helper, cr, 0);
2733	else
2734		error = bus_dmamap_load(sc->ciss_buffer_dmat, cr->cr_datamap,
2735					cr->cr_data, cr->cr_length,
2736					ciss_request_map_helper, cr, 0);
2737	if (error != 0)
2738	    return (error);
2739    } else {
2740	/*
2741	 * Post the command to the adapter.
2742	 */
2743	cr->cr_sg_tag = CISS_SG_NONE;
2744	cr->cr_flags |= CISS_REQ_BUSY;
2745	if (sc->ciss_perf)
2746	    CISS_TL_PERF_POST_CMD(sc, cr);
2747	else
2748	    CISS_TL_SIMPLE_POST_CMD(sc, cr->cr_ccphys);
2749    }
2750
2751    return(0);
2752}
2753
2754static void
2755ciss_request_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2756{
2757    struct ciss_command	*cc;
2758    struct ciss_request *cr;
2759    struct ciss_softc	*sc;
2760    int			i;
2761
2762    debug_called(2);
2763
2764    cr = (struct ciss_request *)arg;
2765    sc = cr->cr_sc;
2766    cc = cr->cr_cc;
2767
2768    for (i = 0; i < nseg; i++) {
2769	cc->sg[i].address = segs[i].ds_addr;
2770	cc->sg[i].length = segs[i].ds_len;
2771	cc->sg[i].extension = 0;
2772    }
2773    /* we leave the s/g table entirely within the command */
2774    cc->header.sg_in_list = nseg;
2775    cc->header.sg_total = nseg;
2776
2777    if (cr->cr_flags & CISS_REQ_DATAIN)
2778	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREREAD);
2779    if (cr->cr_flags & CISS_REQ_DATAOUT)
2780	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREWRITE);
2781
2782    if (nseg == 0)
2783	cr->cr_sg_tag = CISS_SG_NONE;
2784    else if (nseg == 1)
2785	cr->cr_sg_tag = CISS_SG_1;
2786    else if (nseg == 2)
2787	cr->cr_sg_tag = CISS_SG_2;
2788    else if (nseg <= 4)
2789	cr->cr_sg_tag = CISS_SG_4;
2790    else if (nseg <= 8)
2791	cr->cr_sg_tag = CISS_SG_8;
2792    else if (nseg <= 16)
2793	cr->cr_sg_tag = CISS_SG_16;
2794    else if (nseg <= 32)
2795	cr->cr_sg_tag = CISS_SG_32;
2796    else
2797	cr->cr_sg_tag = CISS_SG_MAX;
2798
2799    /*
2800     * Post the command to the adapter.
2801     */
2802    cr->cr_flags |= CISS_REQ_BUSY;
2803    if (sc->ciss_perf)
2804	CISS_TL_PERF_POST_CMD(sc, cr);
2805    else
2806	CISS_TL_SIMPLE_POST_CMD(sc, cr->cr_ccphys);
2807}
2808
2809/************************************************************************
2810 * Unmap a request from bus-visible space.
2811 */
2812static void
2813ciss_unmap_request(struct ciss_request *cr)
2814{
2815    struct ciss_softc	*sc;
2816
2817    debug_called(2);
2818
2819    sc = cr->cr_sc;
2820
2821    /* check that unmapping is necessary */
2822    if ((cr->cr_flags & CISS_REQ_MAPPED) == 0)
2823	return;
2824
2825    bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2826		    BUS_DMASYNC_POSTWRITE);
2827
2828    if (cr->cr_data == NULL)
2829	goto out;
2830
2831    if (cr->cr_flags & CISS_REQ_DATAIN)
2832	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTREAD);
2833    if (cr->cr_flags & CISS_REQ_DATAOUT)
2834	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTWRITE);
2835
2836    bus_dmamap_unload(sc->ciss_buffer_dmat, cr->cr_datamap);
2837out:
2838    cr->cr_flags &= ~CISS_REQ_MAPPED;
2839}
2840
2841/************************************************************************
2842 * Attach the driver to CAM.
2843 *
2844 * We put all the logical drives on a single SCSI bus.
2845 */
2846static int
2847ciss_cam_init(struct ciss_softc *sc)
2848{
2849    int			i, maxbus;
2850
2851    debug_called(1);
2852
2853    /*
2854     * Allocate a devq.  We can reuse this for the masked physical
2855     * devices if we decide to export these as well.
2856     */
2857    if ((sc->ciss_cam_devq = cam_simq_alloc(sc->ciss_max_requests - 2)) == NULL) {
2858	ciss_printf(sc, "can't allocate CAM SIM queue\n");
2859	return(ENOMEM);
2860    }
2861
2862    /*
2863     * Create a SIM.
2864     *
2865     * This naturally wastes a bit of memory.  The alternative is to allocate
2866     * and register each bus as it is found, and then track them on a linked
2867     * list.  Unfortunately, the driver has a few places where it needs to
2868     * look up the SIM based solely on bus number, and it's unclear whether
2869     * a list traversal would work for these situations.
2870     */
2871    maxbus = max(sc->ciss_max_logical_bus, sc->ciss_max_physical_bus +
2872		 CISS_PHYSICAL_BASE);
2873    sc->ciss_cam_sim = malloc(maxbus * sizeof(struct cam_sim*),
2874			      CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
2875    if (sc->ciss_cam_sim == NULL) {
2876	ciss_printf(sc, "can't allocate memory for controller SIM\n");
2877	return(ENOMEM);
2878    }
2879
2880    for (i = 0; i < sc->ciss_max_logical_bus; i++) {
2881	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2882						 "ciss", sc,
2883						 device_get_unit(sc->ciss_dev),
2884						 &sc->ciss_mtx,
2885						 2,
2886						 sc->ciss_max_requests - 2,
2887						 sc->ciss_cam_devq)) == NULL) {
2888	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2889	    return(ENOMEM);
2890	}
2891
2892	/*
2893	 * Register bus with this SIM.
2894	 */
2895	mtx_lock(&sc->ciss_mtx);
2896	if (i == 0 || sc->ciss_controllers[i].physical.bus != 0) {
2897	    if (xpt_bus_register(sc->ciss_cam_sim[i], sc->ciss_dev, i) != 0) {
2898		ciss_printf(sc, "can't register SCSI bus %d\n", i);
2899		mtx_unlock(&sc->ciss_mtx);
2900		return (ENXIO);
2901	    }
2902	}
2903	mtx_unlock(&sc->ciss_mtx);
2904    }
2905
2906    for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2907	 CISS_PHYSICAL_BASE; i++) {
2908	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2909						 "ciss", sc,
2910						 device_get_unit(sc->ciss_dev),
2911						 &sc->ciss_mtx, 1,
2912						 sc->ciss_max_requests - 2,
2913						 sc->ciss_cam_devq)) == NULL) {
2914	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2915	    return (ENOMEM);
2916	}
2917
2918	mtx_lock(&sc->ciss_mtx);
2919	if (xpt_bus_register(sc->ciss_cam_sim[i], sc->ciss_dev, i) != 0) {
2920	    ciss_printf(sc, "can't register SCSI bus %d\n", i);
2921	    mtx_unlock(&sc->ciss_mtx);
2922	    return (ENXIO);
2923	}
2924	mtx_unlock(&sc->ciss_mtx);
2925    }
2926
2927    return(0);
2928}
2929
2930/************************************************************************
2931 * Initiate a rescan of the 'logical devices' SIM
2932 */
2933static void
2934ciss_cam_rescan_target(struct ciss_softc *sc, int bus, int target)
2935{
2936    union ccb		*ccb;
2937
2938    debug_called(1);
2939
2940    if ((ccb = xpt_alloc_ccb_nowait()) == NULL) {
2941	ciss_printf(sc, "rescan failed (can't allocate CCB)\n");
2942	return;
2943    }
2944
2945    if (xpt_create_path(&ccb->ccb_h.path, NULL,
2946	    cam_sim_path(sc->ciss_cam_sim[bus]),
2947	    target, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2948	ciss_printf(sc, "rescan failed (can't create path)\n");
2949	xpt_free_ccb(ccb);
2950	return;
2951    }
2952    xpt_rescan(ccb);
2953    /* scan is now in progress */
2954}
2955
2956/************************************************************************
2957 * Handle requests coming from CAM
2958 */
2959static void
2960ciss_cam_action(struct cam_sim *sim, union ccb *ccb)
2961{
2962    struct ciss_softc	*sc;
2963    struct ccb_scsiio	*csio;
2964    int			bus, target;
2965    int			physical;
2966
2967    sc = cam_sim_softc(sim);
2968    bus = cam_sim_bus(sim);
2969    csio = (struct ccb_scsiio *)&ccb->csio;
2970    target = csio->ccb_h.target_id;
2971    physical = CISS_IS_PHYSICAL(bus);
2972
2973    switch (ccb->ccb_h.func_code) {
2974
2975	/* perform SCSI I/O */
2976    case XPT_SCSI_IO:
2977	if (!ciss_cam_action_io(sim, csio))
2978	    return;
2979	break;
2980
2981	/* perform geometry calculations */
2982    case XPT_CALC_GEOMETRY:
2983    {
2984	struct ccb_calc_geometry	*ccg = &ccb->ccg;
2985	struct ciss_ldrive		*ld;
2986
2987	debug(1, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2988
2989	ld = NULL;
2990	if (!physical)
2991	    ld = &sc->ciss_logical[bus][target];
2992
2993	/*
2994	 * Use the cached geometry settings unless the fault tolerance
2995	 * is invalid.
2996	 */
2997	if (physical || ld->cl_geometry.fault_tolerance == 0xFF) {
2998	    u_int32_t			secs_per_cylinder;
2999
3000	    ccg->heads = 255;
3001	    ccg->secs_per_track = 32;
3002	    secs_per_cylinder = ccg->heads * ccg->secs_per_track;
3003	    ccg->cylinders = ccg->volume_size / secs_per_cylinder;
3004	} else {
3005	    ccg->heads = ld->cl_geometry.heads;
3006	    ccg->secs_per_track = ld->cl_geometry.sectors;
3007	    ccg->cylinders = ntohs(ld->cl_geometry.cylinders);
3008	}
3009	ccb->ccb_h.status = CAM_REQ_CMP;
3010        break;
3011    }
3012
3013	/* handle path attribute inquiry */
3014    case XPT_PATH_INQ:
3015    {
3016	struct ccb_pathinq	*cpi = &ccb->cpi;
3017	int			sg_length;
3018
3019	debug(1, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
3020
3021	cpi->version_num = 1;
3022	cpi->hba_inquiry = PI_TAG_ABLE;	/* XXX is this correct? */
3023	cpi->target_sprt = 0;
3024	cpi->hba_misc = 0;
3025	cpi->max_target = sc->ciss_cfg->max_logical_supported;
3026	cpi->max_lun = 0;		/* 'logical drive' channel only */
3027	cpi->initiator_id = sc->ciss_cfg->max_logical_supported;
3028	strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
3029        strncpy(cpi->hba_vid, "msmith@freebsd.org", HBA_IDLEN);
3030        strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
3031        cpi->unit_number = cam_sim_unit(sim);
3032        cpi->bus_id = cam_sim_bus(sim);
3033	cpi->base_transfer_speed = 132 * 1024;	/* XXX what to set this to? */
3034	cpi->transport = XPORT_SPI;
3035	cpi->transport_version = 2;
3036	cpi->protocol = PROTO_SCSI;
3037	cpi->protocol_version = SCSI_REV_2;
3038	if (sc->ciss_cfg->max_sg_length == 0) {
3039		sg_length = 17;
3040	} else {
3041	/* XXX Fix for ZMR cards that advertise max_sg_length == 32
3042	 * Confusing bit here. max_sg_length is usually a power of 2. We always
3043	 * need to subtract 1 to account for partial pages. Then we need to
3044	 * align on a valid PAGE_SIZE so we round down to the nearest power of 2.
3045	 * Add 1 so we can then subtract it out in the assignment to maxio.
3046	 * The reason for all these shenanigans is to create a maxio value that
3047	 * creates IO operations to volumes that yield consistent operations
3048	 * with good performance.
3049	 */
3050		sg_length = sc->ciss_cfg->max_sg_length - 1;
3051		sg_length = (1 << (fls(sg_length) - 1)) + 1;
3052	}
3053	cpi->maxio = (min(CISS_MAX_SG_ELEMENTS, sg_length) - 1) * PAGE_SIZE;
3054	ccb->ccb_h.status = CAM_REQ_CMP;
3055	break;
3056    }
3057
3058    case XPT_GET_TRAN_SETTINGS:
3059    {
3060	struct ccb_trans_settings	*cts = &ccb->cts;
3061	int				bus, target;
3062	struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
3063	struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
3064
3065	bus = cam_sim_bus(sim);
3066	target = cts->ccb_h.target_id;
3067
3068	debug(1, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
3069	/* disconnect always OK */
3070	cts->protocol = PROTO_SCSI;
3071	cts->protocol_version = SCSI_REV_2;
3072	cts->transport = XPORT_SPI;
3073	cts->transport_version = 2;
3074
3075	spi->valid = CTS_SPI_VALID_DISC;
3076	spi->flags = CTS_SPI_FLAGS_DISC_ENB;
3077
3078	scsi->valid = CTS_SCSI_VALID_TQ;
3079	scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
3080
3081	cts->ccb_h.status = CAM_REQ_CMP;
3082	break;
3083    }
3084
3085    default:		/* we can't do this */
3086	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
3087	ccb->ccb_h.status = CAM_REQ_INVALID;
3088	break;
3089    }
3090
3091    xpt_done(ccb);
3092}
3093
3094/************************************************************************
3095 * Handle a CAM SCSI I/O request.
3096 */
3097static int
3098ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
3099{
3100    struct ciss_softc	*sc;
3101    int			bus, target;
3102    struct ciss_request	*cr;
3103    struct ciss_command	*cc;
3104    int			error;
3105
3106    sc = cam_sim_softc(sim);
3107    bus = cam_sim_bus(sim);
3108    target = csio->ccb_h.target_id;
3109
3110    debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
3111
3112    /* check that the CDB pointer is not to a physical address */
3113    if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
3114	debug(3, "  CDB pointer is to physical address");
3115	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3116    }
3117
3118    /* abandon aborted ccbs or those that have failed validation */
3119    if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
3120	debug(3, "abandoning CCB due to abort/validation failure");
3121	return(EINVAL);
3122    }
3123
3124    /* handle emulation of some SCSI commands ourself */
3125    if (ciss_cam_emulate(sc, csio))
3126	return(0);
3127
3128    /*
3129     * Get a request to manage this command.  If we can't, return the
3130     * ccb, freeze the queue and flag so that we unfreeze it when a
3131     * request completes.
3132     */
3133    if ((error = ciss_get_request(sc, &cr)) != 0) {
3134	xpt_freeze_simq(sim, 1);
3135	sc->ciss_flags |= CISS_FLAG_BUSY;
3136	csio->ccb_h.status |= CAM_REQUEUE_REQ;
3137	return(error);
3138    }
3139
3140    /*
3141     * Build the command.
3142     */
3143    cc = cr->cr_cc;
3144    cr->cr_data = csio;
3145    cr->cr_length = csio->dxfer_len;
3146    cr->cr_complete = ciss_cam_complete;
3147    cr->cr_private = csio;
3148
3149    /*
3150     * Target the right logical volume.
3151     */
3152    if (CISS_IS_PHYSICAL(bus))
3153	cc->header.address =
3154	    sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_address;
3155    else
3156	cc->header.address =
3157	    sc->ciss_logical[bus][target].cl_address;
3158    cc->cdb.cdb_length = csio->cdb_len;
3159    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3160    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
3161    if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
3162	cr->cr_flags = CISS_REQ_DATAOUT | CISS_REQ_CCB;
3163	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3164    } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
3165	cr->cr_flags = CISS_REQ_DATAIN | CISS_REQ_CCB;
3166	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3167    } else {
3168	cr->cr_data = NULL;
3169	cr->cr_flags = 0;
3170	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
3171    }
3172    cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
3173    if (csio->ccb_h.flags & CAM_CDB_POINTER) {
3174	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
3175    } else {
3176	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
3177    }
3178
3179    /*
3180     * Submit the request to the adapter.
3181     *
3182     * Note that this may fail if we're unable to map the request (and
3183     * if we ever learn a transport layer other than simple, may fail
3184     * if the adapter rejects the command).
3185     */
3186    if ((error = ciss_start(cr)) != 0) {
3187	xpt_freeze_simq(sim, 1);
3188	csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3189	if (error == EINPROGRESS) {
3190	    error = 0;
3191	} else {
3192	    csio->ccb_h.status |= CAM_REQUEUE_REQ;
3193	    ciss_release_request(cr);
3194	}
3195	return(error);
3196    }
3197
3198    return(0);
3199}
3200
3201/************************************************************************
3202 * Emulate SCSI commands the adapter doesn't handle as we might like.
3203 */
3204static int
3205ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
3206{
3207    int		bus, target;
3208    u_int8_t	opcode;
3209
3210    target = csio->ccb_h.target_id;
3211    bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3212    opcode = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
3213	*(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0];
3214
3215    if (CISS_IS_PHYSICAL(bus)) {
3216	if (sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_online != 1) {
3217	    csio->ccb_h.status |= CAM_SEL_TIMEOUT;
3218	    xpt_done((union ccb *)csio);
3219	    return(1);
3220	} else
3221	    return(0);
3222    }
3223
3224    /*
3225     * Handle requests for volumes that don't exist or are not online.
3226     * A selection timeout is slightly better than an illegal request.
3227     * Other errors might be better.
3228     */
3229    if (sc->ciss_logical[bus][target].cl_status != CISS_LD_ONLINE) {
3230	csio->ccb_h.status |= CAM_SEL_TIMEOUT;
3231	xpt_done((union ccb *)csio);
3232	return(1);
3233    }
3234
3235    /* if we have to fake Synchronise Cache */
3236    if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
3237	/*
3238	 * If this is a Synchronise Cache command, typically issued when
3239	 * a device is closed, flush the adapter and complete now.
3240	 */
3241	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
3242	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
3243	    ciss_flush_adapter(sc);
3244	    csio->ccb_h.status |= CAM_REQ_CMP;
3245	    xpt_done((union ccb *)csio);
3246	    return(1);
3247	}
3248    }
3249
3250    /*
3251     * A CISS target can only ever have one lun per target. REPORT_LUNS requires
3252     * at least one LUN field to be pre created for us, so snag it and fill in
3253     * the least significant byte indicating 1 LUN here.  Emulate the command
3254     * return to shut up warning on console of a CDB error.  swb
3255     */
3256    if (opcode == REPORT_LUNS && csio->dxfer_len > 0) {
3257       csio->data_ptr[3] = 8;
3258       csio->ccb_h.status |= CAM_REQ_CMP;
3259       xpt_done((union ccb *)csio);
3260       return(1);
3261    }
3262
3263    return(0);
3264}
3265
3266/************************************************************************
3267 * Check for possibly-completed commands.
3268 */
3269static void
3270ciss_cam_poll(struct cam_sim *sim)
3271{
3272    cr_qhead_t qh;
3273    struct ciss_softc	*sc = cam_sim_softc(sim);
3274
3275    debug_called(2);
3276
3277    STAILQ_INIT(&qh);
3278    if (sc->ciss_perf)
3279	ciss_perf_done(sc, &qh);
3280    else
3281	ciss_done(sc, &qh);
3282    ciss_complete(sc, &qh);
3283}
3284
3285/************************************************************************
3286 * Handle completion of a command - pass results back through the CCB
3287 */
3288static void
3289ciss_cam_complete(struct ciss_request *cr)
3290{
3291    struct ciss_softc		*sc;
3292    struct ciss_command		*cc;
3293    struct ciss_error_info	*ce;
3294    struct ccb_scsiio		*csio;
3295    int				scsi_status;
3296    int				command_status;
3297
3298    debug_called(2);
3299
3300    sc = cr->cr_sc;
3301    cc = cr->cr_cc;
3302    ce = (struct ciss_error_info *)&(cc->sg[0]);
3303    csio = (struct ccb_scsiio *)cr->cr_private;
3304
3305    /*
3306     * Extract status values from request.
3307     */
3308    ciss_report_request(cr, &command_status, &scsi_status);
3309    csio->scsi_status = scsi_status;
3310
3311    /*
3312     * Handle specific SCSI status values.
3313     */
3314    switch(scsi_status) {
3315	/* no status due to adapter error */
3316    case -1:
3317	debug(0, "adapter error");
3318	csio->ccb_h.status |= CAM_REQ_CMP_ERR;
3319	break;
3320
3321	/* no status due to command completed OK */
3322    case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
3323	debug(2, "SCSI_STATUS_OK");
3324	csio->ccb_h.status |= CAM_REQ_CMP;
3325	break;
3326
3327	/* check condition, sense data included */
3328    case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
3329	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d\n",
3330	      ce->sense_length, ce->residual_count);
3331	bzero(&csio->sense_data, SSD_FULL_SIZE);
3332	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
3333	if (csio->sense_len > ce->sense_length)
3334		csio->sense_resid = csio->sense_len - ce->sense_length;
3335	else
3336		csio->sense_resid = 0;
3337	csio->resid = ce->residual_count;
3338	csio->ccb_h.status |= CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
3339#ifdef CISS_DEBUG
3340	{
3341	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
3342	    debug(0, "sense key %x", scsi_get_sense_key(sns, csio->sense_len -
3343		  csio->sense_resid, /*show_errors*/ 1));
3344	}
3345#endif
3346	break;
3347
3348    case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
3349	debug(0, "SCSI_STATUS_BUSY");
3350	csio->ccb_h.status |= CAM_SCSI_BUSY;
3351	break;
3352
3353    default:
3354	debug(0, "unknown status 0x%x", csio->scsi_status);
3355	csio->ccb_h.status |= CAM_REQ_CMP_ERR;
3356	break;
3357    }
3358
3359    /* handle post-command fixup */
3360    ciss_cam_complete_fixup(sc, csio);
3361
3362    ciss_release_request(cr);
3363    if (sc->ciss_flags & CISS_FLAG_BUSY) {
3364	sc->ciss_flags &= ~CISS_FLAG_BUSY;
3365	if (csio->ccb_h.status & CAM_RELEASE_SIMQ)
3366	    xpt_release_simq(xpt_path_sim(csio->ccb_h.path), 0);
3367	else
3368	    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3369    }
3370    xpt_done((union ccb *)csio);
3371}
3372
3373/********************************************************************************
3374 * Fix up the result of some commands here.
3375 */
3376static void
3377ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
3378{
3379    struct scsi_inquiry_data	*inq;
3380    struct ciss_ldrive		*cl;
3381    uint8_t			*cdb;
3382    int				bus, target;
3383
3384    cdb = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
3385	 (uint8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes;
3386    if (cdb[0] == INQUIRY &&
3387	(cdb[1] & SI_EVPD) == 0 &&
3388	(csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN &&
3389	csio->dxfer_len >= SHORT_INQUIRY_LENGTH) {
3390
3391	inq = (struct scsi_inquiry_data *)csio->data_ptr;
3392	target = csio->ccb_h.target_id;
3393	bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3394
3395	/*
3396	 * If the controller is in JBOD mode, there are no logical volumes.
3397	 * Let the disks be probed and dealt with via CAM.  Else, mask off
3398	 * the physical disks and setup the parts of the inq structure for
3399	 * the logical volume.  swb
3400	 */
3401	if( !(sc->ciss_id->PowerUPNvramFlags & PWR_UP_FLAG_JBOD_ENABLED)){
3402		if (CISS_IS_PHYSICAL(bus)) {
3403	    		if (SID_TYPE(inq) == T_DIRECT)
3404				inq->device = (inq->device & 0xe0) | T_NODEVICE;
3405	    		return;
3406		}
3407		cl = &sc->ciss_logical[bus][target];
3408
3409		padstr(inq->vendor, "HP",
3410	       		SID_VENDOR_SIZE);
3411		padstr(inq->product,
3412	       		ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance),
3413	       		SID_PRODUCT_SIZE);
3414		padstr(inq->revision,
3415	       		ciss_name_ldrive_status(cl->cl_lstatus->status),
3416	       		SID_REVISION_SIZE);
3417	}
3418    }
3419}
3420
3421
3422/********************************************************************************
3423 * Name the device at (target)
3424 *
3425 * XXX is this strictly correct?
3426 */
3427static int
3428ciss_name_device(struct ciss_softc *sc, int bus, int target)
3429{
3430    struct cam_periph	*periph;
3431    struct cam_path	*path;
3432    int			status;
3433
3434    if (CISS_IS_PHYSICAL(bus))
3435	return (0);
3436
3437    status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim[bus]),
3438			     target, 0);
3439
3440    if (status == CAM_REQ_CMP) {
3441	mtx_lock(&sc->ciss_mtx);
3442	xpt_path_lock(path);
3443	periph = cam_periph_find(path, NULL);
3444	xpt_path_unlock(path);
3445	mtx_unlock(&sc->ciss_mtx);
3446	xpt_free_path(path);
3447	if (periph != NULL) {
3448		sprintf(sc->ciss_logical[bus][target].cl_name, "%s%d",
3449			periph->periph_name, periph->unit_number);
3450		return(0);
3451	}
3452    }
3453    sc->ciss_logical[bus][target].cl_name[0] = 0;
3454    return(ENOENT);
3455}
3456
3457/************************************************************************
3458 * Periodic status monitoring.
3459 */
3460static void
3461ciss_periodic(void *arg)
3462{
3463    struct ciss_softc	*sc;
3464    struct ciss_request	*cr = NULL;
3465    struct ciss_command	*cc = NULL;
3466    int			error = 0;
3467
3468    debug_called(1);
3469
3470    sc = (struct ciss_softc *)arg;
3471
3472    /*
3473     * Check the adapter heartbeat.
3474     */
3475    if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
3476	sc->ciss_heart_attack++;
3477	debug(0, "adapter heart attack in progress 0x%x/%d",
3478	      sc->ciss_heartbeat, sc->ciss_heart_attack);
3479	if (sc->ciss_heart_attack == 3) {
3480	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
3481	    ciss_disable_adapter(sc);
3482	    return;
3483	}
3484    } else {
3485	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
3486	sc->ciss_heart_attack = 0;
3487	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
3488    }
3489
3490    /*
3491     * Send the NOP message and wait for a response.
3492     */
3493    if (ciss_nop_message_heartbeat != 0 && (error = ciss_get_request(sc, &cr)) == 0) {
3494	cc = cr->cr_cc;
3495	cr->cr_complete = ciss_nop_complete;
3496	cc->cdb.cdb_length = 1;
3497	cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
3498	cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3499	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3500	cc->cdb.timeout = 0;
3501	cc->cdb.cdb[0] = CISS_OPCODE_MESSAGE_NOP;
3502
3503	if ((error = ciss_start(cr)) != 0) {
3504	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED\n");
3505	}
3506    }
3507
3508    /*
3509     * If the notify event request has died for some reason, or has
3510     * not started yet, restart it.
3511     */
3512    if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
3513	debug(0, "(re)starting Event Notify chain");
3514	ciss_notify_event(sc);
3515    }
3516
3517    /*
3518     * Reschedule.
3519     */
3520    callout_reset(&sc->ciss_periodic, CISS_HEARTBEAT_RATE * hz, ciss_periodic, sc);
3521}
3522
3523static void
3524ciss_nop_complete(struct ciss_request *cr)
3525{
3526    struct ciss_softc		*sc;
3527    static int			first_time = 1;
3528
3529    sc = cr->cr_sc;
3530    if (ciss_report_request(cr, NULL, NULL) != 0) {
3531	if (first_time == 1) {
3532	    first_time = 0;
3533	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED (not logging anymore)\n");
3534	}
3535    }
3536
3537    ciss_release_request(cr);
3538}
3539
3540/************************************************************************
3541 * Disable the adapter.
3542 *
3543 * The all requests in completed queue is failed with hardware error.
3544 * This will cause failover in a multipath configuration.
3545 */
3546static void
3547ciss_disable_adapter(struct ciss_softc *sc)
3548{
3549    cr_qhead_t			qh;
3550    struct ciss_request		*cr;
3551    struct ciss_command		*cc;
3552    struct ciss_error_info	*ce;
3553    int				i;
3554
3555    CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
3556    pci_disable_busmaster(sc->ciss_dev);
3557    sc->ciss_flags &= ~CISS_FLAG_RUNNING;
3558
3559    for (i = 1; i < sc->ciss_max_requests; i++) {
3560	cr = &sc->ciss_request[i];
3561	if ((cr->cr_flags & CISS_REQ_BUSY) == 0)
3562	    continue;
3563
3564	cc = cr->cr_cc;
3565	ce = (struct ciss_error_info *)&(cc->sg[0]);
3566	ce->command_status = CISS_CMD_STATUS_HARDWARE_ERROR;
3567	ciss_enqueue_complete(cr, &qh);
3568    }
3569
3570    for (;;) {
3571	if ((cr = ciss_dequeue_complete(sc, &qh)) == NULL)
3572	    break;
3573
3574	/*
3575	 * If the request has a callback, invoke it.
3576	 */
3577	if (cr->cr_complete != NULL) {
3578	    cr->cr_complete(cr);
3579	    continue;
3580	}
3581
3582	/*
3583	 * If someone is sleeping on this request, wake them up.
3584	 */
3585	if (cr->cr_flags & CISS_REQ_SLEEP) {
3586	    cr->cr_flags &= ~CISS_REQ_SLEEP;
3587	    wakeup(cr);
3588	    continue;
3589	}
3590    }
3591}
3592
3593/************************************************************************
3594 * Request a notification response from the adapter.
3595 *
3596 * If (cr) is NULL, this is the first request of the adapter, so
3597 * reset the adapter's message pointer and start with the oldest
3598 * message available.
3599 */
3600static void
3601ciss_notify_event(struct ciss_softc *sc)
3602{
3603    struct ciss_request		*cr;
3604    struct ciss_command		*cc;
3605    struct ciss_notify_cdb	*cnc;
3606    int				error;
3607
3608    debug_called(1);
3609
3610    cr = sc->ciss_periodic_notify;
3611
3612    /* get a request if we don't already have one */
3613    if (cr == NULL) {
3614	if ((error = ciss_get_request(sc, &cr)) != 0) {
3615	    debug(0, "can't get notify event request");
3616	    goto out;
3617	}
3618	sc->ciss_periodic_notify = cr;
3619	cr->cr_complete = ciss_notify_complete;
3620	debug(1, "acquired request %d", cr->cr_tag);
3621    }
3622
3623    /*
3624     * Get a databuffer if we don't already have one, note that the
3625     * adapter command wants a larger buffer than the actual
3626     * structure.
3627     */
3628    if (cr->cr_data == NULL) {
3629	if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3630	    debug(0, "can't get notify event request buffer");
3631	    error = ENOMEM;
3632	    goto out;
3633	}
3634	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3635    }
3636
3637    /* re-setup the request's command (since we never release it) XXX overkill*/
3638    ciss_preen_command(cr);
3639
3640    /* (re)build the notify event command */
3641    cc = cr->cr_cc;
3642    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3643    cc->header.address.physical.bus = 0;
3644    cc->header.address.physical.target = 0;
3645
3646    cc->cdb.cdb_length = sizeof(*cnc);
3647    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3648    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3649    cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3650    cc->cdb.timeout = 0;	/* no timeout, we hope */
3651
3652    cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3653    bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
3654    cnc->opcode = CISS_OPCODE_READ;
3655    cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
3656    cnc->timeout = 0;		/* no timeout, we hope */
3657    cnc->synchronous = 0;
3658    cnc->ordered = 0;
3659    cnc->seek_to_oldest = 0;
3660    if ((sc->ciss_flags & CISS_FLAG_RUNNING) == 0)
3661	cnc->new_only = 1;
3662    else
3663	cnc->new_only = 0;
3664    cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3665
3666    /* submit the request */
3667    error = ciss_start(cr);
3668
3669 out:
3670    if (error) {
3671	if (cr != NULL) {
3672	    if (cr->cr_data != NULL)
3673		free(cr->cr_data, CISS_MALLOC_CLASS);
3674	    ciss_release_request(cr);
3675	}
3676	sc->ciss_periodic_notify = NULL;
3677	debug(0, "can't submit notify event request");
3678	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3679    } else {
3680	debug(1, "notify event submitted");
3681	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
3682    }
3683}
3684
3685static void
3686ciss_notify_complete(struct ciss_request *cr)
3687{
3688    struct ciss_command	*cc;
3689    struct ciss_notify	*cn;
3690    struct ciss_softc	*sc;
3691    int			scsi_status;
3692    int			command_status;
3693    debug_called(1);
3694
3695    cc = cr->cr_cc;
3696    cn = (struct ciss_notify *)cr->cr_data;
3697    sc = cr->cr_sc;
3698
3699    /*
3700     * Report request results, decode status.
3701     */
3702    ciss_report_request(cr, &command_status, &scsi_status);
3703
3704    /*
3705     * Abort the chain on a fatal error.
3706     *
3707     * XXX which of these are actually errors?
3708     */
3709    if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
3710	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
3711	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
3712	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
3713		    ciss_name_command_status(command_status));
3714	ciss_release_request(cr);
3715	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3716	return;
3717    }
3718
3719    /*
3720     * If the adapter gave us a text message, print it.
3721     */
3722    if (cn->message[0] != 0)
3723	ciss_printf(sc, "*** %.80s\n", cn->message);
3724
3725    debug(0, "notify event class %d subclass %d detail %d",
3726		cn->class, cn->subclass, cn->detail);
3727
3728    /*
3729     * If the response indicates that the notifier has been aborted,
3730     * release the notifier command.
3731     */
3732    if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
3733	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
3734	(cn->detail == 1)) {
3735	debug(0, "notifier exiting");
3736	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3737	ciss_release_request(cr);
3738	sc->ciss_periodic_notify = NULL;
3739	wakeup(&sc->ciss_periodic_notify);
3740    } else {
3741	/* Handle notify events in a kernel thread */
3742	ciss_enqueue_notify(cr);
3743	sc->ciss_periodic_notify = NULL;
3744	wakeup(&sc->ciss_periodic_notify);
3745	wakeup(&sc->ciss_notify);
3746    }
3747    /*
3748     * Send a new notify event command, if we're not aborting.
3749     */
3750    if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
3751	ciss_notify_event(sc);
3752    }
3753}
3754
3755/************************************************************************
3756 * Abort the Notify Event chain.
3757 *
3758 * Note that we can't just abort the command in progress; we have to
3759 * explicitly issue an Abort Notify Event command in order for the
3760 * adapter to clean up correctly.
3761 *
3762 * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
3763 * the chain will not restart itself.
3764 */
3765static int
3766ciss_notify_abort(struct ciss_softc *sc)
3767{
3768    struct ciss_request		*cr;
3769    struct ciss_command		*cc;
3770    struct ciss_notify_cdb	*cnc;
3771    int				error, command_status, scsi_status;
3772
3773    debug_called(1);
3774
3775    cr = NULL;
3776    error = 0;
3777
3778    /* verify that there's an outstanding command */
3779    if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3780	goto out;
3781
3782    /* get a command to issue the abort with */
3783    if ((error = ciss_get_request(sc, &cr)))
3784	goto out;
3785
3786    /* get a buffer for the result */
3787    if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3788	debug(0, "can't get notify event request buffer");
3789	error = ENOMEM;
3790	goto out;
3791    }
3792    cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3793
3794    /* build the CDB */
3795    cc = cr->cr_cc;
3796    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3797    cc->header.address.physical.bus = 0;
3798    cc->header.address.physical.target = 0;
3799    cc->cdb.cdb_length = sizeof(*cnc);
3800    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3801    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3802    cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3803    cc->cdb.timeout = 0;	/* no timeout, we hope */
3804
3805    cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3806    bzero(cnc, sizeof(*cnc));
3807    cnc->opcode = CISS_OPCODE_WRITE;
3808    cnc->command = CISS_COMMAND_ABORT_NOTIFY;
3809    cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3810
3811    ciss_print_request(cr);
3812
3813    /*
3814     * Submit the request and wait for it to complete.
3815     */
3816    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3817	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
3818	goto out;
3819    }
3820
3821    /*
3822     * Check response.
3823     */
3824    ciss_report_request(cr, &command_status, &scsi_status);
3825    switch(command_status) {
3826    case CISS_CMD_STATUS_SUCCESS:
3827	break;
3828    case CISS_CMD_STATUS_INVALID_COMMAND:
3829	/*
3830	 * Some older adapters don't support the CISS version of this
3831	 * command.  Fall back to using the BMIC version.
3832	 */
3833	error = ciss_notify_abort_bmic(sc);
3834	if (error != 0)
3835	    goto out;
3836	break;
3837
3838    case CISS_CMD_STATUS_TARGET_STATUS:
3839	/*
3840	 * This can happen if the adapter thinks there wasn't an outstanding
3841	 * Notify Event command but we did.  We clean up here.
3842	 */
3843	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
3844	    if (sc->ciss_periodic_notify != NULL)
3845		ciss_release_request(sc->ciss_periodic_notify);
3846	    error = 0;
3847	    goto out;
3848	}
3849	/* FALLTHROUGH */
3850
3851    default:
3852	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
3853		    ciss_name_command_status(command_status));
3854	error = EIO;
3855	goto out;
3856    }
3857
3858    /*
3859     * Sleep waiting for the notifier command to complete.  Note
3860     * that if it doesn't, we may end up in a bad situation, since
3861     * the adapter may deliver it later.  Also note that the adapter
3862     * requires the Notify Event command to be cancelled in order to
3863     * maintain internal bookkeeping.
3864     */
3865    while (sc->ciss_periodic_notify != NULL) {
3866	error = msleep(&sc->ciss_periodic_notify, &sc->ciss_mtx, PRIBIO, "cissNEA", hz * 5);
3867	if (error == EWOULDBLOCK) {
3868	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
3869	    break;
3870	}
3871    }
3872
3873 out:
3874    /* release the cancel request */
3875    if (cr != NULL) {
3876	if (cr->cr_data != NULL)
3877	    free(cr->cr_data, CISS_MALLOC_CLASS);
3878	ciss_release_request(cr);
3879    }
3880    if (error == 0)
3881	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3882    return(error);
3883}
3884
3885/************************************************************************
3886 * Abort the Notify Event chain using a BMIC command.
3887 */
3888static int
3889ciss_notify_abort_bmic(struct ciss_softc *sc)
3890{
3891    struct ciss_request			*cr;
3892    int					error, command_status;
3893
3894    debug_called(1);
3895
3896    cr = NULL;
3897    error = 0;
3898
3899    /* verify that there's an outstanding command */
3900    if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3901	goto out;
3902
3903    /*
3904     * Build a BMIC command to cancel the Notify on Event command.
3905     *
3906     * Note that we are sending a CISS opcode here.  Odd.
3907     */
3908    if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
3909				       NULL, 0)) != 0)
3910	goto out;
3911
3912    /*
3913     * Submit the request and wait for it to complete.
3914     */
3915    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3916	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
3917	goto out;
3918    }
3919
3920    /*
3921     * Check response.
3922     */
3923    ciss_report_request(cr, &command_status, NULL);
3924    switch(command_status) {
3925    case CISS_CMD_STATUS_SUCCESS:
3926	break;
3927    default:
3928	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
3929		    ciss_name_command_status(command_status));
3930	error = EIO;
3931	goto out;
3932    }
3933
3934out:
3935    if (cr != NULL)
3936	ciss_release_request(cr);
3937    return(error);
3938}
3939
3940/************************************************************************
3941 * Handle rescanning all the logical volumes when a notify event
3942 * causes the drives to come online or offline.
3943 */
3944static void
3945ciss_notify_rescan_logical(struct ciss_softc *sc)
3946{
3947    struct ciss_lun_report      *cll;
3948    struct ciss_ldrive		*ld;
3949    int                         i, j, ndrives;
3950
3951    /*
3952     * We must rescan all logical volumes to get the right logical
3953     * drive address.
3954     */
3955    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
3956                           sc->ciss_cfg->max_logical_supported);
3957    if (cll == NULL)
3958        return;
3959
3960    ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
3961
3962    /*
3963     * Delete any of the drives which were destroyed by the
3964     * firmware.
3965     */
3966    for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3967	for (j = 0; j < sc->ciss_cfg->max_logical_supported; j++) {
3968	    ld = &sc->ciss_logical[i][j];
3969
3970	    if (ld->cl_update == 0)
3971		continue;
3972
3973	    if (ld->cl_status != CISS_LD_ONLINE) {
3974		ciss_cam_rescan_target(sc, i, j);
3975		ld->cl_update = 0;
3976		if (ld->cl_ldrive)
3977		    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
3978		if (ld->cl_lstatus)
3979		    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
3980
3981		ld->cl_ldrive = NULL;
3982		ld->cl_lstatus = NULL;
3983	    }
3984	}
3985    }
3986
3987    /*
3988     * Scan for new drives.
3989     */
3990    for (i = 0; i < ndrives; i++) {
3991	int	bus, target;
3992
3993	bus 	= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
3994	target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
3995	ld	= &sc->ciss_logical[bus][target];
3996
3997	if (ld->cl_update == 0)
3998		continue;
3999
4000	ld->cl_update		= 0;
4001	ld->cl_address		= cll->lun[i];
4002	ld->cl_controller	= &sc->ciss_controllers[bus];
4003	if (ciss_identify_logical(sc, ld) == 0) {
4004	    ciss_cam_rescan_target(sc, bus, target);
4005	}
4006    }
4007    free(cll, CISS_MALLOC_CLASS);
4008}
4009
4010/************************************************************************
4011 * Handle a notify event relating to the status of a logical drive.
4012 *
4013 * XXX need to be able to defer some of these to properly handle
4014 *     calling the "ID Physical drive" command, unless the 'extended'
4015 *     drive IDs are always in BIG_MAP format.
4016 */
4017static void
4018ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
4019{
4020    struct ciss_ldrive	*ld;
4021    int			bus, target;
4022    int			rescan_ld;
4023
4024    debug_called(2);
4025
4026    bus		= cn->device.physical.bus;
4027    target	= cn->data.logical_status.logical_drive;
4028    ld		= &sc->ciss_logical[bus][target];
4029
4030    switch (cn->subclass) {
4031    case CISS_NOTIFY_LOGICAL_STATUS:
4032	switch (cn->detail) {
4033	case 0:
4034	    ciss_name_device(sc, bus, target);
4035	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%b\n",
4036			cn->data.logical_status.logical_drive, ld->cl_name,
4037			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
4038			ciss_name_ldrive_status(cn->data.logical_status.new_state),
4039			cn->data.logical_status.spare_state,
4040			"\20\1configured\2rebuilding\3failed\4in use\5available\n");
4041
4042	    /*
4043	     * Update our idea of the drive's status.
4044	     */
4045	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
4046	    if (ld->cl_lstatus != NULL)
4047		ld->cl_lstatus->status = cn->data.logical_status.new_state;
4048
4049	    /*
4050	     * Have CAM rescan the drive if its status has changed.
4051	     */
4052            rescan_ld = (cn->data.logical_status.previous_state !=
4053                         cn->data.logical_status.new_state) ? 1 : 0;
4054	    if (rescan_ld) {
4055		ld->cl_update = 1;
4056		ciss_notify_rescan_logical(sc);
4057	    }
4058
4059	    break;
4060
4061	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
4062	    ciss_name_device(sc, bus, target);
4063	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
4064			cn->data.logical_status.logical_drive, ld->cl_name);
4065	    ciss_accept_media(sc, ld);
4066
4067	    ld->cl_update = 1;
4068	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
4069	    ciss_notify_rescan_logical(sc);
4070	    break;
4071
4072	case 2:
4073	case 3:
4074	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
4075			cn->data.rebuild_aborted.logical_drive,
4076			ld->cl_name,
4077			(cn->detail == 2) ? "read" : "write");
4078	    break;
4079	}
4080	break;
4081
4082    case CISS_NOTIFY_LOGICAL_ERROR:
4083	if (cn->detail == 0) {
4084	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
4085			cn->data.io_error.logical_drive,
4086			ld->cl_name,
4087			cn->data.io_error.failure_bus,
4088			cn->data.io_error.failure_drive);
4089	    /* XXX should we take the drive down at this point, or will we be told? */
4090	}
4091	break;
4092
4093    case CISS_NOTIFY_LOGICAL_SURFACE:
4094	if (cn->detail == 0)
4095	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
4096			cn->data.consistency_completed.logical_drive,
4097			ld->cl_name);
4098	break;
4099    }
4100}
4101
4102/************************************************************************
4103 * Handle a notify event relating to the status of a physical drive.
4104 */
4105static void
4106ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
4107{
4108}
4109
4110/************************************************************************
4111 * Handle a notify event relating to the status of a physical drive.
4112 */
4113static void
4114ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn)
4115{
4116    struct ciss_lun_report *cll = NULL;
4117    int bus, target;
4118
4119    switch (cn->subclass) {
4120    case CISS_NOTIFY_HOTPLUG_PHYSICAL:
4121    case CISS_NOTIFY_HOTPLUG_NONDISK:
4122	bus = CISS_BIG_MAP_BUS(sc, cn->data.drive.big_physical_drive_number);
4123	target =
4124	    CISS_BIG_MAP_TARGET(sc, cn->data.drive.big_physical_drive_number);
4125
4126	if (cn->detail == 0) {
4127	    /*
4128	     * Mark the device offline so that it'll start producing selection
4129	     * timeouts to the upper layer.
4130	     */
4131	    if ((bus >= 0) && (target >= 0))
4132		sc->ciss_physical[bus][target].cp_online = 0;
4133	} else {
4134	    /*
4135	     * Rescan the physical lun list for new items
4136	     */
4137	    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
4138				   sc->ciss_cfg->max_physical_supported);
4139	    if (cll == NULL) {
4140		ciss_printf(sc, "Warning, cannot get physical lun list\n");
4141		break;
4142	    }
4143	    ciss_filter_physical(sc, cll);
4144	}
4145	break;
4146
4147    default:
4148	ciss_printf(sc, "Unknown hotplug event %d\n", cn->subclass);
4149	return;
4150    }
4151
4152    if (cll != NULL)
4153	free(cll, CISS_MALLOC_CLASS);
4154}
4155
4156/************************************************************************
4157 * Handle deferred processing of notify events.  Notify events may need
4158 * sleep which is unsafe during an interrupt.
4159 */
4160static void
4161ciss_notify_thread(void *arg)
4162{
4163    struct ciss_softc		*sc;
4164    struct ciss_request		*cr;
4165    struct ciss_notify		*cn;
4166
4167    sc = (struct ciss_softc *)arg;
4168#if __FreeBSD_version >= 500000
4169    mtx_lock(&sc->ciss_mtx);
4170#endif
4171
4172    for (;;) {
4173	if (STAILQ_EMPTY(&sc->ciss_notify) != 0 &&
4174	    (sc->ciss_flags & CISS_FLAG_THREAD_SHUT) == 0) {
4175	    msleep(&sc->ciss_notify, &sc->ciss_mtx, PUSER, "idle", 0);
4176	}
4177
4178	if (sc->ciss_flags & CISS_FLAG_THREAD_SHUT)
4179	    break;
4180
4181	cr = ciss_dequeue_notify(sc);
4182
4183	if (cr == NULL)
4184		panic("cr null");
4185	cn = (struct ciss_notify *)cr->cr_data;
4186
4187	switch (cn->class) {
4188	case CISS_NOTIFY_HOTPLUG:
4189	    ciss_notify_hotplug(sc, cn);
4190	    break;
4191	case CISS_NOTIFY_LOGICAL:
4192	    ciss_notify_logical(sc, cn);
4193	    break;
4194	case CISS_NOTIFY_PHYSICAL:
4195	    ciss_notify_physical(sc, cn);
4196	    break;
4197	}
4198
4199	ciss_release_request(cr);
4200
4201    }
4202    sc->ciss_notify_thread = NULL;
4203    wakeup(&sc->ciss_notify_thread);
4204
4205#if __FreeBSD_version >= 500000
4206    mtx_unlock(&sc->ciss_mtx);
4207#endif
4208    kproc_exit(0);
4209}
4210
4211/************************************************************************
4212 * Start the notification kernel thread.
4213 */
4214static void
4215ciss_spawn_notify_thread(struct ciss_softc *sc)
4216{
4217
4218#if __FreeBSD_version > 500005
4219    if (kproc_create((void(*)(void *))ciss_notify_thread, sc,
4220		       &sc->ciss_notify_thread, 0, 0, "ciss_notify%d",
4221		       device_get_unit(sc->ciss_dev)))
4222#else
4223    if (kproc_create((void(*)(void *))ciss_notify_thread, sc,
4224		       &sc->ciss_notify_thread, "ciss_notify%d",
4225		       device_get_unit(sc->ciss_dev)))
4226#endif
4227	panic("Could not create notify thread\n");
4228}
4229
4230/************************************************************************
4231 * Kill the notification kernel thread.
4232 */
4233static void
4234ciss_kill_notify_thread(struct ciss_softc *sc)
4235{
4236
4237    if (sc->ciss_notify_thread == NULL)
4238	return;
4239
4240    sc->ciss_flags |= CISS_FLAG_THREAD_SHUT;
4241    wakeup(&sc->ciss_notify);
4242    msleep(&sc->ciss_notify_thread, &sc->ciss_mtx, PUSER, "thtrm", 0);
4243}
4244
4245/************************************************************************
4246 * Print a request.
4247 */
4248static void
4249ciss_print_request(struct ciss_request *cr)
4250{
4251    struct ciss_softc	*sc;
4252    struct ciss_command	*cc;
4253    int			i;
4254
4255    sc = cr->cr_sc;
4256    cc = cr->cr_cc;
4257
4258    ciss_printf(sc, "REQUEST @ %p\n", cr);
4259    ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
4260	      cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
4261	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
4262    ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
4263		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
4264    switch(cc->header.address.mode.mode) {
4265    case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
4266    case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
4267	ciss_printf(sc, "  physical bus %d target %d\n",
4268		    cc->header.address.physical.bus, cc->header.address.physical.target);
4269	break;
4270    case CISS_HDR_ADDRESS_MODE_LOGICAL:
4271	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
4272	break;
4273    }
4274    ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
4275		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
4276		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
4277		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
4278		cc->cdb.cdb_length,
4279		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
4280		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
4281		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
4282		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
4283		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
4284		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
4285		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
4286    ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
4287
4288    if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
4289	/* XXX print error info */
4290    } else {
4291	/* since we don't use chained s/g, don't support it here */
4292	for (i = 0; i < cc->header.sg_in_list; i++) {
4293	    if ((i % 4) == 0)
4294		ciss_printf(sc, "   ");
4295	    printf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
4296	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
4297		printf("\n");
4298	}
4299    }
4300}
4301
4302/************************************************************************
4303 * Print information about the status of a logical drive.
4304 */
4305static void
4306ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
4307{
4308    int		bus, target, i;
4309
4310    if (ld->cl_lstatus == NULL) {
4311	printf("does not exist\n");
4312	return;
4313    }
4314
4315    /* print drive status */
4316    switch(ld->cl_lstatus->status) {
4317    case CISS_LSTATUS_OK:
4318	printf("online\n");
4319	break;
4320    case CISS_LSTATUS_INTERIM_RECOVERY:
4321	printf("in interim recovery mode\n");
4322	break;
4323    case CISS_LSTATUS_READY_RECOVERY:
4324	printf("ready to begin recovery\n");
4325	break;
4326    case CISS_LSTATUS_RECOVERING:
4327	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4328	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4329	printf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
4330	       bus, target, ld->cl_lstatus->blocks_to_recover);
4331	break;
4332    case CISS_LSTATUS_EXPANDING:
4333	printf("being expanded, %u blocks remaining\n",
4334	       ld->cl_lstatus->blocks_to_recover);
4335	break;
4336    case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4337	printf("queued for expansion\n");
4338	break;
4339    case CISS_LSTATUS_FAILED:
4340	printf("queued for expansion\n");
4341	break;
4342    case CISS_LSTATUS_WRONG_PDRIVE:
4343	printf("wrong physical drive inserted\n");
4344	break;
4345    case CISS_LSTATUS_MISSING_PDRIVE:
4346	printf("missing a needed physical drive\n");
4347	break;
4348    case CISS_LSTATUS_BECOMING_READY:
4349	printf("becoming ready\n");
4350	break;
4351    }
4352
4353    /* print failed physical drives */
4354    for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
4355	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
4356	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
4357	if (bus == -1)
4358	    continue;
4359	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
4360		    ld->cl_lstatus->drive_failure_map[i]);
4361    }
4362}
4363
4364#ifdef CISS_DEBUG
4365#include "opt_ddb.h"
4366#ifdef DDB
4367#include <ddb/ddb.h>
4368/************************************************************************
4369 * Print information about the controller/driver.
4370 */
4371static void
4372ciss_print_adapter(struct ciss_softc *sc)
4373{
4374    int		i, j;
4375
4376    ciss_printf(sc, "ADAPTER:\n");
4377    for (i = 0; i < CISSQ_COUNT; i++) {
4378	ciss_printf(sc, "%s     %d/%d\n",
4379	    i == 0 ? "free" :
4380	    i == 1 ? "busy" : "complete",
4381	    sc->ciss_qstat[i].q_length,
4382	    sc->ciss_qstat[i].q_max);
4383    }
4384    ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
4385    ciss_printf(sc, "flags %b\n", sc->ciss_flags,
4386	"\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n");
4387
4388    for (i = 0; i < sc->ciss_max_logical_bus; i++) {
4389	for (j = 0; j < sc->ciss_cfg->max_logical_supported; j++) {
4390	    ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
4391	    ciss_print_ldrive(sc, &sc->ciss_logical[i][j]);
4392	}
4393    }
4394
4395    /* XXX Should physical drives be printed out here? */
4396
4397    for (i = 1; i < sc->ciss_max_requests; i++)
4398	ciss_print_request(sc->ciss_request + i);
4399}
4400
4401/* DDB hook */
4402DB_COMMAND(ciss_prt, db_ciss_prt)
4403{
4404    struct ciss_softc	*sc;
4405    devclass_t dc;
4406    int maxciss, i;
4407
4408    dc = devclass_find("ciss");
4409    if ( dc == NULL ) {
4410        printf("%s: can't find devclass!\n", __func__);
4411        return;
4412    }
4413    maxciss = devclass_get_maxunit(dc);
4414    for (i = 0; i < maxciss; i++) {
4415        sc = devclass_get_softc(dc, i);
4416	ciss_print_adapter(sc);
4417    }
4418}
4419#endif
4420#endif
4421
4422/************************************************************************
4423 * Return a name for a logical drive status value.
4424 */
4425static const char *
4426ciss_name_ldrive_status(int status)
4427{
4428    switch (status) {
4429    case CISS_LSTATUS_OK:
4430	return("OK");
4431    case CISS_LSTATUS_FAILED:
4432	return("failed");
4433    case CISS_LSTATUS_NOT_CONFIGURED:
4434	return("not configured");
4435    case CISS_LSTATUS_INTERIM_RECOVERY:
4436	return("interim recovery");
4437    case CISS_LSTATUS_READY_RECOVERY:
4438	return("ready for recovery");
4439    case CISS_LSTATUS_RECOVERING:
4440	return("recovering");
4441    case CISS_LSTATUS_WRONG_PDRIVE:
4442	return("wrong physical drive inserted");
4443    case CISS_LSTATUS_MISSING_PDRIVE:
4444	return("missing physical drive");
4445    case CISS_LSTATUS_EXPANDING:
4446	return("expanding");
4447    case CISS_LSTATUS_BECOMING_READY:
4448	return("becoming ready");
4449    case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4450	return("queued for expansion");
4451    }
4452    return("unknown status");
4453}
4454
4455/************************************************************************
4456 * Return an online/offline/nonexistent value for a logical drive
4457 * status value.
4458 */
4459static int
4460ciss_decode_ldrive_status(int status)
4461{
4462    switch(status) {
4463    case CISS_LSTATUS_NOT_CONFIGURED:
4464	return(CISS_LD_NONEXISTENT);
4465
4466    case CISS_LSTATUS_OK:
4467    case CISS_LSTATUS_INTERIM_RECOVERY:
4468    case CISS_LSTATUS_READY_RECOVERY:
4469    case CISS_LSTATUS_RECOVERING:
4470    case CISS_LSTATUS_EXPANDING:
4471    case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4472	return(CISS_LD_ONLINE);
4473
4474    case CISS_LSTATUS_FAILED:
4475    case CISS_LSTATUS_WRONG_PDRIVE:
4476    case CISS_LSTATUS_MISSING_PDRIVE:
4477    case CISS_LSTATUS_BECOMING_READY:
4478    default:
4479	return(CISS_LD_OFFLINE);
4480    }
4481}
4482
4483
4484/************************************************************************
4485 * Return a name for a logical drive's organisation.
4486 */
4487static const char *
4488ciss_name_ldrive_org(int org)
4489{
4490    switch(org) {
4491    case CISS_LDRIVE_RAID0:
4492	return("RAID 0");
4493    case CISS_LDRIVE_RAID1:
4494	return("RAID 1(1+0)");
4495    case CISS_LDRIVE_RAID4:
4496	return("RAID 4");
4497    case CISS_LDRIVE_RAID5:
4498	return("RAID 5");
4499    case CISS_LDRIVE_RAID51:
4500	return("RAID 5+1");
4501    case CISS_LDRIVE_RAIDADG:
4502	return("RAID ADG");
4503    }
4504    return("unkown");
4505}
4506
4507/************************************************************************
4508 * Return a name for a command status value.
4509 */
4510static const char *
4511ciss_name_command_status(int status)
4512{
4513    switch(status) {
4514    case CISS_CMD_STATUS_SUCCESS:
4515	return("success");
4516    case CISS_CMD_STATUS_TARGET_STATUS:
4517	return("target status");
4518    case CISS_CMD_STATUS_DATA_UNDERRUN:
4519	return("data underrun");
4520    case CISS_CMD_STATUS_DATA_OVERRUN:
4521	return("data overrun");
4522    case CISS_CMD_STATUS_INVALID_COMMAND:
4523	return("invalid command");
4524    case CISS_CMD_STATUS_PROTOCOL_ERROR:
4525	return("protocol error");
4526    case CISS_CMD_STATUS_HARDWARE_ERROR:
4527	return("hardware error");
4528    case CISS_CMD_STATUS_CONNECTION_LOST:
4529	return("connection lost");
4530    case CISS_CMD_STATUS_ABORTED:
4531	return("aborted");
4532    case CISS_CMD_STATUS_ABORT_FAILED:
4533	return("abort failed");
4534    case CISS_CMD_STATUS_UNSOLICITED_ABORT:
4535	return("unsolicited abort");
4536    case CISS_CMD_STATUS_TIMEOUT:
4537	return("timeout");
4538    case CISS_CMD_STATUS_UNABORTABLE:
4539	return("unabortable");
4540    }
4541    return("unknown status");
4542}
4543
4544/************************************************************************
4545 * Handle an open on the control device.
4546 */
4547static int
4548ciss_open(struct cdev *dev, int flags, int fmt, struct thread *p)
4549{
4550    struct ciss_softc	*sc;
4551
4552    debug_called(1);
4553
4554    sc = (struct ciss_softc *)dev->si_drv1;
4555
4556    /* we might want to veto if someone already has us open */
4557
4558    mtx_lock(&sc->ciss_mtx);
4559    sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
4560    mtx_unlock(&sc->ciss_mtx);
4561    return(0);
4562}
4563
4564/************************************************************************
4565 * Handle the last close on the control device.
4566 */
4567static int
4568ciss_close(struct cdev *dev, int flags, int fmt, struct thread *p)
4569{
4570    struct ciss_softc	*sc;
4571
4572    debug_called(1);
4573
4574    sc = (struct ciss_softc *)dev->si_drv1;
4575
4576    mtx_lock(&sc->ciss_mtx);
4577    sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
4578    mtx_unlock(&sc->ciss_mtx);
4579    return (0);
4580}
4581
4582/********************************************************************************
4583 * Handle adapter-specific control operations.
4584 *
4585 * Note that the API here is compatible with the Linux driver, in order to
4586 * simplify the porting of Compaq's userland tools.
4587 */
4588static int
4589ciss_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int32_t flag, struct thread *p)
4590{
4591    struct ciss_softc		*sc;
4592    IOCTL_Command_struct	*ioc	= (IOCTL_Command_struct *)addr;
4593#ifdef __amd64__
4594    IOCTL_Command_struct32	*ioc32	= (IOCTL_Command_struct32 *)addr;
4595    IOCTL_Command_struct	ioc_swab;
4596#endif
4597    int				error;
4598
4599    debug_called(1);
4600
4601    sc = (struct ciss_softc *)dev->si_drv1;
4602    error = 0;
4603    mtx_lock(&sc->ciss_mtx);
4604
4605    switch(cmd) {
4606    case CCISS_GETQSTATS:
4607    {
4608	union ciss_statrequest *cr = (union ciss_statrequest *)addr;
4609
4610	switch (cr->cs_item) {
4611	case CISSQ_FREE:
4612	case CISSQ_NOTIFY:
4613	    bcopy(&sc->ciss_qstat[cr->cs_item], &cr->cs_qstat,
4614		sizeof(struct ciss_qstat));
4615	    break;
4616	default:
4617	    error = ENOIOCTL;
4618	    break;
4619	}
4620
4621	break;
4622    }
4623
4624    case CCISS_GETPCIINFO:
4625    {
4626	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
4627
4628	pis->bus = pci_get_bus(sc->ciss_dev);
4629	pis->dev_fn = pci_get_slot(sc->ciss_dev);
4630        pis->board_id = (pci_get_subvendor(sc->ciss_dev) << 16) |
4631                pci_get_subdevice(sc->ciss_dev);
4632
4633	break;
4634    }
4635
4636    case CCISS_GETINTINFO:
4637    {
4638	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4639
4640	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
4641	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
4642
4643	break;
4644    }
4645
4646    case CCISS_SETINTINFO:
4647    {
4648	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4649
4650	if ((cis->delay == 0) && (cis->count == 0)) {
4651	    error = EINVAL;
4652	    break;
4653	}
4654
4655	/*
4656	 * XXX apparently this is only safe if the controller is idle,
4657	 *     we should suspend it before doing this.
4658	 */
4659	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
4660	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
4661
4662	if (ciss_update_config(sc))
4663	    error = EIO;
4664
4665	/* XXX resume the controller here */
4666	break;
4667    }
4668
4669    case CCISS_GETNODENAME:
4670	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
4671	      sizeof(NodeName_type));
4672	break;
4673
4674    case CCISS_SETNODENAME:
4675	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
4676	      sizeof(NodeName_type));
4677	if (ciss_update_config(sc))
4678	    error = EIO;
4679	break;
4680
4681    case CCISS_GETHEARTBEAT:
4682	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
4683	break;
4684
4685    case CCISS_GETBUSTYPES:
4686	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
4687	break;
4688
4689    case CCISS_GETFIRMVER:
4690	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
4691	      sizeof(FirmwareVer_type));
4692	break;
4693
4694    case CCISS_GETDRIVERVER:
4695	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
4696	break;
4697
4698    case CCISS_REVALIDVOLS:
4699	/*
4700	 * This is a bit ugly; to do it "right" we really need
4701	 * to find any disks that have changed, kick CAM off them,
4702	 * then rescan only these disks.  It'd be nice if they
4703	 * a) told us which disk(s) they were going to play with,
4704	 * and b) which ones had arrived. 8(
4705	 */
4706	break;
4707
4708#ifdef __amd64__
4709    case CCISS_PASSTHRU32:
4710	ioc_swab.LUN_info	= ioc32->LUN_info;
4711	ioc_swab.Request	= ioc32->Request;
4712	ioc_swab.error_info	= ioc32->error_info;
4713	ioc_swab.buf_size	= ioc32->buf_size;
4714	ioc_swab.buf		= (u_int8_t *)(uintptr_t)ioc32->buf;
4715	ioc			= &ioc_swab;
4716	/* FALLTHROUGH */
4717#endif
4718
4719    case CCISS_PASSTHRU:
4720	error = ciss_user_command(sc, ioc);
4721	break;
4722
4723    default:
4724	debug(0, "unknown ioctl 0x%lx", cmd);
4725
4726	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
4727	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
4728	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
4729	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
4730	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
4731	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
4732	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
4733	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
4734	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
4735	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
4736	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
4737
4738	error = ENOIOCTL;
4739	break;
4740    }
4741
4742    mtx_unlock(&sc->ciss_mtx);
4743    return(error);
4744}
4745