sd.c revision 1.321 1 /* $NetBSD: sd.c,v 1.321 2016/12/16 14:58:53 mlelstv Exp $ */
2
3 /*-
4 * Copyright (c) 1998, 2003, 2004 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Charles M. Hannum.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Originally written by Julian Elischer (julian (at) dialix.oz.au)
34 * for TRW Financial Systems for use under the MACH(2.5) operating system.
35 *
36 * TRW Financial Systems, in accordance with their agreement with Carnegie
37 * Mellon University, makes this software available to CMU to distribute
38 * or use in any manner that they see fit as long as this message is kept with
39 * the software. For this reason TFS also grants any other persons or
40 * organisations permission to use or modify this software.
41 *
42 * TFS supplies this software to be publicly redistributed
43 * on the understanding that TFS is not responsible for the correct
44 * functioning of this software in any circumstances.
45 *
46 * Ported to run under 386BSD by Julian Elischer (julian (at) dialix.oz.au) Sept 1992
47 */
48
49 #include <sys/cdefs.h>
50 __KERNEL_RCSID(0, "$NetBSD: sd.c,v 1.321 2016/12/16 14:58:53 mlelstv Exp $");
51
52 #ifdef _KERNEL_OPT
53 #include "opt_scsi.h"
54 #endif
55
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/kernel.h>
59 #include <sys/file.h>
60 #include <sys/stat.h>
61 #include <sys/ioctl.h>
62 #include <sys/scsiio.h>
63 #include <sys/buf.h>
64 #include <sys/bufq.h>
65 #include <sys/uio.h>
66 #include <sys/malloc.h>
67 #include <sys/errno.h>
68 #include <sys/device.h>
69 #include <sys/disklabel.h>
70 #include <sys/disk.h>
71 #include <sys/proc.h>
72 #include <sys/conf.h>
73 #include <sys/vnode.h>
74
75 #include <dev/scsipi/scsi_spc.h>
76 #include <dev/scsipi/scsipi_all.h>
77 #include <dev/scsipi/scsi_all.h>
78 #include <dev/scsipi/scsipi_disk.h>
79 #include <dev/scsipi/scsi_disk.h>
80 #include <dev/scsipi/scsiconf.h>
81 #include <dev/scsipi/scsipi_base.h>
82 #include <dev/scsipi/sdvar.h>
83
84 #include <prop/proplib.h>
85
86 #define SDUNIT(dev) DISKUNIT(dev)
87 #define SDPART(dev) DISKPART(dev)
88 #define SDMINOR(unit, part) DISKMINOR(unit, part)
89 #define MAKESDDEV(maj, unit, part) MAKEDISKDEV(maj, unit, part)
90
91 #define SDLABELDEV(dev) (MAKESDDEV(major(dev), SDUNIT(dev), RAW_PART))
92
93 #define SD_DEFAULT_BLKSIZE 512
94
95 static void sdminphys(struct buf *);
96 static void sdstart(struct scsipi_periph *);
97 static void sdrestart(void *);
98 static void sddone(struct scsipi_xfer *, int);
99 static bool sd_suspend(device_t, const pmf_qual_t *);
100 static bool sd_shutdown(device_t, int);
101 static int sd_interpret_sense(struct scsipi_xfer *);
102 static int sd_diskstart(device_t, struct buf *);
103 static int sd_dumpblocks(device_t, void *, daddr_t, int);
104 static void sd_iosize(device_t, int *);
105 static int sd_lastclose(device_t);
106 static int sd_firstopen(device_t, dev_t, int, int);
107 static void sd_label(device_t, struct disklabel *);
108
109 static int sd_mode_sense(struct sd_softc *, u_int8_t, void *, size_t, int,
110 int, int *);
111 static int sd_mode_select(struct sd_softc *, u_int8_t, void *, size_t, int,
112 int);
113 static int sd_validate_blksize(struct scsipi_periph *, int);
114 static u_int64_t sd_read_capacity(struct scsipi_periph *, int *, int flags);
115 static int sd_get_simplifiedparms(struct sd_softc *, struct disk_parms *,
116 int);
117 static int sd_get_capacity(struct sd_softc *, struct disk_parms *, int);
118 static int sd_get_parms(struct sd_softc *, struct disk_parms *, int);
119 static int sd_get_parms_page4(struct sd_softc *, struct disk_parms *,
120 int);
121 static int sd_get_parms_page5(struct sd_softc *, struct disk_parms *,
122 int);
123
124 static int sd_flush(struct sd_softc *, int);
125 static int sd_getcache(struct sd_softc *, int *);
126 static int sd_setcache(struct sd_softc *, int);
127
128 static int sdmatch(device_t, cfdata_t, void *);
129 static void sdattach(device_t, device_t, void *);
130 static int sddetach(device_t, int);
131 static void sd_set_geometry(struct sd_softc *);
132
133 CFATTACH_DECL3_NEW(sd, sizeof(struct sd_softc), sdmatch, sdattach, sddetach,
134 NULL, NULL, NULL, DVF_DETACH_SHUTDOWN);
135
136 extern struct cfdriver sd_cd;
137
138 static const struct scsipi_inquiry_pattern sd_patterns[] = {
139 {T_DIRECT, T_FIXED,
140 "", "", ""},
141 {T_DIRECT, T_REMOV,
142 "", "", ""},
143 {T_OPTICAL, T_FIXED,
144 "", "", ""},
145 {T_OPTICAL, T_REMOV,
146 "", "", ""},
147 {T_SIMPLE_DIRECT, T_FIXED,
148 "", "", ""},
149 {T_SIMPLE_DIRECT, T_REMOV,
150 "", "", ""},
151 };
152
153 static dev_type_open(sdopen);
154 static dev_type_close(sdclose);
155 static dev_type_read(sdread);
156 static dev_type_write(sdwrite);
157 static dev_type_ioctl(sdioctl);
158 static dev_type_strategy(sdstrategy);
159 static dev_type_dump(sddump);
160 static dev_type_size(sdsize);
161
162 const struct bdevsw sd_bdevsw = {
163 .d_open = sdopen,
164 .d_close = sdclose,
165 .d_strategy = sdstrategy,
166 .d_ioctl = sdioctl,
167 .d_dump = sddump,
168 .d_psize = sdsize,
169 .d_discard = nodiscard,
170 .d_flag = D_DISK | D_MPSAFE
171 };
172
173 const struct cdevsw sd_cdevsw = {
174 .d_open = sdopen,
175 .d_close = sdclose,
176 .d_read = sdread,
177 .d_write = sdwrite,
178 .d_ioctl = sdioctl,
179 .d_stop = nostop,
180 .d_tty = notty,
181 .d_poll = nopoll,
182 .d_mmap = nommap,
183 .d_kqfilter = nokqfilter,
184 .d_discard = nodiscard,
185 .d_flag = D_DISK | D_MPSAFE
186 };
187
188 static struct dkdriver sddkdriver = {
189 .d_open = sdopen,
190 .d_close = sdclose,
191 .d_strategy = sdstrategy,
192 .d_minphys = sdminphys,
193 .d_diskstart = sd_diskstart,
194 .d_dumpblocks = sd_dumpblocks,
195 .d_iosize = sd_iosize,
196 .d_firstopen = sd_firstopen,
197 .d_lastclose = sd_lastclose,
198 .d_label = sd_label,
199 };
200
201 static const struct scsipi_periphsw sd_switch = {
202 sd_interpret_sense, /* check our error handler first */
203 sdstart, /* have a queue, served by this */
204 NULL, /* have no async handler */
205 sddone, /* deal with stats at interrupt time */
206 };
207
208 struct sd_mode_sense_data {
209 /*
210 * XXX
211 * We are not going to parse this as-is -- it just has to be large
212 * enough.
213 */
214 union {
215 struct scsi_mode_parameter_header_6 small;
216 struct scsi_mode_parameter_header_10 big;
217 } header;
218 struct scsi_general_block_descriptor blk_desc;
219 union scsi_disk_pages pages;
220 };
221
222 /*
223 * The routine called by the low level scsi routine when it discovers
224 * A device suitable for this driver
225 */
226 static int
227 sdmatch(device_t parent, cfdata_t match,
228 void *aux)
229 {
230 struct scsipibus_attach_args *sa = aux;
231 int priority;
232
233 (void)scsipi_inqmatch(&sa->sa_inqbuf,
234 sd_patterns, sizeof(sd_patterns) / sizeof(sd_patterns[0]),
235 sizeof(sd_patterns[0]), &priority);
236
237 return (priority);
238 }
239
240 /*
241 * Attach routine common to atapi & scsi.
242 */
243 static void
244 sdattach(device_t parent, device_t self, void *aux)
245 {
246 struct sd_softc *sd = device_private(self);
247 struct dk_softc *dksc = &sd->sc_dksc;
248 struct scsipibus_attach_args *sa = aux;
249 struct scsipi_periph *periph = sa->sa_periph;
250 int error, result, dtype;
251 struct disk_parms *dp = &sd->params;
252 char pbuf[9];
253
254 SC_DEBUG(periph, SCSIPI_DB2, ("sdattach: "));
255
256 sd->type = (sa->sa_inqbuf.type & SID_TYPE);
257 strncpy(sd->name, sa->sa_inqbuf.product, sizeof(sd->name));
258
259 if (sd->type == T_SIMPLE_DIRECT)
260 periph->periph_quirks |= PQUIRK_ONLYBIG | PQUIRK_NOBIGMODESENSE;
261
262 switch (SCSIPI_BUSTYPE_TYPE(scsipi_periph_bustype(sa->sa_periph))) {
263 case SCSIPI_BUSTYPE_SCSI:
264 dtype = DKTYPE_SCSI;
265 if (periph->periph_version == 0)
266 sd->flags |= SDF_ANCIENT;
267 break;
268 case SCSIPI_BUSTYPE_ATAPI:
269 dtype = DKTYPE_ATAPI;
270 break;
271 default:
272 dtype = DKTYPE_UNKNOWN;
273 break;
274 }
275
276 /* Initialize dk and disk structure. */
277 dk_init(dksc, self, dtype);
278 disk_init(&dksc->sc_dkdev, dksc->sc_xname, &sddkdriver);
279
280 /* Attach dk and disk subsystems */
281 dk_attach(dksc);
282 disk_attach(&dksc->sc_dkdev);
283
284 bufq_alloc(&dksc->sc_bufq, BUFQ_DISK_DEFAULT_STRAT, BUFQ_SORT_RAWBLOCK);
285
286 callout_init(&sd->sc_callout, 0);
287
288 /*
289 * Store information needed to contact our base driver
290 */
291 sd->sc_periph = periph;
292
293 periph->periph_dev = dksc->sc_dev;
294 periph->periph_switch = &sd_switch;
295
296 /*
297 * Increase our openings to the maximum-per-periph
298 * supported by the adapter. This will either be
299 * clamped down or grown by the adapter if necessary.
300 */
301 periph->periph_openings =
302 SCSIPI_CHAN_MAX_PERIPH(periph->periph_channel);
303 periph->periph_flags |= PERIPH_GROW_OPENINGS;
304
305 /*
306 * Use the subdriver to request information regarding the drive.
307 */
308 aprint_naive("\n");
309 aprint_normal("\n");
310
311 if (periph->periph_quirks & PQUIRK_START)
312 (void)scsipi_start(periph, SSS_START, XS_CTL_SILENT);
313
314 error = scsipi_test_unit_ready(periph,
315 XS_CTL_DISCOVERY | XS_CTL_IGNORE_ILLEGAL_REQUEST |
316 XS_CTL_IGNORE_MEDIA_CHANGE | XS_CTL_SILENT_NODEV);
317 if (error)
318 result = SDGP_RESULT_OFFLINE;
319 else
320 result = sd_get_parms(sd, &sd->params, XS_CTL_DISCOVERY);
321
322 aprint_normal_dev(dksc->sc_dev, "");
323 switch (result) {
324 case SDGP_RESULT_OK:
325 format_bytes(pbuf, sizeof(pbuf),
326 (u_int64_t)dp->disksize * dp->blksize);
327 aprint_normal(
328 "%s, %ld cyl, %ld head, %ld sec, %ld bytes/sect x %llu sectors",
329 pbuf, dp->cyls, dp->heads, dp->sectors, dp->blksize,
330 (unsigned long long)dp->disksize);
331 break;
332
333 case SDGP_RESULT_OFFLINE:
334 aprint_normal("drive offline");
335 break;
336
337 case SDGP_RESULT_UNFORMATTED:
338 aprint_normal("unformatted media");
339 break;
340
341 #ifdef DIAGNOSTIC
342 default:
343 panic("sdattach: unknown result from get_parms");
344 break;
345 #endif
346 }
347 aprint_normal("\n");
348
349 /* Discover wedges on this disk. */
350 dkwedge_discover(&dksc->sc_dkdev);
351
352 /*
353 * Establish a shutdown hook so that we can ensure that
354 * our data has actually made it onto the platter at
355 * shutdown time. Note that this relies on the fact
356 * that the shutdown hooks at the "leaves" of the device tree
357 * are run, first (thus guaranteeing that our hook runs before
358 * our ancestors').
359 */
360 if (!pmf_device_register1(self, sd_suspend, NULL, sd_shutdown))
361 aprint_error_dev(self, "couldn't establish power handler\n");
362 }
363
364 static int
365 sddetach(device_t self, int flags)
366 {
367 struct sd_softc *sd = device_private(self);
368 struct dk_softc *dksc = &sd->sc_dksc;
369 struct scsipi_periph *periph = sd->sc_periph;
370 struct scsipi_channel *chan = periph->periph_channel;
371 int bmaj, cmaj, i, mn, rc;
372
373 if ((rc = disk_begindetach(&dksc->sc_dkdev, sd_lastclose, self, flags)) != 0)
374 return rc;
375
376 /* locate the major number */
377 bmaj = bdevsw_lookup_major(&sd_bdevsw);
378 cmaj = cdevsw_lookup_major(&sd_cdevsw);
379
380 /* Nuke the vnodes for any open instances */
381 for (i = 0; i < MAXPARTITIONS; i++) {
382 mn = SDMINOR(device_unit(self), i);
383 vdevgone(bmaj, mn, mn, VBLK);
384 vdevgone(cmaj, mn, mn, VCHR);
385 }
386
387 /* kill any pending restart */
388 callout_stop(&sd->sc_callout);
389
390 dk_drain(dksc);
391
392 /* Kill off any pending commands. */
393 mutex_enter(chan_mtx(chan));
394 scsipi_kill_pending(periph);
395 mutex_exit(chan_mtx(chan));
396
397 bufq_free(dksc->sc_bufq);
398
399 /* Delete all of our wedges. */
400 dkwedge_delall(&dksc->sc_dkdev);
401
402 /* Detach from the disk list. */
403 disk_detach(&dksc->sc_dkdev);
404 disk_destroy(&dksc->sc_dkdev);
405
406 dk_detach(dksc);
407
408 callout_destroy(&sd->sc_callout);
409
410 pmf_device_deregister(self);
411
412 return (0);
413 }
414
415 /*
416 * Serialized by caller
417 */
418 static int
419 sd_firstopen(device_t self, dev_t dev, int flag, int fmt)
420 {
421 struct sd_softc *sd = device_private(self);
422 struct scsipi_periph *periph = sd->sc_periph;
423 struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
424 int error, silent;
425 int part, removable;
426
427 part = SDPART(dev);
428
429 error = scsipi_adapter_addref(adapt);
430 if (error)
431 return error;
432
433 if ((part == RAW_PART && fmt == S_IFCHR) || (flag & FSILENT))
434 silent = XS_CTL_SILENT;
435 else
436 silent = 0;
437
438 /* Check that it is still responding and ok. */
439 error = scsipi_test_unit_ready(periph,
440 XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
441 silent);
442
443 /*
444 * Start the pack spinning if necessary. Always allow the
445 * raw parition to be opened, for raw IOCTLs. Data transfers
446 * will check for SDEV_MEDIA_LOADED.
447 */
448 if (error == EIO) {
449 error = scsipi_start(periph, SSS_START, silent);
450 if (error == EINVAL)
451 error = EIO;
452 }
453 if (error)
454 goto bad;
455
456 removable = (periph->periph_flags & PERIPH_REMOVABLE) != 0;
457 if (removable) {
458 /* Lock the pack in. */
459 error = scsipi_prevent(periph, SPAMR_PREVENT_DT,
460 XS_CTL_IGNORE_ILLEGAL_REQUEST |
461 XS_CTL_IGNORE_MEDIA_CHANGE |
462 XS_CTL_SILENT);
463 if (error)
464 goto bad;
465 }
466
467 if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
468 int param_error;
469
470 /*
471 * Load the physical device parameters.
472 *
473 * Note that if media is present but unformatted,
474 * we allow the open (so that it can be formatted!).
475 * The drive should refuse real I/O, if the media is
476 * unformatted.
477 */
478 param_error = sd_get_parms(sd, &sd->params, 0);
479 if (param_error == SDGP_RESULT_OFFLINE) {
480 error = ENXIO;
481 goto bad2;
482 }
483 periph->periph_flags |= PERIPH_MEDIA_LOADED;
484
485 SC_DEBUG(periph, SCSIPI_DB3, ("Params loaded "));
486 }
487
488 periph->periph_flags |= PERIPH_OPEN;
489 return 0;
490
491 bad2:
492 if (removable)
493 scsipi_prevent(periph, SPAMR_ALLOW,
494 XS_CTL_IGNORE_ILLEGAL_REQUEST |
495 XS_CTL_IGNORE_MEDIA_CHANGE |
496 XS_CTL_SILENT);
497
498 bad:
499 scsipi_adapter_delref(adapt);
500 return error;
501 }
502
503 /*
504 * open the device. Make sure the partition info is a up-to-date as can be.
505 */
506 static int
507 sdopen(dev_t dev, int flag, int fmt, struct lwp *l)
508 {
509 struct sd_softc *sd;
510 struct dk_softc *dksc;
511 struct scsipi_periph *periph;
512 int unit, part;
513 int error;
514
515 unit = SDUNIT(dev);
516 sd = device_lookup_private(&sd_cd, unit);
517 if (sd == NULL)
518 return (ENXIO);
519 dksc = &sd->sc_dksc;
520
521 if (!device_is_active(dksc->sc_dev))
522 return (ENODEV);
523
524 periph = sd->sc_periph;
525 part = SDPART(dev);
526
527 SC_DEBUG(periph, SCSIPI_DB1,
528 ("sdopen: dev=0x%"PRIx64" (unit %d (of %d), partition %d)\n",
529 dev, unit, sd_cd.cd_ndevs, SDPART(dev)));
530
531 /*
532 * If any partition is open, but the disk has been invalidated,
533 * disallow further opens of non-raw partition
534 */
535 if ((periph->periph_flags & (PERIPH_OPEN | PERIPH_MEDIA_LOADED)) ==
536 PERIPH_OPEN) {
537 if (part != RAW_PART || fmt != S_IFCHR)
538 return EIO;
539 }
540
541 error = dk_open(dksc, dev, flag, fmt, l);
542
543 SC_DEBUG(periph, SCSIPI_DB3, ("open complete\n"));
544
545 return error;
546 }
547
548 /*
549 * Serialized by caller
550 */
551 static int
552 sd_lastclose(device_t self)
553 {
554 struct sd_softc *sd = device_private(self);
555 struct dk_softc *dksc = &sd->sc_dksc;
556 struct scsipi_periph *periph = sd->sc_periph;
557 struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
558
559 /*
560 * If the disk cache needs flushing, and the disk supports
561 * it, do it now.
562 */
563 if ((sd->flags & SDF_DIRTY) != 0) {
564 if (sd_flush(sd, 0)) {
565 aprint_error_dev(dksc->sc_dev,
566 "cache synchronization failed\n");
567 sd->flags &= ~SDF_FLUSHING;
568 } else
569 sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
570 }
571
572 scsipi_wait_drain(periph);
573
574 if (periph->periph_flags & PERIPH_REMOVABLE)
575 scsipi_prevent(periph, SPAMR_ALLOW,
576 XS_CTL_IGNORE_ILLEGAL_REQUEST |
577 XS_CTL_IGNORE_NOT_READY |
578 XS_CTL_SILENT);
579 periph->periph_flags &= ~PERIPH_OPEN;
580
581 scsipi_wait_drain(periph);
582
583 scsipi_adapter_delref(adapt);
584
585 return 0;
586 }
587
588 /*
589 * close the device.. only called if we are the LAST occurence of an open
590 * device. Convenient now but usually a pain.
591 */
592 static int
593 sdclose(dev_t dev, int flag, int fmt, struct lwp *l)
594 {
595 struct sd_softc *sd;
596 struct dk_softc *dksc;
597 int unit;
598
599 unit = SDUNIT(dev);
600 sd = device_lookup_private(&sd_cd, unit);
601 dksc = &sd->sc_dksc;
602
603 return dk_close(dksc, dev, flag, fmt, l);
604 }
605
606 /*
607 * Actually translate the requested transfer into one the physical driver
608 * can understand. The transfer is described by a buf and will include
609 * only one physical transfer.
610 */
611 static void
612 sdstrategy(struct buf *bp)
613 {
614 struct sd_softc *sd = device_lookup_private(&sd_cd, SDUNIT(bp->b_dev));
615 struct dk_softc *dksc = &sd->sc_dksc;
616 struct scsipi_periph *periph = sd->sc_periph;
617
618 SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdstrategy "));
619 SC_DEBUG(sd->sc_periph, SCSIPI_DB1,
620 ("%d bytes @ blk %" PRId64 "\n", bp->b_bcount, bp->b_blkno));
621
622 /*
623 * If the device has been made invalid, error out
624 */
625 if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 ||
626 !device_is_active(dksc->sc_dev)) {
627 if (periph->periph_flags & PERIPH_OPEN)
628 bp->b_error = EIO;
629 else
630 bp->b_error = ENODEV;
631
632 bp->b_resid = bp->b_bcount;
633 biodone(bp);
634 return;
635 }
636
637 dk_strategy(dksc, bp);
638 }
639
640 /*
641 * Issue single I/O command
642 *
643 * Called from dk_start and implicitely from dk_strategy
644 */
645 static int
646 sd_diskstart(device_t dev, struct buf *bp)
647 {
648 struct sd_softc *sd = device_private(dev);
649 struct scsipi_periph *periph = sd->sc_periph;
650 struct scsipi_channel *chan = periph->periph_channel;
651 struct scsipi_rw_16 cmd16;
652 struct scsipi_rw_10 cmd_big;
653 struct scsi_rw_6 cmd_small;
654 struct scsipi_generic *cmdp;
655 struct scsipi_xfer *xs;
656 int error, flags, nblks, cmdlen;
657
658 mutex_enter(chan_mtx(chan));
659
660 if (periph->periph_active >= periph->periph_openings) {
661 error = EAGAIN;
662 goto out;
663 }
664
665 /*
666 * there is excess capacity, but a special waits
667 * It'll need the adapter as soon as we clear out of the
668 * way and let it run (user level wait).
669 */
670 if (periph->periph_flags & PERIPH_WAITING) {
671 periph->periph_flags &= ~PERIPH_WAITING;
672 cv_broadcast(periph_cv_periph(periph));
673 error = EAGAIN;
674 goto out;
675 }
676
677 /*
678 * If the device has become invalid, abort all the
679 * reads and writes until all files have been closed and
680 * re-opened
681 */
682 if (__predict_false(
683 (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)) {
684 error = EIO;
685 goto out;
686 }
687
688 /*
689 * Mark the disk dirty so that the cache will be
690 * flushed on close.
691 */
692 if ((bp->b_flags & B_READ) == 0)
693 sd->flags |= SDF_DIRTY;
694
695 if (sd->params.blksize == DEV_BSIZE)
696 nblks = bp->b_bcount >> DEV_BSHIFT;
697 else
698 nblks = howmany(bp->b_bcount, sd->params.blksize);
699
700 /*
701 * Fill out the scsi command. Use the smallest CDB possible
702 * (6-byte, 10-byte, or 16-byte).
703 */
704 if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
705 ((nblks & 0xff) == nblks) &&
706 !(periph->periph_quirks & PQUIRK_ONLYBIG)) {
707 /* 6-byte CDB */
708 memset(&cmd_small, 0, sizeof(cmd_small));
709 cmd_small.opcode = (bp->b_flags & B_READ) ?
710 SCSI_READ_6_COMMAND : SCSI_WRITE_6_COMMAND;
711 _lto3b(bp->b_rawblkno, cmd_small.addr);
712 cmd_small.length = nblks & 0xff;
713 cmdlen = sizeof(cmd_small);
714 cmdp = (struct scsipi_generic *)&cmd_small;
715 } else if ((bp->b_rawblkno & 0xffffffff) == bp->b_rawblkno) {
716 /* 10-byte CDB */
717 memset(&cmd_big, 0, sizeof(cmd_big));
718 cmd_big.opcode = (bp->b_flags & B_READ) ?
719 READ_10 : WRITE_10;
720 _lto4b(bp->b_rawblkno, cmd_big.addr);
721 _lto2b(nblks, cmd_big.length);
722 cmdlen = sizeof(cmd_big);
723 cmdp = (struct scsipi_generic *)&cmd_big;
724 } else {
725 /* 16-byte CDB */
726 memset(&cmd16, 0, sizeof(cmd16));
727 cmd16.opcode = (bp->b_flags & B_READ) ?
728 READ_16 : WRITE_16;
729 _lto8b(bp->b_rawblkno, cmd16.addr);
730 _lto4b(nblks, cmd16.length);
731 cmdlen = sizeof(cmd16);
732 cmdp = (struct scsipi_generic *)&cmd16;
733 }
734
735 /*
736 * Figure out what flags to use.
737 */
738 flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
739 if (bp->b_flags & B_READ)
740 flags |= XS_CTL_DATA_IN;
741 else
742 flags |= XS_CTL_DATA_OUT;
743
744 /*
745 * Call the routine that chats with the adapter.
746 * Note: we cannot sleep as we may be an interrupt
747 */
748 xs = scsipi_make_xs_locked(periph, cmdp, cmdlen,
749 (u_char *)bp->b_data, bp->b_bcount,
750 SDRETRIES, SD_IO_TIMEOUT, bp, flags);
751 if (__predict_false(xs == NULL)) {
752 /*
753 * out of memory. Keep this buffer in the queue, and
754 * retry later.
755 */
756 callout_reset(&sd->sc_callout, hz / 2, sdrestart, sd);
757 error = 0;
758 goto out;
759 }
760
761 error = scsipi_execute_xs(xs);
762 /* with a scsipi_xfer preallocated, scsipi_command can't fail */
763 KASSERT(error == 0);
764
765 out:
766 mutex_exit(chan_mtx(chan));
767
768 return error;
769 }
770
771 /*
772 * Recover I/O request after memory shortage
773 *
774 * Called from callout
775 */
776 static void
777 sdrestart(void *v)
778 {
779 struct sd_softc *sd = v;
780 struct dk_softc *dksc = &sd->sc_dksc;
781
782 dk_start(dksc, NULL);
783 }
784
785 /*
786 * Recover I/O request after memory shortage
787 *
788 * Called from scsipi midlayer when resources have been freed
789 * with channel lock held
790 */
791 static void
792 sdstart(struct scsipi_periph *periph)
793 {
794 struct sd_softc *sd = device_private(periph->periph_dev);
795 struct dk_softc *dksc = &sd->sc_dksc;
796 struct scsipi_channel *chan = periph->periph_channel;
797
798 /*
799 * release channel lock as dk_start may need to acquire
800 * other locks
801 *
802 * sdstart is called from scsipi_put_xs and all its callers
803 * release the lock afterwards. So releasing it here
804 * doesn't matter.
805 */
806 mutex_exit(chan_mtx(chan));
807
808 dk_start(dksc, NULL);
809
810 mutex_enter(chan_mtx(chan));
811 }
812
813 static void
814 sddone(struct scsipi_xfer *xs, int error)
815 {
816 struct sd_softc *sd = device_private(xs->xs_periph->periph_dev);
817 struct dk_softc *dksc = &sd->sc_dksc;
818 struct buf *bp = xs->bp;
819
820 if (sd->flags & SDF_FLUSHING) {
821 /* Flush completed, no longer dirty. */
822 sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
823 }
824
825 if (bp) {
826 bp->b_error = error;
827 bp->b_resid = xs->resid;
828 if (error) {
829 /* on a read/write error bp->b_resid is zero, so fix */
830 bp->b_resid = bp->b_bcount;
831 }
832
833 dk_done(dksc, bp);
834 /* dk_start is called from scsipi_complete */
835 }
836 }
837
838 static void
839 sdminphys(struct buf *bp)
840 {
841 struct sd_softc *sd = device_lookup_private(&sd_cd, SDUNIT(bp->b_dev));
842 struct dk_softc *dksc = &sd->sc_dksc;
843 long xmax;
844
845 /*
846 * If the device is ancient, we want to make sure that
847 * the transfer fits into a 6-byte cdb.
848 *
849 * XXX Note that the SCSI-I spec says that 256-block transfers
850 * are allowed in a 6-byte read/write, and are specified
851 * by settng the "length" to 0. However, we're conservative
852 * here, allowing only 255-block transfers in case an
853 * ancient device gets confused by length == 0. A length of 0
854 * in a 10-byte read/write actually means 0 blocks.
855 */
856 if ((sd->flags & SDF_ANCIENT) &&
857 ((sd->sc_periph->periph_flags &
858 (PERIPH_REMOVABLE | PERIPH_MEDIA_LOADED)) != PERIPH_REMOVABLE)) {
859 xmax = dksc->sc_dkdev.dk_geom.dg_secsize * 0xff;
860
861 if (bp->b_bcount > xmax)
862 bp->b_bcount = xmax;
863 }
864
865 scsipi_adapter_minphys(sd->sc_periph->periph_channel, bp);
866 }
867
868 static void
869 sd_iosize(device_t dev, int *count)
870 {
871 struct buf B;
872 int bmaj;
873
874 bmaj = bdevsw_lookup_major(&sd_bdevsw);
875 B.b_dev = MAKESDDEV(bmaj,device_unit(dev),RAW_PART);
876 B.b_bcount = *count;
877
878 sdminphys(&B);
879
880 *count = B.b_bcount;
881 }
882
883 static int
884 sdread(dev_t dev, struct uio *uio, int ioflag)
885 {
886
887 return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
888 }
889
890 static int
891 sdwrite(dev_t dev, struct uio *uio, int ioflag)
892 {
893
894 return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
895 }
896
897 /*
898 * Perform special action on behalf of the user
899 * Knows about the internals of this device
900 */
901 static int
902 sdioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
903 {
904 struct sd_softc *sd = device_lookup_private(&sd_cd, SDUNIT(dev));
905 struct dk_softc *dksc = &sd->sc_dksc;
906 struct scsipi_periph *periph = sd->sc_periph;
907
908 int part = SDPART(dev);
909 int error;
910
911 SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdioctl 0x%lx ", cmd));
912
913 /*
914 * If the device is not valid, some IOCTLs can still be
915 * handled on the raw partition. Check this here.
916 */
917 if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 &&
918 part != RAW_PART)
919 return (EIO);
920
921 switch (cmd) {
922 case DIOCLOCK:
923 if (periph->periph_flags & PERIPH_REMOVABLE)
924 return (scsipi_prevent(periph,
925 (*(int *)addr) ?
926 SPAMR_PREVENT_DT : SPAMR_ALLOW, 0));
927 else
928 return (ENOTTY);
929
930 case DIOCEJECT:
931 if ((periph->periph_flags & PERIPH_REMOVABLE) == 0)
932 return (ENOTTY);
933 if (*(int *)addr == 0) {
934 /*
935 * Don't force eject: check that we are the only
936 * partition open. If so, unlock it.
937 */
938 if (DK_BUSY(dksc, part) == 0) {
939 error = scsipi_prevent(periph, SPAMR_ALLOW,
940 XS_CTL_IGNORE_NOT_READY);
941 if (error)
942 return (error);
943 } else {
944 return (EBUSY);
945 }
946 }
947 /* FALLTHROUGH */
948 case ODIOCEJECT:
949 return ((periph->periph_flags & PERIPH_REMOVABLE) == 0 ?
950 ENOTTY : scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
951
952 case DIOCGCACHE:
953 return (sd_getcache(sd, (int *) addr));
954
955 case DIOCSCACHE:
956 if ((flag & FWRITE) == 0)
957 return (EBADF);
958 return (sd_setcache(sd, *(int *) addr));
959
960 case DIOCCACHESYNC:
961 /*
962 * XXX Do we really need to care about having a writable
963 * file descriptor here?
964 */
965 if ((flag & FWRITE) == 0)
966 return (EBADF);
967 if (((sd->flags & SDF_DIRTY) != 0 || *(int *)addr != 0)) {
968 error = sd_flush(sd, 0);
969 if (error) {
970 sd->flags &= ~SDF_FLUSHING;
971 return (error);
972 }
973 sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
974 }
975 return (0);
976
977 default:
978 error = dk_ioctl(dksc, dev, cmd, addr, flag, l);
979 if (error == ENOTTY)
980 error = scsipi_do_ioctl(periph, dev, cmd, addr, flag, l);
981 return (error);
982 }
983
984 #ifdef DIAGNOSTIC
985 panic("sdioctl: impossible");
986 #endif
987 }
988
989 static void
990 sd_label(device_t self, struct disklabel *lp)
991 {
992 struct sd_softc *sd = device_private(self);
993
994 strncpy(lp->d_typename, sd->name, 16);
995 lp->d_rpm = sd->params.rot_rate;
996 if (sd->sc_periph->periph_flags & PERIPH_REMOVABLE)
997 lp->d_flags |= D_REMOVABLE;
998 }
999
1000 static bool
1001 sd_shutdown(device_t self, int how)
1002 {
1003 struct sd_softc *sd = device_private(self);
1004 struct dk_softc *dksc = &sd->sc_dksc;
1005
1006 /*
1007 * If the disk cache needs to be flushed, and the disk supports
1008 * it, flush it. We're cold at this point, so we poll for
1009 * completion.
1010 */
1011 if ((sd->flags & SDF_DIRTY) != 0) {
1012 if (sd_flush(sd, XS_CTL_NOSLEEP|XS_CTL_POLL)) {
1013 aprint_error_dev(dksc->sc_dev,
1014 "cache synchronization failed\n");
1015 sd->flags &= ~SDF_FLUSHING;
1016 } else
1017 sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
1018 }
1019 return true;
1020 }
1021
1022 static bool
1023 sd_suspend(device_t dv, const pmf_qual_t *qual)
1024 {
1025 return sd_shutdown(dv, boothowto); /* XXX no need to poll */
1026 }
1027
1028 /*
1029 * Check Errors
1030 */
1031 static int
1032 sd_interpret_sense(struct scsipi_xfer *xs)
1033 {
1034 struct scsipi_periph *periph = xs->xs_periph;
1035 struct scsipi_channel *chan = periph->periph_channel;
1036 struct scsi_sense_data *sense = &xs->sense.scsi_sense;
1037 struct sd_softc *sd = device_private(periph->periph_dev);
1038 struct dk_softc *dksc = &sd->sc_dksc;
1039 int error, retval = EJUSTRETURN;
1040
1041 /*
1042 * If the periph is already recovering, just do the normal
1043 * error processing.
1044 */
1045 if (periph->periph_flags & PERIPH_RECOVERING)
1046 return (retval);
1047
1048 /*
1049 * Ignore errors from accessing illegal fields (e.g. trying to
1050 * lock the door of a digicam, which doesn't have a door that
1051 * can be locked) for the SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL command.
1052 */
1053 if (xs->cmd->opcode == SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL &&
1054 SSD_SENSE_KEY(sense->flags) == SKEY_ILLEGAL_REQUEST &&
1055 sense->asc == 0x24 &&
1056 sense->ascq == 0x00) { /* Illegal field in CDB */
1057 if (!(xs->xs_control & XS_CTL_SILENT)) {
1058 scsipi_printaddr(periph);
1059 printf("no door lock\n");
1060 }
1061 xs->xs_control |= XS_CTL_IGNORE_ILLEGAL_REQUEST;
1062 return (retval);
1063 }
1064
1065
1066
1067 /*
1068 * If the device is not open yet, let the generic code handle it.
1069 */
1070 if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
1071 return (retval);
1072
1073 /*
1074 * If it isn't a extended or extended/deferred error, let
1075 * the generic code handle it.
1076 */
1077 if (SSD_RCODE(sense->response_code) != SSD_RCODE_CURRENT &&
1078 SSD_RCODE(sense->response_code) != SSD_RCODE_DEFERRED)
1079 return (retval);
1080
1081 if (SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY &&
1082 sense->asc == 0x4) {
1083 if (sense->ascq == 0x01) {
1084 /*
1085 * Unit In The Process Of Becoming Ready.
1086 */
1087 printf("%s: waiting for pack to spin up...\n",
1088 dksc->sc_xname);
1089 if (!callout_pending(&periph->periph_callout))
1090 scsipi_periph_freeze(periph, 1);
1091 callout_reset(&periph->periph_callout,
1092 5 * hz, scsipi_periph_timed_thaw, periph);
1093 retval = ERESTART;
1094 } else if (sense->ascq == 0x02) {
1095 printf("%s: pack is stopped, restarting...\n",
1096 dksc->sc_xname);
1097 mutex_enter(chan_mtx(chan));
1098 periph->periph_flags |= PERIPH_RECOVERING;
1099 mutex_exit(chan_mtx(chan));
1100 error = scsipi_start(periph, SSS_START,
1101 XS_CTL_URGENT|XS_CTL_HEAD_TAG|
1102 XS_CTL_THAW_PERIPH|XS_CTL_FREEZE_PERIPH);
1103 if (error) {
1104 aprint_error_dev(dksc->sc_dev,
1105 "unable to restart pack\n");
1106 retval = error;
1107 } else
1108 retval = ERESTART;
1109 mutex_enter(chan_mtx(chan));
1110 periph->periph_flags &= ~PERIPH_RECOVERING;
1111 mutex_exit(chan_mtx(chan));
1112 }
1113 }
1114 if (SSD_SENSE_KEY(sense->flags) == SKEY_MEDIUM_ERROR &&
1115 sense->asc == 0x31 &&
1116 sense->ascq == 0x00) { /* maybe for any asq ? */
1117 /* Medium Format Corrupted */
1118 retval = EFTYPE;
1119 }
1120 return (retval);
1121 }
1122
1123
1124 static int
1125 sdsize(dev_t dev)
1126 {
1127 struct sd_softc *sd;
1128 struct dk_softc *dksc;
1129 int unit;
1130
1131 unit = SDUNIT(dev);
1132 sd = device_lookup_private(&sd_cd, unit);
1133 if (sd == NULL)
1134 return (-1);
1135 dksc = &sd->sc_dksc;
1136
1137 if (!device_is_active(dksc->sc_dev))
1138 return (-1);
1139
1140 return dk_size(dksc, dev);
1141 }
1142
1143 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
1144 static struct scsipi_xfer sx;
1145
1146 /*
1147 * dump all of physical memory into the partition specified, starting
1148 * at offset 'dumplo' into the partition.
1149 */
1150 static int
1151 sddump(dev_t dev, daddr_t blkno, void *va, size_t size)
1152 {
1153 struct sd_softc *sd;
1154 struct dk_softc *dksc;
1155 struct scsipi_periph *periph;
1156 int unit;
1157
1158 unit = SDUNIT(dev);
1159 if ((sd = device_lookup_private(&sd_cd, unit)) == NULL)
1160 return (ENXIO);
1161 dksc = &sd->sc_dksc;
1162
1163 if (!device_is_active(dksc->sc_dev))
1164 return (ENODEV);
1165
1166 periph = sd->sc_periph;
1167
1168 /* Make sure it was initialized. */
1169 if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
1170 return (ENXIO);
1171
1172 return dk_dump(dksc, dev, blkno, va, size);
1173 }
1174
1175 static int
1176 sd_dumpblocks(device_t dev, void *va, daddr_t blkno, int nblk)
1177 {
1178 struct sd_softc *sd = device_private(dev);
1179 struct dk_softc *dksc = &sd->sc_dksc;
1180 struct disk_geom *dg = &dksc->sc_dkdev.dk_geom;
1181 struct scsipi_rw_10 cmd; /* write command */
1182 struct scsipi_xfer *xs; /* ... convenience */
1183 struct scsipi_periph *periph;
1184 struct scsipi_channel *chan;
1185 size_t sectorsize;
1186
1187 periph = sd->sc_periph;
1188 chan = periph->periph_channel;
1189
1190 sectorsize = dg->dg_secsize;
1191
1192 xs = &sx;
1193
1194 #ifndef SD_DUMP_NOT_TRUSTED
1195 /*
1196 * Fill out the scsi command
1197 */
1198 memset(&cmd, 0, sizeof(cmd));
1199 cmd.opcode = WRITE_10;
1200 _lto4b(blkno, cmd.addr);
1201 _lto2b(nblk, cmd.length);
1202 /*
1203 * Fill out the scsipi_xfer structure
1204 * Note: we cannot sleep as we may be an interrupt
1205 * don't use scsipi_command() as it may want to wait
1206 * for an xs.
1207 */
1208 memset(xs, 0, sizeof(sx));
1209 xs->xs_control |= XS_CTL_NOSLEEP | XS_CTL_POLL |
1210 XS_CTL_DATA_OUT;
1211 xs->xs_status = 0;
1212 xs->xs_periph = periph;
1213 xs->xs_retries = SDRETRIES;
1214 xs->timeout = 10000; /* 10000 millisecs for a disk ! */
1215 xs->cmd = (struct scsipi_generic *)&cmd;
1216 xs->cmdlen = sizeof(cmd);
1217 xs->resid = nblk * sectorsize;
1218 xs->error = XS_NOERROR;
1219 xs->bp = 0;
1220 xs->data = va;
1221 xs->datalen = nblk * sectorsize;
1222 callout_init(&xs->xs_callout, 0);
1223
1224 /*
1225 * Pass all this info to the scsi driver.
1226 */
1227 scsipi_adapter_request(chan, ADAPTER_REQ_RUN_XFER, xs);
1228 if ((xs->xs_status & XS_STS_DONE) == 0 ||
1229 xs->error != XS_NOERROR)
1230 return (EIO);
1231 #else /* SD_DUMP_NOT_TRUSTED */
1232 /* Let's just talk about this first... */
1233 printf("sd%d: dump addr 0x%x, blk %d\n", unit, va, blkno);
1234 delay(500 * 1000); /* half a second */
1235 #endif /* SD_DUMP_NOT_TRUSTED */
1236
1237 return (0);
1238 }
1239
1240 static int
1241 sd_mode_sense(struct sd_softc *sd, u_int8_t byte2, void *sense, size_t size,
1242 int page, int flags, int *big)
1243 {
1244
1245 if ((sd->sc_periph->periph_quirks & PQUIRK_ONLYBIG) &&
1246 !(sd->sc_periph->periph_quirks & PQUIRK_NOBIGMODESENSE)) {
1247 *big = 1;
1248 return scsipi_mode_sense_big(sd->sc_periph, byte2, page, sense,
1249 size + sizeof(struct scsi_mode_parameter_header_10),
1250 flags, SDRETRIES, 6000);
1251 } else {
1252 *big = 0;
1253 return scsipi_mode_sense(sd->sc_periph, byte2, page, sense,
1254 size + sizeof(struct scsi_mode_parameter_header_6),
1255 flags, SDRETRIES, 6000);
1256 }
1257 }
1258
1259 static int
1260 sd_mode_select(struct sd_softc *sd, u_int8_t byte2, void *sense, size_t size,
1261 int flags, int big)
1262 {
1263
1264 if (big) {
1265 struct scsi_mode_parameter_header_10 *header = sense;
1266
1267 _lto2b(0, header->data_length);
1268 return scsipi_mode_select_big(sd->sc_periph, byte2, sense,
1269 size + sizeof(struct scsi_mode_parameter_header_10),
1270 flags, SDRETRIES, 6000);
1271 } else {
1272 struct scsi_mode_parameter_header_6 *header = sense;
1273
1274 header->data_length = 0;
1275 return scsipi_mode_select(sd->sc_periph, byte2, sense,
1276 size + sizeof(struct scsi_mode_parameter_header_6),
1277 flags, SDRETRIES, 6000);
1278 }
1279 }
1280
1281 /*
1282 * sd_validate_blksize:
1283 *
1284 * Validate the block size. Print error if periph is specified,
1285 */
1286 static int
1287 sd_validate_blksize(struct scsipi_periph *periph, int len)
1288 {
1289
1290 switch (len) {
1291 case 256:
1292 case 512:
1293 case 1024:
1294 case 2048:
1295 case 4096:
1296 return 1;
1297 }
1298
1299 if (periph) {
1300 scsipi_printaddr(periph);
1301 printf("%s sector size: 0x%x. Defaulting to %d bytes.\n",
1302 (len ^ (1 << (ffs(len) - 1))) ?
1303 "preposterous" : "unsupported",
1304 len, SD_DEFAULT_BLKSIZE);
1305 }
1306
1307 return 0;
1308 }
1309
1310 /*
1311 * sd_read_capacity:
1312 *
1313 * Find out from the device what its capacity is.
1314 */
1315 static u_int64_t
1316 sd_read_capacity(struct scsipi_periph *periph, int *blksize, int flags)
1317 {
1318 union {
1319 struct scsipi_read_capacity_10 cmd;
1320 struct scsipi_read_capacity_16 cmd16;
1321 } cmd;
1322 union {
1323 struct scsipi_read_capacity_10_data data;
1324 struct scsipi_read_capacity_16_data data16;
1325 } *datap;
1326 uint64_t rv;
1327
1328 memset(&cmd, 0, sizeof(cmd));
1329 cmd.cmd.opcode = READ_CAPACITY_10;
1330
1331 /*
1332 * Don't allocate data buffer on stack;
1333 * The lower driver layer might use the same stack and
1334 * if it uses region which is in the same cacheline,
1335 * cache flush ops against the data buffer won't work properly.
1336 */
1337 datap = malloc(sizeof(*datap), M_TEMP, M_WAITOK);
1338 if (datap == NULL)
1339 return 0;
1340
1341 /*
1342 * If the command works, interpret the result as a 4 byte
1343 * number of blocks
1344 */
1345 rv = 0;
1346 memset(datap, 0, sizeof(datap->data));
1347 if (scsipi_command(periph, (void *)&cmd.cmd, sizeof(cmd.cmd),
1348 (void *)datap, sizeof(datap->data), SCSIPIRETRIES, 20000, NULL,
1349 flags | XS_CTL_DATA_IN | XS_CTL_SILENT) != 0)
1350 goto out;
1351
1352 if (_4btol(datap->data.addr) != 0xffffffff) {
1353 *blksize = _4btol(datap->data.length);
1354 rv = _4btol(datap->data.addr) + 1;
1355 goto out;
1356 }
1357
1358 /*
1359 * Device is larger than can be reflected by READ CAPACITY (10).
1360 * Try READ CAPACITY (16).
1361 */
1362
1363 memset(&cmd, 0, sizeof(cmd));
1364 cmd.cmd16.opcode = READ_CAPACITY_16;
1365 cmd.cmd16.byte2 = SRC16_SERVICE_ACTION;
1366 _lto4b(sizeof(datap->data16), cmd.cmd16.len);
1367
1368 memset(datap, 0, sizeof(datap->data16));
1369 if (scsipi_command(periph, (void *)&cmd.cmd16, sizeof(cmd.cmd16),
1370 (void *)datap, sizeof(datap->data16), SCSIPIRETRIES, 20000, NULL,
1371 flags | XS_CTL_DATA_IN | XS_CTL_SILENT) != 0)
1372 goto out;
1373
1374 *blksize = _4btol(datap->data16.length);
1375 rv = _8btol(datap->data16.addr) + 1;
1376
1377 out:
1378 free(datap, M_TEMP);
1379 return rv;
1380 }
1381
1382 static int
1383 sd_get_simplifiedparms(struct sd_softc *sd, struct disk_parms *dp, int flags)
1384 {
1385 struct {
1386 struct scsi_mode_parameter_header_6 header;
1387 /* no block descriptor */
1388 u_int8_t pg_code; /* page code (should be 6) */
1389 u_int8_t pg_length; /* page length (should be 11) */
1390 u_int8_t wcd; /* bit0: cache disable */
1391 u_int8_t lbs[2]; /* logical block size */
1392 u_int8_t size[5]; /* number of log. blocks */
1393 u_int8_t pp; /* power/performance */
1394 u_int8_t flags;
1395 u_int8_t resvd;
1396 } scsipi_sense;
1397 u_int64_t blocks;
1398 int error, blksize;
1399
1400 /*
1401 * sd_read_capacity (ie "read capacity") and mode sense page 6
1402 * give the same information. Do both for now, and check
1403 * for consistency.
1404 * XXX probably differs for removable media
1405 */
1406 dp->blksize = SD_DEFAULT_BLKSIZE;
1407 if ((blocks = sd_read_capacity(sd->sc_periph, &blksize, flags)) == 0)
1408 return (SDGP_RESULT_OFFLINE); /* XXX? */
1409
1410 error = scsipi_mode_sense(sd->sc_periph, SMS_DBD, 6,
1411 &scsipi_sense.header, sizeof(scsipi_sense),
1412 flags, SDRETRIES, 6000);
1413
1414 if (error != 0)
1415 return (SDGP_RESULT_OFFLINE); /* XXX? */
1416
1417 dp->blksize = blksize;
1418 if (!sd_validate_blksize(NULL, dp->blksize))
1419 dp->blksize = _2btol(scsipi_sense.lbs);
1420 if (!sd_validate_blksize(sd->sc_periph, dp->blksize))
1421 dp->blksize = SD_DEFAULT_BLKSIZE;
1422
1423 /*
1424 * Create a pseudo-geometry.
1425 */
1426 dp->heads = 64;
1427 dp->sectors = 32;
1428 dp->cyls = blocks / (dp->heads * dp->sectors);
1429 dp->disksize = _5btol(scsipi_sense.size);
1430 if (dp->disksize <= UINT32_MAX && dp->disksize != blocks) {
1431 printf("RBC size: mode sense=%llu, get cap=%llu\n",
1432 (unsigned long long)dp->disksize,
1433 (unsigned long long)blocks);
1434 dp->disksize = blocks;
1435 }
1436 dp->disksize512 = (dp->disksize * dp->blksize) / DEV_BSIZE;
1437
1438 return (SDGP_RESULT_OK);
1439 }
1440
1441 /*
1442 * Get the scsi driver to send a full inquiry to the * device and use the
1443 * results to fill out the disk parameter structure.
1444 */
1445 static int
1446 sd_get_capacity(struct sd_softc *sd, struct disk_parms *dp, int flags)
1447 {
1448 u_int64_t blocks;
1449 int error, blksize;
1450 #if 0
1451 int i;
1452 u_int8_t *p;
1453 #endif
1454
1455 dp->disksize = blocks = sd_read_capacity(sd->sc_periph, &blksize,
1456 flags);
1457 if (blocks == 0) {
1458 struct scsipi_read_format_capacities cmd;
1459 struct {
1460 struct scsipi_capacity_list_header header;
1461 struct scsipi_capacity_descriptor desc;
1462 } __packed data;
1463
1464 memset(&cmd, 0, sizeof(cmd));
1465 memset(&data, 0, sizeof(data));
1466 cmd.opcode = READ_FORMAT_CAPACITIES;
1467 _lto2b(sizeof(data), cmd.length);
1468
1469 error = scsipi_command(sd->sc_periph,
1470 (void *)&cmd, sizeof(cmd), (void *)&data, sizeof(data),
1471 SDRETRIES, 20000, NULL,
1472 flags | XS_CTL_DATA_IN);
1473 if (error == EFTYPE) {
1474 /* Medium Format Corrupted, handle as not formatted */
1475 return (SDGP_RESULT_UNFORMATTED);
1476 }
1477 if (error || data.header.length == 0)
1478 return (SDGP_RESULT_OFFLINE);
1479
1480 #if 0
1481 printf("rfc: length=%d\n", data.header.length);
1482 printf("rfc result:"); for (i = sizeof(struct scsipi_capacity_list_header) + data.header.length, p = (void *)&data; i; i--, p++) printf(" %02x", *p); printf("\n");
1483 #endif
1484 switch (data.desc.byte5 & SCSIPI_CAP_DESC_CODE_MASK) {
1485 case SCSIPI_CAP_DESC_CODE_RESERVED:
1486 case SCSIPI_CAP_DESC_CODE_FORMATTED:
1487 break;
1488
1489 case SCSIPI_CAP_DESC_CODE_UNFORMATTED:
1490 return (SDGP_RESULT_UNFORMATTED);
1491
1492 case SCSIPI_CAP_DESC_CODE_NONE:
1493 return (SDGP_RESULT_OFFLINE);
1494 }
1495
1496 dp->disksize = blocks = _4btol(data.desc.nblks);
1497 if (blocks == 0)
1498 return (SDGP_RESULT_OFFLINE); /* XXX? */
1499
1500 blksize = _3btol(data.desc.blklen);
1501
1502 } else if (!sd_validate_blksize(NULL, blksize)) {
1503 struct sd_mode_sense_data scsipi_sense;
1504 int big, bsize;
1505 struct scsi_general_block_descriptor *bdesc;
1506
1507 memset(&scsipi_sense, 0, sizeof(scsipi_sense));
1508 error = sd_mode_sense(sd, 0, &scsipi_sense,
1509 sizeof(scsipi_sense.blk_desc), 0, flags | XS_CTL_SILENT, &big);
1510 if (!error) {
1511 if (big) {
1512 bdesc = (void *)(&scsipi_sense.header.big + 1);
1513 bsize = _2btol(scsipi_sense.header.big.blk_desc_len);
1514 } else {
1515 bdesc = (void *)(&scsipi_sense.header.small + 1);
1516 bsize = scsipi_sense.header.small.blk_desc_len;
1517 }
1518
1519 #if 0
1520 printf("page 0 sense:"); for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i; i--, p++) printf(" %02x", *p); printf("\n");
1521 printf("page 0 bsize=%d\n", bsize);
1522 printf("page 0 ok\n");
1523 #endif
1524
1525 if (bsize >= 8) {
1526 blksize = _3btol(bdesc->blklen);
1527 }
1528 }
1529 }
1530
1531 if (!sd_validate_blksize(sd->sc_periph, blksize))
1532 blksize = SD_DEFAULT_BLKSIZE;
1533
1534 dp->blksize = blksize;
1535 dp->disksize512 = (blocks * dp->blksize) / DEV_BSIZE;
1536 return (0);
1537 }
1538
1539 static int
1540 sd_get_parms_page4(struct sd_softc *sd, struct disk_parms *dp, int flags)
1541 {
1542 struct sd_mode_sense_data scsipi_sense;
1543 int error;
1544 int big, byte2;
1545 size_t poffset;
1546 union scsi_disk_pages *pages;
1547
1548 byte2 = SMS_DBD;
1549 again:
1550 memset(&scsipi_sense, 0, sizeof(scsipi_sense));
1551 error = sd_mode_sense(sd, byte2, &scsipi_sense,
1552 (byte2 ? 0 : sizeof(scsipi_sense.blk_desc)) +
1553 sizeof(scsipi_sense.pages.rigid_geometry), 4,
1554 flags | XS_CTL_SILENT, &big);
1555 if (error) {
1556 if (byte2 == SMS_DBD) {
1557 /* No result; try once more with DBD off */
1558 byte2 = 0;
1559 goto again;
1560 }
1561 return (error);
1562 }
1563
1564 if (big) {
1565 poffset = sizeof scsipi_sense.header.big;
1566 poffset += _2btol(scsipi_sense.header.big.blk_desc_len);
1567 } else {
1568 poffset = sizeof scsipi_sense.header.small;
1569 poffset += scsipi_sense.header.small.blk_desc_len;
1570 }
1571
1572 if (poffset > sizeof(scsipi_sense) - sizeof(pages->rigid_geometry))
1573 return ERESTART;
1574
1575 pages = (void *)((u_long)&scsipi_sense + poffset);
1576 #if 0
1577 {
1578 size_t i;
1579 u_int8_t *p;
1580
1581 printf("page 4 sense:");
1582 for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i;
1583 i--, p++)
1584 printf(" %02x", *p);
1585 printf("\n");
1586 printf("page 4 pg_code=%d sense=%p/%p\n",
1587 pages->rigid_geometry.pg_code, &scsipi_sense, pages);
1588 }
1589 #endif
1590
1591 if ((pages->rigid_geometry.pg_code & PGCODE_MASK) != 4)
1592 return (ERESTART);
1593
1594 SC_DEBUG(sd->sc_periph, SCSIPI_DB3,
1595 ("%d cyls, %d heads, %d precomp, %d red_write, %d land_zone\n",
1596 _3btol(pages->rigid_geometry.ncyl),
1597 pages->rigid_geometry.nheads,
1598 _2btol(pages->rigid_geometry.st_cyl_wp),
1599 _2btol(pages->rigid_geometry.st_cyl_rwc),
1600 _2btol(pages->rigid_geometry.land_zone)));
1601
1602 /*
1603 * KLUDGE!! (for zone recorded disks)
1604 * give a number of sectors so that sec * trks * cyls
1605 * is <= disk_size
1606 * can lead to wasted space! THINK ABOUT THIS !
1607 */
1608 dp->heads = pages->rigid_geometry.nheads;
1609 dp->cyls = _3btol(pages->rigid_geometry.ncyl);
1610 if (dp->heads == 0 || dp->cyls == 0)
1611 return (ERESTART);
1612 dp->sectors = dp->disksize / (dp->heads * dp->cyls); /* XXX */
1613
1614 dp->rot_rate = _2btol(pages->rigid_geometry.rpm);
1615 if (dp->rot_rate == 0)
1616 dp->rot_rate = 3600;
1617
1618 #if 0
1619 printf("page 4 ok\n");
1620 #endif
1621 return (0);
1622 }
1623
1624 static int
1625 sd_get_parms_page5(struct sd_softc *sd, struct disk_parms *dp, int flags)
1626 {
1627 struct sd_mode_sense_data scsipi_sense;
1628 int error;
1629 int big, byte2;
1630 size_t poffset;
1631 union scsi_disk_pages *pages;
1632
1633 byte2 = SMS_DBD;
1634 again:
1635 memset(&scsipi_sense, 0, sizeof(scsipi_sense));
1636 error = sd_mode_sense(sd, 0, &scsipi_sense,
1637 (byte2 ? 0 : sizeof(scsipi_sense.blk_desc)) +
1638 sizeof(scsipi_sense.pages.flex_geometry), 5,
1639 flags | XS_CTL_SILENT, &big);
1640 if (error) {
1641 if (byte2 == SMS_DBD) {
1642 /* No result; try once more with DBD off */
1643 byte2 = 0;
1644 goto again;
1645 }
1646 return (error);
1647 }
1648
1649 if (big) {
1650 poffset = sizeof scsipi_sense.header.big;
1651 poffset += _2btol(scsipi_sense.header.big.blk_desc_len);
1652 } else {
1653 poffset = sizeof scsipi_sense.header.small;
1654 poffset += scsipi_sense.header.small.blk_desc_len;
1655 }
1656
1657 if (poffset > sizeof(scsipi_sense) - sizeof(pages->flex_geometry))
1658 return ERESTART;
1659
1660 pages = (void *)((u_long)&scsipi_sense + poffset);
1661 #if 0
1662 {
1663 size_t i;
1664 u_int8_t *p;
1665
1666 printf("page 5 sense:");
1667 for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i;
1668 i--, p++)
1669 printf(" %02x", *p);
1670 printf("\n");
1671 printf("page 5 pg_code=%d sense=%p/%p\n",
1672 pages->flex_geometry.pg_code, &scsipi_sense, pages);
1673 }
1674 #endif
1675
1676 if ((pages->flex_geometry.pg_code & PGCODE_MASK) != 5)
1677 return (ERESTART);
1678
1679 SC_DEBUG(sd->sc_periph, SCSIPI_DB3,
1680 ("%d cyls, %d heads, %d sec, %d bytes/sec\n",
1681 _3btol(pages->flex_geometry.ncyl),
1682 pages->flex_geometry.nheads,
1683 pages->flex_geometry.ph_sec_tr,
1684 _2btol(pages->flex_geometry.bytes_s)));
1685
1686 dp->heads = pages->flex_geometry.nheads;
1687 dp->cyls = _2btol(pages->flex_geometry.ncyl);
1688 dp->sectors = pages->flex_geometry.ph_sec_tr;
1689 if (dp->heads == 0 || dp->cyls == 0 || dp->sectors == 0)
1690 return (ERESTART);
1691
1692 dp->rot_rate = _2btol(pages->rigid_geometry.rpm);
1693 if (dp->rot_rate == 0)
1694 dp->rot_rate = 3600;
1695
1696 #if 0
1697 printf("page 5 ok\n");
1698 #endif
1699 return (0);
1700 }
1701
1702 static int
1703 sd_get_parms(struct sd_softc *sd, struct disk_parms *dp, int flags)
1704 {
1705 struct dk_softc *dksc = &sd->sc_dksc;
1706 int error;
1707
1708 /*
1709 * If offline, the SDEV_MEDIA_LOADED flag will be
1710 * cleared by the caller if necessary.
1711 */
1712 if (sd->type == T_SIMPLE_DIRECT) {
1713 error = sd_get_simplifiedparms(sd, dp, flags);
1714 if (!error)
1715 goto setprops;
1716 return (error);
1717 }
1718
1719 error = sd_get_capacity(sd, dp, flags);
1720 if (error)
1721 return (error);
1722
1723 if (sd->type == T_OPTICAL)
1724 goto page0;
1725
1726 if (sd->sc_periph->periph_flags & PERIPH_REMOVABLE) {
1727 if (!sd_get_parms_page5(sd, dp, flags) ||
1728 !sd_get_parms_page4(sd, dp, flags))
1729 goto setprops;
1730 } else {
1731 if (!sd_get_parms_page4(sd, dp, flags) ||
1732 !sd_get_parms_page5(sd, dp, flags))
1733 goto setprops;
1734 }
1735
1736 page0:
1737 printf("%s: fabricating a geometry\n", dksc->sc_xname);
1738 /* Try calling driver's method for figuring out geometry. */
1739 if (!sd->sc_periph->periph_channel->chan_adapter->adapt_getgeom ||
1740 !(*sd->sc_periph->periph_channel->chan_adapter->adapt_getgeom)
1741 (sd->sc_periph, dp, dp->disksize)) {
1742 /*
1743 * Use adaptec standard fictitious geometry
1744 * this depends on which controller (e.g. 1542C is
1745 * different. but we have to put SOMETHING here..)
1746 */
1747 dp->heads = 64;
1748 dp->sectors = 32;
1749 dp->cyls = dp->disksize / (64 * 32);
1750 }
1751 dp->rot_rate = 3600;
1752
1753 setprops:
1754 sd_set_geometry(sd);
1755
1756 return (SDGP_RESULT_OK);
1757 }
1758
1759 static int
1760 sd_flush(struct sd_softc *sd, int flags)
1761 {
1762 struct scsipi_periph *periph = sd->sc_periph;
1763 struct scsi_synchronize_cache_10 cmd;
1764
1765 /*
1766 * If the device is SCSI-2, issue a SYNCHRONIZE CACHE.
1767 * We issue with address 0 length 0, which should be
1768 * interpreted by the device as "all remaining blocks
1769 * starting at address 0". We ignore ILLEGAL REQUEST
1770 * in the event that the command is not supported by
1771 * the device, and poll for completion so that we know
1772 * that the cache has actually been flushed.
1773 *
1774 * Unless, that is, the device can't handle the SYNCHRONIZE CACHE
1775 * command, as indicated by our quirks flags.
1776 *
1777 * XXX What about older devices?
1778 */
1779 if (periph->periph_version < 2 ||
1780 (periph->periph_quirks & PQUIRK_NOSYNCCACHE))
1781 return (0);
1782
1783 sd->flags |= SDF_FLUSHING;
1784 memset(&cmd, 0, sizeof(cmd));
1785 cmd.opcode = SCSI_SYNCHRONIZE_CACHE_10;
1786
1787 return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
1788 SDRETRIES, 100000, NULL, flags | XS_CTL_IGNORE_ILLEGAL_REQUEST));
1789 }
1790
1791 static int
1792 sd_getcache(struct sd_softc *sd, int *bitsp)
1793 {
1794 struct scsipi_periph *periph = sd->sc_periph;
1795 struct sd_mode_sense_data scsipi_sense;
1796 int error, bits = 0;
1797 int big;
1798 union scsi_disk_pages *pages;
1799
1800 if (periph->periph_version < 2)
1801 return (EOPNOTSUPP);
1802
1803 memset(&scsipi_sense, 0, sizeof(scsipi_sense));
1804 error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
1805 sizeof(scsipi_sense.pages.caching_params), 8, 0, &big);
1806 if (error)
1807 return (error);
1808
1809 if (big)
1810 pages = (void *)(&scsipi_sense.header.big + 1);
1811 else
1812 pages = (void *)(&scsipi_sense.header.small + 1);
1813
1814 if ((pages->caching_params.flags & CACHING_RCD) == 0)
1815 bits |= DKCACHE_READ;
1816 if (pages->caching_params.flags & CACHING_WCE)
1817 bits |= DKCACHE_WRITE;
1818 if (pages->caching_params.pg_code & PGCODE_PS)
1819 bits |= DKCACHE_SAVE;
1820
1821 memset(&scsipi_sense, 0, sizeof(scsipi_sense));
1822 error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
1823 sizeof(scsipi_sense.pages.caching_params),
1824 SMS_PCTRL_CHANGEABLE|8, 0, &big);
1825 if (error == 0) {
1826 if (big)
1827 pages = (void *)(&scsipi_sense.header.big + 1);
1828 else
1829 pages = (void *)(&scsipi_sense.header.small + 1);
1830
1831 if (pages->caching_params.flags & CACHING_RCD)
1832 bits |= DKCACHE_RCHANGE;
1833 if (pages->caching_params.flags & CACHING_WCE)
1834 bits |= DKCACHE_WCHANGE;
1835 }
1836
1837 *bitsp = bits;
1838
1839 return (0);
1840 }
1841
1842 static int
1843 sd_setcache(struct sd_softc *sd, int bits)
1844 {
1845 struct scsipi_periph *periph = sd->sc_periph;
1846 struct sd_mode_sense_data scsipi_sense;
1847 int error;
1848 uint8_t oflags, byte2 = 0;
1849 int big;
1850 union scsi_disk_pages *pages;
1851
1852 if (periph->periph_version < 2)
1853 return (EOPNOTSUPP);
1854
1855 memset(&scsipi_sense, 0, sizeof(scsipi_sense));
1856 error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
1857 sizeof(scsipi_sense.pages.caching_params), 8, 0, &big);
1858 if (error)
1859 return (error);
1860
1861 if (big)
1862 pages = (void *)(&scsipi_sense.header.big + 1);
1863 else
1864 pages = (void *)(&scsipi_sense.header.small + 1);
1865
1866 oflags = pages->caching_params.flags;
1867
1868 if (bits & DKCACHE_READ)
1869 pages->caching_params.flags &= ~CACHING_RCD;
1870 else
1871 pages->caching_params.flags |= CACHING_RCD;
1872
1873 if (bits & DKCACHE_WRITE)
1874 pages->caching_params.flags |= CACHING_WCE;
1875 else
1876 pages->caching_params.flags &= ~CACHING_WCE;
1877
1878 if (oflags == pages->caching_params.flags)
1879 return (0);
1880
1881 pages->caching_params.pg_code &= PGCODE_MASK;
1882
1883 if (bits & DKCACHE_SAVE)
1884 byte2 |= SMS_SP;
1885
1886 return (sd_mode_select(sd, byte2|SMS_PF, &scsipi_sense,
1887 sizeof(struct scsi_mode_page_header) +
1888 pages->caching_params.pg_length, 0, big));
1889 }
1890
1891 static void
1892 sd_set_geometry(struct sd_softc *sd)
1893 {
1894 struct dk_softc *dksc = &sd->sc_dksc;
1895 struct disk_geom *dg = &dksc->sc_dkdev.dk_geom;
1896
1897 memset(dg, 0, sizeof(*dg));
1898
1899 dg->dg_secperunit = sd->params.disksize;
1900 dg->dg_secsize = sd->params.blksize;
1901 dg->dg_nsectors = sd->params.sectors;
1902 dg->dg_ntracks = sd->params.heads;
1903 dg->dg_ncylinders = sd->params.cyls;
1904
1905 disk_set_info(dksc->sc_dev, &dksc->sc_dkdev, NULL);
1906 }
1907