SILI - Get read log page 10 working, improve error handling.
[dragonfly.git] / sys / dev / disk / sili / sili.c
1 /*
2  * Copyright (c) 2009 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *
35  * Copyright (c) 2006 David Gwynne <dlg@openbsd.org>
36  *
37  * Permission to use, copy, modify, and distribute this software for any
38  * purpose with or without fee is hereby granted, provided that the above
39  * copyright notice and this permission notice appear in all copies.
40  *
41  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
42  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
43  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
44  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
45  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
46  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
47  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
48  *
49  *
50  *
51  * $OpenBSD: sili.c,v 1.147 2009/02/16 21:19:07 miod Exp $
52  */
53
54 #include "sili.h"
55
56 void    sili_port_interrupt_enable(struct sili_port *ap);
57 void    sili_port_interrupt_redisable(struct sili_port *ap);
58 void    sili_port_interrupt_reenable(struct sili_port *ap);
59
60 int     sili_load_prb(struct sili_ccb *);
61 void    sili_unload_prb(struct sili_ccb *);
62 static void sili_load_prb_callback(void *info, bus_dma_segment_t *segs,
63                                     int nsegs, int error);
64 void    sili_start(struct sili_ccb *);
65 int     sili_port_softreset(struct sili_port *ap);
66 int     sili_port_pmprobe(struct sili_port *ap);
67 int     sili_port_hardreset(struct sili_port *ap, int hard);
68 void    sili_port_hardstop(struct sili_port *ap);
69 void    sili_port_listen(struct sili_port *ap);
70
71 static void sili_ata_cmd_timeout_unserialized(void *);
72 static int sili_core_timeout(struct sili_ccb *ccb, int really_error);
73 void    sili_quick_timeout(struct sili_ccb *ccb);
74 void    sili_check_active_timeouts(struct sili_port *ap);
75
76 #if 0
77 void    sili_beg_exclusive_access(struct sili_port *ap, struct ata_port *at);
78 void    sili_end_exclusive_access(struct sili_port *ap, struct ata_port *at);
79 #endif
80 void    sili_issue_pending_commands(struct sili_port *ap, struct sili_ccb *ccb);
81
82 void    sili_port_read_ncq_error(struct sili_port *, int);
83
84 struct sili_dmamem *sili_dmamem_alloc(struct sili_softc *, bus_dma_tag_t tag);
85 void    sili_dmamem_free(struct sili_softc *, struct sili_dmamem *);
86 static void sili_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error);
87
88 static void sili_dummy_done(struct ata_xfer *xa);
89 static void sili_empty_done(struct sili_ccb *ccb);
90 static void sili_ata_cmd_done(struct sili_ccb *ccb);
91
92 /* Wait for all bits in _b to be cleared */
93 #define sili_pwait_clr(_ap, _r, _b) \
94         sili_pwait_eq((_ap), SILI_PWAIT_TIMEOUT, (_r), (_b), 0)
95 #define sili_pwait_clr_to(_ap, _to,  _r, _b) \
96         sili_pwait_eq((_ap), _to, (_r), (_b), 0)
97
98 /* Wait for all bits in _b to be set */
99 #define sili_pwait_set(_ap, _r, _b) \
100         sili_pwait_eq((_ap), SILI_PWAIT_TIMEOUT, (_r), (_b), (_b))
101 #define sili_pwait_set_to(_ap, _to, _r, _b) \
102         sili_pwait_eq((_ap), _to, (_r), (_b), (_b))
103
104 #define SILI_PWAIT_TIMEOUT      1000
105
106 /*
107  * Initialize the global SILI hardware.  This code does not set up any of
108  * its ports.
109  */
110 int
111 sili_init(struct sili_softc *sc)
112 {
113         DPRINTF(SILI_D_VERBOSE, " GHC 0x%b",
114                 sili_read(sc, SILI_REG_GHC), SILI_FMT_GHC);
115
116         /*
117          * Reset the entire chip.  This also resets all ports.
118          *
119          * The spec doesn't say anything about how long we have to
120          * wait, so wait 10ms.
121          */
122         sili_write(sc, SILI_REG_GCTL, SILI_REG_GCTL_GRESET);
123         sili_os_sleep(10);
124         sili_write(sc, SILI_REG_GCTL, 0);
125         sili_os_sleep(10);
126
127         return (0);
128 }
129
130 /*
131  * Allocate and initialize an SILI port.
132  */
133 int
134 sili_port_alloc(struct sili_softc *sc, u_int port)
135 {
136         struct sili_port        *ap;
137         struct ata_port         *at;
138         struct sili_prb         *prb;
139         struct sili_ccb         *ccb;
140         int     rc = ENOMEM;
141         int     error;
142         int     i;
143
144         ap = kmalloc(sizeof(*ap), M_DEVBUF, M_WAITOK | M_ZERO);
145
146         ksnprintf(ap->ap_name, sizeof(ap->ap_name), "%s%d.%d",
147                   device_get_name(sc->sc_dev),
148                   device_get_unit(sc->sc_dev),
149                   port);
150         sc->sc_ports[port] = ap;
151         kprintf("%s: allocate port\n", PORTNAME(ap));
152
153         /*
154          * Allocate enough so we never have to reallocate, it makes
155          * it easier.
156          *
157          * ap_pmcount will be reduced by the scan if we encounter the
158          * port multiplier port prior to target 15.
159          */
160         if (ap->ap_ata == NULL) {
161                 ap->ap_ata = kmalloc(sizeof(*ap->ap_ata) * SILI_MAX_PMPORTS,
162                                      M_DEVBUF, M_INTWAIT | M_ZERO);
163                 for (i = 0; i < SILI_MAX_PMPORTS; ++i) {
164                         at = &ap->ap_ata[i];
165                         at->at_sili_port = ap;
166                         at->at_target = i;
167                         at->at_probe = ATA_PROBE_NEED_INIT;
168                         at->at_features |= ATA_PORT_F_RESCAN;
169                         ksnprintf(at->at_name, sizeof(at->at_name),
170                                   "%s.%d", ap->ap_name, i);
171                 }
172         }
173         if (bus_space_subregion(sc->sc_piot, sc->sc_pioh,
174                                 SILI_PORT_REGION(port), SILI_PORT_SIZE,
175                                 &ap->ap_ioh) != 0) {
176                 device_printf(sc->sc_dev,
177                               "unable to create register window for port %d\n",
178                               port);
179                 goto freeport;
180         }
181
182         ap->ap_sc = sc;
183         ap->ap_num = port;
184         ap->ap_probe = ATA_PROBE_NEED_INIT;
185         TAILQ_INIT(&ap->ap_ccb_free);
186         TAILQ_INIT(&ap->ap_ccb_pending);
187         lockinit(&ap->ap_ccb_lock, "silipo", 0, 0);
188
189         /* Disable port interrupts */
190         sili_pwrite(ap, SILI_PREG_INT_DISABLE, SILI_PREG_INT_MASK);
191
192         /*
193          * Reset the port.  This is similar to a Device Reset but far
194          * more invasive.  We use Device Reset in our hardreset function.
195          * This function also does the same OOB initialization sequence
196          * that Device Reset does.
197          *
198          * NOTE: SILI_PREG_STATUS_READY will not be asserted unless and until
199          *       a device is connected to the port, so we can't use it to
200          *       verify that the port exists.
201          */
202         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_RESET);
203         if (sili_pread(ap, SILI_PREG_STATUS) & SILI_PREG_STATUS_READY) {
204                 device_printf(sc->sc_dev,
205                               "Port %d will not go into reset\n", port);
206                 goto freeport;
207         }
208         sili_os_sleep(10);
209         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESUME);
210         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESET);
211
212         /*
213          * Adjust FIFO thresholds to improve PCI-e use.
214          */
215         sili_pwrite(ap, SILI_PREG_FIFO_CTL,
216                 SILI_PREG_FIFO_CTL_ENCODE(1024, 1024));
217
218         /*
219          * Allocate the SGE Table
220          */
221         ap->ap_dmamem_prbs = sili_dmamem_alloc(sc, sc->sc_tag_prbs);
222         if (ap->ap_dmamem_prbs == NULL) {
223                 kprintf("%s: NOSGET\n", PORTNAME(ap));
224                 goto freeport;
225         }
226
227         /*
228          * Set up the SGE table base address
229          */
230         ap->ap_prbs = (struct sili_prb *)SILI_DMA_KVA(ap->ap_dmamem_prbs);
231
232         /*
233          * Allocate a CCB for each command slot
234          */
235         ap->ap_ccbs = kmalloc(sizeof(struct sili_ccb) * sc->sc_ncmds, M_DEVBUF,
236                               M_WAITOK | M_ZERO);
237         if (ap->ap_ccbs == NULL) {
238                 device_printf(sc->sc_dev,
239                               "unable to allocate command list for port %d\n",
240                               port);
241                 goto freeport;
242         }
243
244         /*
245          * Port control register setup.
246          */
247         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_NOAUTOCC);
248         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_32BITDMA |
249                                            SILI_PREG_CTL_PMA |
250                                            SILI_PREG_CTL_NOAUTOCC);
251
252         /*
253          * Most structures are in the port BAR.  Assign convenient
254          * pointers in the CCBs
255          */
256
257         for (i = 0; i < sc->sc_ncmds; i++) {
258                 ccb = &ap->ap_ccbs[i];
259
260                 error = bus_dmamap_create(sc->sc_tag_data, BUS_DMA_ALLOCNOW,
261                                           &ccb->ccb_dmamap);
262                 if (error) {
263                         device_printf(sc->sc_dev,
264                                       "unable to create dmamap for port %d "
265                                       "ccb %d\n", port, i);
266                         goto freeport;
267                 }
268
269                 /*
270                  * WARNING!!!  Access to the rfis is only allowed under very
271                  *             carefully controlled circumstances because it
272                  *             is located in the LRAM and reading from the
273                  *             LRAM has hardware issues which can blow the
274                  *             port up.  I kid you not (from Linux, and
275                  *             verified by testing here).
276                  */
277                 callout_init(&ccb->ccb_timeout);
278                 ccb->ccb_slot = i;
279                 ccb->ccb_port = ap;
280                 ccb->ccb_prb = &ap->ap_prbs[i];
281                 ccb->ccb_prb_paddr = SILI_DMA_DVA(ap->ap_dmamem_prbs) +
282                                      sizeof(*ccb->ccb_prb) * i;
283                 ccb->ccb_xa.fis = &ccb->ccb_prb->prb_h2d;
284                 prb = bus_space_kva(ap->ap_sc->sc_iot, ap->ap_ioh,
285                                     SILI_PREG_LRAM_SLOT(i));
286                 ccb->ccb_prb_lram = prb;
287                 /*
288                  * Point our rfis to host-memory instead of the LRAM PRB.
289                  * It will be copied back if ATA_F_AUTOSENSE is set.  The
290                  * LRAM PRB is buggy.
291                  */
292                 /*ccb->ccb_xa.rfis = &prb->prb_d2h;*/
293                 ccb->ccb_xa.rfis = (void *)ccb->ccb_xa.fis;
294
295                 ccb->ccb_xa.packetcmd = prb_packet(ccb->ccb_prb);
296                 ccb->ccb_xa.tag = i;
297
298                 ccb->ccb_xa.state = ATA_S_COMPLETE;
299
300                 /*
301                  * Reserve CCB[1] as the error CCB.  It doesn't matter
302                  * which one we use for the Sili controllers.
303                  */
304                 if (i == 1)
305                         ap->ap_err_ccb = ccb;
306                 else
307                         sili_put_ccb(ccb);
308         }
309         kprintf("%s: start port\n", PORTNAME(ap));
310         sili_os_start_port(ap);
311         return(0);
312 freeport:
313         sili_port_free(sc, port);
314         return (rc);
315 }
316
317 /*
318  * [re]initialize an idle port.  No CCBs should be active.
319  *
320  * If at is NULL we are initializing a directly connected port, otherwise
321  * we are indirectly initializing a port multiplier port.
322  *
323  * This function is called during the initial port allocation sequence
324  * and is also called on hot-plug insertion.  We take no chances and
325  * use a hardreset instead of a softreset.
326  *
327  * This function is the only way to move a failed port back to active
328  * status.
329  *
330  * Returns 0 if a device is successfully detected.
331  */
332 int
333 sili_port_init(struct sili_port *ap, struct ata_port *atx)
334 {
335         u_int32_t data;
336         int rc;
337
338         /*
339          * Clear all notification bits
340          */
341         if (atx == NULL && (ap->ap_sc->sc_flags & SILI_F_SSNTF))
342                 sili_pwrite(ap, SILI_PREG_SNTF, -1);
343
344         /*
345          * Make sure the port is out of continuous COMRESET mode.
346          */
347         data = SILI_PREG_SCTL_SPM_NONE |
348                SILI_PREG_SCTL_IPM_NONE |
349                SILI_PREG_SCTL_SPD_NONE |
350                SILI_PREG_SCTL_DET_NONE;
351         if (SiliForceGen1 & (1 << ap->ap_num)) {
352                 data &= ~SILI_PREG_SCTL_SPD_NONE;
353                 data |= SILI_PREG_SCTL_SPD_GEN1;
354         }
355         sili_pwrite(ap, SILI_PREG_SCTL, data);
356
357         /*
358          * Hard-reset the port.  If a device is detected but it is busy
359          * we try a second time, this time cycling the phy as well.
360          *
361          * XXX note: hard reset mode 2 (cycling the PHY) is not reliable.
362          */
363         if (atx)
364                 atx->at_probe = ATA_PROBE_NEED_HARD_RESET;
365         else
366                 ap->ap_probe = ATA_PROBE_NEED_HARD_RESET;
367
368         rc = sili_port_reset(ap, atx, 1);
369 #if 0
370         rc = sili_port_reset(ap, atx, 1);
371         if (rc == EBUSY) {
372                 rc = sili_port_reset(ap, atx, 2);
373         }
374 #endif
375
376         switch (rc) {
377         case ENODEV:
378                 /*
379                  * We had problems talking to the device on the port.
380                  */
381                 if (atx) {
382                         sili_pm_read(ap, atx->at_target,
383                                      SATA_PMREG_SSTS, &data);
384
385                         switch(data & SATA_PM_SSTS_DET) {
386                         case SATA_PM_SSTS_DET_DEV_NE:
387                                 kprintf("%s: Device not communicating\n",
388                                         ATANAME(ap, atx));
389                                 break;
390                         case SATA_PM_SSTS_DET_PHYOFFLINE:
391                                 kprintf("%s: PHY offline\n",
392                                         ATANAME(ap, atx));
393                                 break;
394                         default:
395                                 kprintf("%s: No device detected\n",
396                                         ATANAME(ap, atx));
397                                 break;
398                         }
399                 } else {
400                         data = sili_pread(ap, SILI_PREG_SSTS);
401
402                         switch(data & SATA_PM_SSTS_DET) {
403                         case SILI_PREG_SSTS_DET_DEV_NE:
404                                 kprintf("%s: Device not communicating\n",
405                                         ATANAME(ap, atx));
406                                 break;
407                         case SILI_PREG_SSTS_DET_OFFLINE:
408                                 kprintf("%s: PHY offline\n",
409                                         ATANAME(ap, atx));
410                                 break;
411                         default:
412                                 kprintf("%s: No device detected\n",
413                                         ATANAME(ap, atx));
414                                 break;
415                         }
416                 }
417                 break;
418
419         case EBUSY:
420                 /*
421                  * The device on the port is still telling us its busy,
422                  * which means that it is not properly handling a SATA
423                  * port COMRESET.
424                  *
425                  * It may be possible to softreset the device using CLO
426                  * and a device reset command.
427                  */
428                 if (atx) {
429                         kprintf("%s: Device on port is bricked, giving up\n",
430                                 ATANAME(ap, atx));
431                 } else {
432                         kprintf("%s: Device on port is bricked, "
433                                 "trying softreset\n", PORTNAME(ap));
434
435                         rc = sili_port_reset(ap, atx, 0);
436                         if (rc) {
437                                 kprintf("%s: Unable unbrick device\n",
438                                         PORTNAME(ap));
439                         } else {
440                                 kprintf("%s: Successfully unbricked\n",
441                                         PORTNAME(ap));
442                         }
443                 }
444                 break;
445
446         default:
447                 break;
448         }
449
450         /*
451          * Command transfers can only be enabled if a device was successfully
452          * detected.
453          *
454          * Allocate or deallocate the ap_ata array here too.
455          */
456         if (atx == NULL) {
457                 switch(ap->ap_type) {
458                 case ATA_PORT_T_NONE:
459                         ap->ap_pmcount = 0;
460                         break;
461                 case ATA_PORT_T_PM:
462                         /* already set */
463                         break;
464                 default:
465                         ap->ap_pmcount = 1;
466                         break;
467                 }
468         }
469
470         /*
471          * Flush interrupts on the port. XXX
472          *
473          * Enable interrupts on the port whether a device is sitting on
474          * it or not, to handle hot-plug events.
475          */
476         if (atx == NULL) {
477 #if 0
478                 sili_pwrite(ap, SILI_PREG_IS, sili_pread(ap, SILI_PREG_IS));
479                 sili_write(ap->ap_sc, SILI_REG_IS, 1 << ap->ap_num);
480 #endif
481                 sili_port_interrupt_enable(ap);
482         }
483         return(rc);
484 }
485
486 /*
487  * Handle an errored port.  This routine is called when the only
488  * commands left on the queue are expired, meaning we can safely
489  * go through a port init to clear its state.
490  *
491  * We complete the expired CCBs and then restart the queue.
492  */
493 static
494 void
495 sili_port_reinit(struct sili_port *ap)
496 {
497         struct sili_ccb *ccb;
498         struct ata_port *at;
499         int slot;
500         int target;
501         u_int32_t data;
502         int reentrant;
503
504         reentrant = (ap->ap_flags & AP_F_ERR_CCB_RESERVED) ? 1 : 0;
505
506         if (bootverbose) {
507                 kprintf("%s: reiniting port after error reent=%d "
508                         "expired=%08x\n",
509                         PORTNAME(ap), reentrant, ap->ap_expired);
510         }
511
512         /*
513          * Clear port resume, clear bits 16:13 in the port device status
514          * register.  This is from the data sheet.
515          *
516          * Data sheet does not specify a delay but it seems prudent.
517          */
518         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESUME);
519         sili_os_sleep(10);
520         for (target = 0; target < SILI_MAX_PMPORTS; ++target) {
521                 data = sili_pread(ap, SILI_PREG_PM_STATUS(target));
522                 data &= ~(SILI_PREG_PM_STATUS_SERVICE |
523                           SILI_PREG_PM_STATUS_LEGACY |
524                           SILI_PREG_PM_STATUS_NATIVE |
525                           SILI_PREG_PM_STATUS_VBSY);
526                 sili_pwrite(ap, SILI_PREG_PM_STATUS(target), data);
527                 sili_pwrite(ap, SILI_PREG_PM_QACTIVE(target), 0);
528         }
529
530         /*
531          * Issue a Port Initialize and wait for it to clear.  This flushes
532          * commands but does not reset the port.  Then wait for port ready.
533          */
534         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_INIT);
535         if (sili_pwait_clr(ap, SILI_PREG_STATUS, SILI_PREG_CTL_INIT)) {
536                 kprintf("%s: Unable to reinit, port failed\n",
537                         PORTNAME(ap));
538         }
539         if (sili_pwait_set(ap, SILI_PREG_STATUS, SILI_PREG_STATUS_READY)) {
540                 kprintf("%s: Unable to reinit, port will not come ready\n",
541                         PORTNAME(ap));
542         }
543
544         /*
545          * If reentrant, stop here.  Otherwise the state for the original
546          * ahci_port_reinit() will get ripped out from under it.
547          */
548         if (reentrant)
549                 return;
550
551         /*
552          * Read the LOG ERROR page for targets that returned a specific
553          * D2H FIS with ERR set.
554          */
555         for (target = 0; target < SILI_MAX_PMPORTS; ++target) {
556                 at = &ap->ap_ata[target];
557                 if (at->at_features & ATA_PORT_F_READLOG) {
558                         at->at_features &= ~ATA_PORT_F_READLOG;
559                         sili_port_read_ncq_error(ap, target);
560                 }
561         }
562
563         /*
564          * Finally clean out the expired commands, we've probed the error
565          * status (or hopefully probed the error status).  Well, ok,
566          * we probably didn't XXX.
567          */
568         while (ap->ap_expired) {
569                 slot = ffs(ap->ap_expired) - 1;
570                 ap->ap_expired &= ~(1 << slot);
571                 KKASSERT(ap->ap_active & (1 << slot));
572                 ap->ap_active &= ~(1 << slot);
573                 --ap->ap_active_cnt;
574                 ccb = &ap->ap_ccbs[slot];
575                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
576                 ccb->ccb_done(ccb);
577                 ccb->ccb_xa.complete(&ccb->ccb_xa);
578         }
579
580         /*
581          * Wow.  All done.  We can get the port moving again.
582          */
583         if (ap->ap_probe == ATA_PROBE_FAILED) {
584                 kprintf("%s: reinit failed, port is dead\n", PORTNAME(ap));
585                 while ((ccb = TAILQ_FIRST(&ap->ap_ccb_pending)) != NULL) {
586                         TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
587                         ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_DESIRED;
588                         ccb->ccb_xa.state = ATA_S_TIMEOUT;
589                         ccb->ccb_done(ccb);
590                         ccb->ccb_xa.complete(&ccb->ccb_xa);
591                 }
592         } else {
593                 sili_issue_pending_commands(ap, NULL);
594         }
595 }
596
597 /*
598  * Enable or re-enable interrupts on a port.
599  *
600  * This routine is called from the port initialization code or from the
601  * helper thread as the real interrupt may be forced to turn off certain
602  * interrupt sources.
603  */
604 void
605 sili_port_interrupt_enable(struct sili_port *ap)
606 {
607         u_int32_t data;
608
609         data =  SILI_PREG_INT_CCOMPLETE | SILI_PREG_INT_CERROR |
610                 SILI_PREG_INT_PHYRDYCHG | SILI_PREG_INT_DEVEXCHG |
611                 SILI_PREG_INT_DECODE | SILI_PREG_INT_CRC |
612                 SILI_PREG_INT_HANDSHK | SILI_PREG_INT_PMCHANGE;
613         if (ap->ap_sc->sc_flags & SILI_F_SSNTF)
614                 data |= SILI_PREG_INT_SDB;
615         sili_pwrite(ap, SILI_PREG_INT_ENABLE, data);
616 }
617
618 void
619 sili_port_interrupt_redisable(struct sili_port *ap)
620 {
621         u_int32_t data;
622
623         data = sili_read(ap->ap_sc, SILI_REG_GCTL);
624         data &= SILI_REG_GINT_PORTMASK;
625         data &= ~(1 << ap->ap_num);
626         sili_write(ap->ap_sc, SILI_REG_GCTL, data);
627 }
628
629 void
630 sili_port_interrupt_reenable(struct sili_port *ap)
631 {
632         u_int32_t data;
633
634         data = sili_read(ap->ap_sc, SILI_REG_GCTL);
635         data &= SILI_REG_GINT_PORTMASK;
636         data |= (1 << ap->ap_num);
637         sili_write(ap->ap_sc, SILI_REG_GCTL, data);
638 }
639
640 /*
641  * Run the port / target state machine from a main context.
642  *
643  * The state machine for the port is always run.
644  *
645  * If atx is non-NULL run the state machine for a particular target.
646  * If atx is NULL run the state machine for all targets.
647  */
648 void
649 sili_port_state_machine(struct sili_port *ap, int initial)
650 {
651         struct ata_port *at;
652         u_int32_t data;
653         int target;
654         int didsleep;
655         int loop;
656
657         /*
658          * State machine for port.  Note that CAM is not yet associated
659          * during the initial parallel probe and the port's probe state
660          * will not get past ATA_PROBE_NEED_IDENT.
661          */
662         {
663                 if (initial == 0 && ap->ap_probe <= ATA_PROBE_NEED_HARD_RESET) {
664                         kprintf("%s: Waiting 10 seconds on insertion\n",
665                                 PORTNAME(ap));
666                         sili_os_sleep(10000);
667                         initial = 1;
668                 }
669                 if (ap->ap_probe == ATA_PROBE_NEED_INIT)
670                         sili_port_init(ap, NULL);
671                 if (ap->ap_probe == ATA_PROBE_NEED_HARD_RESET)
672                         sili_port_reset(ap, NULL, 1);
673                 if (ap->ap_probe == ATA_PROBE_NEED_SOFT_RESET)
674                         sili_port_reset(ap, NULL, 0);
675                 if (ap->ap_probe == ATA_PROBE_NEED_IDENT)
676                         sili_cam_probe(ap, NULL);
677         }
678         if (ap->ap_type != ATA_PORT_T_PM) {
679                 if (ap->ap_probe == ATA_PROBE_FAILED) {
680                         sili_cam_changed(ap, NULL, 0);
681                 } else if (ap->ap_probe >= ATA_PROBE_NEED_IDENT) {
682                         sili_cam_changed(ap, NULL, 1);
683                 }
684                 return;
685         }
686
687         /*
688          * Port Multiplier state machine.
689          *
690          * Get a mask of changed targets and combine with any runnable
691          * states already present.
692          */
693         for (loop = 0; ;++loop) {
694                 if (sili_pm_read(ap, 15, SATA_PMREG_EINFO, &data)) {
695                         kprintf("%s: PM unable to read hot-plug bitmap\n",
696                                 PORTNAME(ap));
697                         break;
698                 }
699
700                 /*
701                  * Do at least one loop, then stop if no more state changes
702                  * have occured.  The PM might not generate a new
703                  * notification until we clear the entire bitmap.
704                  */
705                 if (loop && data == 0)
706                         break;
707
708                 /*
709                  * New devices showing up in the bitmap require some spin-up
710                  * time before we start probing them.  Reset didsleep.  The
711                  * first new device we detect will sleep before probing.
712                  *
713                  * This only applies to devices whos change bit is set in
714                  * the data, and does not apply to the initial boot-time
715                  * probe.
716                  */
717                 didsleep = 0;
718
719                 for (target = 0; target < ap->ap_pmcount; ++target) {
720                         at = &ap->ap_ata[target];
721
722                         /*
723                          * Check the target state for targets behind the PM
724                          * which have changed state.  This will adjust
725                          * at_probe and set ATA_PORT_F_RESCAN
726                          *
727                          * We want to wait at least 10 seconds before probing
728                          * a newly inserted device.  If the check status
729                          * indicates a device is present and in need of a
730                          * hard reset, we make sure we have slept before
731                          * continuing.
732                          *
733                          * We also need to wait at least 1 second for the
734                          * PHY state to change after insertion, if we
735                          * haven't already waited the 10 seconds.
736                          *
737                          * NOTE: When pm_check_good finds a good port it
738                          *       typically starts us in probe state
739                          *       NEED_HARD_RESET rather than INIT.
740                          */
741                         if (data & (1 << target)) {
742                                 if (initial == 0 && didsleep == 0)
743                                         sili_os_sleep(1000);
744                                 sili_pm_check_good(ap, target);
745                                 if (initial == 0 && didsleep == 0 &&
746                                     at->at_probe <= ATA_PROBE_NEED_HARD_RESET
747                                 ) {
748                                         didsleep = 1;
749                                         kprintf("%s: Waiting 10 seconds on insertion\n", PORTNAME(ap));
750                                         sili_os_sleep(10000);
751                                 }
752                         }
753
754                         /*
755                          * Report hot-plug events before the probe state
756                          * really gets hot.  Only actual events are reported
757                          * here to reduce spew.
758                          */
759                         if (data & (1 << target)) {
760                                 kprintf("%s: HOTPLUG (PM) - ", ATANAME(ap, at));
761                                 switch(at->at_probe) {
762                                 case ATA_PROBE_NEED_INIT:
763                                 case ATA_PROBE_NEED_HARD_RESET:
764                                         kprintf("Device inserted\n");
765                                         break;
766                                 case ATA_PROBE_FAILED:
767                                         kprintf("Device removed\n");
768                                         break;
769                                 default:
770                                         kprintf("Device probe in progress\n");
771                                         break;
772                                 }
773                         }
774
775                         /*
776                          * Run through the state machine as necessary if
777                          * the port is not marked failed.
778                          *
779                          * The state machine may stop at NEED_IDENT if
780                          * CAM is not yet attached.
781                          *
782                          * Acquire exclusive access to the port while we
783                          * are doing this.  This prevents command-completion
784                          * from queueing commands for non-polled targets
785                          * inbetween our probe steps.  We need to do this
786                          * because the reset probes can generate severe PHY
787                          * and protocol errors and soft-brick the port.
788                          */
789                         if (at->at_probe != ATA_PROBE_FAILED &&
790                             at->at_probe != ATA_PROBE_GOOD) {
791 #if 0
792                                 sili_beg_exclusive_access(ap, at);
793 #endif
794                                 if (at->at_probe == ATA_PROBE_NEED_INIT)
795                                         sili_port_init(ap, at);
796                                 if (at->at_probe == ATA_PROBE_NEED_HARD_RESET)
797                                         sili_port_reset(ap, at, 1);
798                                 if (at->at_probe == ATA_PROBE_NEED_SOFT_RESET)
799                                         sili_port_reset(ap, at, 0);
800                                 if (at->at_probe == ATA_PROBE_NEED_IDENT)
801                                         sili_cam_probe(ap, at);
802 #if 0
803                                 sili_end_exclusive_access(ap, at);
804 #endif
805                         }
806
807                         /*
808                          * Add or remove from CAM
809                          */
810                         if (at->at_features & ATA_PORT_F_RESCAN) {
811                                 at->at_features &= ~ATA_PORT_F_RESCAN;
812                                 if (at->at_probe == ATA_PROBE_FAILED) {
813                                         sili_cam_changed(ap, at, 0);
814                                 } else if (at->at_probe >= ATA_PROBE_NEED_IDENT) {
815                                         sili_cam_changed(ap, at, 1);
816                                 }
817                         }
818                         data &= ~(1 << target);
819                 }
820                 if (data) {
821                         kprintf("%s: WARNING (PM): extra bits set in "
822                                 "EINFO: %08x\n", PORTNAME(ap), data);
823                         while (target < SILI_MAX_PMPORTS) {
824                                 sili_pm_check_good(ap, target);
825                                 ++target;
826                         }
827                 }
828         }
829 }
830
831 /*
832  * De-initialize and detach a port.
833  */
834 void
835 sili_port_free(struct sili_softc *sc, u_int port)
836 {
837         struct sili_port                *ap = sc->sc_ports[port];
838         struct sili_ccb                 *ccb;
839
840         /*
841          * Ensure port is disabled and its interrupts are all flushed.
842          */
843         if (ap->ap_sc) {
844                 sili_os_stop_port(ap);
845                 sili_pwrite(ap, SILI_PREG_INT_DISABLE, SILI_PREG_INT_MASK);
846                 sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_RESET);
847                 sili_write(ap->ap_sc, SILI_REG_GCTL,
848                         sili_read(ap->ap_sc, SILI_REG_GCTL) &
849                         ~SILI_REG_GINT_PORTST(ap->ap_num));
850         }
851
852         if (ap->ap_ccbs) {
853                 while ((ccb = sili_get_ccb(ap)) != NULL) {
854                         if (ccb->ccb_dmamap) {
855                                 bus_dmamap_destroy(sc->sc_tag_data,
856                                                    ccb->ccb_dmamap);
857                                 ccb->ccb_dmamap = NULL;
858                         }
859                 }
860                 if ((ccb = ap->ap_err_ccb) != NULL) {
861                         if (ccb->ccb_dmamap) {
862                                 bus_dmamap_destroy(sc->sc_tag_data,
863                                                    ccb->ccb_dmamap);
864                                 ccb->ccb_dmamap = NULL;
865                         }
866                         ap->ap_err_ccb = NULL;
867                 }
868                 kfree(ap->ap_ccbs, M_DEVBUF);
869                 ap->ap_ccbs = NULL;
870         }
871
872         if (ap->ap_dmamem_prbs) {
873                 sili_dmamem_free(sc, ap->ap_dmamem_prbs);
874                 ap->ap_dmamem_prbs = NULL;
875         }
876         if (ap->ap_ata) {
877                 kfree(ap->ap_ata, M_DEVBUF);
878                 ap->ap_ata = NULL;
879         }
880
881         /* bus_space(9) says we dont free the subregions handle */
882
883         kfree(ap, M_DEVBUF);
884         sc->sc_ports[port] = NULL;
885 }
886
887 /*
888  * Reset a port.
889  *
890  * If hard is 0 perform a softreset of the port.
891  * If hard is 1 perform a hard reset of the port.
892  * If hard is 2 perform a hard reset of the port and cycle the phy.
893  *
894  * If at is non-NULL an indirect port via a port-multiplier is being
895  * reset, otherwise a direct port is being reset.
896  *
897  * NOTE: Indirect ports can only be soft-reset.
898  */
899 int
900 sili_port_reset(struct sili_port *ap, struct ata_port *at, int hard)
901 {
902         int rc;
903
904         if (hard) {
905                 if (at)
906                         rc = sili_pm_hardreset(ap, at->at_target, hard);
907                 else
908                         rc = sili_port_hardreset(ap, hard);
909         } else {
910                 if (at)
911                         rc = sili_pm_softreset(ap, at->at_target);
912                 else
913                         rc = sili_port_softreset(ap);
914         }
915         return(rc);
916 }
917
918 /*
919  * SILI soft reset, Section 10.4.1
920  *
921  * (at) will be NULL when soft-resetting a directly-attached device, and
922  * non-NULL when soft-resetting a device through a port multiplier.
923  *
924  * This function keeps port communications intact and attempts to generate
925  * a reset to the connected device using device commands.
926  */
927 int
928 sili_port_softreset(struct sili_port *ap)
929 {
930         struct sili_ccb         *ccb = NULL;
931         struct sili_prb         *prb;
932         int                     error;
933         u_int32_t               sig;
934
935         error = EIO;
936
937         kprintf("%s: START SOFTRESET\n", PORTNAME(ap));
938
939         DPRINTF(SILI_D_VERBOSE, "%s: soft reset\n", PORTNAME(ap));
940
941         crit_enter();
942         ap->ap_state = AP_S_NORMAL;
943
944         /*
945          * Prep the special soft-reset SII command.
946          */
947         ccb = sili_get_err_ccb(ap);
948         ccb->ccb_done = sili_empty_done;
949         ccb->ccb_xa.flags = ATA_F_POLL | ATA_F_AUTOSENSE | ATA_F_EXCLUSIVE;
950         ccb->ccb_xa.complete = sili_dummy_done;
951         ccb->ccb_xa.at = NULL;
952
953         prb = ccb->ccb_prb;
954         bzero(&prb->prb_h2d, sizeof(prb->prb_h2d));
955         prb->prb_h2d.flags = 0;
956         prb->prb_control = SILI_PRB_CTRL_SOFTRESET;
957         prb->prb_override = 0;
958
959         ccb->ccb_xa.state = ATA_S_PENDING;
960         ccb->ccb_xa.flags = 0;
961
962                                 /* XXX */
963         if (sili_poll(ccb, 8000, sili_quick_timeout) != ATA_S_COMPLETE) {
964                 kprintf("%s: First FIS failed\n", PORTNAME(ap));
965                 goto err;
966         }
967
968         sig = (prb->prb_d2h.lba_high << 24) |
969               (prb->prb_d2h.lba_mid << 16) |
970               (prb->prb_d2h.lba_low << 8) |
971               (prb->prb_d2h.sector_count);
972         kprintf("%s: SOFTRESET SIGNATURE %08x\n", PORTNAME(ap), sig);
973
974         /*
975          * If the softreset is trying to clear a BSY condition after a
976          * normal portreset we assign the port type.
977          *
978          * If the softreset is being run first as part of the ccb error
979          * processing code then report if the device signature changed
980          * unexpectedly.
981          */
982         if (ap->ap_type == ATA_PORT_T_NONE) {
983                 ap->ap_type = sili_port_signature(ap, NULL, sig);
984         } else {
985                 if (sili_port_signature(ap, NULL, sig) != ap->ap_type) {
986                         kprintf("%s: device signature unexpectedly "
987                                 "changed\n", PORTNAME(ap));
988                         error = EBUSY; /* XXX */
989                 }
990         }
991         error = 0;
992 err:
993         if (ccb != NULL) {
994                 sili_put_err_ccb(ccb);
995         }
996
997         /*
998          * If we failed to softreset make the port quiescent, otherwise
999          * make sure the port's start/stop state matches what it was on
1000          * entry.
1001          *
1002          * Don't kill the port if the softreset is on a port multiplier
1003          * target, that would kill all the targets!
1004          */
1005         kprintf("%s: END SOFTRESET %d prob=%d state=%d\n", PORTNAME(ap), error, ap->ap_probe, ap->ap_state);
1006         if (error) {
1007                 sili_port_hardstop(ap);
1008                 /* ap_probe set to failed */
1009         } else {
1010                 ap->ap_probe = ATA_PROBE_NEED_IDENT;
1011         }
1012         crit_exit();
1013
1014         if (bootverbose)
1015                 kprintf("%s: END SOFTRESET\n", PORTNAME(ap));
1016
1017         return (error);
1018 }
1019
1020 /*
1021  * SILI port reset, Section 10.4.2
1022  *
1023  * This function does a hard reset of the port.  Note that the device
1024  * connected to the port could still end-up hung.
1025  */
1026 int
1027 sili_port_hardreset(struct sili_port *ap, int hard)
1028 {
1029         u_int32_t r;
1030         int     error;
1031         int     loop;
1032
1033         DPRINTF(SILI_D_VERBOSE, "%s: port reset\n", PORTNAME(ap));
1034
1035         ap->ap_state = AP_S_NORMAL;
1036         error = 0;
1037
1038         /*
1039          * Issue Device Reset.
1040          *
1041          * NOTE:  Unlike Port Reset, the port ready signal will not
1042          *        go active unless a device is established to be on
1043          *        the port.
1044          */
1045         sili_pwrite(ap, SILI_PREG_SERR, -1);
1046         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_PMA);
1047         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESUME);
1048         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_DEVRESET);
1049         if (sili_pwait_clr(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_DEVRESET)) {
1050                 kprintf("%s: hardreset failed to clear\n", PORTNAME(ap));
1051         }
1052
1053         /*
1054          * Try to determine if there is a device on the port.
1055          *
1056          * Give the device 3/10 second to at least be detected.
1057          */
1058         loop = 300;
1059         while (loop > 0) {
1060                 r = sili_pread(ap, SILI_PREG_SSTS);
1061                 if (r & SILI_PREG_SSTS_DET)
1062                         break;
1063                 loop -= sili_os_softsleep();
1064         }
1065         if (loop <= 0) {
1066                 if (bootverbose) {
1067                         kprintf("%s: Port appears to be unplugged\n",
1068                                 PORTNAME(ap));
1069                 }
1070                 error = ENODEV;
1071         }
1072
1073         /*
1074          * There is something on the port.  Give the device 3 seconds
1075          * to fully negotiate.
1076          */
1077         if (error == 0 &&
1078             sili_pwait_eq(ap, 3000, SILI_PREG_SSTS,
1079                           SILI_PREG_SSTS_DET, SILI_PREG_SSTS_DET_DEV)) {
1080                 if (bootverbose) {
1081                         kprintf("%s: Device may be powered down\n",
1082                                 PORTNAME(ap));
1083                 }
1084                 error = ENODEV;
1085         }
1086
1087         /*
1088          * Wait for the port to become ready.
1089          *
1090          * This can take more then a second, give it 3 seconds.  If we
1091          * succeed give the device another 3ms after that.
1092          *
1093          * NOTE: Port multipliers can do two things here.  First they can
1094          *       return device-ready if a device is on target 0 and also
1095          *       return the signature for that device.  If there is no
1096          *       device on target 0 then BSY/DRQ is never cleared and
1097          *       it never comes ready.
1098          */
1099         if (error == 0 && sili_pwait_set_to(ap, 3000, SILI_PREG_STATUS,
1100                                             SILI_PREG_STATUS_READY)) {
1101                 /*
1102                  * The device is bricked or its a port multiplier and will
1103                  * not unbusy until we do the pmprobe CLO softreset sequence.
1104                  */
1105                 error = sili_port_pmprobe(ap);
1106                 if (error) {
1107                         kprintf("%s: Device will not come ready\n",
1108                                 PORTNAME(ap));
1109                 } else {
1110                         ap->ap_type = ATA_PORT_T_PM;
1111                 }
1112         } else if (error == 0) {
1113                 /*
1114                  * The sili's hardreset doesn't return a signature (does it)?
1115                  * In anycase, set the type so the signature gets set by
1116                  * the softreset stage.
1117                  */
1118                 error = sili_port_pmprobe(ap);
1119                 if (error) {
1120                         ap->ap_type = ATA_PORT_T_NONE;
1121                         error = 0;
1122                 } else {
1123                         ap->ap_type = ATA_PORT_T_PM;
1124                         kprintf("%s: Port multiplier detected\n",
1125                                 PORTNAME(ap));
1126                 }
1127         }
1128
1129         /*
1130          * hard-stop the port if we failed.  This will set ap_probe
1131          * to FAILED.
1132          */
1133         if (error) {
1134                 sili_port_hardstop(ap);
1135                 /* ap_probe set to failed */
1136         } else {
1137                 if (ap->ap_type == ATA_PORT_T_PM)
1138                         ap->ap_probe = ATA_PROBE_GOOD;
1139                 else
1140                         ap->ap_probe = ATA_PROBE_NEED_SOFT_RESET;
1141         }
1142         return (error);
1143 }
1144
1145 /*
1146  * SILI port multiplier probe.  This routine is run by the hardreset code
1147  * if it gets past the device detect.
1148  *
1149  * All we do here is call sili_pm_softreset().  The Sili chip does all the
1150  * hard work for us.
1151  *
1152  * Return 0 on success, non-zero on failure.
1153  */
1154 int
1155 sili_port_pmprobe(struct sili_port *ap)
1156 {
1157         struct ata_port *at;
1158         int error;
1159         int i;
1160
1161         /*
1162          * If we don't support port multipliers don't try to detect one.
1163          */
1164         if ((ap->ap_sc->sc_flags & SILI_F_SPM) == 0)
1165                 return (ENODEV);
1166
1167         /*
1168          * The port may be unhappy from its hardreset if there's a PM
1169          * but no device at target 0.  If we try to shove the softreset
1170          * for target 15 down its throat it will pop a gasket.
1171          *
1172          * Reiniting the port.. kind of a soft reset of its command
1173          * processor which otherwise does not effect the port registers,
1174          * seems to fix the problem.
1175          */
1176         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_PMA);
1177         sili_port_reinit(ap);
1178         ap->ap_state = AP_S_NORMAL;
1179         error = sili_pm_softreset(ap, 15);
1180         if (error == 0) {
1181                 ap->ap_ata[15].at_probe = ATA_PROBE_GOOD;
1182         } else {
1183                 error = EBUSY;
1184         }
1185
1186         kprintf("PMPROBE3 %d\n", error);
1187
1188         if (error == 0 && sili_pm_identify(ap)) {
1189                 kprintf("%s: PM - cannot identify port multiplier\n",
1190                         PORTNAME(ap));
1191                 error = EBUSY;
1192         }
1193         kprintf("PMPROBE3 %d %d %d\n", error, ap->ap_probe, ap->ap_state);
1194
1195         /*
1196          * If we probed the PM reset the state for the targets behind
1197          * it so they get probed by the state machine.
1198          */
1199         if (error == 0) {
1200                 for (i = 0; i < SILI_MAX_PMPORTS; ++i) {
1201                         at = &ap->ap_ata[i];
1202                         at->at_probe = ATA_PROBE_NEED_INIT;
1203                         at->at_features |= ATA_PORT_F_RESCAN;
1204                         at->at_features &= ~ATA_PORT_F_READLOG;
1205                 }
1206         }
1207
1208         /*
1209          * If we failed turn off PMA, otherwise identify the port multiplier.
1210          * CAM will iterate the devices.
1211          */
1212         if (error)
1213                 sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_PMA);
1214         return(error);
1215 }
1216
1217 /*
1218  * Hard-stop on hot-swap device removal.  See 10.10.1
1219  *
1220  * Place the port in a mode that will allow it to detect hot-swap insertions.
1221  * This is a bit imprecise because just setting-up SCTL to DET_INIT doesn't
1222  * seem to do the job.
1223  */
1224 void
1225 sili_port_hardstop(struct sili_port *ap)
1226 {
1227         struct sili_ccb *ccb;
1228         struct ata_port *at;
1229         int i;
1230         int slot;
1231
1232         ap->ap_state = AP_S_FATAL_ERROR;
1233         ap->ap_probe = ATA_PROBE_FAILED;
1234         ap->ap_type = ATA_PORT_T_NONE;
1235
1236         /*
1237          * Clean up AT sub-ports on SATA port.
1238          */
1239         for (i = 0; ap->ap_ata && i < SILI_MAX_PMPORTS; ++i) {
1240                 at = &ap->ap_ata[i];
1241                 at->at_type = ATA_PORT_T_NONE;
1242                 at->at_probe = ATA_PROBE_FAILED;
1243                 at->at_features &= ~ATA_PORT_F_READLOG;
1244         }
1245
1246         /*
1247          * Kill the port.  Don't bother waiting for it to transition
1248          * back up.
1249          */
1250         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_RESET);
1251         if (sili_pread(ap, SILI_PREG_STATUS) & SILI_PREG_STATUS_READY) {
1252                 kprintf("%s: Port will not go into reset\n",
1253                         PORTNAME(ap));
1254         }
1255         sili_os_sleep(10);
1256         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESUME);
1257         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESET);
1258
1259         /*
1260          * Turn off port-multiplier control bit
1261          */
1262         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_PMA);
1263
1264         /*
1265          * Clean up the command list.
1266          */
1267         while (ap->ap_active) {
1268                 slot = ffs(ap->ap_active) - 1;
1269                 ap->ap_active &= ~(1 << slot);
1270                 ap->ap_expired &= ~(1 << slot);
1271                 --ap->ap_active_cnt;
1272                 ccb = &ap->ap_ccbs[slot];
1273                 if (ccb->ccb_xa.flags & ATA_F_TIMEOUT_RUNNING) {
1274                         callout_stop(&ccb->ccb_timeout);
1275                         ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_RUNNING;
1276                 }
1277                 ccb->ccb_xa.flags &= ~(ATA_F_TIMEOUT_DESIRED |
1278                                        ATA_F_TIMEOUT_EXPIRED);
1279                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
1280                 ccb->ccb_done(ccb);
1281                 ccb->ccb_xa.complete(&ccb->ccb_xa);
1282         }
1283         while ((ccb = TAILQ_FIRST(&ap->ap_ccb_pending)) != NULL) {
1284                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
1285                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
1286                 ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_DESIRED;
1287                 ccb->ccb_done(ccb);
1288                 ccb->ccb_xa.complete(&ccb->ccb_xa);
1289         }
1290         KKASSERT(ap->ap_active_cnt == 0);
1291
1292         /*
1293          * Put the port into a listen mode, we want to get insertion/removal
1294          * events.
1295          */
1296         sili_port_listen(ap);
1297 }
1298
1299 /*
1300  * Place port into a listen mode for hotplug events only.  The port has
1301  * already been reset and the command processor may not be ready due
1302  * to the lack of a device.
1303  */
1304 void
1305 sili_port_listen(struct sili_port *ap)
1306 {
1307         u_int32_t data;
1308
1309 #if 1
1310         data = SILI_PREG_SCTL_SPM_NONE |
1311                SILI_PREG_SCTL_IPM_NONE |
1312                SILI_PREG_SCTL_SPD_NONE |
1313                SILI_PREG_SCTL_DET_INIT;
1314         if (SiliForceGen1 & (1 << ap->ap_num)) {
1315                 data &= ~SILI_PREG_SCTL_SPD_NONE;
1316                 data |= SILI_PREG_SCTL_SPD_GEN1;
1317         }
1318 #endif
1319         sili_pwrite(ap, SILI_PREG_SERR, -1);
1320         sili_pwrite(ap, SILI_PREG_INT_ENABLE, SILI_PREG_INT_PHYRDYCHG |
1321                                               SILI_PREG_INT_DEVEXCHG);
1322 }
1323
1324 /*
1325  * Figure out what type of device is connected to the port, ATAPI or
1326  * DISK.
1327  */
1328 int
1329 sili_port_signature(struct sili_port *ap, struct ata_port *at, u_int32_t sig)
1330 {
1331         if (bootverbose)
1332                 kprintf("%s: sig %08x\n", ATANAME(ap, at), sig);
1333         if ((sig & 0xffff0000) == (SATA_SIGNATURE_ATAPI & 0xffff0000)) {
1334                 return(ATA_PORT_T_ATAPI);
1335         } else if ((sig & 0xffff0000) ==
1336                  (SATA_SIGNATURE_PORT_MULTIPLIER & 0xffff0000)) {
1337                 return(ATA_PORT_T_PM);
1338         } else {
1339                 return(ATA_PORT_T_DISK);
1340         }
1341 }
1342
1343 /*
1344  * Load the DMA descriptor table for a CCB's buffer.
1345  *
1346  * NOTE: ATA_F_PIO is auto-selected by sili part.
1347  */
1348 int
1349 sili_load_prb(struct sili_ccb *ccb)
1350 {
1351         struct sili_port                *ap = ccb->ccb_port;
1352         struct sili_softc               *sc = ap->ap_sc;
1353         struct ata_xfer                 *xa = &ccb->ccb_xa;
1354         struct sili_prb                 *prb = ccb->ccb_prb;
1355         struct sili_sge                 *sge;
1356         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
1357         int                             error;
1358
1359         /*
1360          * Set up the PRB.  The PRB contains 2 SGE's (1 if it is an ATAPI
1361          * command).  The SGE must be set up to link to the rest of our
1362          * SGE array, in blocks of four SGEs (a SGE table) starting at
1363          */
1364         prb->prb_xfer_count = 0;
1365         prb->prb_control = 0;
1366         prb->prb_override = 0;
1367         sge = (ccb->ccb_xa.flags & ATA_F_PACKET) ?
1368                 &prb->prb_sge_packet : &prb->prb_sge_normal;
1369         if (xa->datalen == 0) {
1370                 sge->sge_flags = SILI_SGE_FLAGS_TRM | SILI_SGE_FLAGS_DRD;
1371                 sge->sge_count = 0;
1372                 return (0);
1373         }
1374
1375         if (ccb->ccb_xa.flags & ATA_F_READ)
1376                 prb->prb_control |= SILI_PRB_CTRL_READ;
1377         if (ccb->ccb_xa.flags & ATA_F_WRITE)
1378                 prb->prb_control |= SILI_PRB_CTRL_WRITE;
1379         sge->sge_flags = SILI_SGE_FLAGS_LNK;
1380         sge->sge_count = 0;
1381         sge->sge_paddr = ccb->ccb_prb_paddr +
1382                          offsetof(struct sili_prb, prb_sge[0]);
1383
1384         /*
1385          * Load our sge array.
1386          */
1387         error = bus_dmamap_load(sc->sc_tag_data, dmap,
1388                                 xa->data, xa->datalen,
1389                                 sili_load_prb_callback,
1390                                 ccb,
1391                                 ((xa->flags & ATA_F_NOWAIT) ?
1392                                     BUS_DMA_NOWAIT : BUS_DMA_WAITOK));
1393         if (error != 0) {
1394                 kprintf("%s: error %d loading dmamap\n", PORTNAME(ap), error);
1395                 return (1);
1396         }
1397
1398         bus_dmamap_sync(sc->sc_tag_data, dmap,
1399                         (xa->flags & ATA_F_READ) ?
1400                             BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
1401
1402         return (0);
1403
1404 #ifdef DIAGNOSTIC
1405 diagerr:
1406         bus_dmamap_unload(sc->sc_tag_data, dmap);
1407         return (1);
1408 #endif
1409 }
1410
1411 /*
1412  * Callback from BUSDMA system to load the segment list.
1413  *
1414  * The scatter/gather table is loaded by the sili chip in blocks of
1415  * four SGE's.  If a continuance is required the last entry in each
1416  * block must point to the next block.
1417  */
1418 static
1419 void
1420 sili_load_prb_callback(void *info, bus_dma_segment_t *segs, int nsegs,
1421                         int error)
1422 {
1423         struct sili_ccb *ccb = info;
1424         struct sili_sge *sge;
1425         int sgi;
1426
1427         KKASSERT(nsegs <= SILI_MAX_SGET);
1428
1429         sgi = 0;
1430         sge = &ccb->ccb_prb->prb_sge[0];
1431         while (nsegs) {
1432                 if ((sgi & 3) == 3) {
1433                         sge->sge_paddr = htole64(ccb->ccb_prb_paddr +
1434                                                  offsetof(struct sili_prb,
1435                                                         prb_sge[sgi + 1]));
1436                         sge->sge_count = 0;
1437                         sge->sge_flags = SILI_SGE_FLAGS_LNK;
1438                 } else {
1439                         sge->sge_paddr = htole64(segs->ds_addr);
1440                         sge->sge_count = htole32(segs->ds_len);
1441                         sge->sge_flags = 0;
1442                         --nsegs;
1443                         ++segs;
1444                 }
1445                 ++sge;
1446                 ++sgi;
1447         }
1448         --sge;
1449         sge->sge_flags |= SILI_SGE_FLAGS_TRM;
1450 }
1451
1452 void
1453 sili_unload_prb(struct sili_ccb *ccb)
1454 {
1455         struct sili_port                *ap = ccb->ccb_port;
1456         struct sili_softc               *sc = ap->ap_sc;
1457         struct ata_xfer                 *xa = &ccb->ccb_xa;
1458         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
1459
1460         if (xa->datalen != 0) {
1461                 bus_dmamap_sync(sc->sc_tag_data, dmap,
1462                                 (xa->flags & ATA_F_READ) ?
1463                                 BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1464
1465                 bus_dmamap_unload(sc->sc_tag_data, dmap);
1466
1467                 if (ccb->ccb_xa.flags & ATA_F_NCQ)
1468                         xa->resid = 0;
1469                 else
1470                         xa->resid = xa->datalen -
1471                                     le32toh(ccb->ccb_prb->prb_xfer_count);
1472         }
1473 }
1474
1475 /*
1476  * Start a command and poll for completion.
1477  *
1478  * timeout is in ms and only counts once the command gets on-chip.
1479  *
1480  * Returns ATA_S_* state, compare against ATA_S_COMPLETE to determine
1481  * that no error occured.
1482  *
1483  * NOTE: If the caller specifies a NULL timeout function the caller is
1484  *       responsible for clearing hardware state on failure, but we will
1485  *       deal with removing the ccb from any pending queue.
1486  *
1487  * NOTE: NCQ should never be used with this function.
1488  *
1489  * NOTE: If the port is in a failed state and stopped we do not try
1490  *       to activate the ccb.
1491  */
1492 int
1493 sili_poll(struct sili_ccb *ccb, int timeout,
1494           void (*timeout_fn)(struct sili_ccb *))
1495 {
1496         struct sili_port *ap = ccb->ccb_port;
1497
1498         if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR) {
1499                 ccb->ccb_xa.state = ATA_S_ERROR;
1500                 return(ccb->ccb_xa.state);
1501         }
1502
1503         sili_start(ccb);
1504
1505         do {
1506                 sili_port_intr(ap, 1);
1507                 switch(ccb->ccb_xa.state) {
1508                 case ATA_S_ONCHIP:
1509                         timeout -= sili_os_softsleep();
1510                         break;
1511                 case ATA_S_PENDING:
1512                         /*
1513                          * The packet can get stuck on the pending queue
1514                          * if the port refuses to come ready.  XXX
1515                          */
1516 #if 0
1517                         if (xxx AP_F_EXCLUSIVE_ACCESS)
1518                                 timeout -= sili_os_softsleep();
1519                         else
1520 #endif
1521                                 sili_os_softsleep();
1522                         sili_check_active_timeouts(ap);
1523                         break;
1524                 default:
1525                         return (ccb->ccb_xa.state);
1526                 }
1527         } while (timeout > 0);
1528
1529         kprintf("%s: Poll timeout slot %d\n",
1530                 ATANAME(ap, ccb->ccb_xa.at),
1531                 ccb->ccb_slot);
1532
1533         timeout_fn(ccb);
1534
1535         return(ccb->ccb_xa.state);
1536 }
1537
1538 /*
1539  * When polling we have to check if the currently active CCB(s)
1540  * have timed out as the callout will be deadlocked while we
1541  * hold the port lock.
1542  */
1543 void
1544 sili_check_active_timeouts(struct sili_port *ap)
1545 {
1546         struct sili_ccb *ccb;
1547         u_int32_t mask;
1548         int tag;
1549
1550         mask = ap->ap_active;
1551         while (mask) {
1552                 tag = ffs(mask) - 1;
1553                 mask &= ~(1 << tag);
1554                 ccb = &ap->ap_ccbs[tag];
1555                 if (ccb->ccb_xa.flags & ATA_F_TIMEOUT_EXPIRED) {
1556                         sili_core_timeout(ccb, 0);
1557                 }
1558         }
1559 }
1560
1561 static
1562 __inline
1563 void
1564 sili_start_timeout(struct sili_ccb *ccb)
1565 {
1566         if (ccb->ccb_xa.flags & ATA_F_TIMEOUT_DESIRED) {
1567                 ccb->ccb_xa.flags |= ATA_F_TIMEOUT_RUNNING;
1568                 callout_reset(&ccb->ccb_timeout,
1569                               (ccb->ccb_xa.timeout * hz + 999) / 1000,
1570                               sili_ata_cmd_timeout_unserialized, ccb);
1571         }
1572 }
1573
1574 void
1575 sili_start(struct sili_ccb *ccb)
1576 {
1577         struct sili_port                *ap = ccb->ccb_port;
1578 #if 0
1579         struct sili_softc               *sc = ap->ap_sc;
1580 #endif
1581
1582         KKASSERT(ccb->ccb_xa.state == ATA_S_PENDING);
1583
1584         /*
1585          * Sync our SGE table and PRB
1586          */
1587         bus_dmamap_sync(ap->ap_dmamem_prbs->adm_tag,
1588                         ap->ap_dmamem_prbs->adm_map,
1589                         BUS_DMASYNC_PREWRITE);
1590
1591         /*
1592          * XXX dmamap for PRB XXX  BUS_DMASYNC_PREWRITE
1593          */
1594
1595         /*
1596          * Controller will update shared memory!
1597          * XXX bus_dmamap_sync ... BUS_DMASYNC_PREREAD ...
1598          */
1599         /* Prepare RFIS area for write by controller */
1600
1601         /*
1602          * There's no point trying to optimize this, it only shaves a few
1603          * nanoseconds so just queue the command and call our generic issue.
1604          */
1605         sili_issue_pending_commands(ap, ccb);
1606 }
1607
1608 #if 0
1609 /*
1610  * While holding the port lock acquire exclusive access to the port.
1611  *
1612  * This is used when running the state machine to initialize and identify
1613  * targets over a port multiplier.  Setting exclusive access prevents
1614  * sili_port_intr() from activating any requests sitting on the pending
1615  * queue.
1616  */
1617 void
1618 sili_beg_exclusive_access(struct sili_port *ap, struct ata_port *at)
1619 {
1620         KKASSERT((ap->ap_flags & AP_F_EXCLUSIVE_ACCESS) == 0);
1621         ap->ap_flags |= AP_F_EXCLUSIVE_ACCESS;
1622         while (ap->ap_active) {
1623                 sili_port_intr(ap, 1);
1624                 sili_os_softsleep();
1625         }
1626 }
1627
1628 void
1629 sili_end_exclusive_access(struct sili_port *ap, struct ata_port *at)
1630 {
1631         KKASSERT((ap->ap_flags & AP_F_EXCLUSIVE_ACCESS) != 0);
1632         ap->ap_flags &= ~AP_F_EXCLUSIVE_ACCESS;
1633         sili_issue_pending_commands(ap, NULL);
1634 }
1635 #endif
1636
1637 /*
1638  * If ccb is not NULL enqueue and/or issue it.
1639  *
1640  * If ccb is NULL issue whatever we can from the queue.  However, nothing
1641  * new is issued if the exclusive access flag is set or expired ccb's are
1642  * present.
1643  *
1644  * If existing commands are still active (ap_active) we can only
1645  * issue matching new commands.
1646  */
1647 void
1648 sili_issue_pending_commands(struct sili_port *ap, struct sili_ccb *ccb)
1649 {
1650         /*
1651          * Enqueue the ccb.
1652          *
1653          * If just running the queue and in exclusive access mode we
1654          * just return.  Also in this case if there are any expired ccb's
1655          * we want to clear the queue so the port can be safely stopped.
1656          *
1657          * XXX sili chip - expiration needs to be per-target if PM supports
1658          *      FBSS?
1659          */
1660         if (ccb) {
1661                 TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
1662         } else if (ap->ap_expired) {
1663                 return;
1664         }
1665
1666         /*
1667          * Pull the next ccb off the queue and run it if possible.
1668          * If the port is not ready to accept commands enable the
1669          * ready interrupt instead of starting a new command.
1670          *
1671          * XXX limit ncqdepth for attached devices behind PM
1672          */
1673         while ((ccb = TAILQ_FIRST(&ap->ap_ccb_pending)) != NULL) {
1674                 /*
1675                  * Port may be wedged.
1676                  */
1677                 if ((sili_pread(ap, SILI_PREG_STATUS) &
1678                     SILI_PREG_STATUS_READY) == 0) {
1679                         kprintf("%s: slot %d NOT READY\n",
1680                                 ATANAME(ap, ccb->ccb_xa.at), ccb->ccb_slot);
1681                         sili_pwrite(ap, SILI_PREG_INT_ENABLE,
1682                                     SILI_PREG_INT_READY);
1683                         break;
1684                 }
1685
1686                 /*
1687                  * Handle exclusivity requirements.  ATA_F_EXCLUSIVE is used
1688                  * when we may have to access the rfis which is stored in
1689                  * the LRAM PRB.  Unfortunately reading the LRAM PRB is
1690                  * highly problematic, so requests (like PM requests) which
1691                  * need to access the rfis use exclusive mode and then
1692                  * access the copy made by the port interrupt code back in
1693                  * host memory.
1694                  */
1695                 if (ap->ap_active & ~ap->ap_expired) {
1696                         /*
1697                          * There may be multiple ccb's already running,
1698                          * but there will only be one if it is exclusive.
1699                          * We can't queue a new command in that case.
1700                          *
1701                          * XXX Current AUTOSENSE code forces exclusivity
1702                          *     to simplify the code.
1703                          */
1704                         KKASSERT(ap->ap_last_ccb);
1705                         KKASSERT(ap->ap_active &
1706                                  (1 << ap->ap_last_ccb->ccb_slot));
1707                         if (ap->ap_last_ccb->ccb_xa.flags &
1708                             (ATA_F_EXCLUSIVE | ATA_F_AUTOSENSE)) {
1709                                 break;
1710                         }
1711
1712                         /*
1713                          * If the ccb we want to run is exclusive and ccb's
1714                          * are still active on the port, we can't queue it
1715                          * yet.
1716                          *
1717                          * XXX Current AUTOSENSE code forces exclusivity
1718                          *     to simplify the code.
1719                          */
1720                         if (ccb->ccb_xa.flags &
1721                             (ATA_F_EXCLUSIVE | ATA_F_AUTOSENSE)) {
1722                                 break;
1723                         }
1724                 }
1725
1726                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
1727                 ccb->ccb_xa.state = ATA_S_ONCHIP;
1728                 ap->ap_active |= 1 << ccb->ccb_slot;
1729                 ap->ap_active_cnt++;
1730                 ap->ap_last_ccb = ccb;
1731
1732                 /*
1733                  * We can't use the CMD_FIFO method because it requires us
1734                  * building the PRB in the LRAM, and the LRAM is buggy.  So
1735                  * we use host memory for the PRB.
1736                  */
1737                 sili_pwrite(ap, SILI_PREG_CMDACT(ccb->ccb_slot),
1738                             (u_int32_t)ccb->ccb_prb_paddr);
1739                 sili_pwrite(ap, SILI_PREG_CMDACT(ccb->ccb_slot) + 4,
1740                             (u_int32_t)(ccb->ccb_prb_paddr >> 32));
1741                 /* sili_pwrite(ap, SILI_PREG_CMD_FIFO, ccb->ccb_slot); */
1742                 sili_start_timeout(ccb);
1743         }
1744 }
1745
1746 void
1747 sili_intr(void *arg)
1748 {
1749         struct sili_softc       *sc = arg;
1750         struct sili_port        *ap;
1751         u_int32_t               gint;
1752         int                     port;
1753
1754         /*
1755          * Check if the master enable is up, and whether any interrupts are
1756          * pending.
1757          *
1758          * Clear the ints we got.
1759          */
1760         if ((sc->sc_flags & SILI_F_INT_GOOD) == 0)
1761                 return;
1762         gint = sili_read(sc, SILI_REG_GINT);
1763         if (gint == 0 || gint == 0xffffffff)
1764                 return;
1765         sili_write(sc, SILI_REG_GINT, gint);
1766
1767         /*
1768          * Process interrupts for each port in a non-blocking fashion.
1769          */
1770         while (gint & SILI_REG_GINT_PORTMASK) {
1771                 port = ffs(gint) - 1;
1772                 ap = sc->sc_ports[port];
1773                 if (ap) {
1774                         if (sili_os_lock_port_nb(ap) == 0) {
1775                                 sili_port_intr(ap, 0);
1776                                 sili_os_unlock_port(ap);
1777                         } else {
1778                                 sili_port_interrupt_redisable(ap);
1779                                 sili_os_signal_port_thread(ap, AP_SIGF_PORTINT);
1780                         }
1781                 }
1782                 gint &= ~(1 << port);
1783         }
1784 }
1785
1786 /*
1787  * Core called from helper thread.
1788  */
1789 void
1790 sili_port_thread_core(struct sili_port *ap, int mask)
1791 {
1792         /*
1793          * Process any expired timedouts.
1794          */
1795         sili_os_lock_port(ap);
1796         if (mask & AP_SIGF_TIMEOUT) {
1797                 sili_check_active_timeouts(ap);
1798         }
1799
1800         /*
1801          * Process port interrupts which require a higher level of
1802          * intervention.
1803          */
1804         if (mask & AP_SIGF_PORTINT) {
1805                 sili_port_intr(ap, 1);
1806                 sili_port_interrupt_reenable(ap);
1807                 sili_os_unlock_port(ap);
1808         } else {
1809                 sili_os_unlock_port(ap);
1810         }
1811 }
1812
1813 /*
1814  * Core per-port interrupt handler.
1815  *
1816  * If blockable is 0 we cannot call sili_os_sleep() at all and we can only
1817  * deal with normal command completions which do not require blocking.
1818  */
1819 void
1820 sili_port_intr(struct sili_port *ap, int blockable)
1821 {
1822         struct sili_softc       *sc = ap->ap_sc;
1823         u_int32_t               is;
1824         int                     slot;
1825         struct sili_ccb         *ccb = NULL;
1826         struct ata_port         *ccb_at = NULL;
1827 #ifdef DIAGNOSTIC
1828         u_int32_t               tmp;
1829 #endif
1830         u_int32_t               active;
1831         const u_int32_t         blockable_mask = SILI_PREG_IST_PHYRDYCHG |
1832                                                  SILI_PREG_IST_DEVEXCHG |
1833                                                  SILI_PREG_IST_CERROR |
1834                                                  SILI_PREG_IST_DECODE |
1835                                                  SILI_PREG_IST_CRC |
1836                                                  SILI_PREG_IST_HANDSHK;
1837         const u_int32_t         fatal_mask     = SILI_PREG_IST_PHYRDYCHG |
1838                                                  SILI_PREG_IST_DEVEXCHG |
1839                                                  SILI_PREG_IST_DECODE |
1840                                                  SILI_PREG_IST_CRC |
1841                                                  SILI_PREG_IST_HANDSHK;
1842
1843         enum { NEED_NOTHING, NEED_HOTPLUG_INSERT,
1844                NEED_HOTPLUG_REMOVE } need = NEED_NOTHING;
1845
1846         /*
1847          * NOTE: CCOMPLETE was automatically cleared when we read INT_STATUS.
1848          */
1849         is = sili_pread(ap, SILI_PREG_INT_STATUS);
1850         is &= SILI_PREG_IST_MASK;
1851         if (is & SILI_PREG_IST_CCOMPLETE)
1852                 sili_pwrite(ap, SILI_PREG_INT_STATUS, SILI_PREG_IST_CCOMPLETE);
1853
1854         /*
1855          * If we can't block then we can't handle these here.  Disable
1856          * the interrupts in question so we don't live-lock, the helper
1857          * thread will re-enable them.
1858          *
1859          * If the port is in a completely failed state we do not want
1860          * to drop through to failed-command-processing if blockable is 0,
1861          * just let the thread deal with it all.
1862          *
1863          * Otherwise we fall through and still handle DHRS and any commands
1864          * which completed normally.  Even if we are errored we haven't
1865          * stopped the port yet so CI/SACT are still good.
1866          */
1867         if (blockable == 0) {
1868                 if (ap->ap_state == AP_S_FATAL_ERROR) {
1869                         sili_port_interrupt_redisable(ap);
1870                         sili_os_signal_port_thread(ap, AP_SIGF_PORTINT);
1871                         /*is &= ~blockable_mask;*/
1872                         return;
1873                 }
1874                 if (is & blockable_mask) {
1875                         sili_port_interrupt_redisable(ap);
1876                         sili_os_signal_port_thread(ap, AP_SIGF_PORTINT);
1877                         /*is &= ~blockable_mask;*/
1878                         return;
1879                 }
1880         }
1881
1882         if (is & SILI_PREG_IST_CERROR) {
1883                 /*
1884                  * Command failed (blockable).
1885                  *
1886                  * This stops command processing.  We can extract the PM
1887                  * target from the PMP field in SILI_PREG_CONTEXT.  The
1888                  * tag is not necessarily valid so don't use that.
1889                  *
1890                  * We must then expire all CCB's for that target and resume
1891                  * processing if any other targets have active commands.
1892                  * Particular error codes can be recovered by reading the LOG
1893                  * page.
1894                  *
1895                  * The expire handling code will do the rest, which is
1896                  * basically to reset the port once the only active
1897                  * commands remaining are all expired.
1898                  */
1899                 u_int32_t error;
1900                 int       target;
1901                 int       resume = 1;
1902
1903                 target = (sili_pread(ap, SILI_PREG_CONTEXT) >>
1904                           SILI_PREG_CONTEXT_PMPORT_SHIFT) &
1905                           SILI_PREG_CONTEXT_PMPORT_MASK;
1906                 sili_pwrite(ap, SILI_PREG_INT_STATUS, SILI_PREG_IST_CERROR);
1907                 active = ap->ap_active & ~ap->ap_expired;
1908                 error = sili_pread(ap, SILI_PREG_CERROR);
1909                 kprintf("%s.%d target error %d active=%08x hactive=%08x "
1910                         "SERR=%b\n",
1911                         PORTNAME(ap), target, error,
1912                         active, sili_pread(ap, SILI_PREG_SLOTST),
1913                         sili_pread(ap, SILI_PREG_SERR), SILI_PFMT_SERR);
1914
1915                 while (active) {
1916                         slot = ffs(active) - 1;
1917                         ccb = &ap->ap_ccbs[slot];
1918                         if ((ccb_at = ccb->ccb_xa.at) == NULL)
1919                                 ccb_at = &ap->ap_ata[0];
1920                         if (target == ccb_at->at_target) {
1921                                 if (ccb->ccb_xa.flags & ATA_F_NCQ &&
1922                                     (error == SILI_PREG_CERROR_DEVICE ||
1923                                      error == SILI_PREG_CERROR_SDBERROR)) {
1924                                         ccb_at->at_features |= ATA_PORT_F_READLOG;
1925                                 }
1926                                 if (sili_core_timeout(ccb, 1) == 0)
1927                                         resume = 0;
1928                         }
1929                         active &= ~(1 << slot);
1930                 }
1931
1932                 /*
1933                  * Resume will be 0 if the timeout reinited and restarted
1934                  * the port.  Otherwise we resume the port to allow other
1935                  * commands to complete.
1936                  */
1937                 if (resume)
1938                         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_RESUME);
1939         }
1940
1941         /*
1942          * Device notification to us (non-blocking)
1943          *
1944          * This is interrupt status SILIPREG_IST_SDB
1945          *
1946          * NOTE!  On some parts notification bits can get set without
1947          *        generating an interrupt.  It is unclear whether this is
1948          *        a bug in the PM (sending a DTOH device setbits with 'N' set
1949          *        and 'I' not set), or a bug in the host controller.
1950          *
1951          *        It only seems to occur under load.
1952          */
1953         if (sc->sc_flags & SILI_F_SSNTF) {
1954                 u_int32_t data;
1955                 const char *xstr;
1956
1957                 data = sili_pread(ap, SILI_PREG_SNTF);
1958                 if (is & SILI_PREG_IST_SDB) {
1959                         sili_pwrite(ap, SILI_PREG_INT_STATUS,
1960                                     SILI_PREG_IST_SDB);
1961                         is &= ~SILI_PREG_IST_SDB;
1962                         xstr = " (no SDBS!)";
1963                 } else {
1964                         xstr = "";
1965                 }
1966                 if (data) {
1967                         kprintf("%s: NOTIFY %08x%s\n",
1968                                 PORTNAME(ap), data, xstr);
1969                         sili_pwrite(ap, SILI_PREG_SNTF, data);
1970                         sili_cam_changed(ap, NULL, -1);
1971                 }
1972         }
1973
1974         /*
1975          * Port change (hot-plug) (blockable).
1976          *
1977          * A PCS interrupt will occur on hot-plug once communication is
1978          * established.
1979          *
1980          * A PRCS interrupt will occur on hot-unplug (and possibly also
1981          * on hot-plug).
1982          *
1983          * XXX We can then check the CPS (Cold Presence State) bit, if
1984          * supported, to determine if a device is plugged in or not and do
1985          * the right thing.
1986          *
1987          * WARNING:  A PCS interrupt is cleared by clearing DIAG_X, and
1988          *           can also occur if an unsolicited COMINIT is received.
1989          *           If this occurs command processing is automatically
1990          *           stopped (CR goes inactive) and the port must be stopped
1991          *           and restarted.
1992          */
1993         if (is & (SILI_PREG_IST_PHYRDYCHG | SILI_PREG_IST_DEVEXCHG)) {
1994                 /* XXX */
1995                 sili_pwrite(ap, SILI_PREG_SERR,
1996                         (SILI_PREG_SERR_DIAG_N | SILI_PREG_SERR_DIAG_X));
1997                 sili_pwrite(ap, SILI_PREG_INT_STATUS,
1998                     is & (SILI_PREG_IST_PHYRDYCHG | SILI_PREG_IST_DEVEXCHG));
1999
2000                 is &= ~(SILI_PREG_IST_PHYRDYCHG | SILI_PREG_IST_DEVEXCHG);
2001                 kprintf("%s: Port change\n", PORTNAME(ap));
2002
2003                 switch (sili_pread(ap, SILI_PREG_SSTS) & SILI_PREG_SSTS_DET) {
2004                 case SILI_PREG_SSTS_DET_DEV:
2005                         if (ap->ap_type == ATA_PORT_T_NONE &&
2006                             ap->ap_probe == ATA_PROBE_FAILED) {
2007                                 need = NEED_HOTPLUG_INSERT;
2008                                 goto fatal;
2009                         }
2010                         break;
2011                 default:
2012                         kprintf("%s: Device lost\n", PORTNAME(ap));
2013                         if (ap->ap_type != ATA_PORT_T_NONE) {
2014                                 need = NEED_HOTPLUG_REMOVE;
2015                                 goto fatal;
2016                         }
2017                         break;
2018                 }
2019         }
2020
2021         /*
2022          * Check for remaining errors - they are fatal. (blockable)
2023          */
2024         if (is & fatal_mask) {
2025                 u_int32_t serr;
2026
2027                 sili_pwrite(ap, SILI_PREG_INT_STATUS, is & fatal_mask);
2028
2029                 serr = sili_pread(ap, SILI_PREG_SERR);
2030                 kprintf("%s: Unrecoverable errors (IS: %b, SERR: %b), "
2031                         "disabling port.\n",
2032                         PORTNAME(ap),
2033                         is, SILI_PFMT_INT_STATUS,
2034                         serr, SILI_PFMT_SERR
2035                 );
2036                 is &= ~fatal_mask;
2037                 /* XXX try recovery first */
2038                 goto fatal;
2039         }
2040
2041         /*
2042          * Fail all outstanding commands if we know the port won't recover.
2043          *
2044          * We may have a ccb_at if the failed command is known and was
2045          * being sent to a device over a port multiplier (PM).  In this
2046          * case if the port itself has not completely failed we fail just
2047          * the commands related to that target.
2048          */
2049         if (ap->ap_state == AP_S_FATAL_ERROR && ap->ap_active) {
2050 fatal:
2051                 kprintf("%s: Interrupt, fatal error\n", PORTNAME(ap));
2052                 ap->ap_state = AP_S_FATAL_ERROR;
2053 /*failall:*/
2054                 /*
2055                  * Error all the active slots.  If running across a PM
2056                  * try to error out just the slots related to the target.
2057                  */
2058                 active = ap->ap_active & ~ap->ap_expired;
2059
2060                 while (active) {
2061                         slot = ffs(active) - 1;
2062                         active &= ~(1 << slot);
2063                         ccb = &ap->ap_ccbs[slot];
2064                         sili_core_timeout(ccb, 1);
2065                 }
2066         }
2067
2068         /*
2069          * CCB completion (non blocking).
2070          *
2071          * CCB completion is detected by noticing the slot bit in
2072          * the port slot status register has cleared while the bit
2073          * is still set in our ap_active variable.
2074          *
2075          * When completing expired events we must remember to reinit
2076          * the port once everything is clear.
2077          *
2078          * Due to a single-level recursion when reading the log page,
2079          * it is possible for the slot to already have been cleared
2080          * for some expired tags, do not include expired tags in
2081          * the list.
2082          */
2083         active = ap->ap_active & ~sili_pread(ap, SILI_PREG_SLOTST);
2084         active &= ~ap->ap_expired;
2085
2086         while (active) {
2087                 slot = ffs(active) - 1;
2088                 ccb = &ap->ap_ccbs[slot];
2089
2090                 DPRINTF(SILI_D_INTR, "%s: slot %d is complete%s\n",
2091                     PORTNAME(ap), slot, ccb->ccb_xa.state == ATA_S_ERROR ?
2092                     " (error)" : "");
2093
2094                 active &= ~(1 << slot);
2095
2096                 /*
2097                  * XXX sync POSTREAD for return data?
2098                  */
2099                 ap->ap_active &= ~(1 << ccb->ccb_slot);
2100                 --ap->ap_active_cnt;
2101
2102                 /*
2103                  * Complete the ccb.  If the ccb was marked expired it
2104                  * may or may not have been cleared from the port,
2105                  * make sure we mark it as having timed out.
2106                  *
2107                  * In a normal completion if AUTOSENSE is set we copy
2108                  * the PRB LRAM rfis back to the rfis in host-memory.
2109                  *
2110                  * XXX Currently AUTOSENSE also forces exclusivity so we
2111                  *     can safely work around a hardware bug when reading
2112                  *     the LRAM.
2113                  */
2114                 if (ap->ap_expired & (1 << ccb->ccb_slot)) {
2115                         ap->ap_expired &= ~(1 << ccb->ccb_slot);
2116                         ccb->ccb_xa.state = ATA_S_TIMEOUT;
2117                         ccb->ccb_done(ccb);
2118                         ccb->ccb_xa.complete(&ccb->ccb_xa);
2119                 } else {
2120                         if (ccb->ccb_xa.flags & ATA_F_AUTOSENSE) {
2121                                 memcpy(ccb->ccb_xa.rfis,
2122                                        &ccb->ccb_prb_lram->prb_d2h,
2123                                        sizeof(ccb->ccb_prb_lram->prb_d2h));
2124                                 if (ccb->ccb_xa.state == ATA_S_TIMEOUT)
2125                                         ccb->ccb_xa.state = ATA_S_ERROR;
2126                         }
2127                         if (ccb->ccb_xa.state == ATA_S_ONCHIP)
2128                                 ccb->ccb_xa.state = ATA_S_COMPLETE;
2129                         ccb->ccb_done(ccb);
2130                 }
2131         }
2132         if (is & SILI_PREG_IST_READY) {
2133                 is &= ~SILI_PREG_IST_READY;
2134                 sili_pwrite(ap, SILI_PREG_INT_DISABLE, SILI_PREG_INT_READY);
2135                 sili_pwrite(ap, SILI_PREG_INT_STATUS, SILI_PREG_IST_READY);
2136         }
2137
2138         /*
2139          * If we had expired commands and were waiting for
2140          * remaining commands to complete, and they have now
2141          * completed, we can reinit the port.
2142          *
2143          * This will also clean out the expired commands.
2144          * The timeout code also calls sili_port_reinit() if
2145          * the only commands remaining after a timeout are all
2146          * now expired commands.
2147          *
2148          * Otherwise just reissue.
2149          */
2150         if (ap->ap_expired && ap->ap_active == ap->ap_expired)
2151                 sili_port_reinit(ap);
2152         else
2153                 sili_issue_pending_commands(ap, NULL);
2154
2155         /*
2156          * Cleanup.  Will not be set if non-blocking.
2157          */
2158         switch(need) {
2159         case NEED_HOTPLUG_INSERT:
2160                 /*
2161                  * A hot-plug insertion event has occured and all
2162                  * outstanding commands have already been revoked.
2163                  *
2164                  * Don't recurse if this occurs while we are
2165                  * resetting the port.
2166                  *
2167                  * Place the port in a continuous COMRESET state
2168                  * until the INIT code gets to it.
2169                  */
2170                 kprintf("%s: HOTPLUG - Device inserted\n",
2171                         PORTNAME(ap));
2172                 ap->ap_probe = ATA_PROBE_NEED_INIT;
2173                 sili_cam_changed(ap, NULL, -1);
2174                 break;
2175         case NEED_HOTPLUG_REMOVE:
2176                 /*
2177                  * A hot-plug removal event has occured and all
2178                  * outstanding commands have already been revoked.
2179                  *
2180                  * Don't recurse if this occurs while we are
2181                  * resetting the port.
2182                  */
2183                 kprintf("%s: HOTPLUG - Device removed\n",
2184                         PORTNAME(ap));
2185                 sili_port_hardstop(ap);
2186                 /* ap_probe set to failed */
2187                 sili_cam_changed(ap, NULL, -1);
2188                 break;
2189         default:
2190                 break;
2191         }
2192 }
2193
2194 struct sili_ccb *
2195 sili_get_ccb(struct sili_port *ap)
2196 {
2197         struct sili_ccb                 *ccb;
2198
2199         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
2200         ccb = TAILQ_FIRST(&ap->ap_ccb_free);
2201         if (ccb != NULL) {
2202                 KKASSERT(ccb->ccb_xa.state == ATA_S_PUT);
2203                 TAILQ_REMOVE(&ap->ap_ccb_free, ccb, ccb_entry);
2204                 ccb->ccb_xa.state = ATA_S_SETUP;
2205                 ccb->ccb_xa.at = NULL;
2206         }
2207         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
2208
2209         return (ccb);
2210 }
2211
2212 void
2213 sili_put_ccb(struct sili_ccb *ccb)
2214 {
2215         struct sili_port                *ap = ccb->ccb_port;
2216
2217 #ifdef DIAGNOSTIC
2218         if (ccb->ccb_xa.state != ATA_S_COMPLETE &&
2219             ccb->ccb_xa.state != ATA_S_TIMEOUT &&
2220             ccb->ccb_xa.state != ATA_S_ERROR) {
2221                 kprintf("%s: invalid ata_xfer state %02x in sili_put_ccb, "
2222                         "slot %d\n",
2223                         PORTNAME(ccb->ccb_port), ccb->ccb_xa.state,
2224                         ccb->ccb_slot);
2225         }
2226 #endif
2227
2228         ccb->ccb_xa.state = ATA_S_PUT;
2229         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
2230         TAILQ_INSERT_TAIL(&ap->ap_ccb_free, ccb, ccb_entry);
2231         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
2232 }
2233
2234 struct sili_ccb *
2235 sili_get_err_ccb(struct sili_port *ap)
2236 {
2237         struct sili_ccb *err_ccb;
2238
2239         KKASSERT(sili_pread(ap, SILI_PREG_CI) == 0);
2240         KKASSERT((ap->ap_flags & AP_F_ERR_CCB_RESERVED) == 0);
2241         ap->ap_flags |= AP_F_ERR_CCB_RESERVED;
2242
2243 #ifdef DIAGNOSTIC
2244         KKASSERT(ap->ap_err_busy == 0);
2245         ap->ap_err_busy = 1;
2246 #endif
2247         /*
2248          * Grab a CCB to use for error recovery.  This should never fail, as
2249          * we ask atascsi to reserve one for us at init time.
2250          */
2251         err_ccb = ap->ap_err_ccb;
2252         KKASSERT(err_ccb != NULL);
2253         err_ccb->ccb_xa.flags = 0;
2254         err_ccb->ccb_done = sili_empty_done;
2255
2256         return err_ccb;
2257 }
2258
2259 void
2260 sili_put_err_ccb(struct sili_ccb *ccb)
2261 {
2262         struct sili_port *ap = ccb->ccb_port;
2263
2264 #ifdef DIAGNOSTIC
2265         KKASSERT(ap->ap_err_busy);
2266 #endif
2267         KKASSERT((ap->ap_flags & AP_F_ERR_CCB_RESERVED) != 0);
2268
2269         KKASSERT(ccb == ap->ap_err_ccb);
2270
2271 #ifdef DIAGNOSTIC
2272         ap->ap_err_busy = 0;
2273 #endif
2274         ap->ap_flags &= ~AP_F_ERR_CCB_RESERVED;
2275 }
2276
2277 /*
2278  * Read log page to get NCQ error.
2279  *
2280  * Return 0 on success
2281  */
2282 void
2283 sili_port_read_ncq_error(struct sili_port *ap, int target)
2284 {
2285         struct sili_ccb         *ccb;
2286         struct ata_fis_h2d      *fis;
2287         int                     status;
2288
2289         DPRINTF(SILI_D_VERBOSE, "%s: read log page\n", PORTNAME(ap));
2290
2291         /* Prep error CCB for READ LOG EXT, page 10h, 1 sector. */
2292         ccb = sili_get_err_ccb(ap);
2293         ccb->ccb_done = sili_empty_done;
2294         ccb->ccb_xa.flags = ATA_F_NOWAIT | ATA_F_READ | ATA_F_POLL;
2295         ccb->ccb_xa.data = ap->ap_err_scratch;
2296         ccb->ccb_xa.datalen = 512;
2297         ccb->ccb_xa.complete = sili_dummy_done;
2298         ccb->ccb_xa.at = &ap->ap_ata[target];
2299         fis = &ccb->ccb_prb->prb_h2d;
2300         bzero(fis, sizeof(*fis));
2301
2302         fis->type = ATA_FIS_TYPE_H2D;
2303         fis->flags = ATA_H2D_FLAGS_CMD | target;
2304         fis->command = ATA_C_READ_LOG_EXT;
2305         fis->lba_low = 0x10;            /* queued error log page (10h) */
2306         fis->sector_count = 1;          /* number of sectors (1) */
2307         fis->sector_count_exp = 0;
2308         fis->lba_mid = 0;               /* starting offset */
2309         fis->lba_mid_exp = 0;
2310         fis->device = 0;
2311
2312         if (sili_load_prb(ccb) != 0) {
2313                 status = ATA_S_ERROR;
2314         } else {
2315                 ccb->ccb_xa.state = ATA_S_PENDING;
2316                 status = sili_poll(ccb, 1000, sili_quick_timeout);
2317         }
2318
2319         /*
2320          * Just spew if it fails, there isn't much we can do at this point.
2321          */
2322         if (status != ATA_S_COMPLETE) {
2323                 kprintf("%s: log page read failed, slot %d was still active.\n",
2324                         ATANAME(ap, ccb->ccb_xa.at), ccb->ccb_slot);
2325         }
2326
2327         /* Done with the error CCB now. */
2328         sili_unload_prb(ccb);
2329         sili_put_err_ccb(ccb);
2330
2331         /* Extract failed register set and tags from the scratch space. */
2332         if (status == ATA_S_COMPLETE) {
2333                 struct ata_log_page_10h         *log;
2334                 int                             err_slot;
2335
2336                 log = (struct ata_log_page_10h *)ap->ap_err_scratch;
2337                 if (log->err_regs.type & ATA_LOG_10H_TYPE_NOTQUEUED) {
2338                         /*
2339                          * Not queued bit was set - wasn't an NCQ error?
2340                          *
2341                          * XXX This bit seems to be set a lot even for NCQ
2342                          *     errors?
2343                          */
2344                 } else {
2345                         /*
2346                          * Copy back the log record as a D2H register FIS.
2347                          */
2348                         err_slot = log->err_regs.type &
2349                                    ATA_LOG_10H_TYPE_TAG_MASK;
2350                         ccb = &ap->ap_ccbs[err_slot];
2351                         if (ap->ap_expired & (1 << ccb->ccb_slot)) {
2352                                 kprintf("%s: read NCQ error page slot=%d\n",
2353                                         ATANAME(ap, ccb->ccb_xa.at), err_slot
2354                                 );
2355                                 memcpy(&ccb->ccb_prb->prb_d2h, &log->err_regs,
2356                                         sizeof(struct ata_fis_d2h));
2357                                 ccb->ccb_prb->prb_d2h.type = ATA_FIS_TYPE_D2H;
2358                                 ccb->ccb_prb->prb_d2h.flags = 0;
2359                                 if (ccb->ccb_xa.state == ATA_S_TIMEOUT)
2360                                         ccb->ccb_xa.state = ATA_S_ERROR;
2361                         } else {
2362                                 kprintf("%s: read NCQ error page slot=%d, "
2363                                         "slot does not match any cmds\n",
2364
2365                                         ATANAME(ccb->ccb_port, ccb->ccb_xa.at),
2366                                         err_slot
2367                                 );
2368                         }
2369                 }
2370         }
2371 }
2372
2373 /*
2374  * Allocate memory for various structures DMAd by hardware.  The maximum
2375  * number of segments for these tags is 1 so the DMA memory will have a
2376  * single physical base address.
2377  */
2378 struct sili_dmamem *
2379 sili_dmamem_alloc(struct sili_softc *sc, bus_dma_tag_t tag)
2380 {
2381         struct sili_dmamem *adm;
2382         int     error;
2383
2384         adm = kmalloc(sizeof(*adm), M_DEVBUF, M_INTWAIT | M_ZERO);
2385
2386         error = bus_dmamem_alloc(tag, (void **)&adm->adm_kva,
2387                                  BUS_DMA_ZERO, &adm->adm_map);
2388         if (error == 0) {
2389                 adm->adm_tag = tag;
2390                 error = bus_dmamap_load(tag, adm->adm_map,
2391                                         adm->adm_kva,
2392                                         bus_dma_tag_getmaxsize(tag),
2393                                         sili_dmamem_saveseg, &adm->adm_busaddr,
2394                                         0);
2395         }
2396         if (error) {
2397                 if (adm->adm_map) {
2398                         bus_dmamap_destroy(tag, adm->adm_map);
2399                         adm->adm_map = NULL;
2400                         adm->adm_tag = NULL;
2401                         adm->adm_kva = NULL;
2402                 }
2403                 kfree(adm, M_DEVBUF);
2404                 adm = NULL;
2405         }
2406         return (adm);
2407 }
2408
2409 static
2410 void
2411 sili_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error)
2412 {
2413         KKASSERT(error == 0);
2414         KKASSERT(nsegs == 1);
2415         *(bus_addr_t *)info = segs->ds_addr;
2416 }
2417
2418
2419 void
2420 sili_dmamem_free(struct sili_softc *sc, struct sili_dmamem *adm)
2421 {
2422         if (adm->adm_map) {
2423                 bus_dmamap_unload(adm->adm_tag, adm->adm_map);
2424                 bus_dmamap_destroy(adm->adm_tag, adm->adm_map);
2425                 adm->adm_map = NULL;
2426                 adm->adm_tag = NULL;
2427                 adm->adm_kva = NULL;
2428         }
2429         kfree(adm, M_DEVBUF);
2430 }
2431
2432 u_int32_t
2433 sili_read(struct sili_softc *sc, bus_size_t r)
2434 {
2435         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
2436                           BUS_SPACE_BARRIER_READ);
2437         return (bus_space_read_4(sc->sc_iot, sc->sc_ioh, r));
2438 }
2439
2440 void
2441 sili_write(struct sili_softc *sc, bus_size_t r, u_int32_t v)
2442 {
2443         bus_space_write_4(sc->sc_iot, sc->sc_ioh, r, v);
2444         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
2445                           BUS_SPACE_BARRIER_WRITE);
2446 }
2447
2448 u_int32_t
2449 sili_pread(struct sili_port *ap, bus_size_t r)
2450 {
2451         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
2452                           BUS_SPACE_BARRIER_READ);
2453         return (bus_space_read_4(ap->ap_sc->sc_iot, ap->ap_ioh, r));
2454 }
2455
2456 void
2457 sili_pwrite(struct sili_port *ap, bus_size_t r, u_int32_t v)
2458 {
2459         bus_space_write_4(ap->ap_sc->sc_iot, ap->ap_ioh, r, v);
2460         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
2461                           BUS_SPACE_BARRIER_WRITE);
2462 }
2463
2464 /*
2465  * Wait up to (timeout) milliseconds for the masked port register to
2466  * match the target.
2467  *
2468  * Timeout is in milliseconds.
2469  */
2470 int
2471 sili_pwait_eq(struct sili_port *ap, int timeout,
2472               bus_size_t r, u_int32_t mask, u_int32_t target)
2473 {
2474         int     t;
2475
2476         /*
2477          * Loop hard up to 100uS
2478          */
2479         for (t = 0; t < 100; ++t) {
2480                 if ((sili_pread(ap, r) & mask) == target)
2481                         return (0);
2482                 sili_os_hardsleep(1);   /* us */
2483         }
2484
2485         do {
2486                 timeout -= sili_os_softsleep();
2487                 if ((sili_pread(ap, r) & mask) == target)
2488                         return (0);
2489         } while (timeout > 0);
2490         return (1);
2491 }
2492
2493 int
2494 sili_wait_ne(struct sili_softc *sc, bus_size_t r, u_int32_t mask,
2495              u_int32_t target)
2496 {
2497         int     t;
2498
2499         /*
2500          * Loop hard up to 100uS
2501          */
2502         for (t = 0; t < 100; ++t) {
2503                 if ((sili_read(sc, r) & mask) != target)
2504                         return (0);
2505                 sili_os_hardsleep(1);   /* us */
2506         }
2507
2508         /*
2509          * And one millisecond the slow way
2510          */
2511         t = 1000;
2512         do {
2513                 t -= sili_os_softsleep();
2514                 if ((sili_read(sc, r) & mask) != target)
2515                         return (0);
2516         } while (t > 0);
2517
2518         return (1);
2519 }
2520
2521
2522 /*
2523  * Acquire an ata transfer.
2524  *
2525  * Pass a NULL at for direct-attached transfers, and a non-NULL at for
2526  * targets that go through the port multiplier.
2527  */
2528 struct ata_xfer *
2529 sili_ata_get_xfer(struct sili_port *ap, struct ata_port *at)
2530 {
2531         struct sili_ccb         *ccb;
2532
2533         ccb = sili_get_ccb(ap);
2534         if (ccb == NULL) {
2535                 DPRINTF(SILI_D_XFER, "%s: sili_ata_get_xfer: NULL ccb\n",
2536                     PORTNAME(ap));
2537                 return (NULL);
2538         }
2539
2540         DPRINTF(SILI_D_XFER, "%s: sili_ata_get_xfer got slot %d\n",
2541             PORTNAME(ap), ccb->ccb_slot);
2542
2543         bzero(ccb->ccb_xa.fis, sizeof(*ccb->ccb_xa.fis));
2544         ccb->ccb_xa.at = at;
2545         ccb->ccb_xa.fis->type = ATA_FIS_TYPE_H2D;
2546
2547         return (&ccb->ccb_xa);
2548 }
2549
2550 void
2551 sili_ata_put_xfer(struct ata_xfer *xa)
2552 {
2553         struct sili_ccb                 *ccb = (struct sili_ccb *)xa;
2554
2555         DPRINTF(SILI_D_XFER, "sili_ata_put_xfer slot %d\n", ccb->ccb_slot);
2556
2557         sili_put_ccb(ccb);
2558 }
2559
2560 int
2561 sili_ata_cmd(struct ata_xfer *xa)
2562 {
2563         struct sili_ccb                 *ccb = (struct sili_ccb *)xa;
2564
2565         KKASSERT(xa->state == ATA_S_SETUP);
2566
2567         if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR)
2568                 goto failcmd;
2569 #if 0
2570         kprintf("%s: started std command %b ccb %d ccb_at %p %d\n",
2571                 ATANAME(ccb->ccb_port, ccb->ccb_xa.at),
2572                 sili_pread(ccb->ccb_port, SILI_PREG_CMD), SILI_PFMT_CMD,
2573                 ccb->ccb_slot,
2574                 ccb->ccb_xa.at,
2575                 ccb->ccb_xa.at ? ccb->ccb_xa.at->at_target : -1);
2576 #endif
2577
2578         ccb->ccb_done = sili_ata_cmd_done;
2579
2580         if (sili_load_prb(ccb) != 0)
2581                 goto failcmd;
2582
2583         xa->state = ATA_S_PENDING;
2584
2585         if (xa->flags & ATA_F_POLL)
2586                 return (sili_poll(ccb, xa->timeout, sili_ata_cmd_timeout));
2587
2588         crit_enter();
2589         KKASSERT((xa->flags & ATA_F_TIMEOUT_EXPIRED) == 0);
2590         xa->flags |= ATA_F_TIMEOUT_DESIRED;
2591         sili_start(ccb);
2592         crit_exit();
2593         return (xa->state);
2594
2595 failcmd:
2596         crit_enter();
2597         xa->state = ATA_S_ERROR;
2598         xa->complete(xa);
2599         crit_exit();
2600         return (ATA_S_ERROR);
2601 }
2602
2603 static void
2604 sili_ata_cmd_done(struct sili_ccb *ccb)
2605 {
2606         struct ata_xfer                 *xa = &ccb->ccb_xa;
2607
2608         /*
2609          * NOTE: callout does not lock port and may race us modifying
2610          * the flags, so make sure its stopped.
2611          */
2612         if (xa->flags & ATA_F_TIMEOUT_RUNNING) {
2613                 callout_stop(&ccb->ccb_timeout);
2614                 xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
2615         }
2616         xa->flags &= ~(ATA_F_TIMEOUT_DESIRED | ATA_F_TIMEOUT_EXPIRED);
2617
2618         KKASSERT(xa->state != ATA_S_ONCHIP);
2619         sili_unload_prb(ccb);
2620
2621 #ifdef DIAGNOSTIC
2622         else if (xa->state != ATA_S_ERROR && xa->state != ATA_S_TIMEOUT)
2623                 kprintf("%s: invalid ata_xfer state %02x in sili_ata_cmd_done, "
2624                         "slot %d\n",
2625                         PORTNAME(ccb->ccb_port), xa->state, ccb->ccb_slot);
2626 #endif
2627         if (xa->state != ATA_S_TIMEOUT)
2628                 xa->complete(xa);
2629 }
2630
2631 /*
2632  * Timeout from callout, MPSAFE - nothing can mess with the CCB's flags
2633  * while the callout is runing.
2634  *
2635  * We can't safely get the port lock here or delay, we could block
2636  * the callout thread.
2637  */
2638 static void
2639 sili_ata_cmd_timeout_unserialized(void *arg)
2640 {
2641         struct sili_ccb         *ccb = arg;
2642         struct sili_port        *ap = ccb->ccb_port;
2643
2644         ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_RUNNING;
2645         ccb->ccb_xa.flags |= ATA_F_TIMEOUT_EXPIRED;
2646         sili_os_signal_port_thread(ap, AP_SIGF_TIMEOUT);
2647 }
2648
2649 void
2650 sili_ata_cmd_timeout(struct sili_ccb *ccb)
2651 {
2652         sili_core_timeout(ccb, 0);
2653 }
2654
2655 /*
2656  * Timeout code, typically called when the port command processor is running.
2657  *
2658  * Returns 0 if all timeout processing completed, non-zero if it is still
2659  * in progress.
2660  */
2661 static
2662 int
2663 sili_core_timeout(struct sili_ccb *ccb, int really_error)
2664 {
2665         struct ata_xfer         *xa = &ccb->ccb_xa;
2666         struct sili_port        *ap = ccb->ccb_port;
2667         struct ata_port         *at;
2668
2669         at = ccb->ccb_xa.at;
2670
2671         kprintf("%s: CMD %s state=%d slot=%d\n"
2672                 "\t active=%08x\n"
2673                 "\texpired=%08x\n"
2674                 "\thactive=%08x\n",
2675                 ATANAME(ap, at),
2676                 (really_error ? "ERROR" : "TIMEOUT"),
2677                 ccb->ccb_xa.state, ccb->ccb_slot,
2678                 ap->ap_active,
2679                 ap->ap_expired,
2680                 sili_pread(ap, SILI_PREG_SLOTST)
2681         );
2682
2683         /*
2684          * NOTE: Timeout will not be running if the command was polled.
2685          *       If we got here at least one of these flags should be set.
2686          *
2687          *       However, it might be running if we are called from the
2688          *       interrupt error handling code.
2689          */
2690         KKASSERT(xa->flags & (ATA_F_POLL | ATA_F_TIMEOUT_DESIRED |
2691                               ATA_F_TIMEOUT_RUNNING));
2692         if (xa->flags & ATA_F_TIMEOUT_RUNNING) {
2693                 callout_stop(&ccb->ccb_timeout);
2694                 xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
2695         }
2696         xa->flags &= ~ATA_F_TIMEOUT_EXPIRED;
2697
2698         if (ccb->ccb_xa.state == ATA_S_PENDING) {
2699                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
2700                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
2701                 ccb->ccb_done(ccb);
2702                 xa->complete(xa);
2703                 sili_issue_pending_commands(ap, NULL);
2704                 return(1);
2705         }
2706         if (ccb->ccb_xa.state != ATA_S_ONCHIP) {
2707                 kprintf("%s: Unexpected state during timeout: %d\n",
2708                         ATANAME(ap, at), ccb->ccb_xa.state);
2709                 return(1);
2710         }
2711
2712         /*
2713          * We can't process timeouts while other commands are running.
2714          */
2715         ap->ap_expired |= 1 << ccb->ccb_slot;
2716
2717         if (ap->ap_active != ap->ap_expired) {
2718                 kprintf("%s: Deferred timeout until its safe, slot %d\n",
2719                         ATANAME(ap, at), ccb->ccb_slot);
2720                 return(1);
2721         }
2722
2723         /*
2724          * We have to issue a Port reinit.  We don't read an error log
2725          * page for timeouts.  Reiniting the port will clear all pending
2726          * commands.
2727          */
2728         sili_port_reinit(ap);
2729         return(0);
2730 }
2731
2732 /*
2733  * Used by the softreset, pmprobe, and read_ncq_error only, in very
2734  * specialized, controlled circumstances.
2735  */
2736 void
2737 sili_quick_timeout(struct sili_ccb *ccb)
2738 {
2739         struct sili_port *ap = ccb->ccb_port;
2740
2741         switch (ccb->ccb_xa.state) {
2742         case ATA_S_PENDING:
2743                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
2744                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
2745                 break;
2746         case ATA_S_ONCHIP:
2747                 KKASSERT((ap->ap_active & ~ap->ap_expired) ==
2748                          (1 << ccb->ccb_slot));
2749                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
2750                 ap->ap_active &= ~(1 << ccb->ccb_slot);
2751                 KKASSERT(ap->ap_active_cnt > 0);
2752                 --ap->ap_active_cnt;
2753                 sili_port_reinit(ap);
2754                 break;
2755         default:
2756                 panic("%s: sili_quick_timeout: ccb in bad state %d",
2757                       ATANAME(ap, ccb->ccb_xa.at), ccb->ccb_xa.state);
2758         }
2759 }
2760
2761 static void
2762 sili_dummy_done(struct ata_xfer *xa)
2763 {
2764 }
2765
2766 static void
2767 sili_empty_done(struct sili_ccb *ccb)
2768 {
2769 }