d622e2b1d38803ced9c475232f4303503f3eea68
[dragonfly.git] / sys / dev / disk / ahci / ahci_cam.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) 2007 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  * $OpenBSD: atascsi.c,v 1.64 2009/02/16 21:19:06 miod Exp $
50  * $DragonFly$
51  */
52 /*
53  * Implement each SATA port as its own SCSI bus on CAM.  This way we can
54  * implement future port multiplier features as individual devices on the
55  * bus.
56  *
57  * Much of the cdb<->xa conversion code was taken from OpenBSD, the rest
58  * was written natively for DragonFly.
59  */
60
61 #include "ahci.h"
62
63 const char *ScsiTypeArray[32] = {
64         "DIRECT",
65         "SEQUENTIAL",
66         "PRINTER",
67         "PROCESSOR",
68         "WORM",
69         "CDROM",
70         "SCANNER",
71         "OPTICAL",
72         "CHANGER",
73         "COMM",
74         "ASC0",
75         "ASC1",
76         "STORARRAY",
77         "ENCLOSURE",
78         "RBC",
79         "OCRW",
80         "0x10",
81         "OSD",
82         "ADC",
83         "0x13",
84         "0x14",
85         "0x15",
86         "0x16",
87         "0x17",
88         "0x18",
89         "0x19",
90         "0x1A",
91         "0x1B",
92         "0x1C",
93         "0x1D",
94         "0x1E",
95         "NODEVICE"
96 };
97
98 static void ahci_xpt_action(struct cam_sim *sim, union ccb *ccb);
99 static void ahci_xpt_poll(struct cam_sim *sim);
100 static void ahci_xpt_scsi_disk_io(struct ahci_port *ap,
101                         struct ata_port *at, union ccb *ccb);
102 static void ahci_xpt_scsi_atapi_io(struct ahci_port *ap,
103                         struct ata_port *at, union ccb *ccb);
104
105 static void ahci_ata_complete_disk_rw(struct ata_xfer *xa);
106 static void ahci_ata_complete_disk_synchronize_cache(struct ata_xfer *xa);
107 static void ahci_atapi_complete_cmd(struct ata_xfer *xa);
108 static void ahci_ata_dummy_sense(struct scsi_sense_data *sense_data);
109 static void ahci_ata_atapi_sense(struct ata_fis_d2h *rfis,
110                      struct scsi_sense_data *sense_data);
111
112 static int ahci_cam_probe_disk(struct ahci_port *ap, struct ata_port *at);
113 static int ahci_cam_probe_atapi(struct ahci_port *ap, struct ata_port *at);
114 static void ahci_ata_dummy_done(struct ata_xfer *xa);
115 static void ata_fix_identify(struct ata_identify *id);
116 static void ahci_cam_rescan(struct ahci_port *ap);
117
118 int
119 ahci_cam_attach(struct ahci_port *ap)
120 {
121         struct cam_devq *devq;
122         struct cam_sim *sim;
123         int error;
124         int unit;
125
126         /*
127          * We want at least one ccb to be available for error processing
128          * so don't let CAM use more then ncmds - 1.
129          */
130         unit = device_get_unit(ap->ap_sc->sc_dev);
131         if (ap->ap_sc->sc_ncmds > 1)
132                 devq = cam_simq_alloc(ap->ap_sc->sc_ncmds - 1);
133         else
134                 devq = cam_simq_alloc(ap->ap_sc->sc_ncmds);
135         if (devq == NULL) {
136                 return (ENOMEM);
137         }
138         sim = cam_sim_alloc(ahci_xpt_action, ahci_xpt_poll, "ahci",
139                            (void *)ap, unit, &sim_mplock, 1, 1, devq);
140         cam_simq_release(devq);
141         if (sim == NULL) {
142                 return (ENOMEM);
143         }
144         ap->ap_sim = sim;
145         error = xpt_bus_register(ap->ap_sim, ap->ap_num);
146         if (error != CAM_SUCCESS) {
147                 ahci_cam_detach(ap);
148                 return (EINVAL);
149         }
150         ap->ap_flags |= AP_F_BUS_REGISTERED;
151
152         error = ahci_cam_probe(ap, NULL);
153         if (error) {
154                 ahci_cam_detach(ap);
155                 return (EIO);
156         }
157         ap->ap_flags |= AP_F_CAM_ATTACHED;
158
159         return(0);
160 }
161
162 /*
163  * The state of the port has changed.
164  *
165  * If at is NULL the physical port has changed state.
166  * If at is non-NULL a particular target behind a PM has changed state.
167  *
168  * If found is -1 the target state must be queued to a non-interrupt context.
169  * (only works with at == NULL).
170  *
171  * If found is 0 the target was removed.
172  * If found is 1 the target was inserted.
173  */
174 void
175 ahci_cam_changed(struct ahci_port *ap, struct ata_port *atx, int found)
176 {
177         struct cam_path *tmppath;
178         int status;
179         int target;
180
181         target = atx ? atx->at_target : CAM_TARGET_WILDCARD;
182
183         if (ap->ap_sim == NULL)
184                 return;
185         if (found == CAM_TARGET_WILDCARD) {
186                 status = xpt_create_path(&tmppath, NULL,
187                                          cam_sim_path(ap->ap_sim),
188                                          target, CAM_LUN_WILDCARD);
189                 if (status != CAM_REQ_CMP)
190                         return;
191                 ahci_cam_rescan(ap);
192         } else {
193                 status = xpt_create_path(&tmppath, NULL,
194                                          cam_sim_path(ap->ap_sim),
195                                          target,
196                                          CAM_LUN_WILDCARD);
197                 if (status != CAM_REQ_CMP)
198                         return;
199 #if 0
200                 /*
201                  * This confuses CAM
202                  */
203                 if (found)
204                         xpt_async(AC_FOUND_DEVICE, tmppath, NULL);
205                 else
206                         xpt_async(AC_LOST_DEVICE, tmppath, NULL);
207 #endif
208         }
209         xpt_free_path(tmppath);
210 }
211
212 void
213 ahci_cam_detach(struct ahci_port *ap)
214 {
215         int error;
216
217         if ((ap->ap_flags & AP_F_CAM_ATTACHED) == 0)
218                 return;
219         get_mplock();
220         if (ap->ap_sim) {
221                 xpt_freeze_simq(ap->ap_sim, 1);
222         }
223         if (ap->ap_flags & AP_F_BUS_REGISTERED) {
224                 error = xpt_bus_deregister(cam_sim_path(ap->ap_sim));
225                 KKASSERT(error == CAM_REQ_CMP);
226                 ap->ap_flags &= ~AP_F_BUS_REGISTERED;
227         }
228         if (ap->ap_sim) {
229                 cam_sim_free(ap->ap_sim);
230                 ap->ap_sim = NULL;
231         }
232         rel_mplock();
233         ap->ap_flags &= ~AP_F_CAM_ATTACHED;
234 }
235
236 /*
237  * Once the AHCI port has been attached we need to probe for a device or
238  * devices on the port and setup various options.
239  *
240  * If at is NULL we are probing the direct-attached device on the port,
241  * which may or may not be a port multiplier.
242  */
243 int
244 ahci_cam_probe(struct ahci_port *ap, struct ata_port *atx)
245 {
246         struct ata_port *at;
247         struct ata_xfer *xa;
248         u_int64_t       capacity;
249         u_int64_t       capacity_bytes;
250         int             model_len;
251         int             status;
252         int             error;
253         int             devncqdepth;
254         int             i;
255         const char      *wcstr;
256         const char      *rastr;
257         const char      *scstr;
258         const char      *type;
259
260         error = EIO;
261
262         /*
263          * A NULL atx indicates a probe of the directly connected device.
264          * A non-NULL atx indicates a device connected via a port multiplier.
265          * We need to preserve atx for calls to ahci_ata_get_xfer().
266          *
267          * at is always non-NULL.  For directly connected devices we supply
268          * an (at) pointing to target 0.
269          */
270         if (atx == NULL) {
271                 at = ap->ap_ata;        /* direct attached - device 0 */
272                 if (ap->ap_type == ATA_PORT_T_PM) {
273                         kprintf("%s: Found Port Multiplier\n",
274                                 ATANAME(ap, atx));
275                         ap->ap_probe = ATA_PROBE_GOOD;
276                         return (0);
277                 }
278                 at->at_type = ap->ap_type;
279         } else {
280                 at = atx;
281                 if (atx->at_type == ATA_PORT_T_PM) {
282                         kprintf("%s: Bogus device, reducing port count to %d\n",
283                                 ATANAME(ap, atx), atx->at_target);
284                         if (ap->ap_pmcount > atx->at_target)
285                                 ap->ap_pmcount = atx->at_target;
286                         goto err;
287                 }
288         }
289         if (ap->ap_type == ATA_PORT_T_NONE)
290                 goto err;
291         if (at->at_type == ATA_PORT_T_NONE)
292                 goto err;
293
294         /*
295          * Issue identify, saving the result
296          */
297         xa = ahci_ata_get_xfer(ap, atx);
298         xa->complete = ahci_ata_dummy_done;
299         xa->data = &at->at_identify;
300         xa->datalen = sizeof(at->at_identify);
301         xa->fis->flags = ATA_H2D_FLAGS_CMD | at->at_target;
302
303         switch(at->at_type) {
304         case ATA_PORT_T_DISK:
305                 xa->fis->command = ATA_C_IDENTIFY;
306                 type = "DISK";
307                 break;
308         case ATA_PORT_T_ATAPI:
309                 xa->fis->command = ATA_C_ATAPI_IDENTIFY;
310                 type = "ATAPI";
311                 break;
312         default:
313                 xa->fis->command = ATA_C_ATAPI_IDENTIFY;
314                 type = "UNKNOWN(ATAPI?)";
315                 break;
316         }
317         xa->fis->features = 0;
318         xa->fis->device = 0;
319         xa->flags = ATA_F_READ | ATA_F_PIO | ATA_F_POLL;
320         xa->timeout = 1000;
321
322         status = ahci_ata_cmd(xa);
323         if (status != ATA_COMPLETE) {
324                 kprintf("%s: Detected %s device but unable to IDENTIFY\n",
325                         ATANAME(ap, atx), type);
326                 ahci_ata_put_xfer(xa);
327                 goto err;
328         }
329         if (xa->state != ATA_S_COMPLETE) {
330                 kprintf("%s: Detected %s device but unable to IDENTIFY "
331                         " xa->state=%d\n",
332                         ATANAME(ap, atx), type, xa->state);
333                 ahci_ata_put_xfer(xa);
334                 goto err;
335         }
336         ahci_ata_put_xfer(xa);
337
338         ata_fix_identify(&at->at_identify);
339
340         /*
341          * Read capacity using SATA probe info.
342          */
343         if (le16toh(at->at_identify.cmdset83) & 0x0400) {
344                 /* LBA48 feature set supported */
345                 capacity = 0;
346                 for (i = 3; i >= 0; --i) {
347                         capacity <<= 16;
348                         capacity +=
349                             le16toh(at->at_identify.addrsecxt[i]);
350                 }
351         } else {
352                 capacity = le16toh(at->at_identify.addrsec[1]);
353                 capacity <<= 16;
354                 capacity += le16toh(at->at_identify.addrsec[0]);
355         }
356         at->at_capacity = capacity;
357         if (atx == NULL)
358                 ap->ap_probe = ATA_PROBE_GOOD;
359
360         capacity_bytes = capacity * 512;
361
362         /*
363          * Negotiate NCQ, throw away any ata_xfer's beyond the negotiated
364          * number of slots and limit the number of CAM ccb's to one less
365          * so we always have a slot available for recovery.
366          *
367          * NCQ is not used if ap_ncqdepth is 1 or the host controller does
368          * not support it, and in that case the driver can handle extra
369          * ccb's.
370          *
371          * NCQ is currently used only with direct-attached disks.  It is
372          * not used with port multipliers or direct-attached ATAPI devices.
373          *
374          * Remember at least one extra CCB needs to be reserved for the
375          * error ccb.
376          */
377         if ((ap->ap_sc->sc_cap & AHCI_REG_CAP_SNCQ) &&
378             ap->ap_type == ATA_PORT_T_DISK &&
379             (le16toh(at->at_identify.satacap) & (1 << 8))) {
380                 at->at_ncqdepth = (le16toh(at->at_identify.qdepth) & 0x1F) + 1;
381                 devncqdepth = at->at_ncqdepth;
382                 if (at->at_ncqdepth > ap->ap_sc->sc_ncmds)
383                         at->at_ncqdepth = ap->ap_sc->sc_ncmds;
384                 if (at->at_ncqdepth > 1) {
385                         for (i = 0; i < ap->ap_sc->sc_ncmds; ++i) {
386                                 xa = ahci_ata_get_xfer(ap, atx);
387                                 if (xa->tag < at->at_ncqdepth) {
388                                         xa->state = ATA_S_COMPLETE;
389                                         ahci_ata_put_xfer(xa);
390                                 }
391                         }
392                         if (at->at_ncqdepth >= ap->ap_sc->sc_ncmds) {
393                                 cam_devq_resize(ap->ap_sim->devq,
394                                                 at->at_ncqdepth - 1);
395                         }
396                 }
397         } else {
398                 devncqdepth = 0;
399         }
400
401         /*
402          * Make the model string a bit more presentable
403          */
404         for (model_len = 40; model_len; --model_len) {
405                 if (at->at_identify.model[model_len-1] == ' ')
406                         continue;
407                 if (at->at_identify.model[model_len-1] == 0)
408                         continue;
409                 break;
410         }
411
412         /*
413          * Generate informatiive strings.
414          *
415          * NOTE: We do not automatically set write caching, lookahead,
416          *       or the security state for ATAPI devices.
417          */
418         if (at->at_identify.cmdset82 & ATA_IDENTIFY_WRITECACHE) {
419                 if (at->at_identify.features85 & ATA_IDENTIFY_WRITECACHE)
420                         wcstr = "enabled";
421                 else if (at->at_type == ATA_PORT_T_ATAPI)
422                         wcstr = "disabled";
423                 else
424                         wcstr = "enabling";
425         } else {
426                     wcstr = "notsupp";
427         }
428
429         if (at->at_identify.cmdset82 & ATA_IDENTIFY_LOOKAHEAD) {
430                 if (at->at_identify.features85 & ATA_IDENTIFY_LOOKAHEAD)
431                         rastr = "enabled";
432                 else if (at->at_type == ATA_PORT_T_ATAPI)
433                         rastr = "disabled";
434                 else
435                         rastr = "enabling";
436         } else {
437                     rastr = "notsupp";
438         }
439
440         if (at->at_identify.cmdset82 & ATA_IDENTIFY_SECURITY) {
441                 if (at->at_identify.securestatus & ATA_SECURE_FROZEN)
442                         scstr = "frozen";
443                 else if (at->at_type == ATA_PORT_T_ATAPI)
444                         scstr = "unfrozen";
445                 else
446                         scstr = "freezing";
447         } else {
448                     scstr = "notsupp";
449         }
450
451         kprintf("%s: Found %s \"%*.*s %8.8s\" serial=\"%20.20s\"\n"
452                 "%s: tags=%d/%d satacaps=%04x satafeat=%04x "
453                 "capacity=%lld.%02dMB\n"
454                 "%s: f85=%04x f86=%04x f87=%04x WC=%s RA=%s SEC=%s\n",
455                 ATANAME(ap, atx),
456                 type,
457                 model_len, model_len,
458                 at->at_identify.model,
459                 at->at_identify.firmware,
460                 at->at_identify.serial,
461
462                 ATANAME(ap, atx),
463                 devncqdepth, ap->ap_sc->sc_ncmds,
464                 at->at_identify.satacap,
465                 at->at_identify.satafsup,
466                 (long long)capacity_bytes / (1024 * 1024),
467                 (int)(capacity_bytes % (1024 * 1024)) * 100 / (1024 * 1024),
468
469                 ATANAME(ap, atx),
470                 at->at_identify.features85,
471                 at->at_identify.features86,
472                 at->at_identify.features87,
473                 wcstr,
474                 rastr,
475                 scstr
476         );
477
478         /*
479          * Additional type-specific probing
480          */
481         switch(at->at_type) {
482         case ATA_PORT_T_DISK:
483                 error = ahci_cam_probe_disk(ap, atx);
484                 break;
485         case ATA_PORT_T_ATAPI:
486                 error = ahci_cam_probe_atapi(ap, atx);
487                 break;
488         default:
489                 error = EIO;
490                 break;
491         }
492 err:
493         if (error) {
494                 at->at_probe = ATA_PROBE_FAILED;
495                 if (atx == NULL)
496                         ap->ap_probe = at->at_probe;
497         } else {
498                 at->at_probe = ATA_PROBE_GOOD;
499                 if (atx == NULL)
500                         ap->ap_probe = at->at_probe;
501         }
502         return (error);
503 }
504
505 /*
506  * DISK-specific probe after initial ident
507  */
508 static int
509 ahci_cam_probe_disk(struct ahci_port *ap, struct ata_port *atx)
510 {
511         struct ata_port *at;
512         struct ata_xfer *xa;
513         int status;
514
515         at = atx ? atx : ap->ap_ata;
516
517         /*
518          * Enable write cache if supported
519          *
520          * NOTE: "WD My Book" external disk devices have a very poor
521          *       daughter board between the the ESATA and the HD.  Sending
522          *       any ATA_C_SET_FEATURES commands will break the hardware port
523          *       with a fatal protocol error.  However, this device also
524          *       indicates that WRITECACHE is already on and READAHEAD is
525          *       not supported so we avoid the issue.
526          */
527         if ((at->at_identify.cmdset82 & ATA_IDENTIFY_WRITECACHE) &&
528             (at->at_identify.features85 & ATA_IDENTIFY_WRITECACHE) == 0) {
529                 xa = ahci_ata_get_xfer(ap, atx);
530                 xa->complete = ahci_ata_dummy_done;
531                 xa->fis->command = ATA_C_SET_FEATURES;
532                 /*xa->fis->features = ATA_SF_WRITECACHE_EN;*/
533                 xa->fis->features = ATA_SF_LOOKAHEAD_EN;
534                 xa->fis->flags = ATA_H2D_FLAGS_CMD | at->at_target;
535                 xa->fis->device = 0;
536                 xa->flags = ATA_F_READ | ATA_F_PIO | ATA_F_POLL;
537                 xa->timeout = 1000;
538                 xa->datalen = 0;
539                 status = ahci_ata_cmd(xa);
540                 if (status == ATA_COMPLETE)
541                         at->at_features |= ATA_PORT_F_WCACHE;
542                 ahci_ata_put_xfer(xa);
543         }
544
545         /*
546          * Enable readahead if supported
547          */
548         if ((at->at_identify.cmdset82 & ATA_IDENTIFY_LOOKAHEAD) &&
549             (at->at_identify.features85 & ATA_IDENTIFY_LOOKAHEAD) == 0) {
550                 xa = ahci_ata_get_xfer(ap, atx);
551                 xa->complete = ahci_ata_dummy_done;
552                 xa->fis->command = ATA_C_SET_FEATURES;
553                 xa->fis->features = ATA_SF_LOOKAHEAD_EN;
554                 xa->fis->flags = ATA_H2D_FLAGS_CMD | at->at_target;
555                 xa->fis->device = 0;
556                 xa->flags = ATA_F_READ | ATA_F_PIO | ATA_F_POLL;
557                 xa->timeout = 1000;
558                 xa->datalen = 0;
559                 status = ahci_ata_cmd(xa);
560                 if (status == ATA_COMPLETE)
561                         at->at_features |= ATA_PORT_F_RAHEAD;
562                 ahci_ata_put_xfer(xa);
563         }
564
565         /*
566          * FREEZE LOCK the device so malicious users can't lock it on us.
567          * As there is no harm in issuing this to devices that don't
568          * support the security feature set we just send it, and don't bother
569          * checking if the device sends a command abort to tell us it doesn't
570          * support it
571          */
572         if ((at->at_identify.cmdset82 & ATA_IDENTIFY_SECURITY) &&
573             (at->at_identify.securestatus & ATA_SECURE_FROZEN) == 0) {
574                 xa = ahci_ata_get_xfer(ap, atx);
575                 xa->complete = ahci_ata_dummy_done;
576                 xa->fis->command = ATA_C_SEC_FREEZE_LOCK;
577                 xa->fis->flags = ATA_H2D_FLAGS_CMD | at->at_target;
578                 xa->flags = ATA_F_READ | ATA_F_PIO | ATA_F_POLL;
579                 xa->timeout = 1000;
580                 xa->datalen = 0;
581                 status = ahci_ata_cmd(xa);
582                 if (status == ATA_COMPLETE)
583                         at->at_features |= ATA_PORT_F_FRZLCK;
584                 ahci_ata_put_xfer(xa);
585         }
586
587         return (0);
588 }
589
590 /*
591  * ATAPI-specific probe after initial ident
592  */
593 static int
594 ahci_cam_probe_atapi(struct ahci_port *ap, struct ata_port *atx)
595 {
596         return(0);
597 }
598
599 /*
600  * Fix byte ordering so buffers can be accessed as
601  * strings.
602  */
603 static void
604 ata_fix_identify(struct ata_identify *id)
605 {
606         u_int16_t       *swap;
607         int             i;
608
609         swap = (u_int16_t *)id->serial;
610         for (i = 0; i < sizeof(id->serial) / sizeof(u_int16_t); i++)
611                 swap[i] = bswap16(swap[i]);
612
613         swap = (u_int16_t *)id->firmware;
614         for (i = 0; i < sizeof(id->firmware) / sizeof(u_int16_t); i++)
615                 swap[i] = bswap16(swap[i]);
616
617         swap = (u_int16_t *)id->model;
618         for (i = 0; i < sizeof(id->model) / sizeof(u_int16_t); i++)
619                 swap[i] = bswap16(swap[i]);
620 }
621
622 /*
623  * Dummy done callback for xa.
624  */
625 static void
626 ahci_ata_dummy_done(struct ata_xfer *xa)
627 {
628 }
629
630 /*
631  * Use an engineering request to initiate a target scan for devices
632  * behind a port multiplier.
633  *
634  * An asynchronous bus scan is used to avoid reentrancy issues.
635  */
636 static void
637 ahci_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
638 {
639         struct ahci_port *ap = ccb->ccb_h.sim_priv.entries[0].ptr;
640
641         ap->ap_flags &= ~AP_F_SCAN_RUNNING;
642         if (ap->ap_flags & AP_F_SCAN_REQUESTED) {
643                 ap->ap_flags &= ~AP_F_SCAN_REQUESTED;
644                 ahci_cam_rescan(ap);
645         }
646         kfree(ccb, M_TEMP);
647 }
648
649 static void
650 ahci_cam_rescan(struct ahci_port *ap)
651 {
652         struct cam_path *path;
653         union ccb *ccb;
654         int status;
655         int i;
656
657         if (ap->ap_flags & AP_F_SCAN_RUNNING) {
658                 ap->ap_flags |= AP_F_SCAN_REQUESTED;
659                 return;
660         }
661         ap->ap_flags |= AP_F_SCAN_RUNNING;
662         for (i = 0; i < AHCI_MAX_PMPORTS; ++i) {
663                 ap->ap_ata[i].at_features |= ATA_PORT_F_RESCAN;
664         }
665
666         ccb = kmalloc(sizeof(*ccb), M_TEMP, M_WAITOK | M_ZERO);
667         status = xpt_create_path(&path, xpt_periph, cam_sim_path(ap->ap_sim),
668                                  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
669         if (status != CAM_REQ_CMP)
670                 return;
671
672         xpt_setup_ccb(&ccb->ccb_h, path, 5);    /* 5 = low priority */
673         ccb->ccb_h.func_code = XPT_ENG_EXEC | XPT_FC_QUEUED;
674         ccb->ccb_h.cbfcnp = ahci_cam_rescan_callback;
675         ccb->ccb_h.sim_priv.entries[0].ptr = ap;
676         ccb->crcn.flags = CAM_FLAG_NONE;
677         xpt_action(ccb);
678
679         /* scan is now underway */
680 }
681
682 static void
683 ahci_xpt_rescan(struct ahci_port *ap)
684 {
685         struct cam_path *path;
686         union ccb *ccb;
687         int status;
688
689         status = xpt_create_path(&path, xpt_periph, cam_sim_path(ap->ap_sim),
690                                  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
691         if (status != CAM_REQ_CMP)
692                 return;
693         ccb = kmalloc(sizeof(*ccb), M_TEMP, M_WAITOK | M_ZERO);
694         xpt_setup_ccb(&ccb->ccb_h, path, 5);    /* 5 = low priority */
695         ccb->ccb_h.func_code = XPT_SCAN_BUS | XPT_FC_QUEUED;
696         ccb->ccb_h.cbfcnp = ahci_cam_rescan_callback;
697         ccb->ccb_h.sim_priv.entries[0].ptr = ap;
698         ccb->crcn.flags = CAM_FLAG_NONE;
699         xpt_action(ccb);
700 }
701
702 #if 0
703                 ccb = xpt_alloc_ccb();
704                 status = xpt_create_path(&ccb->ccb_h.path, xpt_periph,
705                                          cam_sim_path(ap->ap_sim),
706                                          CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
707                 if (status == CAM_REQ_CMP) {
708                         kprintf("RESCAN SCSI BUS %d\n", ccb->ccb_h.timeout);
709                         ccb->crcn.flags = CAM_FLAG_NONE;
710                         xpt_rescan(ccb);
711                 } else {
712                         xpt_free_ccb(ccb);
713                 }
714 #endif
715
716 /*
717  * Action function - dispatch command
718  */
719 static
720 void
721 ahci_xpt_action(struct cam_sim *sim, union ccb *ccb)
722 {
723         struct ahci_port *ap;
724         struct ata_port  *at, *atx;
725         struct ccb_hdr *ccbh;
726         int unit;
727
728         /* XXX lock */
729         ap = cam_sim_softc(sim);
730         at = ap->ap_ata;
731         atx = NULL;
732         KKASSERT(ap != NULL);
733         ccbh = &ccb->ccb_h;
734         unit = cam_sim_unit(sim);
735
736         /*
737          * Early failure checks.  These checks do not apply to XPT_PATH_INQ,
738          * otherwise the bus rescan will not remove the dead devices when
739          * unplugging a PM.
740          *
741          * For non-wildcards we have one target (0) and one lun (0),
742          * unless we have a port multiplier.
743          *
744          * A wildcard target indicates only the general bus is being
745          * probed.
746          *
747          * Calculate at and atx.  at is always non-NULL.  atx is only
748          * non-NULL for direct-attached devices.  It will be NULL for
749          * devices behind a port multiplier.
750          *
751          * XXX What do we do with a LUN wildcard?
752          */
753         if (ccbh->target_id != CAM_TARGET_WILDCARD &&
754             ccbh->func_code != XPT_PATH_INQ) {
755                 if (ap->ap_type == ATA_PORT_T_NONE) {
756                         ccbh->status = CAM_DEV_NOT_THERE;
757                         xpt_done(ccb);
758                         return;
759                 }
760                 if (ccbh->target_id < 0 || ccbh->target_id >= ap->ap_pmcount) {
761                         ccbh->status = CAM_DEV_NOT_THERE;
762                         xpt_done(ccb);
763                         return;
764                 }
765                 at += ccbh->target_id;
766                 if (ap->ap_type == ATA_PORT_T_PM)
767                         atx = at;
768
769                 if (ccbh->target_lun != CAM_LUN_WILDCARD && ccbh->target_lun) {
770                         ccbh->status = CAM_DEV_NOT_THERE;
771                         xpt_done(ccb);
772                         return;
773                 }
774         }
775
776         /*
777          * Switch on the meta XPT command
778          */
779         switch(ccbh->func_code) {
780         case XPT_ENG_EXEC:
781                 /*
782                  * This routine is called after a port multiplier has been
783                  * probed.
784                  */
785                 ccbh->status = CAM_REQ_CMP;
786                 ahci_port_state_machine(ap);
787                 xpt_done(ccb);
788
789                 /*
790                  * Rescanning the scsi bus should clean up the peripheral
791                  * associations.
792                  */
793                 ahci_xpt_rescan(ap);
794                 break;
795         case XPT_PATH_INQ:
796                 /*
797                  * This command always succeeds, otherwise the bus scan
798                  * will not detach dead devices.
799                  */
800                 ccb->cpi.version_num = 1;
801                 ccb->cpi.hba_inquiry = 0;
802                 ccb->cpi.target_sprt = 0;
803                 ccb->cpi.hba_misc = PIM_SEQSCAN;
804                 ccb->cpi.hba_eng_cnt = 0;
805                 bzero(ccb->cpi.vuhba_flags, sizeof(ccb->cpi.vuhba_flags));
806                 ccb->cpi.max_target = AHCI_MAX_PMPORTS;
807                 ccb->cpi.max_lun = 0;
808                 ccb->cpi.async_flags = 0;
809                 ccb->cpi.hpath_id = 0;
810                 ccb->cpi.initiator_id = AHCI_MAX_PMPORTS - 1;
811                 ccb->cpi.unit_number = cam_sim_unit(sim);
812                 ccb->cpi.bus_id = cam_sim_bus(sim);
813                 ccb->cpi.base_transfer_speed = 150000;
814                 ccb->cpi.transport = XPORT_AHCI;
815                 ccb->cpi.transport_version = 1;
816                 ccb->cpi.protocol = PROTO_SCSI;
817                 ccb->cpi.protocol_version = SCSI_REV_2;
818
819                 ccbh->status = CAM_REQ_CMP;
820                 if (ccbh->target_id != CAM_TARGET_WILDCARD) {
821                         switch(ahci_pread(ap, AHCI_PREG_SSTS) &
822                                AHCI_PREG_SSTS_SPD) {
823                         case AHCI_PREG_SSTS_SPD_GEN1:
824                                 ccb->cpi.base_transfer_speed = 150000;
825                                 break;
826                         case AHCI_PREG_SSTS_SPD_GEN2:
827                                 ccb->cpi.base_transfer_speed = 300000;
828                                 break;
829                         default:
830                                 /* unknown */
831                                 ccb->cpi.base_transfer_speed = 1000;
832                                 break;
833                         }
834 #if 0
835                         if (ap->ap_type == ATA_PORT_T_NONE)
836                                 ccbh->status = CAM_DEV_NOT_THERE;
837 #endif
838                 }
839                 xpt_done(ccb);
840                 break;
841         case XPT_RESET_DEV:
842                 lwkt_serialize_enter(&ap->ap_sc->sc_serializer);
843                 if (ap->ap_type == ATA_PORT_T_NONE) {
844                         ccbh->status = CAM_DEV_NOT_THERE;
845                 } else {
846                         ahci_port_reset(ap, atx, 0);
847                         ccbh->status = CAM_REQ_CMP;
848                 }
849                 lwkt_serialize_exit(&ap->ap_sc->sc_serializer);
850                 xpt_done(ccb);
851                 break;
852         case XPT_RESET_BUS:
853                 lwkt_serialize_enter(&ap->ap_sc->sc_serializer);
854                 ahci_port_reset(ap, NULL, 1);
855                 lwkt_serialize_exit(&ap->ap_sc->sc_serializer);
856                 ccbh->status = CAM_REQ_CMP;
857                 xpt_done(ccb);
858                 break;
859         case XPT_SET_TRAN_SETTINGS:
860                 ccbh->status = CAM_FUNC_NOTAVAIL;
861                 xpt_done(ccb);
862                 break;
863         case XPT_GET_TRAN_SETTINGS:
864                 ccb->cts.protocol = PROTO_SCSI;
865                 ccb->cts.protocol_version = SCSI_REV_2;
866                 ccb->cts.transport = XPORT_AHCI;
867                 ccb->cts.transport_version = XPORT_VERSION_UNSPECIFIED;
868                 ccb->cts.proto_specific.valid = 0;
869                 ccb->cts.xport_specific.valid = 0;
870                 ccbh->status = CAM_REQ_CMP;
871                 xpt_done(ccb);
872                 break;
873         case XPT_CALC_GEOMETRY:
874                 cam_calc_geometry(&ccb->ccg, 1);
875                 xpt_done(ccb);
876                 break;
877         case XPT_SCSI_IO:
878                 switch(at->at_type) {
879                 case ATA_PORT_T_DISK:
880                         ahci_xpt_scsi_disk_io(ap, atx, ccb);
881                         break;
882                 case ATA_PORT_T_ATAPI:
883                         ahci_xpt_scsi_atapi_io(ap, atx, ccb);
884                         break;
885                 default:
886                         ccbh->status = CAM_REQ_INVALID;
887                         xpt_done(ccb);
888                         break;
889                 }
890                 break;
891         default:
892                 ccbh->status = CAM_REQ_INVALID;
893                 xpt_done(ccb);
894                 break;
895         }
896 }
897
898 /*
899  * Poll function.
900  *
901  * Generally this function gets called heavily when interrupts might be
902  * non-operational, during a halt/reboot or panic.
903  */
904 static
905 void
906 ahci_xpt_poll(struct cam_sim *sim)
907 {
908         struct ahci_port *ap;
909
910         ap = cam_sim_softc(sim);
911         crit_enter();
912         lwkt_serialize_enter(&ap->ap_sc->sc_serializer);
913         ahci_port_intr(ap);
914         lwkt_serialize_exit(&ap->ap_sc->sc_serializer);
915         crit_exit();
916 }
917
918 /*
919  * Convert the SCSI command in ccb to an ata_xfer command in xa
920  * for ATA_PORT_T_DISK operations.  Set the completion function
921  * to convert the response back, then dispatch to the OpenBSD AHCI
922  * layer.
923  *
924  * AHCI DISK commands only support a limited command set, and we
925  * fake additional commands to make it play nice with the CAM subsystem.
926  */
927 static
928 void
929 ahci_xpt_scsi_disk_io(struct ahci_port *ap, struct ata_port *atx,
930                       union ccb *ccb)
931 {
932         struct ccb_hdr *ccbh;
933         struct ccb_scsiio *csio;
934         struct ata_xfer *xa;
935         struct ata_port *at;
936         struct ata_fis_h2d *fis;
937         scsi_cdb_t cdb;
938         union scsi_data *rdata;
939         int rdata_len;
940         u_int64_t capacity;
941         u_int64_t lba;
942         u_int32_t count;
943
944         ccbh = &ccb->csio.ccb_h;
945         csio = &ccb->csio;
946         at = atx ? atx : &ap->ap_ata[0];
947
948         /*
949          * XXX not passing NULL at for direct attach!
950          */
951         xa = ahci_ata_get_xfer(ap, atx);
952         rdata = (void *)csio->data_ptr;
953         rdata_len = csio->dxfer_len;
954
955         /*
956          * Build the FIS or process the csio to completion.
957          */
958         cdb = (void *)((ccbh->flags & CAM_CDB_POINTER) ?
959                         csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes);
960
961         switch(cdb->generic.opcode) {
962         case REQUEST_SENSE:
963                 /*
964                  * Auto-sense everything, so explicit sense requests
965                  * return no-sense.
966                  */
967                 ccbh->status = CAM_SCSI_STATUS_ERROR;
968                 break;
969         case INQUIRY:
970                 /*
971                  * Inquiry supported features
972                  *
973                  * [opcode, byte2, page_code, length, control]
974                  */
975                 if (cdb->inquiry.byte2 & SI_EVPD) {
976                         switch(cdb->inquiry.page_code) {
977                         case SVPD_SUPPORTED_PAGE_LIST:
978                                 /* XXX atascsi_disk_vpd_supported */
979                         case SVPD_UNIT_SERIAL_NUMBER:
980                                 /* XXX atascsi_disk_vpd_serial */
981                         case SVPD_UNIT_DEVID:
982                                 /* XXX atascsi_disk_vpd_ident */
983                         default:
984                                 ccbh->status = CAM_FUNC_NOTAVAIL;
985                                 break;
986                         }
987                 } else {
988                         bzero(rdata, rdata_len);
989                         if (rdata_len < SHORT_INQUIRY_LENGTH) {
990                                 ccbh->status = CAM_CCB_LEN_ERR;
991                                 break;
992                         }
993                         if (rdata_len > sizeof(rdata->inquiry_data))
994                                 rdata_len = sizeof(rdata->inquiry_data);
995                         rdata->inquiry_data.device = T_DIRECT;
996                         rdata->inquiry_data.version = SCSI_REV_SPC2;
997                         rdata->inquiry_data.response_format = 2;
998                         rdata->inquiry_data.additional_length = 32;
999                         bcopy("SATA    ", rdata->inquiry_data.vendor, 8);
1000                         bcopy(at->at_identify.model,
1001                               rdata->inquiry_data.product,
1002                               sizeof(rdata->inquiry_data.product));
1003                         bcopy(at->at_identify.firmware,
1004                               rdata->inquiry_data.revision,
1005                               sizeof(rdata->inquiry_data.revision));
1006                         ccbh->status = CAM_REQ_CMP;
1007                 }
1008                 break;
1009         case READ_CAPACITY_16:
1010                 if (cdb->read_capacity_16.service_action != SRC16_SERVICE_ACTION) {
1011                         ccbh->status = CAM_REQ_INVALID;
1012                         break;
1013                 }
1014                 if (rdata_len < sizeof(rdata->read_capacity_data_16)) {
1015                         ccbh->status = CAM_CCB_LEN_ERR;
1016                         break;
1017                 }
1018                 /* fall through */
1019         case READ_CAPACITY:
1020                 if (rdata_len < sizeof(rdata->read_capacity_data)) {
1021                         ccbh->status = CAM_CCB_LEN_ERR;
1022                         break;
1023                 }
1024
1025                 capacity = at->at_capacity;
1026
1027                 bzero(rdata, rdata_len);
1028                 if (cdb->generic.opcode == READ_CAPACITY) {
1029                         rdata_len = sizeof(rdata->read_capacity_data);
1030                         if (capacity > 0xFFFFFFFFU)
1031                                 capacity = 0xFFFFFFFFU;
1032                         bzero(&rdata->read_capacity_data, rdata_len);
1033                         scsi_ulto4b((u_int32_t)capacity - 1,
1034                                     rdata->read_capacity_data.addr);
1035                         scsi_ulto4b(512, rdata->read_capacity_data.length);
1036                 } else {
1037                         rdata_len = sizeof(rdata->read_capacity_data_16);
1038                         bzero(&rdata->read_capacity_data_16, rdata_len);
1039                         scsi_u64to8b(capacity - 1,
1040                                      rdata->read_capacity_data_16.addr);
1041                         scsi_ulto4b(512, rdata->read_capacity_data_16.length);
1042                 }
1043                 ccbh->status = CAM_REQ_CMP;
1044                 break;
1045         case SYNCHRONIZE_CACHE:
1046                 /*
1047                  * Synchronize cache.  Specification says this can take
1048                  * greater then 30 seconds so give it at least 45.
1049                  */
1050                 fis = xa->fis;
1051                 fis->flags = ATA_H2D_FLAGS_CMD;
1052                 fis->command = ATA_C_FLUSH_CACHE;
1053                 fis->device = 0;
1054                 if (xa->timeout < 45000)
1055                         xa->timeout = 45000;
1056                 xa->datalen = 0;
1057                 xa->flags = ATA_F_READ;
1058                 xa->complete = ahci_ata_complete_disk_synchronize_cache;
1059                 break;
1060         case TEST_UNIT_READY:
1061         case START_STOP_UNIT:
1062         case PREVENT_ALLOW:
1063                 /*
1064                  * Just silently return success
1065                  */
1066                 ccbh->status = CAM_REQ_CMP;
1067                 rdata_len = 0;
1068                 break;
1069         case ATA_PASS_12:
1070         case ATA_PASS_16:
1071                 /*
1072                  * XXX implement pass-through
1073                  */
1074                 ccbh->status = CAM_FUNC_NOTAVAIL;
1075                 break;
1076         default:
1077                 switch(cdb->generic.opcode) {
1078                 case READ_6:
1079                         lba = scsi_3btoul(cdb->rw_6.addr) & 0x1FFFFF;
1080                         count = cdb->rw_6.length ? cdb->rw_6.length : 0x100;
1081                         xa->flags = ATA_F_READ;
1082                         break;
1083                 case READ_10:
1084                         lba = scsi_4btoul(cdb->rw_10.addr);
1085                         count = scsi_2btoul(cdb->rw_10.length);
1086                         xa->flags = ATA_F_READ;
1087                         break;
1088                 case READ_12:
1089                         lba = scsi_4btoul(cdb->rw_12.addr);
1090                         count = scsi_4btoul(cdb->rw_12.length);
1091                         xa->flags = ATA_F_READ;
1092                         break;
1093                 case READ_16:
1094                         lba = scsi_8btou64(cdb->rw_16.addr);
1095                         count = scsi_4btoul(cdb->rw_16.length);
1096                         xa->flags = ATA_F_READ;
1097                         break;
1098                 case WRITE_6:
1099                         lba = scsi_3btoul(cdb->rw_6.addr) & 0x1FFFFF;
1100                         count = cdb->rw_6.length ? cdb->rw_6.length : 0x100;
1101                         xa->flags = ATA_F_WRITE;
1102                         break;
1103                 case WRITE_10:
1104                         lba = scsi_4btoul(cdb->rw_10.addr);
1105                         count = scsi_2btoul(cdb->rw_10.length);
1106                         xa->flags = ATA_F_WRITE;
1107                         break;
1108                 case WRITE_12:
1109                         lba = scsi_4btoul(cdb->rw_12.addr);
1110                         count = scsi_4btoul(cdb->rw_12.length);
1111                         xa->flags = ATA_F_WRITE;
1112                         break;
1113                 case WRITE_16:
1114                         lba = scsi_8btou64(cdb->rw_16.addr);
1115                         count = scsi_4btoul(cdb->rw_16.length);
1116                         xa->flags = ATA_F_WRITE;
1117                         break;
1118                 default:
1119                         ccbh->status = CAM_REQ_INVALID;
1120                         break;
1121                 }
1122                 if (ccbh->status != CAM_REQ_INPROG)
1123                         break;
1124
1125                 fis = xa->fis;
1126                 fis->flags = ATA_H2D_FLAGS_CMD;
1127                 fis->lba_low = (u_int8_t)lba;
1128                 fis->lba_mid = (u_int8_t)(lba >> 8);
1129                 fis->lba_high = (u_int8_t)(lba >> 16);
1130                 fis->device = ATA_H2D_DEVICE_LBA;
1131
1132                 /*
1133                  * NCQ only for direct-attached disks, do not currently
1134                  * try to use NCQ with port multipliers.
1135                  */
1136                 if (at->at_ncqdepth > 1 &&
1137                     ap->ap_type == ATA_PORT_T_DISK &&
1138                     (ap->ap_sc->sc_cap & AHCI_REG_CAP_SNCQ) &&
1139                     (ccbh->flags & CAM_POLLED) == 0) {
1140                         /*
1141                          * Use NCQ - always uses 48 bit addressing
1142                          */
1143                         xa->flags |= ATA_F_NCQ;
1144                         fis->command = (xa->flags & ATA_F_WRITE) ?
1145                                         ATA_C_WRITE_FPDMA : ATA_C_READ_FPDMA;
1146                         fis->lba_low_exp = (u_int8_t)(lba >> 24);
1147                         fis->lba_mid_exp = (u_int8_t)(lba >> 32);
1148                         fis->lba_high_exp = (u_int8_t)(lba >> 40);
1149                         fis->sector_count = xa->tag << 3;
1150                         fis->features = (u_int8_t)count;
1151                         fis->features_exp = (u_int8_t)(count >> 8);
1152                 } else if (count > 0x100 || lba > 0xFFFFFFFFU) {
1153                         /*
1154                          * Use LBA48
1155                          */
1156                         fis->command = (xa->flags & ATA_F_WRITE) ?
1157                                         ATA_C_WRITEDMA_EXT : ATA_C_READDMA_EXT;
1158                         fis->lba_low_exp = (u_int8_t)(lba >> 24);
1159                         fis->lba_mid_exp = (u_int8_t)(lba >> 32);
1160                         fis->lba_high_exp = (u_int8_t)(lba >> 40);
1161                         fis->sector_count = (u_int8_t)count;
1162                         fis->sector_count_exp = (u_int8_t)(count >> 8);
1163                 } else {
1164                         /*
1165                          * Use LBA
1166                          *
1167                          * NOTE: 256 sectors is supported, stored as 0.
1168                          */
1169                         fis->command = (xa->flags & ATA_F_WRITE) ?
1170                                         ATA_C_WRITEDMA : ATA_C_READDMA;
1171                         fis->device |= (u_int8_t)(lba >> 24) & 0x0F;
1172                         fis->sector_count = (u_int8_t)count;
1173                 }
1174
1175                 xa->data = csio->data_ptr;
1176                 xa->datalen = csio->dxfer_len;
1177                 xa->complete = ahci_ata_complete_disk_rw;
1178                 xa->timeout = ccbh->timeout;    /* milliseconds */
1179                 if (ccbh->flags & CAM_POLLED)
1180                         xa->flags |= ATA_F_POLL;
1181                 break;
1182         }
1183
1184         /*
1185          * If the request is still in progress the xa and FIS have
1186          * been set up and must be dispatched.  Otherwise the request
1187          * is complete.
1188          */
1189         if (ccbh->status == CAM_REQ_INPROG) {
1190                 KKASSERT(xa->complete != NULL);
1191                 xa->atascsi_private = ccb;
1192                 ccb->ccb_h.sim_priv.entries[0].ptr = ap;
1193                 lwkt_serialize_enter(&ap->ap_sc->sc_serializer);
1194                 fis->flags |= at->at_target;
1195                 ahci_ata_cmd(xa);
1196                 lwkt_serialize_exit(&ap->ap_sc->sc_serializer);
1197         } else {
1198                 ahci_ata_put_xfer(xa);
1199                 xpt_done(ccb);
1200         }
1201 }
1202
1203 /*
1204  * Convert the SCSI command in ccb to an ata_xfer command in xa
1205  * for ATA_PORT_T_ATAPI operations.  Set the completion function
1206  * to convert the response back, then dispatch to the OpenBSD AHCI
1207  * layer.
1208  */
1209 static
1210 void
1211 ahci_xpt_scsi_atapi_io(struct ahci_port *ap, struct ata_port *atx,
1212                         union ccb *ccb)
1213 {
1214         struct ccb_hdr *ccbh;
1215         struct ccb_scsiio *csio;
1216         struct ata_xfer *xa;
1217         struct ata_fis_h2d *fis;
1218         scsi_cdb_t cdbs;
1219         scsi_cdb_t cdbd;
1220         int flags;
1221         struct ata_port *at;
1222
1223         ccbh = &ccb->csio.ccb_h;
1224         csio = &ccb->csio;
1225         at = atx ? atx : &ap->ap_ata[0];
1226
1227         switch (ccbh->flags & CAM_DIR_MASK) {
1228         case CAM_DIR_IN:
1229                 flags = ATA_F_PACKET | ATA_F_READ;
1230                 break;
1231         case CAM_DIR_OUT:
1232                 flags = ATA_F_PACKET | ATA_F_WRITE;
1233                 break;
1234         case CAM_DIR_NONE:
1235                 flags = ATA_F_PACKET;
1236                 break;
1237         default:
1238                 ccbh->status = CAM_REQ_INVALID;
1239                 xpt_done(ccb);
1240                 return;
1241                 /* NOT REACHED */
1242         }
1243
1244         /*
1245          * The command has to fit in the packet command buffer.
1246          */
1247         if (csio->cdb_len < 6 || csio->cdb_len > 16) {
1248                 ccbh->status = CAM_CCB_LEN_ERR;
1249                 xpt_done(ccb);
1250                 return;
1251         }
1252
1253         /*
1254          * Initialize the XA and FIS.
1255          *
1256          * XXX not passing NULL at for direct attach!
1257          */
1258         xa = ahci_ata_get_xfer(ap, atx);
1259         fis = xa->fis;
1260
1261         fis->flags = ATA_H2D_FLAGS_CMD | at->at_target;
1262         fis->command = ATA_C_PACKET;
1263         fis->device = 0;
1264         fis->sector_count = xa->tag << 3;
1265         fis->features = ATA_H2D_FEATURES_DMA |
1266                     ((flags & ATA_F_WRITE) ?
1267                     ATA_H2D_FEATURES_DIR_WRITE : ATA_H2D_FEATURES_DIR_READ);
1268         fis->lba_mid = 0x00;
1269         fis->lba_high = 0x20;
1270
1271         xa->flags = flags;
1272         xa->data = csio->data_ptr;
1273         xa->datalen = csio->dxfer_len;
1274         xa->timeout = ccbh->timeout;    /* milliseconds */
1275
1276         if (ccbh->flags & CAM_POLLED)
1277                 xa->flags |= ATA_F_POLL;
1278
1279         /*
1280          * Copy the cdb to the packetcmd buffer in the FIS using a
1281          * convenient pointer in the xa.
1282          */
1283         cdbs = (void *)((ccbh->flags & CAM_CDB_POINTER) ?
1284                         csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes);
1285         bcopy(cdbs, xa->packetcmd, csio->cdb_len);
1286
1287 #if 0
1288         kprintf("opcode %d cdb_len %d dxfer_len %d\n",
1289                 cdbs->generic.opcode,
1290                 csio->cdb_len, csio->dxfer_len);
1291 #endif
1292
1293         /*
1294          * Some ATAPI commands do not actually follow the SCSI standard.
1295          */
1296         cdbd = (void *)xa->packetcmd;
1297
1298         switch(cdbd->generic.opcode) {
1299         case INQUIRY:
1300                 /*
1301                  * Some ATAPI devices can't handle SI_EVPD being set
1302                  * for a basic inquiry (page_code == 0).
1303                  *
1304                  * Some ATAPI devices can't handle long inquiry lengths,
1305                  * don't ask me why.  Truncate the inquiry length.
1306                  */
1307                 if ((cdbd->inquiry.byte2 & SI_EVPD) &&
1308                     cdbd->inquiry.page_code == 0) {
1309                         cdbd->inquiry.byte2 &= ~SI_EVPD;
1310                 }
1311                 if (cdbd->inquiry.page_code == 0 &&
1312                     cdbd->inquiry.length > SHORT_INQUIRY_LENGTH) {
1313                         cdbd->inquiry.length = SHORT_INQUIRY_LENGTH;
1314                 }
1315                 break;
1316         case READ_6:
1317         case WRITE_6:
1318                 /*
1319                  * Convert *_6 to *_10 commands.  Most ATAPI devices
1320                  * cannot handle the SCSI READ_6 and WRITE_6 commands.
1321                  */
1322                 cdbd->rw_10.opcode |= 0x20;
1323                 cdbd->rw_10.byte2 = 0;
1324                 cdbd->rw_10.addr[0] = cdbs->rw_6.addr[0] & 0x1F;
1325                 cdbd->rw_10.addr[1] = cdbs->rw_6.addr[1];
1326                 cdbd->rw_10.addr[2] = cdbs->rw_6.addr[2];
1327                 cdbd->rw_10.addr[3] = 0;
1328                 cdbd->rw_10.reserved = 0;
1329                 cdbd->rw_10.length[0] = 0;
1330                 cdbd->rw_10.length[1] = cdbs->rw_6.length;
1331                 cdbd->rw_10.control = cdbs->rw_6.control;
1332                 break;
1333         default:
1334                 break;
1335         }
1336
1337         /*
1338          * And dispatch
1339          */
1340         xa->complete = ahci_atapi_complete_cmd;
1341         xa->atascsi_private = ccb;
1342         ccb->ccb_h.sim_priv.entries[0].ptr = ap;
1343         ahci_ata_cmd(xa);
1344 }
1345
1346 /*
1347  * Completion function for ATA_PORT_T_DISK cache synchronization.
1348  */
1349 static
1350 void
1351 ahci_ata_complete_disk_synchronize_cache(struct ata_xfer *xa)
1352 {
1353         union ccb *ccb = xa->atascsi_private;
1354         struct ccb_hdr *ccbh = &ccb->ccb_h;
1355         struct ahci_port *ap = ccb->ccb_h.sim_priv.entries[0].ptr;
1356
1357         switch(xa->state) {
1358         case ATA_S_COMPLETE:
1359                 ccbh->status = CAM_REQ_CMP;
1360                 ccb->csio.scsi_status = SCSI_STATUS_OK;
1361                 break;
1362         case ATA_S_ERROR:
1363                 kprintf("%s: synchronize_cache: error\n",
1364                         ATANAME(ap, xa->at));
1365                 ccbh->status = CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
1366                 ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1367                 ahci_ata_dummy_sense(&ccb->csio.sense_data);
1368                 break;
1369         case ATA_S_TIMEOUT:
1370                 kprintf("%s: synchronize_cache: timeout\n",
1371                         ATANAME(ap, xa->at));
1372                 ccbh->status = CAM_CMD_TIMEOUT;
1373                 break;
1374         default:
1375                 kprintf("%s: synchronize_cache: unknown state %d\n",
1376                         ATANAME(ap, xa->at), xa->state);
1377                 ccbh->status = CAM_REQ_CMP_ERR;
1378                 break;
1379         }
1380         ahci_ata_put_xfer(xa);
1381         lwkt_serialize_exit(&ap->ap_sc->sc_serializer);
1382         xpt_done(ccb);
1383         lwkt_serialize_enter(&ap->ap_sc->sc_serializer);
1384 }
1385
1386 /*
1387  * Completion function for ATA_PORT_T_DISK I/O
1388  */
1389 static
1390 void
1391 ahci_ata_complete_disk_rw(struct ata_xfer *xa)
1392 {
1393         union ccb *ccb = xa->atascsi_private;
1394         struct ccb_hdr *ccbh = &ccb->ccb_h;
1395         struct ahci_port *ap = ccb->ccb_h.sim_priv.entries[0].ptr;
1396
1397         switch(xa->state) {
1398         case ATA_S_COMPLETE:
1399                 ccbh->status = CAM_REQ_CMP;
1400                 ccb->csio.scsi_status = SCSI_STATUS_OK;
1401                 break;
1402         case ATA_S_ERROR:
1403                 kprintf("%s: disk_rw: error\n", ATANAME(ap, xa->at));
1404                 ccbh->status = CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
1405                 ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1406                 ahci_ata_dummy_sense(&ccb->csio.sense_data);
1407                 break;
1408         case ATA_S_TIMEOUT:
1409                 kprintf("%s: disk_rw: timeout\n", ATANAME(ap, xa->at));
1410                 ccbh->status = CAM_CMD_TIMEOUT;
1411                 break;
1412         default:
1413                 kprintf("%s: disk_rw: unknown state %d\n",
1414                         ATANAME(ap, xa->at), xa->state);
1415                 ccbh->status = CAM_REQ_CMP_ERR;
1416                 break;
1417         }
1418         ccb->csio.resid = xa->resid;
1419         ahci_ata_put_xfer(xa);
1420         lwkt_serialize_exit(&ap->ap_sc->sc_serializer);
1421         xpt_done(ccb);
1422         lwkt_serialize_enter(&ap->ap_sc->sc_serializer);
1423 }
1424
1425 /*
1426  * Completion function for ATA_PORT_T_ATAPI I/O
1427  *
1428  * Sense data is returned in the rfis.
1429  */
1430 static
1431 void
1432 ahci_atapi_complete_cmd(struct ata_xfer *xa)
1433 {
1434         union ccb *ccb = xa->atascsi_private;
1435         struct ccb_hdr *ccbh = &ccb->ccb_h;
1436         struct ahci_port *ap = ccb->ccb_h.sim_priv.entries[0].ptr;
1437         scsi_cdb_t cdb;
1438
1439         cdb = (void *)((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1440                         ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes);
1441
1442         switch(xa->state) {
1443         case ATA_S_COMPLETE:
1444                 ccbh->status = CAM_REQ_CMP;
1445                 ccb->csio.scsi_status = SCSI_STATUS_OK;
1446                 break;
1447         case ATA_S_ERROR:
1448                 kprintf("%s: cmd %d: error\n",
1449                         PORTNAME(ap), cdb->generic.opcode);
1450                 ccbh->status = CAM_SCSI_STATUS_ERROR;
1451                 ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1452                 ahci_ata_atapi_sense(&xa->rfis, &ccb->csio.sense_data);
1453                 break;
1454         case ATA_S_TIMEOUT:
1455                 kprintf("%s: cmd %d: timeout\n",
1456                         PORTNAME(ap), cdb->generic.opcode);
1457                 ccbh->status = CAM_CMD_TIMEOUT;
1458                 break;
1459         default:
1460                 kprintf("%s: cmd %d: unknown state %d\n",
1461                         PORTNAME(ap), cdb->generic.opcode, xa->state);
1462                 ccbh->status = CAM_REQ_CMP_ERR;
1463                 break;
1464         }
1465         ccb->csio.resid = xa->resid;
1466         ahci_ata_put_xfer(xa);
1467         lwkt_serialize_exit(&ap->ap_sc->sc_serializer);
1468         xpt_done(ccb);
1469         lwkt_serialize_enter(&ap->ap_sc->sc_serializer);
1470 }
1471
1472 /*
1473  * Construct dummy sense data for errors on DISKs
1474  */
1475 static
1476 void
1477 ahci_ata_dummy_sense(struct scsi_sense_data *sense_data)
1478 {
1479         sense_data->error_code = SSD_ERRCODE_VALID | SSD_CURRENT_ERROR;
1480         sense_data->segment = 0;
1481         sense_data->flags = SSD_KEY_MEDIUM_ERROR;
1482         sense_data->info[0] = 0;
1483         sense_data->info[1] = 0;
1484         sense_data->info[2] = 0;
1485         sense_data->info[3] = 0;
1486         sense_data->extra_len = 0;
1487 }
1488
1489 /*
1490  * Construct atapi sense data for errors on ATAPI
1491  *
1492  * The ATAPI sense data is stored in the passed rfis and must be converted
1493  * to SCSI sense data.
1494  */
1495 static
1496 void
1497 ahci_ata_atapi_sense(struct ata_fis_d2h *rfis,
1498                      struct scsi_sense_data *sense_data)
1499 {
1500         sense_data->error_code = SSD_ERRCODE_VALID | SSD_CURRENT_ERROR;
1501         sense_data->segment = 0;
1502         sense_data->flags = (rfis->error & 0xF0) >> 4;
1503         if (rfis->error & 0x04)
1504                 sense_data->flags |= SSD_KEY_ILLEGAL_REQUEST;
1505         if (rfis->error & 0x02)
1506                 sense_data->flags |= SSD_EOM;
1507         if (rfis->error & 0x01)
1508                 sense_data->flags |= SSD_ILI;
1509         sense_data->info[0] = 0;
1510         sense_data->info[1] = 0;
1511         sense_data->info[2] = 0;
1512         sense_data->info[3] = 0;
1513         sense_data->extra_len = 0;
1514 }