xref: /freebsd/sys/dev/mvs/mvs.c (revision b1f9167f94059fd55c630891d359bcff987bd7eb)
1 /*-
2  * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
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 ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/module.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/ata.h>
35 #include <sys/bus.h>
36 #include <sys/conf.h>
37 #include <sys/endian.h>
38 #include <sys/malloc.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <vm/uma.h>
42 #include <machine/stdarg.h>
43 #include <machine/resource.h>
44 #include <machine/bus.h>
45 #include <sys/rman.h>
46 #include <dev/pci/pcivar.h>
47 #include "mvs.h"
48 
49 #include <cam/cam.h>
50 #include <cam/cam_ccb.h>
51 #include <cam/cam_sim.h>
52 #include <cam/cam_xpt_sim.h>
53 #include <cam/cam_debug.h>
54 
55 /* local prototypes */
56 static int mvs_ch_init(device_t dev);
57 static int mvs_ch_deinit(device_t dev);
58 static int mvs_ch_suspend(device_t dev);
59 static int mvs_ch_resume(device_t dev);
60 static void mvs_dmainit(device_t dev);
61 static void mvs_dmasetupc_cb(void *xsc,
62 	bus_dma_segment_t *segs, int nsegs, int error);
63 static void mvs_dmafini(device_t dev);
64 static void mvs_slotsalloc(device_t dev);
65 static void mvs_slotsfree(device_t dev);
66 static void mvs_setup_edma_queues(device_t dev);
67 static void mvs_set_edma_mode(device_t dev, enum mvs_edma_mode mode);
68 static void mvs_ch_pm(void *arg);
69 static void mvs_ch_intr_locked(void *data);
70 static void mvs_ch_intr(void *data);
71 static void mvs_reset(device_t dev);
72 static void mvs_softreset(device_t dev, union ccb *ccb);
73 
74 static int mvs_sata_connect(struct mvs_channel *ch);
75 static int mvs_sata_phy_reset(device_t dev);
76 static int mvs_wait(device_t dev, u_int s, u_int c, int t);
77 static void mvs_tfd_read(device_t dev, union ccb *ccb);
78 static void mvs_tfd_write(device_t dev, union ccb *ccb);
79 static void mvs_legacy_intr(device_t dev, int poll);
80 static void mvs_crbq_intr(device_t dev);
81 static void mvs_begin_transaction(device_t dev, union ccb *ccb);
82 static void mvs_legacy_execute_transaction(struct mvs_slot *slot);
83 static void mvs_timeout(struct mvs_slot *slot);
84 static void mvs_dmasetprd(void *arg,
85 	bus_dma_segment_t *segs, int nsegs, int error);
86 static void mvs_requeue_frozen(device_t dev);
87 static void mvs_execute_transaction(struct mvs_slot *slot);
88 static void mvs_end_transaction(struct mvs_slot *slot, enum mvs_err_type et);
89 
90 static void mvs_issue_recovery(device_t dev);
91 static void mvs_process_read_log(device_t dev, union ccb *ccb);
92 static void mvs_process_request_sense(device_t dev, union ccb *ccb);
93 
94 static void mvsaction(struct cam_sim *sim, union ccb *ccb);
95 static void mvspoll(struct cam_sim *sim);
96 
97 static MALLOC_DEFINE(M_MVS, "MVS driver", "MVS driver data buffers");
98 
99 #define recovery_type		spriv_field0
100 #define RECOVERY_NONE		0
101 #define RECOVERY_READ_LOG	1
102 #define RECOVERY_REQUEST_SENSE	2
103 #define recovery_slot		spriv_field1
104 
105 static int
106 mvs_ch_probe(device_t dev)
107 {
108 
109 	device_set_desc_copy(dev, "Marvell SATA channel");
110 	return (0);
111 }
112 
113 static int
114 mvs_ch_attach(device_t dev)
115 {
116 	struct mvs_controller *ctlr = device_get_softc(device_get_parent(dev));
117 	struct mvs_channel *ch = device_get_softc(dev);
118 	struct cam_devq *devq;
119 	int rid, error, i, sata_rev = 0;
120 
121 	ch->dev = dev;
122 	ch->unit = (intptr_t)device_get_ivars(dev);
123 	ch->quirks = ctlr->quirks;
124 	mtx_init(&ch->mtx, "MVS channel lock", NULL, MTX_DEF);
125 	resource_int_value(device_get_name(dev),
126 	    device_get_unit(dev), "pm_level", &ch->pm_level);
127 	if (ch->pm_level > 3)
128 		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
129 	callout_init_mtx(&ch->reset_timer, &ch->mtx, 0);
130 	resource_int_value(device_get_name(dev),
131 	    device_get_unit(dev), "sata_rev", &sata_rev);
132 	for (i = 0; i < 16; i++) {
133 		ch->user[i].revision = sata_rev;
134 		ch->user[i].mode = 0;
135 		ch->user[i].bytecount = (ch->quirks & MVS_Q_GENIIE) ? 8192 : 2048;
136 		ch->user[i].tags = MVS_MAX_SLOTS;
137 		ch->curr[i] = ch->user[i];
138 		if (ch->pm_level) {
139 			ch->user[i].caps = CTS_SATA_CAPS_H_PMREQ |
140 			    CTS_SATA_CAPS_H_APST |
141 			    CTS_SATA_CAPS_D_PMREQ | CTS_SATA_CAPS_D_APST;
142 		}
143 		ch->user[i].caps |= CTS_SATA_CAPS_H_AN;
144 	}
145 	rid = ch->unit;
146 	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
147 	    &rid, RF_ACTIVE)))
148 		return (ENXIO);
149 	mvs_dmainit(dev);
150 	mvs_slotsalloc(dev);
151 	mvs_ch_init(dev);
152 	mtx_lock(&ch->mtx);
153 	rid = ATA_IRQ_RID;
154 	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
155 	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
156 		device_printf(dev, "Unable to map interrupt\n");
157 		error = ENXIO;
158 		goto err0;
159 	}
160 	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
161 	    mvs_ch_intr_locked, dev, &ch->ih))) {
162 		device_printf(dev, "Unable to setup interrupt\n");
163 		error = ENXIO;
164 		goto err1;
165 	}
166 	/* Create the device queue for our SIM. */
167 	devq = cam_simq_alloc(MVS_MAX_SLOTS - 1);
168 	if (devq == NULL) {
169 		device_printf(dev, "Unable to allocate simq\n");
170 		error = ENOMEM;
171 		goto err1;
172 	}
173 	/* Construct SIM entry */
174 	ch->sim = cam_sim_alloc(mvsaction, mvspoll, "mvsch", ch,
175 	    device_get_unit(dev), &ch->mtx,
176 	    2, (ch->quirks & MVS_Q_GENI) ? 0 : MVS_MAX_SLOTS - 1,
177 	    devq);
178 	if (ch->sim == NULL) {
179 		cam_simq_free(devq);
180 		device_printf(dev, "unable to allocate sim\n");
181 		error = ENOMEM;
182 		goto err1;
183 	}
184 	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
185 		device_printf(dev, "unable to register xpt bus\n");
186 		error = ENXIO;
187 		goto err2;
188 	}
189 	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
190 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
191 		device_printf(dev, "unable to create path\n");
192 		error = ENXIO;
193 		goto err3;
194 	}
195 	if (ch->pm_level > 3) {
196 		callout_reset(&ch->pm_timer,
197 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
198 		    mvs_ch_pm, dev);
199 	}
200 	mtx_unlock(&ch->mtx);
201 	return (0);
202 
203 err3:
204 	xpt_bus_deregister(cam_sim_path(ch->sim));
205 err2:
206 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
207 err1:
208 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
209 err0:
210 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
211 	mtx_unlock(&ch->mtx);
212 	mtx_destroy(&ch->mtx);
213 	return (error);
214 }
215 
216 static int
217 mvs_ch_detach(device_t dev)
218 {
219 	struct mvs_channel *ch = device_get_softc(dev);
220 
221 	mtx_lock(&ch->mtx);
222 	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
223 	/* Forget about reset. */
224 	if (ch->resetting) {
225 		ch->resetting = 0;
226 		xpt_release_simq(ch->sim, TRUE);
227 	}
228 	xpt_free_path(ch->path);
229 	xpt_bus_deregister(cam_sim_path(ch->sim));
230 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
231 	mtx_unlock(&ch->mtx);
232 
233 	if (ch->pm_level > 3)
234 		callout_drain(&ch->pm_timer);
235 	callout_drain(&ch->reset_timer);
236 	bus_teardown_intr(dev, ch->r_irq, ch->ih);
237 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
238 
239 	mvs_ch_deinit(dev);
240 	mvs_slotsfree(dev);
241 	mvs_dmafini(dev);
242 
243 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
244 	mtx_destroy(&ch->mtx);
245 	return (0);
246 }
247 
248 static int
249 mvs_ch_init(device_t dev)
250 {
251 	struct mvs_channel *ch = device_get_softc(dev);
252 	uint32_t reg;
253 
254 	/* Disable port interrupts */
255 	ATA_OUTL(ch->r_mem, EDMA_IEM, 0);
256 	/* Stop EDMA */
257 	ch->curr_mode = MVS_EDMA_UNKNOWN;
258 	mvs_set_edma_mode(dev, MVS_EDMA_OFF);
259 	/* Clear and configure FIS interrupts. */
260 	ATA_OUTL(ch->r_mem, SATA_FISIC, 0);
261 	reg = ATA_INL(ch->r_mem, SATA_FISC);
262 	reg |= SATA_FISC_FISWAIT4HOSTRDYEN_B1;
263 	ATA_OUTL(ch->r_mem, SATA_FISC, reg);
264 	reg = ATA_INL(ch->r_mem, SATA_FISIM);
265 	reg |= SATA_FISC_FISWAIT4HOSTRDYEN_B1;
266 	ATA_OUTL(ch->r_mem, SATA_FISC, reg);
267 	/* Clear SATA error register. */
268 	ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
269 	/* Clear any outstanding error interrupts. */
270 	ATA_OUTL(ch->r_mem, EDMA_IEC, 0);
271 	/* Unmask all error interrupts */
272 	ATA_OUTL(ch->r_mem, EDMA_IEM, ~EDMA_IE_TRANSIENT);
273 	return (0);
274 }
275 
276 static int
277 mvs_ch_deinit(device_t dev)
278 {
279 	struct mvs_channel *ch = device_get_softc(dev);
280 
281 	/* Stop EDMA */
282 	mvs_set_edma_mode(dev, MVS_EDMA_OFF);
283 	/* Disable port interrupts. */
284 	ATA_OUTL(ch->r_mem, EDMA_IEM, 0);
285 	return (0);
286 }
287 
288 static int
289 mvs_ch_suspend(device_t dev)
290 {
291 	struct mvs_channel *ch = device_get_softc(dev);
292 
293 	mtx_lock(&ch->mtx);
294 	xpt_freeze_simq(ch->sim, 1);
295 	while (ch->oslots)
296 		msleep(ch, &ch->mtx, PRIBIO, "mvssusp", hz/100);
297 	/* Forget about reset. */
298 	if (ch->resetting) {
299 		ch->resetting = 0;
300 		callout_stop(&ch->reset_timer);
301 		xpt_release_simq(ch->sim, TRUE);
302 	}
303 	mvs_ch_deinit(dev);
304 	mtx_unlock(&ch->mtx);
305 	return (0);
306 }
307 
308 static int
309 mvs_ch_resume(device_t dev)
310 {
311 	struct mvs_channel *ch = device_get_softc(dev);
312 
313 	mtx_lock(&ch->mtx);
314 	mvs_ch_init(dev);
315 	mvs_reset(dev);
316 	xpt_release_simq(ch->sim, TRUE);
317 	mtx_unlock(&ch->mtx);
318 	return (0);
319 }
320 
321 struct mvs_dc_cb_args {
322 	bus_addr_t maddr;
323 	int error;
324 };
325 
326 static void
327 mvs_dmainit(device_t dev)
328 {
329 	struct mvs_channel *ch = device_get_softc(dev);
330 	struct mvs_dc_cb_args dcba;
331 
332 	/* EDMA command request area. */
333 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
334 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
335 	    NULL, NULL, MVS_WORKRQ_SIZE, 1, MVS_WORKRQ_SIZE,
336 	    0, NULL, NULL, &ch->dma.workrq_tag))
337 		goto error;
338 	if (bus_dmamem_alloc(ch->dma.workrq_tag, (void **)&ch->dma.workrq, 0,
339 	    &ch->dma.workrq_map))
340 		goto error;
341 	if (bus_dmamap_load(ch->dma.workrq_tag, ch->dma.workrq_map,
342 	    ch->dma.workrq, MVS_WORKRQ_SIZE, mvs_dmasetupc_cb, &dcba, 0) ||
343 	    dcba.error) {
344 		bus_dmamem_free(ch->dma.workrq_tag,
345 		    ch->dma.workrq, ch->dma.workrq_map);
346 		goto error;
347 	}
348 	ch->dma.workrq_bus = dcba.maddr;
349 	/* EDMA command response area. */
350 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 256, 0,
351 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
352 	    NULL, NULL, MVS_WORKRP_SIZE, 1, MVS_WORKRP_SIZE,
353 	    0, NULL, NULL, &ch->dma.workrp_tag))
354 		goto error;
355 	if (bus_dmamem_alloc(ch->dma.workrp_tag, (void **)&ch->dma.workrp, 0,
356 	    &ch->dma.workrp_map))
357 		goto error;
358 	if (bus_dmamap_load(ch->dma.workrp_tag, ch->dma.workrp_map,
359 	    ch->dma.workrp, MVS_WORKRP_SIZE, mvs_dmasetupc_cb, &dcba, 0) ||
360 	    dcba.error) {
361 		bus_dmamem_free(ch->dma.workrp_tag,
362 		    ch->dma.workrp, ch->dma.workrp_map);
363 		goto error;
364 	}
365 	ch->dma.workrp_bus = dcba.maddr;
366 	/* Data area. */
367 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 2, MVS_EPRD_MAX,
368 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
369 	    NULL, NULL,
370 	    MVS_SG_ENTRIES * PAGE_SIZE * MVS_MAX_SLOTS,
371 	    MVS_SG_ENTRIES, MVS_EPRD_MAX,
372 	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
373 		goto error;
374 	}
375 	return;
376 
377 error:
378 	device_printf(dev, "WARNING - DMA initialization failed\n");
379 	mvs_dmafini(dev);
380 }
381 
382 static void
383 mvs_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
384 {
385 	struct mvs_dc_cb_args *dcba = (struct mvs_dc_cb_args *)xsc;
386 
387 	if (!(dcba->error = error))
388 		dcba->maddr = segs[0].ds_addr;
389 }
390 
391 static void
392 mvs_dmafini(device_t dev)
393 {
394 	struct mvs_channel *ch = device_get_softc(dev);
395 
396 	if (ch->dma.data_tag) {
397 		bus_dma_tag_destroy(ch->dma.data_tag);
398 		ch->dma.data_tag = NULL;
399 	}
400 	if (ch->dma.workrp_bus) {
401 		bus_dmamap_unload(ch->dma.workrp_tag, ch->dma.workrp_map);
402 		bus_dmamem_free(ch->dma.workrp_tag,
403 		    ch->dma.workrp, ch->dma.workrp_map);
404 		ch->dma.workrp_bus = 0;
405 		ch->dma.workrp = NULL;
406 	}
407 	if (ch->dma.workrp_tag) {
408 		bus_dma_tag_destroy(ch->dma.workrp_tag);
409 		ch->dma.workrp_tag = NULL;
410 	}
411 	if (ch->dma.workrq_bus) {
412 		bus_dmamap_unload(ch->dma.workrq_tag, ch->dma.workrq_map);
413 		bus_dmamem_free(ch->dma.workrq_tag,
414 		    ch->dma.workrq, ch->dma.workrq_map);
415 		ch->dma.workrq_bus = 0;
416 		ch->dma.workrq = NULL;
417 	}
418 	if (ch->dma.workrq_tag) {
419 		bus_dma_tag_destroy(ch->dma.workrq_tag);
420 		ch->dma.workrq_tag = NULL;
421 	}
422 }
423 
424 static void
425 mvs_slotsalloc(device_t dev)
426 {
427 	struct mvs_channel *ch = device_get_softc(dev);
428 	int i;
429 
430 	/* Alloc and setup command/dma slots */
431 	bzero(ch->slot, sizeof(ch->slot));
432 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
433 		struct mvs_slot *slot = &ch->slot[i];
434 
435 		slot->dev = dev;
436 		slot->slot = i;
437 		slot->state = MVS_SLOT_EMPTY;
438 		slot->ccb = NULL;
439 		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
440 
441 		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
442 			device_printf(ch->dev, "FAILURE - create data_map\n");
443 	}
444 }
445 
446 static void
447 mvs_slotsfree(device_t dev)
448 {
449 	struct mvs_channel *ch = device_get_softc(dev);
450 	int i;
451 
452 	/* Free all dma slots */
453 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
454 		struct mvs_slot *slot = &ch->slot[i];
455 
456 		callout_drain(&slot->timeout);
457 		if (slot->dma.data_map) {
458 			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
459 			slot->dma.data_map = NULL;
460 		}
461 	}
462 }
463 
464 static void
465 mvs_setup_edma_queues(device_t dev)
466 {
467 	struct mvs_channel *ch = device_get_softc(dev);
468 	uint64_t work;
469 
470 	/* Requests queue. */
471 	work = ch->dma.workrq_bus;
472 	ATA_OUTL(ch->r_mem, EDMA_REQQBAH, work >> 32);
473 	ATA_OUTL(ch->r_mem, EDMA_REQQIP, work & 0xffffffff);
474 	ATA_OUTL(ch->r_mem, EDMA_REQQOP, work & 0xffffffff);
475 	bus_dmamap_sync(ch->dma.workrq_tag, ch->dma.workrq_map,
476 	    BUS_DMASYNC_PREWRITE);
477 	/* Reponses queue. */
478 	memset(ch->dma.workrp, 0xff, MVS_WORKRP_SIZE);
479 	work = ch->dma.workrp_bus;
480 	ATA_OUTL(ch->r_mem, EDMA_RESQBAH, work >> 32);
481 	ATA_OUTL(ch->r_mem, EDMA_RESQIP, work & 0xffffffff);
482 	ATA_OUTL(ch->r_mem, EDMA_RESQOP, work & 0xffffffff);
483 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
484 	    BUS_DMASYNC_PREREAD);
485 	ch->out_idx = 0;
486 	ch->in_idx = 0;
487 }
488 
489 static void
490 mvs_set_edma_mode(device_t dev, enum mvs_edma_mode mode)
491 {
492 	struct mvs_channel *ch = device_get_softc(dev);
493 	int timeout;
494 	uint32_t ecfg, fcfg, hc, ltm, unkn;
495 
496 	if (mode == ch->curr_mode)
497 		return;
498 	/* If we are running, we should stop first. */
499 	if (ch->curr_mode != MVS_EDMA_OFF) {
500 		ATA_OUTL(ch->r_mem, EDMA_CMD, EDMA_CMD_EDSEDMA);
501 		timeout = 0;
502 		while (ATA_INL(ch->r_mem, EDMA_CMD) & EDMA_CMD_EENEDMA) {
503 			DELAY(1000);
504 			if (timeout++ > 1000) {
505 				device_printf(dev, "stopping EDMA engine failed\n");
506 				break;
507 			}
508 		};
509 	}
510 	ch->curr_mode = mode;
511 	ch->fbs_enabled = 0;
512 	ch->fake_busy = 0;
513 	/* Report mode to controller. Needed for correct CCC operation. */
514 	MVS_EDMA(device_get_parent(dev), dev, mode);
515 	/* Configure new mode. */
516 	ecfg = EDMA_CFG_RESERVED | EDMA_CFG_RESERVED2 | EDMA_CFG_EHOSTQUEUECACHEEN;
517 	if (ch->pm_present) {
518 		ecfg |= EDMA_CFG_EMASKRXPM;
519 		if (ch->quirks & MVS_Q_GENIIE) {
520 			ecfg |= EDMA_CFG_EEDMAFBS;
521 			ch->fbs_enabled = 1;
522 		}
523 	}
524 	if (ch->quirks & MVS_Q_GENI)
525 		ecfg |= EDMA_CFG_ERDBSZ;
526 	else if (ch->quirks & MVS_Q_GENII)
527 		ecfg |= EDMA_CFG_ERDBSZEXT | EDMA_CFG_EWRBUFFERLEN;
528 	if (ch->quirks & MVS_Q_CT)
529 		ecfg |= EDMA_CFG_ECUTTHROUGHEN;
530 	if (mode != MVS_EDMA_OFF)
531 		ecfg |= EDMA_CFG_EEARLYCOMPLETIONEN;
532 	if (mode == MVS_EDMA_QUEUED)
533 		ecfg |= EDMA_CFG_EQUE;
534 	else if (mode == MVS_EDMA_NCQ)
535 		ecfg |= EDMA_CFG_ESATANATVCMDQUE;
536 	ATA_OUTL(ch->r_mem, EDMA_CFG, ecfg);
537 	mvs_setup_edma_queues(dev);
538 	if (ch->quirks & MVS_Q_GENIIE) {
539 		/* Configure FBS-related registers */
540 		fcfg = ATA_INL(ch->r_mem, SATA_FISC);
541 		ltm = ATA_INL(ch->r_mem, SATA_LTM);
542 		hc = ATA_INL(ch->r_mem, EDMA_HC);
543 		if (ch->fbs_enabled) {
544 			fcfg |= SATA_FISC_FISDMAACTIVATESYNCRESP;
545 			if (mode == MVS_EDMA_NCQ) {
546 				fcfg &= ~SATA_FISC_FISWAIT4HOSTRDYEN_B0;
547 				hc &= ~EDMA_IE_EDEVERR;
548 			} else {
549 				fcfg |= SATA_FISC_FISWAIT4HOSTRDYEN_B0;
550 				hc |= EDMA_IE_EDEVERR;
551 			}
552 			ltm |= (1 << 8);
553 		} else {
554 			fcfg &= ~SATA_FISC_FISDMAACTIVATESYNCRESP;
555 			fcfg &= ~SATA_FISC_FISWAIT4HOSTRDYEN_B0;
556 			hc |= EDMA_IE_EDEVERR;
557 			ltm &= ~(1 << 8);
558 		}
559 		ATA_OUTL(ch->r_mem, SATA_FISC, fcfg);
560 		ATA_OUTL(ch->r_mem, SATA_LTM, ltm);
561 		ATA_OUTL(ch->r_mem, EDMA_HC, hc);
562 		/* This is some magic, required to handle several DRQs
563 		 * with basic DMA. */
564 		unkn = ATA_INL(ch->r_mem, EDMA_UNKN_RESD);
565 		if (mode == MVS_EDMA_OFF)
566 			unkn |= 1;
567 		else
568 			unkn &= ~1;
569 		ATA_OUTL(ch->r_mem, EDMA_UNKN_RESD, unkn);
570 	}
571 	/* Run EDMA. */
572 	if (mode != MVS_EDMA_OFF)
573 		ATA_OUTL(ch->r_mem, EDMA_CMD, EDMA_CMD_EENEDMA);
574 }
575 
576 devclass_t mvs_devclass;
577 devclass_t mvsch_devclass;
578 static device_method_t mvsch_methods[] = {
579 	DEVMETHOD(device_probe,     mvs_ch_probe),
580 	DEVMETHOD(device_attach,    mvs_ch_attach),
581 	DEVMETHOD(device_detach,    mvs_ch_detach),
582 	DEVMETHOD(device_suspend,   mvs_ch_suspend),
583 	DEVMETHOD(device_resume,    mvs_ch_resume),
584 	{ 0, 0 }
585 };
586 static driver_t mvsch_driver = {
587         "mvsch",
588         mvsch_methods,
589         sizeof(struct mvs_channel)
590 };
591 DRIVER_MODULE(mvsch, mvs, mvsch_driver, mvsch_devclass, 0, 0);
592 DRIVER_MODULE(mvsch, sata, mvsch_driver, mvsch_devclass, 0, 0);
593 
594 static void
595 mvs_phy_check_events(device_t dev, u_int32_t serr)
596 {
597 	struct mvs_channel *ch = device_get_softc(dev);
598 
599 	if (ch->pm_level == 0) {
600 		u_int32_t status = ATA_INL(ch->r_mem, SATA_SS);
601 		union ccb *ccb;
602 
603 		if (bootverbose) {
604 			if (((status & SATA_SS_DET_MASK) == SATA_SS_DET_PHY_ONLINE) &&
605 			    ((status & SATA_SS_SPD_MASK) != SATA_SS_SPD_NO_SPEED) &&
606 			    ((status & SATA_SS_IPM_MASK) == SATA_SS_IPM_ACTIVE)) {
607 				device_printf(dev, "CONNECT requested\n");
608 			} else
609 				device_printf(dev, "DISCONNECT requested\n");
610 		}
611 		mvs_reset(dev);
612 		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
613 			return;
614 		if (xpt_create_path(&ccb->ccb_h.path, NULL,
615 		    cam_sim_path(ch->sim),
616 		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
617 			xpt_free_ccb(ccb);
618 			return;
619 		}
620 		xpt_rescan(ccb);
621 	}
622 }
623 
624 static void
625 mvs_notify_events(device_t dev)
626 {
627 	struct mvs_channel *ch = device_get_softc(dev);
628 	struct cam_path *dpath;
629 	uint32_t fis;
630 	int d;
631 
632 	/* Try to read PMP field from SDB FIS. Present only for Gen-IIe. */
633 	fis = ATA_INL(ch->r_mem, SATA_FISDW0);
634 	if ((fis & 0x80ff) == 0x80a1)
635 		d = (fis & 0x0f00) >> 8;
636 	else
637 		d = ch->pm_present ? 15 : 0;
638 	if (bootverbose)
639 		device_printf(dev, "SNTF %d\n", d);
640 	if (xpt_create_path(&dpath, NULL,
641 	    xpt_path_path_id(ch->path), d, 0) == CAM_REQ_CMP) {
642 		xpt_async(AC_SCSI_AEN, dpath, NULL);
643 		xpt_free_path(dpath);
644 	}
645 }
646 
647 static void
648 mvs_ch_intr_locked(void *data)
649 {
650 	struct mvs_intr_arg *arg = (struct mvs_intr_arg *)data;
651 	device_t dev = (device_t)arg->arg;
652 	struct mvs_channel *ch = device_get_softc(dev);
653 
654 	mtx_lock(&ch->mtx);
655 	mvs_ch_intr(data);
656 	mtx_unlock(&ch->mtx);
657 }
658 
659 static void
660 mvs_ch_pm(void *arg)
661 {
662 	device_t dev = (device_t)arg;
663 	struct mvs_channel *ch = device_get_softc(dev);
664 	uint32_t work;
665 
666 	if (ch->numrslots != 0)
667 		return;
668 	/* If we are idle - request power state transition. */
669 	work = ATA_INL(ch->r_mem, SATA_SC);
670 	work &= ~SATA_SC_SPM_MASK;
671 	if (ch->pm_level == 4)
672 		work |= SATA_SC_SPM_PARTIAL;
673 	else
674 		work |= SATA_SC_SPM_SLUMBER;
675 	ATA_OUTL(ch->r_mem, SATA_SC, work);
676 }
677 
678 static void
679 mvs_ch_pm_wake(device_t dev)
680 {
681 	struct mvs_channel *ch = device_get_softc(dev);
682 	uint32_t work;
683 	int timeout = 0;
684 
685 	work = ATA_INL(ch->r_mem, SATA_SS);
686 	if (work & SATA_SS_IPM_ACTIVE)
687 		return;
688 	/* If we are not in active state - request power state transition. */
689 	work = ATA_INL(ch->r_mem, SATA_SC);
690 	work &= ~SATA_SC_SPM_MASK;
691 	work |= SATA_SC_SPM_ACTIVE;
692 	ATA_OUTL(ch->r_mem, SATA_SC, work);
693 	/* Wait for transition to happen. */
694 	while ((ATA_INL(ch->r_mem, SATA_SS) & SATA_SS_IPM_ACTIVE) == 0 &&
695 	    timeout++ < 100) {
696 		DELAY(100);
697 	}
698 }
699 
700 static void
701 mvs_ch_intr(void *data)
702 {
703 	struct mvs_intr_arg *arg = (struct mvs_intr_arg *)data;
704 	device_t dev = (device_t)arg->arg;
705 	struct mvs_channel *ch = device_get_softc(dev);
706 	uint32_t iec, serr = 0, fisic = 0;
707 	enum mvs_err_type et;
708 	int i, ccs, port = -1, selfdis = 0;
709 	int edma = (ch->numtslots != 0 || ch->numdslots != 0);
710 
711 	/* New item in response queue. */
712 	if ((arg->cause & 2) && edma)
713 		mvs_crbq_intr(dev);
714 	/* Some error or special event. */
715 	if (arg->cause & 1) {
716 		iec = ATA_INL(ch->r_mem, EDMA_IEC);
717 		if (iec & EDMA_IE_SERRINT) {
718 			serr = ATA_INL(ch->r_mem, SATA_SE);
719 			ATA_OUTL(ch->r_mem, SATA_SE, serr);
720 		}
721 		/* EDMA self-disabled due to error. */
722 		if (iec & EDMA_IE_ESELFDIS)
723 			selfdis = 1;
724 		/* Transport interrupt. */
725 		if (iec & EDMA_IE_ETRANSINT) {
726 			/* For Gen-I this bit means self-disable. */
727 			if (ch->quirks & MVS_Q_GENI)
728 				selfdis = 1;
729 			/* For Gen-II this bit means SDB-N. */
730 			else if (ch->quirks & MVS_Q_GENII)
731 				fisic = SATA_FISC_FISWAIT4HOSTRDYEN_B1;
732 			else	/* For Gen-IIe - read FIS interrupt cause. */
733 				fisic = ATA_INL(ch->r_mem, SATA_FISIC);
734 		}
735 		if (selfdis)
736 			ch->curr_mode = MVS_EDMA_UNKNOWN;
737 		ATA_OUTL(ch->r_mem, EDMA_IEC, ~iec);
738 		/* Interface errors or Device error. */
739 		if (iec & (0xfc1e9000 | EDMA_IE_EDEVERR)) {
740 			port = -1;
741 			if (ch->numpslots != 0) {
742 				ccs = 0;
743 			} else {
744 				if (ch->quirks & MVS_Q_GENIIE)
745 					ccs = EDMA_S_EIOID(ATA_INL(ch->r_mem, EDMA_S));
746 				else
747 					ccs = EDMA_S_EDEVQUETAG(ATA_INL(ch->r_mem, EDMA_S));
748 				/* Check if error is one-PMP-port-specific, */
749 				if (ch->fbs_enabled) {
750 					/* Which ports were active. */
751 					for (i = 0; i < 16; i++) {
752 						if (ch->numrslotspd[i] == 0)
753 							continue;
754 						if (port == -1)
755 							port = i;
756 						else if (port != i) {
757 							port = -2;
758 							break;
759 						}
760 					}
761 					/* If several ports were active and EDMA still enabled -
762 					 * other ports are probably unaffected and may continue.
763 					 */
764 					if (port == -2 && !selfdis) {
765 						uint16_t p = ATA_INL(ch->r_mem, SATA_SATAITC) >> 16;
766 						port = ffs(p) - 1;
767 						if (port != (fls(p) - 1))
768 							port = -2;
769 					}
770 				}
771 			}
772 			mvs_requeue_frozen(dev);
773 			for (i = 0; i < MVS_MAX_SLOTS; i++) {
774 				/* XXX: reqests in loading state. */
775 				if (((ch->rslots >> i) & 1) == 0)
776 					continue;
777 				if (port >= 0 &&
778 				    ch->slot[i].ccb->ccb_h.target_id != port)
779 					continue;
780 				if (iec & EDMA_IE_EDEVERR) { /* Device error. */
781 				    if (port != -2) {
782 					if (ch->numtslots == 0) {
783 						/* Untagged operation. */
784 						if (i == ccs)
785 							et = MVS_ERR_TFE;
786 						else
787 							et = MVS_ERR_INNOCENT;
788 					} else {
789 						/* Tagged operation. */
790 						et = MVS_ERR_NCQ;
791 					}
792 				    } else {
793 					et = MVS_ERR_TFE;
794 					ch->fatalerr = 1;
795 				    }
796 				} else if (iec & 0xfc1e9000) {
797 					if (ch->numtslots == 0 &&
798 					    i != ccs && port != -2)
799 						et = MVS_ERR_INNOCENT;
800 					else
801 						et = MVS_ERR_SATA;
802 				} else
803 					et = MVS_ERR_INVALID;
804 				mvs_end_transaction(&ch->slot[i], et);
805 			}
806 		}
807 		/* Process SDB-N. */
808 		if (fisic & SATA_FISC_FISWAIT4HOSTRDYEN_B1)
809 			mvs_notify_events(dev);
810 		if (fisic)
811 			ATA_OUTL(ch->r_mem, SATA_FISIC, ~fisic);
812 		/* Process hot-plug. */
813 		if ((iec & (EDMA_IE_EDEVDIS | EDMA_IE_EDEVCON)) ||
814 		    (serr & SATA_SE_PHY_CHANGED))
815 			mvs_phy_check_events(dev, serr);
816 	}
817 	/* Legacy mode device interrupt. */
818 	if ((arg->cause & 2) && !edma)
819 		mvs_legacy_intr(dev, arg->cause & 4);
820 }
821 
822 static uint8_t
823 mvs_getstatus(device_t dev, int clear)
824 {
825 	struct mvs_channel *ch = device_get_softc(dev);
826 	uint8_t status = ATA_INB(ch->r_mem, clear ? ATA_STATUS : ATA_ALTSTAT);
827 
828 	if (ch->fake_busy) {
829 		if (status & (ATA_S_BUSY | ATA_S_DRQ | ATA_S_ERROR))
830 			ch->fake_busy = 0;
831 		else
832 			status |= ATA_S_BUSY;
833 	}
834 	return (status);
835 }
836 
837 static void
838 mvs_legacy_intr(device_t dev, int poll)
839 {
840 	struct mvs_channel *ch = device_get_softc(dev);
841 	struct mvs_slot *slot = &ch->slot[0]; /* PIO is always in slot 0. */
842 	union ccb *ccb = slot->ccb;
843 	enum mvs_err_type et = MVS_ERR_NONE;
844 	int port;
845 	u_int length, resid, size;
846 	uint8_t buf[2];
847 	uint8_t status, ireason;
848 
849 	/* Clear interrupt and get status. */
850 	status = mvs_getstatus(dev, 1);
851 	if (slot->state < MVS_SLOT_RUNNING)
852 	    return;
853 	port = ccb->ccb_h.target_id & 0x0f;
854 	/* Wait a bit for late !BUSY status update. */
855 	if (status & ATA_S_BUSY) {
856 		if (poll)
857 			return;
858 		DELAY(100);
859 		if ((status = mvs_getstatus(dev, 1)) & ATA_S_BUSY) {
860 			DELAY(1000);
861 			if ((status = mvs_getstatus(dev, 1)) & ATA_S_BUSY)
862 				return;
863 		}
864 	}
865 	/* If we got an error, we are done. */
866 	if (status & ATA_S_ERROR) {
867 		et = MVS_ERR_TFE;
868 		goto end_finished;
869 	}
870 	if (ccb->ccb_h.func_code == XPT_ATA_IO) { /* ATA PIO */
871 		ccb->ataio.res.status = status;
872 		/* Are we moving data? */
873 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
874 		    /* If data read command - get them. */
875 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
876 			if (mvs_wait(dev, ATA_S_DRQ, ATA_S_BUSY, 1000) < 0) {
877 			    device_printf(dev, "timeout waiting for read DRQ\n");
878 			    et = MVS_ERR_TIMEOUT;
879 			    xpt_freeze_simq(ch->sim, 1);
880 			    ch->toslots |= (1 << slot->slot);
881 			    goto end_finished;
882 			}
883 			ATA_INSW_STRM(ch->r_mem, ATA_DATA,
884 			   (uint16_t *)(ccb->ataio.data_ptr + ch->donecount),
885 			   ch->transfersize / 2);
886 		    }
887 		    /* Update how far we've gotten. */
888 		    ch->donecount += ch->transfersize;
889 		    /* Do we need more? */
890 		    if (ccb->ataio.dxfer_len > ch->donecount) {
891 			/* Set this transfer size according to HW capabilities */
892 			ch->transfersize = min(ccb->ataio.dxfer_len - ch->donecount,
893 			    ch->transfersize);
894 			/* If data write command - put them */
895 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
896 				if (mvs_wait(dev, ATA_S_DRQ, ATA_S_BUSY, 1000) < 0) {
897 				    device_printf(dev,
898 					"timeout waiting for write DRQ\n");
899 				    et = MVS_ERR_TIMEOUT;
900 				    xpt_freeze_simq(ch->sim, 1);
901 				    ch->toslots |= (1 << slot->slot);
902 				    goto end_finished;
903 				}
904 				ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
905 				   (uint16_t *)(ccb->ataio.data_ptr + ch->donecount),
906 				   ch->transfersize / 2);
907 				return;
908 			}
909 			/* If data read command, return & wait for interrupt */
910 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
911 				return;
912 		    }
913 		}
914 	} else if (ch->basic_dma) {	/* ATAPI DMA */
915 		if (status & ATA_S_DWF)
916 			et = MVS_ERR_TFE;
917 		else if (ATA_INL(ch->r_mem, DMA_S) & DMA_S_ERR)
918 			et = MVS_ERR_TFE;
919 		/* Stop basic DMA. */
920 		ATA_OUTL(ch->r_mem, DMA_C, 0);
921 		goto end_finished;
922 	} else {			/* ATAPI PIO */
923 		length = ATA_INB(ch->r_mem,ATA_CYL_LSB) |
924 		    (ATA_INB(ch->r_mem,ATA_CYL_MSB) << 8);
925 		size = min(ch->transfersize, length);
926 		ireason = ATA_INB(ch->r_mem,ATA_IREASON);
927 		switch ((ireason & (ATA_I_CMD | ATA_I_IN)) |
928 			(status & ATA_S_DRQ)) {
929 
930 		case ATAPI_P_CMDOUT:
931 		    device_printf(dev, "ATAPI CMDOUT\n");
932 		    /* Return wait for interrupt */
933 		    return;
934 
935 		case ATAPI_P_WRITE:
936 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
937 			device_printf(dev, "trying to write on read buffer\n");
938 			et = MVS_ERR_TFE;
939 			goto end_finished;
940 			break;
941 		    }
942 		    ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
943 			(uint16_t *)(ccb->csio.data_ptr + ch->donecount),
944 			(size + 1) / 2);
945 		    for (resid = ch->transfersize + (size & 1);
946 			resid < length; resid += sizeof(int16_t))
947 			    ATA_OUTW(ch->r_mem, ATA_DATA, 0);
948 		    ch->donecount += length;
949 		    /* Set next transfer size according to HW capabilities */
950 		    ch->transfersize = min(ccb->csio.dxfer_len - ch->donecount,
951 			    ch->curr[ccb->ccb_h.target_id].bytecount);
952 		    /* Return wait for interrupt */
953 		    return;
954 
955 		case ATAPI_P_READ:
956 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
957 			device_printf(dev, "trying to read on write buffer\n");
958 			et = MVS_ERR_TFE;
959 			goto end_finished;
960 		    }
961 		    if (size >= 2) {
962 			ATA_INSW_STRM(ch->r_mem, ATA_DATA,
963 			    (uint16_t *)(ccb->csio.data_ptr + ch->donecount),
964 			    size / 2);
965 		    }
966 		    if (size & 1) {
967 			ATA_INSW_STRM(ch->r_mem, ATA_DATA, (void*)buf, 1);
968 			((uint8_t *)ccb->csio.data_ptr + ch->donecount +
969 			    (size & ~1))[0] = buf[0];
970 		    }
971 		    for (resid = ch->transfersize + (size & 1);
972 			resid < length; resid += sizeof(int16_t))
973 			    ATA_INW(ch->r_mem, ATA_DATA);
974 		    ch->donecount += length;
975 		    /* Set next transfer size according to HW capabilities */
976 		    ch->transfersize = min(ccb->csio.dxfer_len - ch->donecount,
977 			    ch->curr[ccb->ccb_h.target_id].bytecount);
978 		    /* Return wait for interrupt */
979 		    return;
980 
981 		case ATAPI_P_DONEDRQ:
982 		    device_printf(dev,
983 			  "WARNING - DONEDRQ non conformant device\n");
984 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
985 			ATA_INSW_STRM(ch->r_mem, ATA_DATA,
986 			    (uint16_t *)(ccb->csio.data_ptr + ch->donecount),
987 			    length / 2);
988 			ch->donecount += length;
989 		    }
990 		    else if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
991 			ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
992 			    (uint16_t *)(ccb->csio.data_ptr + ch->donecount),
993 			    length / 2);
994 			ch->donecount += length;
995 		    }
996 		    else
997 			et = MVS_ERR_TFE;
998 		    /* FALLTHROUGH */
999 
1000 		case ATAPI_P_ABORT:
1001 		case ATAPI_P_DONE:
1002 		    if (status & (ATA_S_ERROR | ATA_S_DWF))
1003 			et = MVS_ERR_TFE;
1004 		    goto end_finished;
1005 
1006 		default:
1007 		    device_printf(dev, "unknown transfer phase"
1008 			" (status %02x, ireason %02x)\n",
1009 			status, ireason);
1010 		    et = MVS_ERR_TFE;
1011 		}
1012 	}
1013 
1014 end_finished:
1015 	mvs_end_transaction(slot, et);
1016 }
1017 
1018 static void
1019 mvs_crbq_intr(device_t dev)
1020 {
1021 	struct mvs_channel *ch = device_get_softc(dev);
1022 	struct mvs_crpb *crpb;
1023 	union ccb *ccb;
1024 	int in_idx, fin_idx, cin_idx, slot;
1025 	uint32_t val;
1026 	uint16_t flags;
1027 
1028 	val = ATA_INL(ch->r_mem, EDMA_RESQIP);
1029 	if (val == 0)
1030 		val = ATA_INL(ch->r_mem, EDMA_RESQIP);
1031 	in_idx = (val & EDMA_RESQP_ERPQP_MASK) >>
1032 	    EDMA_RESQP_ERPQP_SHIFT;
1033 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
1034 	    BUS_DMASYNC_POSTREAD);
1035 	fin_idx = cin_idx = ch->in_idx;
1036 	ch->in_idx = in_idx;
1037 	while (in_idx != cin_idx) {
1038 		crpb = (struct mvs_crpb *)
1039 		    (ch->dma.workrp + MVS_CRPB_OFFSET +
1040 		    (MVS_CRPB_SIZE * cin_idx));
1041 		slot = le16toh(crpb->id) & MVS_CRPB_TAG_MASK;
1042 		flags = le16toh(crpb->rspflg);
1043 		/*
1044 		 * Handle only successfull completions here.
1045 		 * Errors will be handled by main intr handler.
1046 		 */
1047 #if defined(__i386__) || defined(__amd64__)
1048 		if (crpb->id == 0xffff && crpb->rspflg == 0xffff) {
1049 			device_printf(dev, "Unfilled CRPB "
1050 			    "%d (%d->%d) tag %d flags %04x rs %08x\n",
1051 			    cin_idx, fin_idx, in_idx, slot, flags, ch->rslots);
1052 		} else
1053 #endif
1054 		if (ch->numtslots != 0 ||
1055 		    (flags & EDMA_IE_EDEVERR) == 0) {
1056 #if defined(__i386__) || defined(__amd64__)
1057 			crpb->id = 0xffff;
1058 			crpb->rspflg = 0xffff;
1059 #endif
1060 			if (ch->slot[slot].state >= MVS_SLOT_RUNNING) {
1061 				ccb = ch->slot[slot].ccb;
1062 				ccb->ataio.res.status =
1063 				    (flags & MVS_CRPB_ATASTS_MASK) >>
1064 				    MVS_CRPB_ATASTS_SHIFT;
1065 				mvs_end_transaction(&ch->slot[slot], MVS_ERR_NONE);
1066 			} else {
1067 				device_printf(dev, "Unused tag in CRPB "
1068 				    "%d (%d->%d) tag %d flags %04x rs %08x\n",
1069 				    cin_idx, fin_idx, in_idx, slot, flags,
1070 				    ch->rslots);
1071 			}
1072 		} else {
1073 			device_printf(dev,
1074 			    "CRPB with error %d tag %d flags %04x\n",
1075 			    cin_idx, slot, flags);
1076 		}
1077 		cin_idx = (cin_idx + 1) & (MVS_MAX_SLOTS - 1);
1078 	}
1079 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
1080 	    BUS_DMASYNC_PREREAD);
1081 	if (cin_idx == ch->in_idx) {
1082 		ATA_OUTL(ch->r_mem, EDMA_RESQOP,
1083 		    ch->dma.workrp_bus | (cin_idx << EDMA_RESQP_ERPQP_SHIFT));
1084 	}
1085 }
1086 
1087 /* Must be called with channel locked. */
1088 static int
1089 mvs_check_collision(device_t dev, union ccb *ccb)
1090 {
1091 	struct mvs_channel *ch = device_get_softc(dev);
1092 
1093 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1094 		/* NCQ DMA */
1095 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1096 			/* Can't mix NCQ and non-NCQ DMA commands. */
1097 			if (ch->numdslots != 0)
1098 				return (1);
1099 			/* Can't mix NCQ and PIO commands. */
1100 			if (ch->numpslots != 0)
1101 				return (1);
1102 			/* If we have no FBS */
1103 			if (!ch->fbs_enabled) {
1104 				/* Tagged command while tagged to other target is active. */
1105 				if (ch->numtslots != 0 &&
1106 				    ch->taggedtarget != ccb->ccb_h.target_id)
1107 					return (1);
1108 			}
1109 		/* Non-NCQ DMA */
1110 		} else if (ccb->ataio.cmd.flags & CAM_ATAIO_DMA) {
1111 			/* Can't mix non-NCQ DMA and NCQ commands. */
1112 			if (ch->numtslots != 0)
1113 				return (1);
1114 			/* Can't mix non-NCQ DMA and PIO commands. */
1115 			if (ch->numpslots != 0)
1116 				return (1);
1117 		/* PIO */
1118 		} else {
1119 			/* Can't mix PIO with anything. */
1120 			if (ch->numrslots != 0)
1121 				return (1);
1122 		}
1123 		if (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)) {
1124 			/* Atomic command while anything active. */
1125 			if (ch->numrslots != 0)
1126 				return (1);
1127 		}
1128 	} else { /* ATAPI */
1129 		/* ATAPI goes without EDMA, so can't mix it with anything. */
1130 		if (ch->numrslots != 0)
1131 			return (1);
1132 	}
1133 	/* We have some atomic command running. */
1134 	if (ch->aslots != 0)
1135 		return (1);
1136 	return (0);
1137 }
1138 
1139 static void
1140 mvs_tfd_read(device_t dev, union ccb *ccb)
1141 {
1142 	struct mvs_channel *ch = device_get_softc(dev);
1143 	struct ata_res *res = &ccb->ataio.res;
1144 
1145 	res->status = ATA_INB(ch->r_mem, ATA_ALTSTAT);
1146 	res->error =  ATA_INB(ch->r_mem, ATA_ERROR);
1147 	res->device = ATA_INB(ch->r_mem, ATA_DRIVE);
1148 	ATA_OUTB(ch->r_mem, ATA_CONTROL, ATA_A_HOB);
1149 	res->sector_count_exp = ATA_INB(ch->r_mem, ATA_COUNT);
1150 	res->lba_low_exp = ATA_INB(ch->r_mem, ATA_SECTOR);
1151 	res->lba_mid_exp = ATA_INB(ch->r_mem, ATA_CYL_LSB);
1152 	res->lba_high_exp = ATA_INB(ch->r_mem, ATA_CYL_MSB);
1153 	ATA_OUTB(ch->r_mem, ATA_CONTROL, 0);
1154 	res->sector_count = ATA_INB(ch->r_mem, ATA_COUNT);
1155 	res->lba_low = ATA_INB(ch->r_mem, ATA_SECTOR);
1156 	res->lba_mid = ATA_INB(ch->r_mem, ATA_CYL_LSB);
1157 	res->lba_high = ATA_INB(ch->r_mem, ATA_CYL_MSB);
1158 }
1159 
1160 static void
1161 mvs_tfd_write(device_t dev, union ccb *ccb)
1162 {
1163 	struct mvs_channel *ch = device_get_softc(dev);
1164 	struct ata_cmd *cmd = &ccb->ataio.cmd;
1165 
1166 	ATA_OUTB(ch->r_mem, ATA_DRIVE, cmd->device);
1167 	ATA_OUTB(ch->r_mem, ATA_CONTROL, cmd->control);
1168 	ATA_OUTB(ch->r_mem, ATA_FEATURE, cmd->features_exp);
1169 	ATA_OUTB(ch->r_mem, ATA_FEATURE, cmd->features);
1170 	ATA_OUTB(ch->r_mem, ATA_COUNT, cmd->sector_count_exp);
1171 	ATA_OUTB(ch->r_mem, ATA_COUNT, cmd->sector_count);
1172 	ATA_OUTB(ch->r_mem, ATA_SECTOR, cmd->lba_low_exp);
1173 	ATA_OUTB(ch->r_mem, ATA_SECTOR, cmd->lba_low);
1174 	ATA_OUTB(ch->r_mem, ATA_CYL_LSB, cmd->lba_mid_exp);
1175 	ATA_OUTB(ch->r_mem, ATA_CYL_LSB, cmd->lba_mid);
1176 	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, cmd->lba_high_exp);
1177 	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, cmd->lba_high);
1178 	ATA_OUTB(ch->r_mem, ATA_COMMAND, cmd->command);
1179 }
1180 
1181 
1182 /* Must be called with channel locked. */
1183 static void
1184 mvs_begin_transaction(device_t dev, union ccb *ccb)
1185 {
1186 	struct mvs_channel *ch = device_get_softc(dev);
1187 	struct mvs_slot *slot;
1188 	int slotn, tag;
1189 
1190 	if (ch->pm_level > 0)
1191 		mvs_ch_pm_wake(dev);
1192 	/* Softreset is a special case. */
1193 	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1194 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1195 		mvs_softreset(dev, ccb);
1196 		return;
1197 	}
1198 	/* Choose empty slot. */
1199 	slotn = ffs(~ch->oslots) - 1;
1200 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1201 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1202 		if (ch->quirks & MVS_Q_GENIIE)
1203 			tag = ffs(~ch->otagspd[ccb->ccb_h.target_id]) - 1;
1204 		else
1205 			tag = slotn;
1206 	} else
1207 		tag = 0;
1208 	/* Occupy chosen slot. */
1209 	slot = &ch->slot[slotn];
1210 	slot->ccb = ccb;
1211 	slot->tag = tag;
1212 	/* Stop PM timer. */
1213 	if (ch->numrslots == 0 && ch->pm_level > 3)
1214 		callout_stop(&ch->pm_timer);
1215 	/* Update channel stats. */
1216 	ch->oslots |= (1 << slot->slot);
1217 	ch->numrslots++;
1218 	ch->numrslotspd[ccb->ccb_h.target_id]++;
1219 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1220 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1221 			ch->otagspd[ccb->ccb_h.target_id] |= (1 << slot->tag);
1222 			ch->numtslots++;
1223 			ch->numtslotspd[ccb->ccb_h.target_id]++;
1224 			ch->taggedtarget = ccb->ccb_h.target_id;
1225 			mvs_set_edma_mode(dev, MVS_EDMA_NCQ);
1226 		} else if (ccb->ataio.cmd.flags & CAM_ATAIO_DMA) {
1227 			ch->numdslots++;
1228 			mvs_set_edma_mode(dev, MVS_EDMA_ON);
1229 		} else {
1230 			ch->numpslots++;
1231 			mvs_set_edma_mode(dev, MVS_EDMA_OFF);
1232 		}
1233 		if (ccb->ataio.cmd.flags &
1234 		    (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)) {
1235 			ch->aslots |= (1 << slot->slot);
1236 		}
1237 	} else {
1238 		uint8_t *cdb = (ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1239 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes;
1240 		ch->numpslots++;
1241 		/* Use ATAPI DMA only for commands without under-/overruns. */
1242 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1243 		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA &&
1244 		    (ch->quirks & MVS_Q_SOC) == 0 &&
1245 		    (cdb[0] == 0x08 ||
1246 		     cdb[0] == 0x0a ||
1247 		     cdb[0] == 0x28 ||
1248 		     cdb[0] == 0x2a ||
1249 		     cdb[0] == 0x88 ||
1250 		     cdb[0] == 0x8a ||
1251 		     cdb[0] == 0xa8 ||
1252 		     cdb[0] == 0xaa ||
1253 		     cdb[0] == 0xbe)) {
1254 			ch->basic_dma = 1;
1255 		}
1256 		mvs_set_edma_mode(dev, MVS_EDMA_OFF);
1257 	}
1258 	if (ch->numpslots == 0 || ch->basic_dma) {
1259 		slot->state = MVS_SLOT_LOADING;
1260 		bus_dmamap_load_ccb(ch->dma.data_tag, slot->dma.data_map,
1261 		    ccb, mvs_dmasetprd, slot, 0);
1262 	} else
1263 		mvs_legacy_execute_transaction(slot);
1264 }
1265 
1266 /* Locked by busdma engine. */
1267 static void
1268 mvs_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1269 {
1270 	struct mvs_slot *slot = arg;
1271 	struct mvs_channel *ch = device_get_softc(slot->dev);
1272 	struct mvs_eprd *eprd;
1273 	int i;
1274 
1275 	if (error) {
1276 		device_printf(slot->dev, "DMA load error\n");
1277 		mvs_end_transaction(slot, MVS_ERR_INVALID);
1278 		return;
1279 	}
1280 	KASSERT(nsegs <= MVS_SG_ENTRIES, ("too many DMA segment entries\n"));
1281 	/* If there is only one segment - no need to use S/G table on Gen-IIe. */
1282 	if (nsegs == 1 && ch->basic_dma == 0 && (ch->quirks & MVS_Q_GENIIE)) {
1283 		slot->dma.addr = segs[0].ds_addr;
1284 		slot->dma.len = segs[0].ds_len;
1285 	} else {
1286 		slot->dma.addr = 0;
1287 		/* Get a piece of the workspace for this EPRD */
1288 		eprd = (struct mvs_eprd *)
1289 		    (ch->dma.workrq + MVS_EPRD_OFFSET + (MVS_EPRD_SIZE * slot->slot));
1290 		/* Fill S/G table */
1291 		for (i = 0; i < nsegs; i++) {
1292 			eprd[i].prdbal = htole32(segs[i].ds_addr);
1293 			eprd[i].bytecount = htole32(segs[i].ds_len & MVS_EPRD_MASK);
1294 			eprd[i].prdbah = htole32((segs[i].ds_addr >> 16) >> 16);
1295 		}
1296 		eprd[i - 1].bytecount |= htole32(MVS_EPRD_EOF);
1297 	}
1298 	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1299 	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1300 	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1301 	if (ch->basic_dma)
1302 		mvs_legacy_execute_transaction(slot);
1303 	else
1304 		mvs_execute_transaction(slot);
1305 }
1306 
1307 static void
1308 mvs_legacy_execute_transaction(struct mvs_slot *slot)
1309 {
1310 	device_t dev = slot->dev;
1311 	struct mvs_channel *ch = device_get_softc(dev);
1312 	bus_addr_t eprd;
1313 	union ccb *ccb = slot->ccb;
1314 	int port = ccb->ccb_h.target_id & 0x0f;
1315 	int timeout;
1316 
1317 	slot->state = MVS_SLOT_RUNNING;
1318 	ch->rslots |= (1 << slot->slot);
1319 	ATA_OUTB(ch->r_mem, SATA_SATAICTL, port << SATA_SATAICTL_PMPTX_SHIFT);
1320 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1321 		mvs_tfd_write(dev, ccb);
1322 		/* Device reset doesn't interrupt. */
1323 		if (ccb->ataio.cmd.command == ATA_DEVICE_RESET) {
1324 			int timeout = 1000000;
1325 			do {
1326 			    DELAY(10);
1327 			    ccb->ataio.res.status = ATA_INB(ch->r_mem, ATA_STATUS);
1328 			} while (ccb->ataio.res.status & ATA_S_BUSY && timeout--);
1329 			mvs_legacy_intr(dev, 1);
1330 			return;
1331 		}
1332 		ch->donecount = 0;
1333 		if (ccb->ataio.cmd.command == ATA_READ_MUL ||
1334 		    ccb->ataio.cmd.command == ATA_READ_MUL48 ||
1335 		    ccb->ataio.cmd.command == ATA_WRITE_MUL ||
1336 		    ccb->ataio.cmd.command == ATA_WRITE_MUL48) {
1337 			ch->transfersize = min(ccb->ataio.dxfer_len,
1338 			    ch->curr[port].bytecount);
1339 		} else
1340 			ch->transfersize = min(ccb->ataio.dxfer_len, 512);
1341 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE)
1342 			ch->fake_busy = 1;
1343 		/* If data write command - output the data */
1344 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1345 			if (mvs_wait(dev, ATA_S_DRQ, ATA_S_BUSY, 1000) < 0) {
1346 				device_printf(dev,
1347 				    "timeout waiting for write DRQ\n");
1348 				xpt_freeze_simq(ch->sim, 1);
1349 				ch->toslots |= (1 << slot->slot);
1350 				mvs_end_transaction(slot, MVS_ERR_TIMEOUT);
1351 				return;
1352 			}
1353 			ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
1354 			   (uint16_t *)(ccb->ataio.data_ptr + ch->donecount),
1355 			   ch->transfersize / 2);
1356 		}
1357 	} else {
1358 		ch->donecount = 0;
1359 		ch->transfersize = min(ccb->csio.dxfer_len,
1360 		    ch->curr[port].bytecount);
1361 		/* Write ATA PACKET command. */
1362 		if (ch->basic_dma) {
1363 			ATA_OUTB(ch->r_mem, ATA_FEATURE, ATA_F_DMA);
1364 			ATA_OUTB(ch->r_mem, ATA_CYL_LSB, 0);
1365 		    	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, 0);
1366 		} else {
1367 			ATA_OUTB(ch->r_mem, ATA_FEATURE, 0);
1368 			ATA_OUTB(ch->r_mem, ATA_CYL_LSB, ch->transfersize);
1369 		    	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, ch->transfersize >> 8);
1370 		}
1371 		ATA_OUTB(ch->r_mem, ATA_COMMAND, ATA_PACKET_CMD);
1372 		ch->fake_busy = 1;
1373 		/* Wait for ready to write ATAPI command block */
1374 		if (mvs_wait(dev, 0, ATA_S_BUSY, 1000) < 0) {
1375 			device_printf(dev, "timeout waiting for ATAPI !BUSY\n");
1376 			xpt_freeze_simq(ch->sim, 1);
1377 			ch->toslots |= (1 << slot->slot);
1378 			mvs_end_transaction(slot, MVS_ERR_TIMEOUT);
1379 			return;
1380 		}
1381 		timeout = 5000;
1382 		while (timeout--) {
1383 		    int reason = ATA_INB(ch->r_mem, ATA_IREASON);
1384 		    int status = ATA_INB(ch->r_mem, ATA_STATUS);
1385 
1386 		    if (((reason & (ATA_I_CMD | ATA_I_IN)) |
1387 			 (status & (ATA_S_DRQ | ATA_S_BUSY))) == ATAPI_P_CMDOUT)
1388 			break;
1389 		    DELAY(20);
1390 		}
1391 		if (timeout <= 0) {
1392 			device_printf(dev,
1393 			    "timeout waiting for ATAPI command ready\n");
1394 			xpt_freeze_simq(ch->sim, 1);
1395 			ch->toslots |= (1 << slot->slot);
1396 			mvs_end_transaction(slot, MVS_ERR_TIMEOUT);
1397 			return;
1398 		}
1399 		/* Write ATAPI command. */
1400 		ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
1401 		   (uint16_t *)((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1402 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes),
1403 		   ch->curr[port].atapi / 2);
1404 		DELAY(10);
1405 		if (ch->basic_dma) {
1406 			/* Start basic DMA. */
1407 			eprd = ch->dma.workrq_bus + MVS_EPRD_OFFSET +
1408 			    (MVS_EPRD_SIZE * slot->slot);
1409 			ATA_OUTL(ch->r_mem, DMA_DTLBA, eprd);
1410 			ATA_OUTL(ch->r_mem, DMA_DTHBA, (eprd >> 16) >> 16);
1411 			ATA_OUTL(ch->r_mem, DMA_C, DMA_C_START |
1412 			    (((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) ?
1413 			    DMA_C_READ : 0));
1414 		}
1415 	}
1416 	/* Start command execution timeout */
1417 	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 1000,
1418 	    (timeout_t*)mvs_timeout, slot);
1419 }
1420 
1421 /* Must be called with channel locked. */
1422 static void
1423 mvs_execute_transaction(struct mvs_slot *slot)
1424 {
1425 	device_t dev = slot->dev;
1426 	struct mvs_channel *ch = device_get_softc(dev);
1427 	bus_addr_t eprd;
1428 	struct mvs_crqb *crqb;
1429 	struct mvs_crqb_gen2e *crqb2e;
1430 	union ccb *ccb = slot->ccb;
1431 	int port = ccb->ccb_h.target_id & 0x0f;
1432 	int i;
1433 
1434 	/* Get address of the prepared EPRD */
1435 	eprd = ch->dma.workrq_bus + MVS_EPRD_OFFSET + (MVS_EPRD_SIZE * slot->slot);
1436 	/* Prepare CRQB. Gen IIe uses different CRQB format. */
1437 	if (ch->quirks & MVS_Q_GENIIE) {
1438 		crqb2e = (struct mvs_crqb_gen2e *)
1439 		    (ch->dma.workrq + MVS_CRQB_OFFSET + (MVS_CRQB_SIZE * ch->out_idx));
1440 		crqb2e->ctrlflg = htole32(
1441 		    ((ccb->ccb_h.flags & CAM_DIR_IN) ? MVS_CRQB2E_READ : 0) |
1442 		    (slot->tag << MVS_CRQB2E_DTAG_SHIFT) |
1443 		    (port << MVS_CRQB2E_PMP_SHIFT) |
1444 		    (slot->slot << MVS_CRQB2E_HTAG_SHIFT));
1445 		/* If there is only one segment - no need to use S/G table. */
1446 		if (slot->dma.addr != 0) {
1447 			eprd = slot->dma.addr;
1448 			crqb2e->ctrlflg |= htole32(MVS_CRQB2E_CPRD);
1449 			crqb2e->drbc = slot->dma.len;
1450 		}
1451 		crqb2e->cprdbl = htole32(eprd);
1452 		crqb2e->cprdbh = htole32((eprd >> 16) >> 16);
1453 		crqb2e->cmd[0] = 0;
1454 		crqb2e->cmd[1] = 0;
1455 		crqb2e->cmd[2] = ccb->ataio.cmd.command;
1456 		crqb2e->cmd[3] = ccb->ataio.cmd.features;
1457 		crqb2e->cmd[4] = ccb->ataio.cmd.lba_low;
1458 		crqb2e->cmd[5] = ccb->ataio.cmd.lba_mid;
1459 		crqb2e->cmd[6] = ccb->ataio.cmd.lba_high;
1460 		crqb2e->cmd[7] = ccb->ataio.cmd.device;
1461 		crqb2e->cmd[8] = ccb->ataio.cmd.lba_low_exp;
1462 		crqb2e->cmd[9] = ccb->ataio.cmd.lba_mid_exp;
1463 		crqb2e->cmd[10] = ccb->ataio.cmd.lba_high_exp;
1464 		crqb2e->cmd[11] = ccb->ataio.cmd.features_exp;
1465 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1466 			crqb2e->cmd[12] = slot->tag << 3;
1467 			crqb2e->cmd[13] = 0;
1468 		} else {
1469 			crqb2e->cmd[12] = ccb->ataio.cmd.sector_count;
1470 			crqb2e->cmd[13] = ccb->ataio.cmd.sector_count_exp;
1471 		}
1472 		crqb2e->cmd[14] = 0;
1473 		crqb2e->cmd[15] = 0;
1474 	} else {
1475 		crqb = (struct mvs_crqb *)
1476 		    (ch->dma.workrq + MVS_CRQB_OFFSET + (MVS_CRQB_SIZE * ch->out_idx));
1477 		crqb->cprdbl = htole32(eprd);
1478 		crqb->cprdbh = htole32((eprd >> 16) >> 16);
1479 		crqb->ctrlflg = htole16(
1480 		    ((ccb->ccb_h.flags & CAM_DIR_IN) ? MVS_CRQB_READ : 0) |
1481 		    (slot->slot << MVS_CRQB_TAG_SHIFT) |
1482 		    (port << MVS_CRQB_PMP_SHIFT));
1483 		i = 0;
1484 		/*
1485 		 * Controller can handle only 11 of 12 ATA registers,
1486 		 * so we have to choose which one to skip.
1487 		 */
1488 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1489 			crqb->cmd[i++] = ccb->ataio.cmd.features_exp;
1490 			crqb->cmd[i++] = 0x11;
1491 		}
1492 		crqb->cmd[i++] = ccb->ataio.cmd.features;
1493 		crqb->cmd[i++] = 0x11;
1494 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1495 			crqb->cmd[i++] = slot->tag << 3;
1496 			crqb->cmd[i++] = 0x12;
1497 		} else {
1498 			crqb->cmd[i++] = ccb->ataio.cmd.sector_count_exp;
1499 			crqb->cmd[i++] = 0x12;
1500 			crqb->cmd[i++] = ccb->ataio.cmd.sector_count;
1501 			crqb->cmd[i++] = 0x12;
1502 		}
1503 		crqb->cmd[i++] = ccb->ataio.cmd.lba_low_exp;
1504 		crqb->cmd[i++] = 0x13;
1505 		crqb->cmd[i++] = ccb->ataio.cmd.lba_low;
1506 		crqb->cmd[i++] = 0x13;
1507 		crqb->cmd[i++] = ccb->ataio.cmd.lba_mid_exp;
1508 		crqb->cmd[i++] = 0x14;
1509 		crqb->cmd[i++] = ccb->ataio.cmd.lba_mid;
1510 		crqb->cmd[i++] = 0x14;
1511 		crqb->cmd[i++] = ccb->ataio.cmd.lba_high_exp;
1512 		crqb->cmd[i++] = 0x15;
1513 		crqb->cmd[i++] = ccb->ataio.cmd.lba_high;
1514 		crqb->cmd[i++] = 0x15;
1515 		crqb->cmd[i++] = ccb->ataio.cmd.device;
1516 		crqb->cmd[i++] = 0x16;
1517 		crqb->cmd[i++] = ccb->ataio.cmd.command;
1518 		crqb->cmd[i++] = 0x97;
1519 	}
1520 	bus_dmamap_sync(ch->dma.workrq_tag, ch->dma.workrq_map,
1521 	    BUS_DMASYNC_PREWRITE);
1522 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
1523 	    BUS_DMASYNC_PREREAD);
1524 	slot->state = MVS_SLOT_RUNNING;
1525 	ch->rslots |= (1 << slot->slot);
1526 	/* Issue command to the controller. */
1527 	ch->out_idx = (ch->out_idx + 1) & (MVS_MAX_SLOTS - 1);
1528 	ATA_OUTL(ch->r_mem, EDMA_REQQIP,
1529 	    ch->dma.workrq_bus + MVS_CRQB_OFFSET + (MVS_CRQB_SIZE * ch->out_idx));
1530 	/* Start command execution timeout */
1531 	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 1000,
1532 	    (timeout_t*)mvs_timeout, slot);
1533 	return;
1534 }
1535 
1536 /* Must be called with channel locked. */
1537 static void
1538 mvs_process_timeout(device_t dev)
1539 {
1540 	struct mvs_channel *ch = device_get_softc(dev);
1541 	int i;
1542 
1543 	mtx_assert(&ch->mtx, MA_OWNED);
1544 	/* Handle the rest of commands. */
1545 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
1546 		/* Do we have a running request on slot? */
1547 		if (ch->slot[i].state < MVS_SLOT_RUNNING)
1548 			continue;
1549 		mvs_end_transaction(&ch->slot[i], MVS_ERR_TIMEOUT);
1550 	}
1551 }
1552 
1553 /* Must be called with channel locked. */
1554 static void
1555 mvs_rearm_timeout(device_t dev)
1556 {
1557 	struct mvs_channel *ch = device_get_softc(dev);
1558 	int i;
1559 
1560 	mtx_assert(&ch->mtx, MA_OWNED);
1561 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
1562 		struct mvs_slot *slot = &ch->slot[i];
1563 
1564 		/* Do we have a running request on slot? */
1565 		if (slot->state < MVS_SLOT_RUNNING)
1566 			continue;
1567 		if ((ch->toslots & (1 << i)) == 0)
1568 			continue;
1569 		callout_reset(&slot->timeout,
1570 		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1571 		    (timeout_t*)mvs_timeout, slot);
1572 	}
1573 }
1574 
1575 /* Locked by callout mechanism. */
1576 static void
1577 mvs_timeout(struct mvs_slot *slot)
1578 {
1579 	device_t dev = slot->dev;
1580 	struct mvs_channel *ch = device_get_softc(dev);
1581 
1582 	/* Check for stale timeout. */
1583 	if (slot->state < MVS_SLOT_RUNNING)
1584 		return;
1585 	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1586 	device_printf(dev, "iec %08x sstat %08x serr %08x edma_s %08x "
1587 	    "dma_c %08x dma_s %08x rs %08x status %02x\n",
1588 	    ATA_INL(ch->r_mem, EDMA_IEC),
1589 	    ATA_INL(ch->r_mem, SATA_SS), ATA_INL(ch->r_mem, SATA_SE),
1590 	    ATA_INL(ch->r_mem, EDMA_S), ATA_INL(ch->r_mem, DMA_C),
1591 	    ATA_INL(ch->r_mem, DMA_S), ch->rslots,
1592 	    ATA_INB(ch->r_mem, ATA_ALTSTAT));
1593 	/* Handle frozen command. */
1594 	mvs_requeue_frozen(dev);
1595 	/* We wait for other commands timeout and pray. */
1596 	if (ch->toslots == 0)
1597 		xpt_freeze_simq(ch->sim, 1);
1598 	ch->toslots |= (1 << slot->slot);
1599 	if ((ch->rslots & ~ch->toslots) == 0)
1600 		mvs_process_timeout(dev);
1601 	else
1602 		device_printf(dev, " ... waiting for slots %08x\n",
1603 		    ch->rslots & ~ch->toslots);
1604 }
1605 
1606 /* Must be called with channel locked. */
1607 static void
1608 mvs_end_transaction(struct mvs_slot *slot, enum mvs_err_type et)
1609 {
1610 	device_t dev = slot->dev;
1611 	struct mvs_channel *ch = device_get_softc(dev);
1612 	union ccb *ccb = slot->ccb;
1613 	int lastto;
1614 
1615 	bus_dmamap_sync(ch->dma.workrq_tag, ch->dma.workrq_map,
1616 	    BUS_DMASYNC_POSTWRITE);
1617 	/* Read result registers to the result struct
1618 	 * May be incorrect if several commands finished same time,
1619 	 * so read only when sure or have to.
1620 	 */
1621 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1622 		struct ata_res *res = &ccb->ataio.res;
1623 
1624 		if ((et == MVS_ERR_TFE) ||
1625 		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1626 			mvs_tfd_read(dev, ccb);
1627 		} else
1628 			bzero(res, sizeof(*res));
1629 	} else {
1630 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1631 		    ch->basic_dma == 0)
1632 			ccb->csio.resid = ccb->csio.dxfer_len - ch->donecount;
1633 	}
1634 	if (ch->numpslots == 0 || ch->basic_dma) {
1635 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1636 			bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1637 			    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1638 			    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1639 			bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1640 		}
1641 	}
1642 	if (et != MVS_ERR_NONE)
1643 		ch->eslots |= (1 << slot->slot);
1644 	/* In case of error, freeze device for proper recovery. */
1645 	if ((et != MVS_ERR_NONE) && (!ch->recoverycmd) &&
1646 	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1647 		xpt_freeze_devq(ccb->ccb_h.path, 1);
1648 		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1649 	}
1650 	/* Set proper result status. */
1651 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1652 	switch (et) {
1653 	case MVS_ERR_NONE:
1654 		ccb->ccb_h.status |= CAM_REQ_CMP;
1655 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1656 			ccb->csio.scsi_status = SCSI_STATUS_OK;
1657 		break;
1658 	case MVS_ERR_INVALID:
1659 		ch->fatalerr = 1;
1660 		ccb->ccb_h.status |= CAM_REQ_INVALID;
1661 		break;
1662 	case MVS_ERR_INNOCENT:
1663 		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1664 		break;
1665 	case MVS_ERR_TFE:
1666 	case MVS_ERR_NCQ:
1667 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1668 			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1669 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1670 		} else {
1671 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1672 		}
1673 		break;
1674 	case MVS_ERR_SATA:
1675 		ch->fatalerr = 1;
1676 		if (!ch->recoverycmd) {
1677 			xpt_freeze_simq(ch->sim, 1);
1678 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1679 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1680 		}
1681 		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1682 		break;
1683 	case MVS_ERR_TIMEOUT:
1684 		if (!ch->recoverycmd) {
1685 			xpt_freeze_simq(ch->sim, 1);
1686 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1687 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1688 		}
1689 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1690 		break;
1691 	default:
1692 		ch->fatalerr = 1;
1693 		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1694 	}
1695 	/* Free slot. */
1696 	ch->oslots &= ~(1 << slot->slot);
1697 	ch->rslots &= ~(1 << slot->slot);
1698 	ch->aslots &= ~(1 << slot->slot);
1699 	slot->state = MVS_SLOT_EMPTY;
1700 	slot->ccb = NULL;
1701 	/* Update channel stats. */
1702 	ch->numrslots--;
1703 	ch->numrslotspd[ccb->ccb_h.target_id]--;
1704 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1705 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1706 			ch->otagspd[ccb->ccb_h.target_id] &= ~(1 << slot->tag);
1707 			ch->numtslots--;
1708 			ch->numtslotspd[ccb->ccb_h.target_id]--;
1709 		} else if (ccb->ataio.cmd.flags & CAM_ATAIO_DMA) {
1710 			ch->numdslots--;
1711 		} else {
1712 			ch->numpslots--;
1713 		}
1714 	} else {
1715 		ch->numpslots--;
1716 		ch->basic_dma = 0;
1717 	}
1718 	/* Cancel timeout state if request completed normally. */
1719 	if (et != MVS_ERR_TIMEOUT) {
1720 		lastto = (ch->toslots == (1 << slot->slot));
1721 		ch->toslots &= ~(1 << slot->slot);
1722 		if (lastto)
1723 			xpt_release_simq(ch->sim, TRUE);
1724 	}
1725 	/* If it was our READ LOG command - process it. */
1726 	if (ccb->ccb_h.recovery_type == RECOVERY_READ_LOG) {
1727 		mvs_process_read_log(dev, ccb);
1728 	/* If it was our REQUEST SENSE command - process it. */
1729 	} else if (ccb->ccb_h.recovery_type == RECOVERY_REQUEST_SENSE) {
1730 		mvs_process_request_sense(dev, ccb);
1731 	/* If it was NCQ or ATAPI command error, put result on hold. */
1732 	} else if (et == MVS_ERR_NCQ ||
1733 	    ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR &&
1734 	     (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)) {
1735 		ch->hold[slot->slot] = ccb;
1736 		ch->holdtag[slot->slot] = slot->tag;
1737 		ch->numhslots++;
1738 	} else
1739 		xpt_done(ccb);
1740 	/* If we have no other active commands, ... */
1741 	if (ch->rslots == 0) {
1742 		/* if there was fatal error - reset port. */
1743 		if (ch->toslots != 0 || ch->fatalerr) {
1744 			mvs_reset(dev);
1745 		} else {
1746 			/* if we have slots in error, we can reinit port. */
1747 			if (ch->eslots != 0) {
1748 				mvs_set_edma_mode(dev, MVS_EDMA_OFF);
1749 				ch->eslots = 0;
1750 			}
1751 			/* if there commands on hold, we can do READ LOG. */
1752 			if (!ch->recoverycmd && ch->numhslots)
1753 				mvs_issue_recovery(dev);
1754 		}
1755 	/* If all the rest of commands are in timeout - give them chance. */
1756 	} else if ((ch->rslots & ~ch->toslots) == 0 &&
1757 	    et != MVS_ERR_TIMEOUT)
1758 		mvs_rearm_timeout(dev);
1759 	/* Unfreeze frozen command. */
1760 	if (ch->frozen && !mvs_check_collision(dev, ch->frozen)) {
1761 		union ccb *fccb = ch->frozen;
1762 		ch->frozen = NULL;
1763 		mvs_begin_transaction(dev, fccb);
1764 		xpt_release_simq(ch->sim, TRUE);
1765 	}
1766 	/* Start PM timer. */
1767 	if (ch->numrslots == 0 && ch->pm_level > 3 &&
1768 	    (ch->curr[ch->pm_present ? 15 : 0].caps & CTS_SATA_CAPS_D_PMREQ)) {
1769 		callout_schedule(&ch->pm_timer,
1770 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1771 	}
1772 }
1773 
1774 static void
1775 mvs_issue_recovery(device_t dev)
1776 {
1777 	struct mvs_channel *ch = device_get_softc(dev);
1778 	union ccb *ccb;
1779 	struct ccb_ataio *ataio;
1780 	struct ccb_scsiio *csio;
1781 	int i;
1782 
1783 	/* Find some held command. */
1784 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
1785 		if (ch->hold[i])
1786 			break;
1787 	}
1788 	ccb = xpt_alloc_ccb_nowait();
1789 	if (ccb == NULL) {
1790 		device_printf(dev, "Unable to allocate recovery command\n");
1791 completeall:
1792 		/* We can't do anything -- complete held commands. */
1793 		for (i = 0; i < MVS_MAX_SLOTS; i++) {
1794 			if (ch->hold[i] == NULL)
1795 				continue;
1796 			ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1797 			ch->hold[i]->ccb_h.status |= CAM_RESRC_UNAVAIL;
1798 			xpt_done(ch->hold[i]);
1799 			ch->hold[i] = NULL;
1800 			ch->numhslots--;
1801 		}
1802 		mvs_reset(dev);
1803 		return;
1804 	}
1805 	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
1806 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1807 		/* READ LOG */
1808 		ccb->ccb_h.recovery_type = RECOVERY_READ_LOG;
1809 		ccb->ccb_h.func_code = XPT_ATA_IO;
1810 		ccb->ccb_h.flags = CAM_DIR_IN;
1811 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1812 		ataio = &ccb->ataio;
1813 		ataio->data_ptr = malloc(512, M_MVS, M_NOWAIT);
1814 		if (ataio->data_ptr == NULL) {
1815 			xpt_free_ccb(ccb);
1816 			device_printf(dev,
1817 			    "Unable to allocate memory for READ LOG command\n");
1818 			goto completeall;
1819 		}
1820 		ataio->dxfer_len = 512;
1821 		bzero(&ataio->cmd, sizeof(ataio->cmd));
1822 		ataio->cmd.flags = CAM_ATAIO_48BIT;
1823 		ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1824 		ataio->cmd.sector_count = 1;
1825 		ataio->cmd.sector_count_exp = 0;
1826 		ataio->cmd.lba_low = 0x10;
1827 		ataio->cmd.lba_mid = 0;
1828 		ataio->cmd.lba_mid_exp = 0;
1829 	} else {
1830 		/* REQUEST SENSE */
1831 		ccb->ccb_h.recovery_type = RECOVERY_REQUEST_SENSE;
1832 		ccb->ccb_h.recovery_slot = i;
1833 		ccb->ccb_h.func_code = XPT_SCSI_IO;
1834 		ccb->ccb_h.flags = CAM_DIR_IN;
1835 		ccb->ccb_h.status = 0;
1836 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1837 		csio = &ccb->csio;
1838 		csio->data_ptr = (void *)&ch->hold[i]->csio.sense_data;
1839 		csio->dxfer_len = ch->hold[i]->csio.sense_len;
1840 		csio->cdb_len = 6;
1841 		bzero(&csio->cdb_io, sizeof(csio->cdb_io));
1842 		csio->cdb_io.cdb_bytes[0] = 0x03;
1843 		csio->cdb_io.cdb_bytes[4] = csio->dxfer_len;
1844 	}
1845 	/* Freeze SIM while doing recovery. */
1846 	ch->recoverycmd = 1;
1847 	xpt_freeze_simq(ch->sim, 1);
1848 	mvs_begin_transaction(dev, ccb);
1849 }
1850 
1851 static void
1852 mvs_process_read_log(device_t dev, union ccb *ccb)
1853 {
1854 	struct mvs_channel *ch = device_get_softc(dev);
1855 	uint8_t *data;
1856 	struct ata_res *res;
1857 	int i;
1858 
1859 	ch->recoverycmd = 0;
1860 
1861 	data = ccb->ataio.data_ptr;
1862 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1863 	    (data[0] & 0x80) == 0) {
1864 		for (i = 0; i < MVS_MAX_SLOTS; i++) {
1865 			if (!ch->hold[i])
1866 				continue;
1867 			if (ch->hold[i]->ccb_h.target_id != ccb->ccb_h.target_id)
1868 				continue;
1869 			if ((data[0] & 0x1F) == ch->holdtag[i]) {
1870 				res = &ch->hold[i]->ataio.res;
1871 				res->status = data[2];
1872 				res->error = data[3];
1873 				res->lba_low = data[4];
1874 				res->lba_mid = data[5];
1875 				res->lba_high = data[6];
1876 				res->device = data[7];
1877 				res->lba_low_exp = data[8];
1878 				res->lba_mid_exp = data[9];
1879 				res->lba_high_exp = data[10];
1880 				res->sector_count = data[12];
1881 				res->sector_count_exp = data[13];
1882 			} else {
1883 				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1884 				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1885 			}
1886 			xpt_done(ch->hold[i]);
1887 			ch->hold[i] = NULL;
1888 			ch->numhslots--;
1889 		}
1890 	} else {
1891 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1892 			device_printf(dev, "Error while READ LOG EXT\n");
1893 		else if ((data[0] & 0x80) == 0) {
1894 			device_printf(dev,
1895 			    "Non-queued command error in READ LOG EXT\n");
1896 		}
1897 		for (i = 0; i < MVS_MAX_SLOTS; i++) {
1898 			if (!ch->hold[i])
1899 				continue;
1900 			if (ch->hold[i]->ccb_h.target_id != ccb->ccb_h.target_id)
1901 				continue;
1902 			xpt_done(ch->hold[i]);
1903 			ch->hold[i] = NULL;
1904 			ch->numhslots--;
1905 		}
1906 	}
1907 	free(ccb->ataio.data_ptr, M_MVS);
1908 	xpt_free_ccb(ccb);
1909 	xpt_release_simq(ch->sim, TRUE);
1910 }
1911 
1912 static void
1913 mvs_process_request_sense(device_t dev, union ccb *ccb)
1914 {
1915 	struct mvs_channel *ch = device_get_softc(dev);
1916 	int i;
1917 
1918 	ch->recoverycmd = 0;
1919 
1920 	i = ccb->ccb_h.recovery_slot;
1921 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1922 		ch->hold[i]->ccb_h.status |= CAM_AUTOSNS_VALID;
1923 	} else {
1924 		ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1925 		ch->hold[i]->ccb_h.status |= CAM_AUTOSENSE_FAIL;
1926 	}
1927 	xpt_done(ch->hold[i]);
1928 	ch->hold[i] = NULL;
1929 	ch->numhslots--;
1930 	xpt_free_ccb(ccb);
1931 	xpt_release_simq(ch->sim, TRUE);
1932 }
1933 
1934 static int
1935 mvs_wait(device_t dev, u_int s, u_int c, int t)
1936 {
1937 	int timeout = 0;
1938 	uint8_t st;
1939 
1940 	while (((st =  mvs_getstatus(dev, 0)) & (s | c)) != s) {
1941 		if (timeout >= t) {
1942 			if (t != 0)
1943 				device_printf(dev, "Wait status %02x\n", st);
1944 			return (-1);
1945 		}
1946 		DELAY(1000);
1947 		timeout++;
1948 	}
1949 	return (timeout);
1950 }
1951 
1952 static void
1953 mvs_requeue_frozen(device_t dev)
1954 {
1955 	struct mvs_channel *ch = device_get_softc(dev);
1956 	union ccb *fccb = ch->frozen;
1957 
1958 	if (fccb) {
1959 		ch->frozen = NULL;
1960 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1961 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1962 			xpt_freeze_devq(fccb->ccb_h.path, 1);
1963 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1964 		}
1965 		xpt_done(fccb);
1966 	}
1967 }
1968 
1969 static void
1970 mvs_reset_to(void *arg)
1971 {
1972 	device_t dev = arg;
1973 	struct mvs_channel *ch = device_get_softc(dev);
1974 	int t;
1975 
1976 	if (ch->resetting == 0)
1977 		return;
1978 	ch->resetting--;
1979 	if ((t = mvs_wait(dev, 0, ATA_S_BUSY | ATA_S_DRQ, 0)) >= 0) {
1980 		if (bootverbose) {
1981 			device_printf(dev,
1982 			    "MVS reset: device ready after %dms\n",
1983 			    (310 - ch->resetting) * 100);
1984 		}
1985 		ch->resetting = 0;
1986 		xpt_release_simq(ch->sim, TRUE);
1987 		return;
1988 	}
1989 	if (ch->resetting == 0) {
1990 		device_printf(dev,
1991 		    "MVS reset: device not ready after 31000ms\n");
1992 		xpt_release_simq(ch->sim, TRUE);
1993 		return;
1994 	}
1995 	callout_schedule(&ch->reset_timer, hz / 10);
1996 }
1997 
1998 static void
1999 mvs_errata(device_t dev)
2000 {
2001 	struct mvs_channel *ch = device_get_softc(dev);
2002 	uint32_t val;
2003 
2004 	if (ch->quirks & MVS_Q_SOC65) {
2005 		val = ATA_INL(ch->r_mem, SATA_PHYM3);
2006 		val &= ~(0x3 << 27);	/* SELMUPF = 1 */
2007 		val |= (0x1 << 27);
2008 		val &= ~(0x3 << 29);	/* SELMUPI = 1 */
2009 		val |= (0x1 << 29);
2010 		ATA_OUTL(ch->r_mem, SATA_PHYM3, val);
2011 
2012 		val = ATA_INL(ch->r_mem, SATA_PHYM4);
2013 		val &= ~0x1;		/* SATU_OD8 = 0 */
2014 		val |= (0x1 << 16);	/* reserved bit 16 = 1 */
2015 		ATA_OUTL(ch->r_mem, SATA_PHYM4, val);
2016 
2017 		val = ATA_INL(ch->r_mem, SATA_PHYM9_GEN2);
2018 		val &= ~0xf;		/* TXAMP[3:0] = 8 */
2019 		val |= 0x8;
2020 		val &= ~(0x1 << 14);	/* TXAMP[4] = 0 */
2021 		ATA_OUTL(ch->r_mem, SATA_PHYM9_GEN2, val);
2022 
2023 		val = ATA_INL(ch->r_mem, SATA_PHYM9_GEN1);
2024 		val &= ~0xf;		/* TXAMP[3:0] = 8 */
2025 		val |= 0x8;
2026 		val &= ~(0x1 << 14);	/* TXAMP[4] = 0 */
2027 		ATA_OUTL(ch->r_mem, SATA_PHYM9_GEN1, val);
2028 	}
2029 }
2030 
2031 static void
2032 mvs_reset(device_t dev)
2033 {
2034 	struct mvs_channel *ch = device_get_softc(dev);
2035 	int i;
2036 
2037 	xpt_freeze_simq(ch->sim, 1);
2038 	if (bootverbose)
2039 		device_printf(dev, "MVS reset...\n");
2040 	/* Forget about previous reset. */
2041 	if (ch->resetting) {
2042 		ch->resetting = 0;
2043 		callout_stop(&ch->reset_timer);
2044 		xpt_release_simq(ch->sim, TRUE);
2045 	}
2046 	/* Requeue freezed command. */
2047 	mvs_requeue_frozen(dev);
2048 	/* Kill the engine and requeue all running commands. */
2049 	mvs_set_edma_mode(dev, MVS_EDMA_OFF);
2050 	ATA_OUTL(ch->r_mem, DMA_C, 0);
2051 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
2052 		/* Do we have a running request on slot? */
2053 		if (ch->slot[i].state < MVS_SLOT_RUNNING)
2054 			continue;
2055 		/* XXX; Commands in loading state. */
2056 		mvs_end_transaction(&ch->slot[i], MVS_ERR_INNOCENT);
2057 	}
2058 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
2059 		if (!ch->hold[i])
2060 			continue;
2061 		xpt_done(ch->hold[i]);
2062 		ch->hold[i] = NULL;
2063 		ch->numhslots--;
2064 	}
2065 	if (ch->toslots != 0)
2066 		xpt_release_simq(ch->sim, TRUE);
2067 	ch->eslots = 0;
2068 	ch->toslots = 0;
2069 	ch->fatalerr = 0;
2070 	ch->fake_busy = 0;
2071 	/* Tell the XPT about the event */
2072 	xpt_async(AC_BUS_RESET, ch->path, NULL);
2073 	ATA_OUTL(ch->r_mem, EDMA_IEM, 0);
2074 	ATA_OUTL(ch->r_mem, EDMA_CMD, EDMA_CMD_EATARST);
2075 	DELAY(25);
2076 	ATA_OUTL(ch->r_mem, EDMA_CMD, 0);
2077 	mvs_errata(dev);
2078 	/* Reset and reconnect PHY, */
2079 	if (!mvs_sata_phy_reset(dev)) {
2080 		if (bootverbose)
2081 			device_printf(dev, "MVS reset: device not found\n");
2082 		ch->devices = 0;
2083 		ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
2084 		ATA_OUTL(ch->r_mem, EDMA_IEC, 0);
2085 		ATA_OUTL(ch->r_mem, EDMA_IEM, ~EDMA_IE_TRANSIENT);
2086 		xpt_release_simq(ch->sim, TRUE);
2087 		return;
2088 	}
2089 	if (bootverbose)
2090 		device_printf(dev, "MVS reset: device found\n");
2091 	/* Wait for clearing busy status. */
2092 	if ((i = mvs_wait(dev, 0, ATA_S_BUSY | ATA_S_DRQ,
2093 	    dumping ? 31000 : 0)) < 0) {
2094 		if (dumping) {
2095 			device_printf(dev,
2096 			    "MVS reset: device not ready after 31000ms\n");
2097 		} else
2098 			ch->resetting = 310;
2099 	} else if (bootverbose)
2100 		device_printf(dev, "MVS reset: device ready after %dms\n", i);
2101 	ch->devices = 1;
2102 	ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
2103 	ATA_OUTL(ch->r_mem, EDMA_IEC, 0);
2104 	ATA_OUTL(ch->r_mem, EDMA_IEM, ~EDMA_IE_TRANSIENT);
2105 	if (ch->resetting)
2106 		callout_reset(&ch->reset_timer, hz / 10, mvs_reset_to, dev);
2107 	else
2108 		xpt_release_simq(ch->sim, TRUE);
2109 }
2110 
2111 static void
2112 mvs_softreset(device_t dev, union ccb *ccb)
2113 {
2114 	struct mvs_channel *ch = device_get_softc(dev);
2115 	int port = ccb->ccb_h.target_id & 0x0f;
2116 	int i, stuck;
2117 	uint8_t status;
2118 
2119 	mvs_set_edma_mode(dev, MVS_EDMA_OFF);
2120 	ATA_OUTB(ch->r_mem, SATA_SATAICTL, port << SATA_SATAICTL_PMPTX_SHIFT);
2121 	ATA_OUTB(ch->r_mem, ATA_CONTROL, ATA_A_RESET);
2122 	DELAY(10000);
2123 	ATA_OUTB(ch->r_mem, ATA_CONTROL, 0);
2124 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2125 	/* Wait for clearing busy status. */
2126 	if ((i = mvs_wait(dev, 0, ATA_S_BUSY, ccb->ccb_h.timeout)) < 0) {
2127 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
2128 		stuck = 1;
2129 	} else {
2130 		status = mvs_getstatus(dev, 0);
2131 		if (status & ATA_S_ERROR)
2132 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
2133 		else
2134 			ccb->ccb_h.status |= CAM_REQ_CMP;
2135 		if (status & ATA_S_DRQ)
2136 			stuck = 1;
2137 		else
2138 			stuck = 0;
2139 	}
2140 	mvs_tfd_read(dev, ccb);
2141 
2142 	/*
2143 	 * XXX: If some device on PMP failed to soft-reset,
2144 	 * try to recover by sending dummy soft-reset to PMP.
2145 	 */
2146 	if (stuck && ch->pm_present && port != 15) {
2147 		ATA_OUTB(ch->r_mem, SATA_SATAICTL,
2148 		    15 << SATA_SATAICTL_PMPTX_SHIFT);
2149 		ATA_OUTB(ch->r_mem, ATA_CONTROL, ATA_A_RESET);
2150 		DELAY(10000);
2151 		ATA_OUTB(ch->r_mem, ATA_CONTROL, 0);
2152 		mvs_wait(dev, 0, ATA_S_BUSY | ATA_S_DRQ, ccb->ccb_h.timeout);
2153 	}
2154 
2155 	xpt_done(ccb);
2156 }
2157 
2158 static int
2159 mvs_sata_connect(struct mvs_channel *ch)
2160 {
2161 	u_int32_t status;
2162 	int timeout, found = 0;
2163 
2164 	/* Wait up to 100ms for "connect well" */
2165 	for (timeout = 0; timeout < 1000 ; timeout++) {
2166 		status = ATA_INL(ch->r_mem, SATA_SS);
2167 		if ((status & SATA_SS_DET_MASK) != SATA_SS_DET_NO_DEVICE)
2168 			found = 1;
2169 		if (((status & SATA_SS_DET_MASK) == SATA_SS_DET_PHY_ONLINE) &&
2170 		    ((status & SATA_SS_SPD_MASK) != SATA_SS_SPD_NO_SPEED) &&
2171 		    ((status & SATA_SS_IPM_MASK) == SATA_SS_IPM_ACTIVE))
2172 			break;
2173 		if ((status & SATA_SS_DET_MASK) == SATA_SS_DET_PHY_OFFLINE) {
2174 			if (bootverbose) {
2175 				device_printf(ch->dev, "SATA offline status=%08x\n",
2176 				    status);
2177 			}
2178 			return (0);
2179 		}
2180 		if (found == 0 && timeout >= 100)
2181 			break;
2182 		DELAY(100);
2183 	}
2184 	if (timeout >= 1000 || !found) {
2185 		if (bootverbose) {
2186 			device_printf(ch->dev,
2187 			    "SATA connect timeout time=%dus status=%08x\n",
2188 			    timeout * 100, status);
2189 		}
2190 		return (0);
2191 	}
2192 	if (bootverbose) {
2193 		device_printf(ch->dev, "SATA connect time=%dus status=%08x\n",
2194 		    timeout * 100, status);
2195 	}
2196 	/* Clear SATA error register */
2197 	ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
2198 	return (1);
2199 }
2200 
2201 static int
2202 mvs_sata_phy_reset(device_t dev)
2203 {
2204 	struct mvs_channel *ch = device_get_softc(dev);
2205 	int sata_rev;
2206 	uint32_t val;
2207 
2208 	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2209 	if (sata_rev == 1)
2210 		val = SATA_SC_SPD_SPEED_GEN1;
2211 	else if (sata_rev == 2)
2212 		val = SATA_SC_SPD_SPEED_GEN2;
2213 	else if (sata_rev == 3)
2214 		val = SATA_SC_SPD_SPEED_GEN3;
2215 	else
2216 		val = 0;
2217 	ATA_OUTL(ch->r_mem, SATA_SC,
2218 	    SATA_SC_DET_RESET | val |
2219 	    SATA_SC_IPM_DIS_PARTIAL | SATA_SC_IPM_DIS_SLUMBER);
2220 	DELAY(1000);
2221 	ATA_OUTL(ch->r_mem, SATA_SC,
2222 	    SATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2223 	    (SATA_SC_IPM_DIS_PARTIAL | SATA_SC_IPM_DIS_SLUMBER)));
2224 	if (!mvs_sata_connect(ch)) {
2225 		if (ch->pm_level > 0)
2226 			ATA_OUTL(ch->r_mem, SATA_SC, SATA_SC_DET_DISABLE);
2227 		return (0);
2228 	}
2229 	return (1);
2230 }
2231 
2232 static int
2233 mvs_check_ids(device_t dev, union ccb *ccb)
2234 {
2235 	struct mvs_channel *ch = device_get_softc(dev);
2236 
2237 	if (ccb->ccb_h.target_id > ((ch->quirks & MVS_Q_GENI) ? 0 : 15)) {
2238 		ccb->ccb_h.status = CAM_TID_INVALID;
2239 		xpt_done(ccb);
2240 		return (-1);
2241 	}
2242 	if (ccb->ccb_h.target_lun != 0) {
2243 		ccb->ccb_h.status = CAM_LUN_INVALID;
2244 		xpt_done(ccb);
2245 		return (-1);
2246 	}
2247 	return (0);
2248 }
2249 
2250 static void
2251 mvsaction(struct cam_sim *sim, union ccb *ccb)
2252 {
2253 	device_t dev, parent;
2254 	struct mvs_channel *ch;
2255 
2256 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("mvsaction func_code=%x\n",
2257 	    ccb->ccb_h.func_code));
2258 
2259 	ch = (struct mvs_channel *)cam_sim_softc(sim);
2260 	dev = ch->dev;
2261 	switch (ccb->ccb_h.func_code) {
2262 	/* Common cases first */
2263 	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2264 	case XPT_SCSI_IO:
2265 		if (mvs_check_ids(dev, ccb))
2266 			return;
2267 		if (ch->devices == 0 ||
2268 		    (ch->pm_present == 0 &&
2269 		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
2270 			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2271 			break;
2272 		}
2273 		ccb->ccb_h.recovery_type = RECOVERY_NONE;
2274 		/* Check for command collision. */
2275 		if (mvs_check_collision(dev, ccb)) {
2276 			/* Freeze command. */
2277 			ch->frozen = ccb;
2278 			/* We have only one frozen slot, so freeze simq also. */
2279 			xpt_freeze_simq(ch->sim, 1);
2280 			return;
2281 		}
2282 		mvs_begin_transaction(dev, ccb);
2283 		return;
2284 	case XPT_EN_LUN:		/* Enable LUN as a target */
2285 	case XPT_TARGET_IO:		/* Execute target I/O request */
2286 	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
2287 	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
2288 	case XPT_ABORT:			/* Abort the specified CCB */
2289 		/* XXX Implement */
2290 		ccb->ccb_h.status = CAM_REQ_INVALID;
2291 		break;
2292 	case XPT_SET_TRAN_SETTINGS:
2293 	{
2294 		struct	ccb_trans_settings *cts = &ccb->cts;
2295 		struct	mvs_device *d;
2296 
2297 		if (mvs_check_ids(dev, ccb))
2298 			return;
2299 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2300 			d = &ch->curr[ccb->ccb_h.target_id];
2301 		else
2302 			d = &ch->user[ccb->ccb_h.target_id];
2303 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2304 			d->revision = cts->xport_specific.sata.revision;
2305 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2306 			d->mode = cts->xport_specific.sata.mode;
2307 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT) {
2308 			d->bytecount = min((ch->quirks & MVS_Q_GENIIE) ? 8192 : 2048,
2309 			    cts->xport_specific.sata.bytecount);
2310 		}
2311 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2312 			d->tags = min(MVS_MAX_SLOTS, cts->xport_specific.sata.tags);
2313 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2314 			ch->pm_present = cts->xport_specific.sata.pm_present;
2315 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
2316 			d->atapi = cts->xport_specific.sata.atapi;
2317 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
2318 			d->caps = cts->xport_specific.sata.caps;
2319 		ccb->ccb_h.status = CAM_REQ_CMP;
2320 		break;
2321 	}
2322 	case XPT_GET_TRAN_SETTINGS:
2323 	/* Get default/user set transfer settings for the target */
2324 	{
2325 		struct	ccb_trans_settings *cts = &ccb->cts;
2326 		struct  mvs_device *d;
2327 		uint32_t status;
2328 
2329 		if (mvs_check_ids(dev, ccb))
2330 			return;
2331 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2332 			d = &ch->curr[ccb->ccb_h.target_id];
2333 		else
2334 			d = &ch->user[ccb->ccb_h.target_id];
2335 		cts->protocol = PROTO_UNSPECIFIED;
2336 		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2337 		cts->transport = XPORT_SATA;
2338 		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2339 		cts->proto_specific.valid = 0;
2340 		cts->xport_specific.sata.valid = 0;
2341 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2342 		    (ccb->ccb_h.target_id == 15 ||
2343 		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2344 			status = ATA_INL(ch->r_mem, SATA_SS) & SATA_SS_SPD_MASK;
2345 			if (status & 0x0f0) {
2346 				cts->xport_specific.sata.revision =
2347 				    (status & 0x0f0) >> 4;
2348 				cts->xport_specific.sata.valid |=
2349 				    CTS_SATA_VALID_REVISION;
2350 			}
2351 			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
2352 //			if (ch->pm_level)
2353 //				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
2354 			cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_AN;
2355 			cts->xport_specific.sata.caps &=
2356 			    ch->user[ccb->ccb_h.target_id].caps;
2357 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2358 		} else {
2359 			cts->xport_specific.sata.revision = d->revision;
2360 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2361 			cts->xport_specific.sata.caps = d->caps;
2362 			if (cts->type == CTS_TYPE_CURRENT_SETTINGS/* &&
2363 			    (ch->quirks & MVS_Q_GENIIE) == 0*/)
2364 				cts->xport_specific.sata.caps &= ~CTS_SATA_CAPS_H_AN;
2365 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2366 		}
2367 		cts->xport_specific.sata.mode = d->mode;
2368 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2369 		cts->xport_specific.sata.bytecount = d->bytecount;
2370 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2371 		cts->xport_specific.sata.pm_present = ch->pm_present;
2372 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2373 		cts->xport_specific.sata.tags = d->tags;
2374 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2375 		cts->xport_specific.sata.atapi = d->atapi;
2376 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
2377 		ccb->ccb_h.status = CAM_REQ_CMP;
2378 		break;
2379 	}
2380 	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2381 	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2382 		mvs_reset(dev);
2383 		ccb->ccb_h.status = CAM_REQ_CMP;
2384 		break;
2385 	case XPT_TERM_IO:		/* Terminate the I/O process */
2386 		/* XXX Implement */
2387 		ccb->ccb_h.status = CAM_REQ_INVALID;
2388 		break;
2389 	case XPT_PATH_INQ:		/* Path routing inquiry */
2390 	{
2391 		struct ccb_pathinq *cpi = &ccb->cpi;
2392 
2393 		parent = device_get_parent(dev);
2394 		cpi->version_num = 1; /* XXX??? */
2395 		cpi->hba_inquiry = PI_SDTR_ABLE;
2396 		if (!(ch->quirks & MVS_Q_GENI)) {
2397 			cpi->hba_inquiry |= PI_SATAPM;
2398 			/* Gen-II is extremely slow with NCQ on PMP. */
2399 			if ((ch->quirks & MVS_Q_GENIIE) || ch->pm_present == 0)
2400 				cpi->hba_inquiry |= PI_TAG_ABLE;
2401 		}
2402 		cpi->target_sprt = 0;
2403 		cpi->hba_misc = PIM_SEQSCAN;
2404 		cpi->hba_eng_cnt = 0;
2405 		if (!(ch->quirks & MVS_Q_GENI))
2406 			cpi->max_target = 15;
2407 		else
2408 			cpi->max_target = 0;
2409 		cpi->max_lun = 0;
2410 		cpi->initiator_id = 0;
2411 		cpi->bus_id = cam_sim_bus(sim);
2412 		cpi->base_transfer_speed = 150000;
2413 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2414 		strncpy(cpi->hba_vid, "Marvell", HBA_IDLEN);
2415 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2416 		cpi->unit_number = cam_sim_unit(sim);
2417 		cpi->transport = XPORT_SATA;
2418 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2419 		cpi->protocol = PROTO_ATA;
2420 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2421 		cpi->maxio = MAXPHYS;
2422 		if ((ch->quirks & MVS_Q_SOC) == 0) {
2423 			cpi->hba_vendor = pci_get_vendor(parent);
2424 			cpi->hba_device = pci_get_device(parent);
2425 			cpi->hba_subvendor = pci_get_subvendor(parent);
2426 			cpi->hba_subdevice = pci_get_subdevice(parent);
2427 		}
2428 		cpi->ccb_h.status = CAM_REQ_CMP;
2429 		break;
2430 	}
2431 	default:
2432 		ccb->ccb_h.status = CAM_REQ_INVALID;
2433 		break;
2434 	}
2435 	xpt_done(ccb);
2436 }
2437 
2438 static void
2439 mvspoll(struct cam_sim *sim)
2440 {
2441 	struct mvs_channel *ch = (struct mvs_channel *)cam_sim_softc(sim);
2442 	struct mvs_intr_arg arg;
2443 
2444 	arg.arg = ch->dev;
2445 	arg.cause = 2 | 4; /* XXX */
2446 	mvs_ch_intr(&arg);
2447 	if (ch->resetting != 0 &&
2448 	    (--ch->resetpolldiv <= 0 || !callout_pending(&ch->reset_timer))) {
2449 		ch->resetpolldiv = 1000;
2450 		mvs_reset_to(ch->dev);
2451 	}
2452 }
2453 
2454