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