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