History log of /openbsd-current/sys/scsi/cd.c
Revision (<<< Hide revision tags) (Show revision tags >>>) Date Author Comments
# 1.266 01-Sep-2022 krw

Stop setting d_bbsize and d_sbsize. Nobody has paid
any attention for some time.

ok otto@ as part of larger diff


Revision tags: OPENBSD_7_1_BASE
# 1.265 11-Jan-2022 jsg

spelling


# 1.264 24-Oct-2021 mpi

Constify struct cfattach.

ok visa@ a long time ago, ok krw@


Revision tags: OPENBSD_6_9_BASE OPENBSD_7_0_BASE
# 1.263 12-Mar-2021 jsg

spelling


Revision tags: OPENBSD_6_8_BASE
# 1.262 22-Sep-2020 krw

Since dlg@'s 2009 scsi midlayer refactoring the 'struct scsi_generic *cmd'
member of 'struct scsi_xfer' has always been pointed at the 'struct scsi_generic
cmdstore' member of the same instance. So nuke 'cmdstore' and remove the '*'
from cmd. Take the address of cmd as required by the various casts.

No intentional functional change.

luna88k test by aoyama@, sparc64 test by jmatthew@

Identification of 2009's last *cmd use and ok jmatthew@


# 1.261 01-Sep-2020 krw

Rename [READ|WRITE]_BIG to [READ|WRITE]_10. Rename struct scsi_rw_big to
struct scsi_rw_10.

ok gnezdo@ jmatthew@ (who also did sparc64 compile test)


# 1.260 29-Aug-2020 krw

More recent MMC specificiations add READ(12)/WRITE(12). So add cd_cmd_rw12()
and let cdstart() use it if the requested i/o is unable to fit into a READ(10).

Certainly better than silently truncating the i/o into a READ(10)/WRITE(10).


# 1.259 29-Aug-2020 krw

Use ISSET() to check b_flags for B_READ.


# 1.258 29-Aug-2020 krw

Use u_int32_t for nsecs, making it crystal clear that the values
are expected to fit into a 4-byte field.


# 1.257 29-Aug-2020 krw

Have [cd|sd]_cmd_rw[6|10|12|16] return the length of the created command and
have the caller assign it to xs->cmdlen. Pass in xs->cmd instead of xs. A
slightly cleaner API that provides the potential of detecting and reacting to a
failure to create the desired command.


# 1.256 28-Aug-2020 krw

Shuffle [cd|sd]start code into closer alignment. Move the initialization of the
xs fields to a more convenient location, shrinking upcoming diffs. Nuke some
Captain Obvious comments.


# 1.255 28-Aug-2020 krw

Abstract cd_cmd_rw6() and cd_cmd_rw10() a la sd_cmd_rw6() and sd_cmd_rw10().


# 1.254 28-Aug-2020 krw

Nuke CDF_ANCIENT, SDF_ANCIENT SDEV_ONLYBIG and bogus check of SID_RelAdr in
favour of simply using the device's claimed SCSI level of support. Except of
course for ATAPI/USB devices which often don't claim anything. Keep assuming
they are at least SCSI-2. Use consistant tests in
sdminphys/cdminphys/sdstart/cdstart.


# 1.253 26-Aug-2020 krw

Remove needless uses of SDEV_ONLYBIG. It was always set when SDEV_UMASS was set,
and was always checked in concert with SDEV_ATAPI. Just rely on SDEV_ATAPI and
SDEV_UMASS in all but the one place sd(4) where SDEV_ONLYBIG is set
independently of SDEV_ATAPI/_UMASS.

ok jmatthew@


# 1.252 22-Aug-2020 krw

The last timeout_add(sc_timeout) died in the great XS_NO_CCB purge of 2017. Nuke
pointless timeout_set(sc_timoeut) and timeout_del(sc_timeout) calls and the
sc_timeout fields themselves.


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.265 11-Jan-2022 jsg

spelling


# 1.264 24-Oct-2021 mpi

Constify struct cfattach.

ok visa@ a long time ago, ok krw@


Revision tags: OPENBSD_6_9_BASE OPENBSD_7_0_BASE
# 1.263 12-Mar-2021 jsg

spelling


Revision tags: OPENBSD_6_8_BASE
# 1.262 22-Sep-2020 krw

Since dlg@'s 2009 scsi midlayer refactoring the 'struct scsi_generic *cmd'
member of 'struct scsi_xfer' has always been pointed at the 'struct scsi_generic
cmdstore' member of the same instance. So nuke 'cmdstore' and remove the '*'
from cmd. Take the address of cmd as required by the various casts.

No intentional functional change.

luna88k test by aoyama@, sparc64 test by jmatthew@

Identification of 2009's last *cmd use and ok jmatthew@


# 1.261 01-Sep-2020 krw

Rename [READ|WRITE]_BIG to [READ|WRITE]_10. Rename struct scsi_rw_big to
struct scsi_rw_10.

ok gnezdo@ jmatthew@ (who also did sparc64 compile test)


# 1.260 29-Aug-2020 krw

More recent MMC specificiations add READ(12)/WRITE(12). So add cd_cmd_rw12()
and let cdstart() use it if the requested i/o is unable to fit into a READ(10).

Certainly better than silently truncating the i/o into a READ(10)/WRITE(10).


# 1.259 29-Aug-2020 krw

Use ISSET() to check b_flags for B_READ.


# 1.258 29-Aug-2020 krw

Use u_int32_t for nsecs, making it crystal clear that the values
are expected to fit into a 4-byte field.


# 1.257 29-Aug-2020 krw

Have [cd|sd]_cmd_rw[6|10|12|16] return the length of the created command and
have the caller assign it to xs->cmdlen. Pass in xs->cmd instead of xs. A
slightly cleaner API that provides the potential of detecting and reacting to a
failure to create the desired command.


# 1.256 28-Aug-2020 krw

Shuffle [cd|sd]start code into closer alignment. Move the initialization of the
xs fields to a more convenient location, shrinking upcoming diffs. Nuke some
Captain Obvious comments.


# 1.255 28-Aug-2020 krw

Abstract cd_cmd_rw6() and cd_cmd_rw10() a la sd_cmd_rw6() and sd_cmd_rw10().


# 1.254 28-Aug-2020 krw

Nuke CDF_ANCIENT, SDF_ANCIENT SDEV_ONLYBIG and bogus check of SID_RelAdr in
favour of simply using the device's claimed SCSI level of support. Except of
course for ATAPI/USB devices which often don't claim anything. Keep assuming
they are at least SCSI-2. Use consistant tests in
sdminphys/cdminphys/sdstart/cdstart.


# 1.253 26-Aug-2020 krw

Remove needless uses of SDEV_ONLYBIG. It was always set when SDEV_UMASS was set,
and was always checked in concert with SDEV_ATAPI. Just rely on SDEV_ATAPI and
SDEV_UMASS in all but the one place sd(4) where SDEV_ONLYBIG is set
independently of SDEV_ATAPI/_UMASS.

ok jmatthew@


# 1.252 22-Aug-2020 krw

The last timeout_add(sc_timeout) died in the great XS_NO_CCB purge of 2017. Nuke
pointless timeout_set(sc_timoeut) and timeout_del(sc_timeout) calls and the
sc_timeout fields themselves.


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.264 24-Oct-2021 mpi

Constify struct cfattach.

ok visa@ a long time ago, ok krw@


Revision tags: OPENBSD_6_9_BASE OPENBSD_7_0_BASE
# 1.263 12-Mar-2021 jsg

spelling


Revision tags: OPENBSD_6_8_BASE
# 1.262 22-Sep-2020 krw

Since dlg@'s 2009 scsi midlayer refactoring the 'struct scsi_generic *cmd'
member of 'struct scsi_xfer' has always been pointed at the 'struct scsi_generic
cmdstore' member of the same instance. So nuke 'cmdstore' and remove the '*'
from cmd. Take the address of cmd as required by the various casts.

No intentional functional change.

luna88k test by aoyama@, sparc64 test by jmatthew@

Identification of 2009's last *cmd use and ok jmatthew@


# 1.261 01-Sep-2020 krw

Rename [READ|WRITE]_BIG to [READ|WRITE]_10. Rename struct scsi_rw_big to
struct scsi_rw_10.

ok gnezdo@ jmatthew@ (who also did sparc64 compile test)


# 1.260 29-Aug-2020 krw

More recent MMC specificiations add READ(12)/WRITE(12). So add cd_cmd_rw12()
and let cdstart() use it if the requested i/o is unable to fit into a READ(10).

Certainly better than silently truncating the i/o into a READ(10)/WRITE(10).


# 1.259 29-Aug-2020 krw

Use ISSET() to check b_flags for B_READ.


# 1.258 29-Aug-2020 krw

Use u_int32_t for nsecs, making it crystal clear that the values
are expected to fit into a 4-byte field.


# 1.257 29-Aug-2020 krw

Have [cd|sd]_cmd_rw[6|10|12|16] return the length of the created command and
have the caller assign it to xs->cmdlen. Pass in xs->cmd instead of xs. A
slightly cleaner API that provides the potential of detecting and reacting to a
failure to create the desired command.


# 1.256 28-Aug-2020 krw

Shuffle [cd|sd]start code into closer alignment. Move the initialization of the
xs fields to a more convenient location, shrinking upcoming diffs. Nuke some
Captain Obvious comments.


# 1.255 28-Aug-2020 krw

Abstract cd_cmd_rw6() and cd_cmd_rw10() a la sd_cmd_rw6() and sd_cmd_rw10().


# 1.254 28-Aug-2020 krw

Nuke CDF_ANCIENT, SDF_ANCIENT SDEV_ONLYBIG and bogus check of SID_RelAdr in
favour of simply using the device's claimed SCSI level of support. Except of
course for ATAPI/USB devices which often don't claim anything. Keep assuming
they are at least SCSI-2. Use consistant tests in
sdminphys/cdminphys/sdstart/cdstart.


# 1.253 26-Aug-2020 krw

Remove needless uses of SDEV_ONLYBIG. It was always set when SDEV_UMASS was set,
and was always checked in concert with SDEV_ATAPI. Just rely on SDEV_ATAPI and
SDEV_UMASS in all but the one place sd(4) where SDEV_ONLYBIG is set
independently of SDEV_ATAPI/_UMASS.

ok jmatthew@


# 1.252 22-Aug-2020 krw

The last timeout_add(sc_timeout) died in the great XS_NO_CCB purge of 2017. Nuke
pointless timeout_set(sc_timoeut) and timeout_del(sc_timeout) calls and the
sc_timeout fields themselves.


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.263 12-Mar-2021 jsg

spelling


Revision tags: OPENBSD_6_8_BASE
# 1.262 22-Sep-2020 krw

Since dlg@'s 2009 scsi midlayer refactoring the 'struct scsi_generic *cmd'
member of 'struct scsi_xfer' has always been pointed at the 'struct scsi_generic
cmdstore' member of the same instance. So nuke 'cmdstore' and remove the '*'
from cmd. Take the address of cmd as required by the various casts.

No intentional functional change.

luna88k test by aoyama@, sparc64 test by jmatthew@

Identification of 2009's last *cmd use and ok jmatthew@


# 1.261 01-Sep-2020 krw

Rename [READ|WRITE]_BIG to [READ|WRITE]_10. Rename struct scsi_rw_big to
struct scsi_rw_10.

ok gnezdo@ jmatthew@ (who also did sparc64 compile test)


# 1.260 29-Aug-2020 krw

More recent MMC specificiations add READ(12)/WRITE(12). So add cd_cmd_rw12()
and let cdstart() use it if the requested i/o is unable to fit into a READ(10).

Certainly better than silently truncating the i/o into a READ(10)/WRITE(10).


# 1.259 29-Aug-2020 krw

Use ISSET() to check b_flags for B_READ.


# 1.258 29-Aug-2020 krw

Use u_int32_t for nsecs, making it crystal clear that the values
are expected to fit into a 4-byte field.


# 1.257 29-Aug-2020 krw

Have [cd|sd]_cmd_rw[6|10|12|16] return the length of the created command and
have the caller assign it to xs->cmdlen. Pass in xs->cmd instead of xs. A
slightly cleaner API that provides the potential of detecting and reacting to a
failure to create the desired command.


# 1.256 28-Aug-2020 krw

Shuffle [cd|sd]start code into closer alignment. Move the initialization of the
xs fields to a more convenient location, shrinking upcoming diffs. Nuke some
Captain Obvious comments.


# 1.255 28-Aug-2020 krw

Abstract cd_cmd_rw6() and cd_cmd_rw10() a la sd_cmd_rw6() and sd_cmd_rw10().


# 1.254 28-Aug-2020 krw

Nuke CDF_ANCIENT, SDF_ANCIENT SDEV_ONLYBIG and bogus check of SID_RelAdr in
favour of simply using the device's claimed SCSI level of support. Except of
course for ATAPI/USB devices which often don't claim anything. Keep assuming
they are at least SCSI-2. Use consistant tests in
sdminphys/cdminphys/sdstart/cdstart.


# 1.253 26-Aug-2020 krw

Remove needless uses of SDEV_ONLYBIG. It was always set when SDEV_UMASS was set,
and was always checked in concert with SDEV_ATAPI. Just rely on SDEV_ATAPI and
SDEV_UMASS in all but the one place sd(4) where SDEV_ONLYBIG is set
independently of SDEV_ATAPI/_UMASS.

ok jmatthew@


# 1.252 22-Aug-2020 krw

The last timeout_add(sc_timeout) died in the great XS_NO_CCB purge of 2017. Nuke
pointless timeout_set(sc_timoeut) and timeout_del(sc_timeout) calls and the
sc_timeout fields themselves.


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.262 22-Sep-2020 krw

Since dlg@'s 2009 scsi midlayer refactoring the 'struct scsi_generic *cmd'
member of 'struct scsi_xfer' has always been pointed at the 'struct scsi_generic
cmdstore' member of the same instance. So nuke 'cmdstore' and remove the '*'
from cmd. Take the address of cmd as required by the various casts.

No intentional functional change.

luna88k test by aoyama@, sparc64 test by jmatthew@

Identification of 2009's last *cmd use and ok jmatthew@


# 1.261 01-Sep-2020 krw

Rename [READ|WRITE]_BIG to [READ|WRITE]_10. Rename struct scsi_rw_big to
struct scsi_rw_10.

ok gnezdo@ jmatthew@ (who also did sparc64 compile test)


# 1.260 29-Aug-2020 krw

More recent MMC specificiations add READ(12)/WRITE(12). So add cd_cmd_rw12()
and let cdstart() use it if the requested i/o is unable to fit into a READ(10).

Certainly better than silently truncating the i/o into a READ(10)/WRITE(10).


# 1.259 29-Aug-2020 krw

Use ISSET() to check b_flags for B_READ.


# 1.258 29-Aug-2020 krw

Use u_int32_t for nsecs, making it crystal clear that the values
are expected to fit into a 4-byte field.


# 1.257 29-Aug-2020 krw

Have [cd|sd]_cmd_rw[6|10|12|16] return the length of the created command and
have the caller assign it to xs->cmdlen. Pass in xs->cmd instead of xs. A
slightly cleaner API that provides the potential of detecting and reacting to a
failure to create the desired command.


# 1.256 28-Aug-2020 krw

Shuffle [cd|sd]start code into closer alignment. Move the initialization of the
xs fields to a more convenient location, shrinking upcoming diffs. Nuke some
Captain Obvious comments.


# 1.255 28-Aug-2020 krw

Abstract cd_cmd_rw6() and cd_cmd_rw10() a la sd_cmd_rw6() and sd_cmd_rw10().


# 1.254 28-Aug-2020 krw

Nuke CDF_ANCIENT, SDF_ANCIENT SDEV_ONLYBIG and bogus check of SID_RelAdr in
favour of simply using the device's claimed SCSI level of support. Except of
course for ATAPI/USB devices which often don't claim anything. Keep assuming
they are at least SCSI-2. Use consistant tests in
sdminphys/cdminphys/sdstart/cdstart.


# 1.253 26-Aug-2020 krw

Remove needless uses of SDEV_ONLYBIG. It was always set when SDEV_UMASS was set,
and was always checked in concert with SDEV_ATAPI. Just rely on SDEV_ATAPI and
SDEV_UMASS in all but the one place sd(4) where SDEV_ONLYBIG is set
independently of SDEV_ATAPI/_UMASS.

ok jmatthew@


# 1.252 22-Aug-2020 krw

The last timeout_add(sc_timeout) died in the great XS_NO_CCB purge of 2017. Nuke
pointless timeout_set(sc_timoeut) and timeout_del(sc_timeout) calls and the
sc_timeout fields themselves.


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.261 01-Sep-2020 krw

Rename [READ|WRITE]_BIG to [READ|WRITE]_10. Rename struct scsi_rw_big to
struct scsi_rw_10.

ok gnezdo@ jmatthew@ (who also did sparc64 compile test)


# 1.260 29-Aug-2020 krw

More recent MMC specificiations add READ(12)/WRITE(12). So add cd_cmd_rw12()
and let cdstart() use it if the requested i/o is unable to fit into a READ(10).

Certainly better than silently truncating the i/o into a READ(10)/WRITE(10).


# 1.259 29-Aug-2020 krw

Use ISSET() to check b_flags for B_READ.


# 1.258 29-Aug-2020 krw

Use u_int32_t for nsecs, making it crystal clear that the values
are expected to fit into a 4-byte field.


# 1.257 29-Aug-2020 krw

Have [cd|sd]_cmd_rw[6|10|12|16] return the length of the created command and
have the caller assign it to xs->cmdlen. Pass in xs->cmd instead of xs. A
slightly cleaner API that provides the potential of detecting and reacting to a
failure to create the desired command.


# 1.256 28-Aug-2020 krw

Shuffle [cd|sd]start code into closer alignment. Move the initialization of the
xs fields to a more convenient location, shrinking upcoming diffs. Nuke some
Captain Obvious comments.


# 1.255 28-Aug-2020 krw

Abstract cd_cmd_rw6() and cd_cmd_rw10() a la sd_cmd_rw6() and sd_cmd_rw10().


# 1.254 28-Aug-2020 krw

Nuke CDF_ANCIENT, SDF_ANCIENT SDEV_ONLYBIG and bogus check of SID_RelAdr in
favour of simply using the device's claimed SCSI level of support. Except of
course for ATAPI/USB devices which often don't claim anything. Keep assuming
they are at least SCSI-2. Use consistant tests in
sdminphys/cdminphys/sdstart/cdstart.


# 1.253 26-Aug-2020 krw

Remove needless uses of SDEV_ONLYBIG. It was always set when SDEV_UMASS was set,
and was always checked in concert with SDEV_ATAPI. Just rely on SDEV_ATAPI and
SDEV_UMASS in all but the one place sd(4) where SDEV_ONLYBIG is set
independently of SDEV_ATAPI/_UMASS.

ok jmatthew@


# 1.252 22-Aug-2020 krw

The last timeout_add(sc_timeout) died in the great XS_NO_CCB purge of 2017. Nuke
pointless timeout_set(sc_timoeut) and timeout_del(sc_timeout) calls and the
sc_timeout fields themselves.


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.260 29-Aug-2020 krw

More recent MMC specificiations add READ(12)/WRITE(12). So add cd_cmd_rw12()
and let cdstart() use it if the requested i/o is unable to fit into a READ(10).

Certainly better than silently truncating the i/o into a READ(10)/WRITE(10).


# 1.259 29-Aug-2020 krw

Use ISSET() to check b_flags for B_READ.


# 1.258 29-Aug-2020 krw

Use u_int32_t for nsecs, making it crystal clear that the values
are expected to fit into a 4-byte field.


# 1.257 29-Aug-2020 krw

Have [cd|sd]_cmd_rw[6|10|12|16] return the length of the created command and
have the caller assign it to xs->cmdlen. Pass in xs->cmd instead of xs. A
slightly cleaner API that provides the potential of detecting and reacting to a
failure to create the desired command.


# 1.256 28-Aug-2020 krw

Shuffle [cd|sd]start code into closer alignment. Move the initialization of the
xs fields to a more convenient location, shrinking upcoming diffs. Nuke some
Captain Obvious comments.


# 1.255 28-Aug-2020 krw

Abstract cd_cmd_rw6() and cd_cmd_rw10() a la sd_cmd_rw6() and sd_cmd_rw10().


# 1.254 28-Aug-2020 krw

Nuke CDF_ANCIENT, SDF_ANCIENT SDEV_ONLYBIG and bogus check of SID_RelAdr in
favour of simply using the device's claimed SCSI level of support. Except of
course for ATAPI/USB devices which often don't claim anything. Keep assuming
they are at least SCSI-2. Use consistant tests in
sdminphys/cdminphys/sdstart/cdstart.


# 1.253 26-Aug-2020 krw

Remove needless uses of SDEV_ONLYBIG. It was always set when SDEV_UMASS was set,
and was always checked in concert with SDEV_ATAPI. Just rely on SDEV_ATAPI and
SDEV_UMASS in all but the one place sd(4) where SDEV_ONLYBIG is set
independently of SDEV_ATAPI/_UMASS.

ok jmatthew@


# 1.252 22-Aug-2020 krw

The last timeout_add(sc_timeout) died in the great XS_NO_CCB purge of 2017. Nuke
pointless timeout_set(sc_timoeut) and timeout_del(sc_timeout) calls and the
sc_timeout fields themselves.


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.257 29-Aug-2020 krw

Have [cd|sd]_cmd_rw[6|10|12|16] return the length of the created command and
have the caller assign it to xs->cmdlen. Pass in xs->cmd instead of xs. A
slightly cleaner API that provides the potential of detecting and reacting to a
failure to create the desired command.


# 1.256 28-Aug-2020 krw

Shuffle [cd|sd]start code into closer alignment. Move the initialization of the
xs fields to a more convenient location, shrinking upcoming diffs. Nuke some
Captain Obvious comments.


# 1.255 28-Aug-2020 krw

Abstract cd_cmd_rw6() and cd_cmd_rw10() a la sd_cmd_rw6() and sd_cmd_rw10().


# 1.254 28-Aug-2020 krw

Nuke CDF_ANCIENT, SDF_ANCIENT SDEV_ONLYBIG and bogus check of SID_RelAdr in
favour of simply using the device's claimed SCSI level of support. Except of
course for ATAPI/USB devices which often don't claim anything. Keep assuming
they are at least SCSI-2. Use consistant tests in
sdminphys/cdminphys/sdstart/cdstart.


# 1.253 26-Aug-2020 krw

Remove needless uses of SDEV_ONLYBIG. It was always set when SDEV_UMASS was set,
and was always checked in concert with SDEV_ATAPI. Just rely on SDEV_ATAPI and
SDEV_UMASS in all but the one place sd(4) where SDEV_ONLYBIG is set
independently of SDEV_ATAPI/_UMASS.

ok jmatthew@


# 1.252 22-Aug-2020 krw

The last timeout_add(sc_timeout) died in the great XS_NO_CCB purge of 2017. Nuke
pointless timeout_set(sc_timoeut) and timeout_del(sc_timeout) calls and the
sc_timeout fields themselves.


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.253 26-Aug-2020 krw

Remove needless uses of SDEV_ONLYBIG. It was always set when SDEV_UMASS was set,
and was always checked in concert with SDEV_ATAPI. Just rely on SDEV_ATAPI and
SDEV_UMASS in all but the one place sd(4) where SDEV_ONLYBIG is set
independently of SDEV_ATAPI/_UMASS.

ok jmatthew@


# 1.252 22-Aug-2020 krw

The last timeout_add(sc_timeout) died in the great XS_NO_CCB purge of 2017. Nuke
pointless timeout_set(sc_timoeut) and timeout_del(sc_timeout) calls and the
sc_timeout fields themselves.


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.252 22-Aug-2020 krw

The last timeout_add(sc_timeout) died in the great XS_NO_CCB purge of 2017. Nuke
pointless timeout_set(sc_timoeut) and timeout_del(sc_timeout) calls and the
sc_timeout fields themselves.


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.251 20-Aug-2020 krw

Revert DYING. At least some USB memory sticks get very upset.


# 1.250 19-Aug-2020 krw

Nuke SDF_DYING, CDF_DYING and ST_DYING flags. Use the scsi_link flag
SDEV_S_DYING instead. Makes it clear that the scsi_link and the [cd|sd|st]
device always agree on their state.


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.249 15-Aug-2020 krw

The last SET()s of CDF_WAITING, SDF_WAITING, and ST_WAITING died in the great
XS_NO_CCB purge of 2017.

Nuke pointless ISSET()/CLR() checks and the #define's.


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.248 11-Aug-2020 krw

Explicitly #include <scsi/scsi_debug.h> rather than assuming scsiconf.h will do
it.

Prepares for removal of #include <scsi/scsi_debug.h> from scsiconf.h as soon as
the alpha tester digs out from hurricane to compile last untested files.


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.247 16-Jul-2020 krw

Access scsibus_softc info (luns, adapter, adapter_target,
adapter_softc, adapter_buswidth) via link->bus rather than using
copies currently residing in the link.


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.246 30-Jun-2020 krw

Nuke unneeded 'sa_inqbuf' member of struct scsi_attach_args. It always
points to the inquiry data contained in the struct scsi_link pointed
to by the other member, sa_sc_link.


Revision tags: OPENBSD_6_7_BASE
# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.245 20-Feb-2020 krw

Relax the grip the dead hand of QBUS (a.k.a. MAXPHYS) has on the
throat of physio().

Allows individual devices to eventually be modified to support larger
physio() (a.k.a. 'raw') i/o's if they prove capable of them.

No immediate functional change.

Tested for many weeks by and ok robert@.


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.244 05-Feb-2020 krw

Nuke unnecessary abstraction 'scsi_minphys()' which just calls
'minphys()'. Just use & check for NULL instead, since 'minphys()' is
always called on the code path ([cd|sd|st]minphys) that calls
physio().


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.243 27-Jan-2020 krw

Make the commonalities of cdminphys, sdminphys and stminphys more
obvious by consistently using the variable names and idiom of
sdminphys.

No functional change.


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.242 26-Jan-2020 krw

Shuffle some names around to make reading the code less headache
inducing. Rename scsi_adapter member 'scsi_minphys' to 'dev_minphys'
to reflect what it is supposed to do. Use consistent naming convention
(<dev>_minphys) for the actual device functions.

No functional change.


# 1.241 25-Jan-2020 krw

Ensure scsi_minphys() is always called on the physio() path.

Will allow simplification of individual driver *minphys() functions.

ok jmatthew@ as part of larger diff


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.240 06-Dec-2019 krw

Various cleanup tweaks. 'return' is not a function. KNF. Whitespace,
Comment fixes.


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.239 05-Dec-2019 krw

Shrink scsi_mode_do_sense() parameter list by eliminating the three
pointers returning possible block descriptor values for block size,
block count and density. Most calls were passing "NULL, NULL, NULL"
since they did not care.

Call scsi_parse_blkdesc() directly in those few cases where one or
more of the values is of interest.

No intentional functional change.


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.238 28-Nov-2019 krw

Always pass a pointer to 'big' to scsi_do_mode_sense().

Sets up some simplifications.


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.237 25-Nov-2019 krw

Use scsi_read_cap[10|16] instead of re-rolling the code.

More careful initialization, better error/debug messages.


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.236 23-Nov-2019 krw

Consistently use ISSET() to check for set flags.


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.235 23-Nov-2019 krw

Consistently use !ISSET() to check for unset flags.


# 1.234 23-Nov-2019 krw

Consistently use SET() to set bits.


# 1.233 22-Nov-2019 krw

Be consistent and always use CLR() to clear flags.


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.232 21-Nov-2019 krw

Be consistent and always use [!]ISSET() to test flags in xs->flags.


# 1.231 21-Nov-2019 krw

Be consistent and always use SET() to set flags in xs->flags.


Revision tags: OPENBSD_6_6_BASE
# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.230 29-Sep-2019 krw

Introduce SC_DEBUG_SENSE() and simplify code by eliminating a bunch
of three line SCSIDEBUG chunks.


# 1.229 29-Sep-2019 krw

Tweak some whitespace to make autoindenter happy. Use consistent naming idiom for
the debug functions.


# 1.228 27-Sep-2019 krw

Add/tweak #endif comments to make spelunking via grep more rewarding.


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.227 01-Sep-2019 krw

Adopt the SCSI versioning #define's from FreeBSD. Eliminate the
now unneeded version_to_spc() mapping array, a duplicate #define
and a couple of magic numbers. Toss in some comments for future
generations of spelunkers.

Makes it possible to check for specific SPC versions when new
features or eliminated features require such a check.

No intentional functional change.


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.226 28-Aug-2019 krw

Introduce SCSI0(), SCSI2() and SCSI3() defines to clarify (some) uses
of SCSISPC() when checking the values of the INQUIRY version field.


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.225 17-Aug-2019 krw

Nuke some unused variables, tweak some declarations and
variable names into a consistant idiom.


Revision tags: OPENBSD_6_5_BASE
# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.224 20-Jan-2019 krw

No leading space(s) before labels.

Prodded by guenther@


# 1.223 20-Jan-2019 krw

When retiring a SCSI request, sometimes the buf's b_error value is
forcibly set to a value. Make sure that in all those cases the B_ERROR
flag is cleared (if b_error is being set to 0) or set (if b_error is
being set to non-zero) appropriately.

ok dlg@ jmatthew@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE
# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision


# 1.222 30-Dec-2017 guenther

Don't pull in <sys/file.h> just to get fcntl.h

ok deraadt@ krw@


Revision tags: OPENBSD_6_2_BASE
# 1.221 08-Sep-2017 deraadt

If you use sys/param.h, you don't need sys/types.h


# 1.220 29-May-2017 krw

To prevent anyone else from stumbling on this (now) archaic bit of
history, nuke all mentions of XS_NO_CCB and the #define.

2006 - 2017. R.I.P.

ok kettenis@ inferred ok dlg@


# 1.219 04-May-2017 deraadt

Also pass the blk offset to disk_unbusy(), so that it can pass it to
the random subsystem as entropy. This value is pretty much unknown,
and anyways our entropy input ring does not saturate from knowns.
ok mikeb djm


Revision tags: OPENBSD_6_0_BASE OPENBSD_6_1_BASE
# 1.218 12-Mar-2016 krw

Standardize on calling local scsi_link variables 'link' instead of
'sc_link'. 'sc_link' is a field in the various device *_softc
structures, where the sc_ prefix was for 'softc'. Reduces potential
mental confusion. Newer code from down under was already using
'link'.

No functional change.

Prompted by bluhm@'s adventures in scsi. ok dlg@ jmatthew@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE
# 1.217 07-Jun-2015 krw

More damned eye searing whitespace.


Revision tags: OPENBSD_5_7_BASE
# 1.216 15-Dec-2014 tedu

convert bcopy to memcpy. ok dlg krw


# 1.215 14-Sep-2014 jsg

remove uneeded proc.h includes
ok mpi@ kspillner@


Revision tags: OPENBSD_5_6_BASE
# 1.214 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


Revision tags: OPENBSD_5_5_BASE
# 1.213 01-Nov-2013 krw

Sprinkle (long long) casts where %lld is being used to print daddr_t
variables. Some random whitespace/knf repairs encountered on the way.

ok miod@ on inspection, feedback & more suggestions from millert@


# 1.212 03-Oct-2013 krw

Print daddr_t variables with %lld, u_int64_t variables with %llu.


# 1.211 27-Sep-2013 krw

scsi_size() is now used only by cd(4). So move it from scsi_base.c
to cd.c and call it cd_size(), like sd_size() lives in sd.c.

Tweak some daddr_t variables to u_int64_t on the way, when they are
for disk sector numbers, not 512-byte block numbers.


# 1.210 15-Sep-2013 krw

cddump() takes a daddr_t parameter. Call that parameter 'blkno' and not
'secno'. This is what sddump() already does and consistant is good.
No function change.


# 1.209 15-Sep-2013 krw

Use DL_SECTOBLK() and DL_BLKTOSEC() to clarify code and remove
repeated handrolling of same code. Use daddr_t variable to
calculate daddr_t return values, and u_int64_t variables to
calculate disk sector values.

No functional change.


Revision tags: OPENBSD_5_4_BASE
# 1.208 11-Jun-2013 deraadt

final removal of daddr64_t. daddr_t has been 64 bit for a long enough
test period; i think 3 years ago the last bugs fell out.
ok otto beck others


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.207 06-Jul-2011 matthew

Eliminate redundant buf validation checks in xxstrategy() methods now
that they're implemented consistently in bounds_check_with_label().

Also, per krw's request, change bounds_check_with_label() to return 0
if the checks succeed, and change the drivers to test == -1 instead of
<= 0. (Man page update to follow; intentionally omitting
arch/vax/mba/hp.c from this commit because it doesn't even build
currently and miod@ promises to kill it soon.)

ok krw@


# 1.206 03-Jul-2011 matthew

Remove config_activate() and DVACT_ACTIVATE. PCMCIA's the only thing
that's ever used it, and it's long since been changed to use
DVACT_{QUIESCE,SUSPEND,RESUME} instead.

ok deraadt@, dlg@; miod@ also agreed with this idea when I brought it
up a few weeks ago


# 1.205 30-Jun-2011 matthew

Refactor some common open/close/detach disk driver code into
subr_disk.c. For now just the MI disk drivers.

ok deraadt@, krw@; jsing@ liked the approach too


# 1.204 19-Jun-2011 deraadt

Use disk_lock_nointr() in the xxclose() routines so that they cannot
be interrupted.
ok matthew


# 1.203 19-Jun-2011 deraadt

Use disk_lock/disk_unlock directly and in the same way in these drivers,
rather than using various wrappings. Convert vnd to using the sc_dk
rwlock instead of using one of its own.
ok matthew


# 1.202 06-Jun-2011 matthew

Delete the long dead LOCKED and WANTED flags from cd(4), sd(4), and
wd(4). They haven't been used for 10+ years, since the drivers were
switched to use disk_lock() and disk_unlock() instead.

No binary change.


# 1.201 05-Jun-2011 matthew

Drop kernel support for the useless DIOCWLABEL ioctl and prune a lot
of silly flag twiddling code in various disk drivers.

ok deraadt@, miod@

N.B., users will need a -current disklabel(8) to be able to write new
disklabels to disk now.


# 1.200 03-Jun-2011 matthew

Get rid of the wlabel argument to bounds_check_with_label(). It's
never done anything in OpenBSD and just clutters disk drivers with
silly flag handling.

More cleanup to follow.

ok deraadt@, millert@; no objections krw@


# 1.199 31-May-2011 matthew

Change a few of the more common disk drivers (sd, cd, wd, rd, and vnd)
to return EBUSY if the user tries to modify an open partition's offset
or size. Only sadness can result if a user tries this, and rejecting
it prevents a race between sdstart() and sdstrategy().

Curiously, there was already code in the kernel and in disklabel(8) to
detect/handle this, but it was effectively disabled because the disk
drivers always used something like "/* sc->sc_dk.dk_openmask */ 0",
and this commented out code has existed since even r1.1 in NetBSD.

I had no problems building a release and messing around with
disklabel(8) for a bit with this diff. Canarying the more common MI
disk drivers until we gain confidence that there aren't any
regressions, then we can switch the remaining drivers.

"I am surprised you got me convinced that this stuff is safe" deraadt@
ok krw@


# 1.198 17-Mar-2011 deraadt

use dma_alloc/dma_free instead of malloc to allocate buffers which need
to be in the right address space.
help from matthew and krw


Revision tags: OPENBSD_4_9_BASE
# 1.197 22-Nov-2010 krw

SCSI devices are assumed to be T_FIXED unless they say otherwise.
cd(4) did not believe any T_FIXED device was its responsibility.
Thus when a USB CD forgot to mention that it is T_REMOV, it appeared
as uk(4).

Make cd(4) accept even T_FIXED devices that claim to be T_CDROM or
T_WORM.

Noticed and fix tested by Rene Maroufi. Closes PR #6513.


# 1.196 23-Sep-2010 jsing

Introduce a DKF_NOLABELREAD flag, which is used by a device to prevent
automatic reading of disklabel on attach.

ok deraadt@ miod@ krw@


# 1.195 22-Sep-2010 matthew

All users of physio(9) now pass NULL as the buf pointer argument, so
no point in keeping it around.

"i like this" thib@ (a while back); ok krw@ and oga@; reminder to
update the man page and tweaks jmc@


# 1.194 21-Sep-2010 krw

Add a real DIOCGPDINFO, allowing access to the physical information
about the device rather than the contents of whichever disklabel
was read. Tweak whitespace in sd.c to make the code appearance
consistant.


# 1.193 20-Sep-2010 deraadt

bufq_drain() does not need to be done in deactivate; we only need
to deactivate transactions we are currently doing.
ok dlg


# 1.192 14-Sep-2010 dlg

scsi_xsh_del the xs handler on DEACTIVATE.

same change as sd.c r1.212. matthew@ pointed out that cd(4) and
st(4) would need the same change.


# 1.191 12-Sep-2010 krw

Make cd the same as sd by calling the cd_parms member of the softc 'params'
rather than 'sc_params'. No change to .o file.


# 1.190 11-Sep-2010 krw

Be more ruthlessly consistent in variable names for blk/block ==
512 == DEV_BSIZE units and variable-sized physical device 'sectors'.
I hope this reduces confusion a bit more. No change to .o files.

ok for intent miod@, with tweak.


# 1.189 08-Sep-2010 jsing

Introduce a disk_lookup() function which calls device_lookup(), before
verifying that the resulting device is present on the disklist. This
avoids a race whereby the disk driver can be accessed as soon as the
softc has been allocated, but before the disk has completed
initialisation and has called disk_attach() (up until this point
dk_label is still a null pointer).

Cut cd(4), sd(4) and wd(4) across to disk_lookup(). All callers of
disk_attach() need to be tested and cut over in due course.

ok deraadt@ krw@


# 1.188 08-Sep-2010 jsing

Store a struct device pointer within struct disk and populate this when
disk_attach() is called by the device driver. We will be building on
this shortly.

ok deraadt@ krw@


# 1.187 07-Sep-2010 deraadt

remove the powerhook code. All architectures now use the ca_activate tree
traversal code to suspend/resume
ok oga kettenis blambert


# 1.186 07-Sep-2010 deraadt

rely on SCSI_AUTOCONF for cd_resume instead of wrapping it in a workq
(which creates a potential race against cd detach)
discussed with krw and dlg seperately


# 1.185 01-Sep-2010 dlg

make struct bufq a member of the softc for devices that use it,
rather than it being a pointer to something that needs to be allocated
at attach. since all these devices need a bufq to operate, it makes
sense to have it allocated as part of the softc and get bufq_init
to just initialise all its fields. it also gets rid of the possibility
that you wont be able to allocate the bufq struct during attach,
which is something you dont want to happen.

secondly, it consistently implements a split between wrapper functions
and the per discipline implementation of the bufq handlers. it
consistently does the locking in the wrappers rather than doing
half in the wrappers and the other half in the implementations.

it also consistently handles the outstanding bufq bq pointer in the
wrappers.

this hides most of the implementation inside kern_bufq.c. the only
stuff left in buf.h is for the bits each implementation needs to
put inside struct buf.

tested by thib@ krw@ and me
ok thib@ matthew@
no objection from krw@


# 1.184 31-Aug-2010 deraadt

Change the powerhook into an activation routine. It has to use a workq.
There is a bit of concern that this workq can race against a detach
happening... any solutions from the peanut gallery?


# 1.183 30-Aug-2010 matthew

Avoid possible aliasing-related compiler issues by always writing to
cmd->opcode through the type casted command pointer rather than
through xs->cmd->opcode.

Requested by deraadt@; ok krw@.


# 1.182 28-Aug-2010 matthew

Garbage collect struct dkdriver.

ok miod@; "please go ahead" jsing@


Revision tags: OPENBSD_4_8_BASE
# 1.181 28-Jul-2010 krw

DVD_INVALIDATE_AGID is a 'no payload' operation, so don't set
xs->datalen and reset xs->data to NULL. This prevents a spurious
attempt to setup (dma map, etc) and possibly attempt data tranfser.

In line with what Linux and FreeBSD do as far as I can tell.

Reduces the delay before my DVD starts playing its movie.

Idea to also set xs->data to NULL from matthew@.

"No objection" matthew@


# 1.180 25-Jul-2010 krw

Missing SCSI_DATA_IN flag in dvd_read_copyright() caused
confusion. Fixes at least my usb DVD reader and The Blue Tick.


# 1.179 25-Jul-2010 krw

Let DVD's play again. Logic reversal prevented copyright reading.

Symptoms noted by oga@. actual bug spotted by dlg@


# 1.178 22-Jul-2010 matthew

Fix a few more scsi_scsi_cmd() removal regressions, caught by
-Wuninitialized.

Silly typo in my first diff noticed by oga@ and krw@; ok krw@


# 1.177 22-Jul-2010 matthew

Appropriately set SCSI_DATA_IN or SCSI_DATA_OUT depending on type of
dvd_auth command. Fixes regression from scsi_scsi_cmd() removal.

ok dlg@


# 1.176 22-Jul-2010 krw

Eliminate scsi_scsi_cmd() now that ss(4) is gone and with it the
last bastardized sync and buf call through scsi_scsi_cmd(). Flatten
code to call scsi_xs_sync() directly for all commands.

Airplane typos shaken out by various.

ok dlg@ matthew@ deraadt@


# 1.175 01-Jul-2010 krw

Die struct scsi_device! Die! Instead, save a pointer to the routine
to interpret sense errors. This is initialized to the basic
interpretation routine, and specific scsi drivers (sd/st/cd) can
replace this with their own. While here kill EJUSTRETURN dance and
make more specialized interpretation routines directly call the
basic routine if desired.

Fixes by matthew@ to my first diff. Most original work by dlg@.

ok matthew@ marco@ dlg@


# 1.174 01-Jul-2010 matthew

Restore setting xs->bp; fixes ncr(4) on VAX.

ok miod@, krw@


# 1.173 30-Jun-2010 krw

Bring cd(4) into line with sd(4) and st(4) by implementing CDF_DYING
to better handle detaching.

ok deraadt@


# 1.172 28-Jun-2010 jsing

Move disk_attach() to the end of the attach functions, at which point the
disk is now ready to handle I/O.

ok krw@ dlg@


# 1.171 15-Jun-2010 dlg

dont pass the dev_t from the scsi device drivers into the midlayer for
ioctl requests, and dont pass the proc pointers around for any ioctl
requests in scsi land at all. neither were used, so trim the fat.

ok krw@ marco@


# 1.170 11-Jun-2010 krw

Restore an unusual XS_SENSE semantic that inadvertantly got lost
in the great re-write. If the scsi device *_interpret_sense()
function returns 0 that means there was no error.

Fixes restore(8) problems seen on certain tape drives.

Found and fix tested by Percey Piper. Suggestions from Matthew
Dempsky. Thanks!

ok dlg@


# 1.169 03-Jun-2010 dlg

cut cd(4) over to use xshandlers. based on the sd(4) diff and includes the
WAITING fix.

tested by sthen@ thib@ sobrado@ krw@ on atapiscsi, atascsi, and real scsi
ok krw@ thib@


# 1.168 01-Jun-2010 thib

move cd, st & ss over to bufq's again.

Tested by myself and krw.
ok krw@


# 1.167 18-May-2010 dlg

dont let sys/ioctl.h imply that you get the ioctls in dkio.h. this
gets rid of #include <sys/dkio.h> in sys/ioctl.h and adds #include
<sys/dkio.h> to the places that actually want and use the disk
ioctls.

this became an issue when krw@'s X build failed when he was testing
a change to dkio.h.
tested by krw@
help from and ok miod@


# 1.166 23-Apr-2010 jsing

Recycle unused disklabel fields in order to create a disklabel unique
identifier, allowing the disk to be identified without relying on the
device name.

ok deraadt@ krw@ beck@ marco@ todd@


# 1.165 12-Apr-2010 dlg

i snuck fine grained locking into the midlayer as part of all the
other stuff ive been doing in here. everything that needs protection
inside the midlayer and the scsi device drivers (sd, cd, etc) uses
mutexes now.

this pushes splbio out of the midlayer. splbio is only taken before
biodone is called now.

ok beck@ marco@ krw@ deraadt@. theyre all terrified, but they all
say if we're going to do then now is the right stage of the dev
cycle.


Revision tags: OPENBSD_4_7_BASE
# 1.164 28-Feb-2010 krw

branches: 1.164.2;
If no TOC header is read, report EIO. Even if the command finished
ok.

Stops cdio(1) from printing bogus TOC info.

ok marco@ beck@


# 1.163 15-Jan-2010 krw

Abstract and merge the manual buf queue manipulating functions into
one place for easier debugging and maintenance. No intended functional
changes.

ok dlg@


# 1.162 15-Jan-2010 krw

Restore XS_BUSY delay behaviour for buf i/o. Same as for sync path.

ok dlg@


# 1.161 12-Jan-2010 dlg

bring sd.c r1.180 over to the other drivers now using the antisemaphore,
ie, dont clear the WAITING flag when restarting the xxstart loops.


# 1.160 11-Jan-2010 krw

Bring mutex protections to ststart, cdstart and ssstart, as already
done in sd. Make names consistant across all three.

ok dlg@ tested (cd) & ok beck@


# 1.159 11-Jan-2010 krw

Be as careful with sd/cd buf queue manipulations as was found necessary for
st's queue manipulations. i.e. ensure b_actb is correctly updated as the
queue becomes empty or has an i/o requeued on it.

Tested on claudio@'s backup crashing box.

ok dlg@ beck@


# 1.158 09-Jan-2010 dlg

dont try to prevent multiple concurrent runs of a devices start routine
by setting flags around the loop. there is a race which can prevent
necessary work being completed by any of the currently running instances
of xxstart.

the caveat with the removal of this code is because multiple xxstarts can
be running at the same time they can cause io reordering, but that is less
of a problem than no io.

found by and fix tested by claudio@
debugged with krw@ claudio@ beck@ deraadt@


# 1.157 16-Dec-2009 dlg

nothing needs to see cd_softc except the driver, so move it into cd.c

ok marco@ guenther@


# 1.156 13-Dec-2009 dlg

prefix all softc members with sc_, not just most of them.


# 1.155 13-Dec-2009 dlg

use sc consistently as the name of the pointer to the softc variable, not
cd.


# 1.154 12-Dec-2009 dlg

move cd(4) from using scsi_scsi_cmd over to scsi_xs_exec for doing io.
this brings it in line with the new midlayer changes.

mostly borrowed from sd(4) changes.

tested by krw@ and me
ok krw@


# 1.153 06-Dec-2009 dlg

nitems(array) is prettier than sizeof(array)/sizeof(array[0])


# 1.152 06-Dec-2009 dlg

whitespace tweaks


# 1.151 06-Dec-2009 dlg

ansify dvd functions a bit.


# 1.150 13-Oct-2009 pirofti

Get rid of devact enum, substitute it with an int and coresponding defines.

This is needed for the addition of further suspend/resume actions.

Okay deraadt@, marco@.


# 1.149 13-Aug-2009 deraadt

Replace the error strings that were being passed around with much simpler
errnos. Note that the error strings are being ignored, since we long ago
decided to not spam the console, and there is no other nice way to use the
errors (without changing the ioctls to pass it back)
The errno is now useful, since we can pass b_error from failing IO up, and
the drive can decide how to use that
ok miod


Revision tags: OPENBSD_4_6_BASE
# 1.148 17-Jun-2009 thib

Revert bufq's. this is inline with the major midlayer reverts that
have been going on. this appears to bring us back to stable state.

lots of testing by oga and ariane and my self.


# 1.147 03-Jun-2009 thib

add a flexible buffer queue (bufq) api, based on the never used
one by tedu@. It doesn't do anything smart yet, it just uses
plain old disksort. we also keep the old method of queueing bufs
since some miods have crazy MD drivers that need some love.

ok beck@, art@
tested by many on many archs.


Revision tags: OPENBSD_4_5_BASE
# 1.146 16-Feb-2009 miod

Extend the scsi_adapter minphys() callback to take a struct scsi_link *
as additional argument. This will allow intermediate layers between
scsi devices such as sd and scsi host adapters to take appropriate
action if necessary.


# 1.145 10-Jan-2009 robert

Add support for the volume buttons and for the eject button found
on apple laptops.
The eject button will only eject the disc when it's not used by
anything.

ok miod@


Revision tags: OPENBSD_4_4_BASE
# 1.144 01-Aug-2008 dlg

silence failures to run scsi_prevent. dmesg spam sucks.

ok krw@ marco@ miod@ deraadt@


# 1.143 26-Jul-2008 krw

deivce -> device typo fix in comment.


# 1.142 22-Jun-2008 krw

Replace MUSTEK_RETRIES, SCANJET_RETRIES and ST_RETRIES with SCSI_RETRIES,
all defined to 4. Replace some magic number 4's with SCSI_RETRIES. Fix a
few lines that were now too long.


# 1.141 21-Jun-2008 krw

fgsch@ points out my last commit changed the retry limit for CD capacity
commands. Bump limit back to the standard 4, and at the same time eliminate
SDRETRIES and CDRETRIES (both defined to 4) in favour of a new define,
SCSI_RETRIES, also defined to 4.


# 1.140 21-Jun-2008 krw

Eliminate cd_size() and use scsi_size() + tweaked cd_get_params()
instead. We do not make use of the PMI and RELADDR bits in the
READ CAPACITY command, and thus there is no difference between
cd and sd capacity handling. Brings cd and sd more into line,
shrinks code and makes things easier to understand.

Make types for blocksize and disksize consistant and MI.

Make cdopen() as silent as sdopen().

ok marco@


# 1.139 17-Jun-2008 krw

Nuke unnecessary re-definition of READ_CAPACITY, scsi_read_capacity, and
scsi_read_cap_data as READ_CD_CAPACITY, scsi_read_cd_capacity and
scsi_read_cd_cap_data respectively. No functional change as all were
identical to their counterparts.


# 1.138 15-Jun-2008 krw

Don't bypass partition bounds check for RAW_PART. We now guarantee that
RAW_PART will always be 0 -> disksize, so the bounds check will always
pass for i/o's to valid addresses. Now the i/o will be properly truncated
if it goes past the end of the device. This prevents various adverse
impacts of issuing i/o's for data past the end of the device.

Repeatedly requested by todd@.

ok weingart@ deraadt@


# 1.137 10-Jun-2008 art

Accidental commit. Clean up.


# 1.136 10-Jun-2008 beck

Buffer cache revamp

1) remove multiple size queues, introduced as a stopgap.
2) decouple pages containing data from their mappings
3) only keep buffers mapped when they actually have to be mapped
(right now, this is when buffers are B_BUSY)
4) New functions to make a buffer busy, and release the busy flag
(buf_acquire and buf_release)
5) Move high/low water marks and statistics counters into a structure
6) Add a sysctl to retrieve buffer cache statistics

Tested in several variants and beat upon by bob and art for a year. run
accidentally on henning's nfs server for a few months...

ok deraadt@, krw@, art@ - who promises to be around to deal with any fallout


# 1.135 27-May-2008 fgsch

nuke unused lba2msf and msf2lba functions. krw@ ok.


Revision tags: OPENBSD_4_3_BASE
# 1.134 16-Sep-2007 krw

MALLOC/FREE -> malloc/free, M_ZERO, extraneous casts,
extraneous #include <malloc.h>


# 1.133 07-Sep-2007 krw

The obvious bzero/memset -> M_ZERO changes.


Revision tags: OPENBSD_4_2_BASE
# 1.132 20-Jun-2007 deraadt

b_cylinder does not need to be set on the callpath down into drivers.
cpu_disklabel can go away, since nothing anymore needs to use it; ok miod


# 1.131 18-Jun-2007 deraadt

avoid modification race in DIOCRLDINFO; ok krw miod


# 1.130 08-Jun-2007 deraadt

all drivers should spoof version 1 labels


# 1.129 07-Jun-2007 deraadt

in OpenBSD as all old BSD unix, RAW_PART always starts at 0, so no
need for special case code; ok krw


# 1.128 06-Jun-2007 deraadt

now that all partition size/offsets are potentially 64-bit, change the
type of all variables to daddr64_t. this includes the APIs for XXsize()
and XXdump(), all range checks inside bio drivers, internal variables
for disklabel handling, and even uvm's swap offsets. re-read numerous
times by otto, miod, krw, thib to look for errors


# 1.127 05-Jun-2007 deraadt

use six new macros to access & store the 48-bit disklabel fields related
to size. tested on almost all machines, double checked by miod and krw
next comes the type handling surrounding these values


# 1.126 01-Jun-2007 krw

Don't initialize d_partitions[RAW_DISK] just before calling
readdisklabel(), since all readdisklabel()'s do that already.

ok deraadt@


# 1.125 25-May-2007 krw

ANSI-fication, minor KNF. No code change. My plane had power outlets
this time!


# 1.124 28-Apr-2007 krw

Fix comments above DISKMINOR uses. DISKMINOR provides minor not major
number (wd.c), and the uses are to find the minimum minor to be
detached.


# 1.123 26-Apr-2007 krw

Use the standard DISKPART/DISKUNIT/etc. defines rather than identical
but differently named SD/CD ones. No change to .o files.

ok deraadt@ dlg@


# 1.122 12-Apr-2007 krw

Add cd_kill_buffers() as a separate function, like sd_kill_buffers()
and for the same reason of preparing for safer handling of users
yanking usb devices out. No functional change.

Copied from bluhm@'s change to sd.c.


# 1.121 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


# 1.120 10-Apr-2007 krw

Always use idiom 'struct cd_softc *cd = (struct cd_softc *)self'. Spotted
by bluhm@ for sd. No change to cd.o.


Revision tags: OPENBSD_4_1_BASE
# 1.119 03-Feb-2007 bluhm

Make comment match code. ok pedro


# 1.118 23-Dec-2006 krw

Add the ability to issue GPCMD_REPORT_KEY and GPCMD_SEND_KEY scsi
commands via the DVD_LU_SEND_RPC_STATE and DVD_HOST_SEND_RPC_STATE
ioctls respectively.

Thus allowing any region protected DVDs mistakenly delivered by Santa
to the wrong region to be viewed on recalcitrant DVD drives (with the
aid of an appropriate utility like regionset).

No change to any current functions.

Found in my hackers@ folder from August.

From netbsd -> Kurt Miller -> jmc@.


# 1.117 12-Dec-2006 krw

Give the SCSI layer the ability to requeue i/o's rejected by a driver
using the new NO_CCB result. Currently a no-op since no driver produces
that result.

ok dlg@ marco@ deraadt@


# 1.116 28-Nov-2006 dlg

rename scsibus_attach_args to scsi_attach_args. this can help avoid
confusing when trying to attach scsibus to a hba, since it is really meant
for attaching scsi devices to scsibus.

ok deraadt@ marco@


# 1.115 27-Nov-2006 beck

more magic removal
ok miod@, deraadt@


# 1.114 27-Nov-2006 beck

get rid of the rest of the asc/ascq magic codes in scsi
ok marco@, deraadt@


# 1.113 08-Oct-2006 beck

Something more closely resembling english in this comment.


# 1.112 07-Oct-2006 beck

make cd-roms retry forever while the device indicates that it is
"becoming ready" - this is done in the exact same way that it
was done for tape in st.c. This commit adds a cd specific interpret_sense
routine to cd.c that will catch the becoming ready case and handle it.
This also removes the need to use crazy timeouts to catch this case.

ok krw@


# 1.111 26-Sep-2006 krw

Zap D_REMOVABLE flag from disklabel. If you didn't already know that
floppies and cd's were removable, displaying that fact in disklabel
output was unlikely to help. And the display in disklabel was the only
use of D_REMOVABLE in the tree.

ok marco@


Revision tags: OPENBSD_4_0_BASE
# 1.110 29-Jul-2006 krw

The version field of scsi_inquiry_data is not a simple numeric value
that specifies the version of SCSI being supported. Even the ANSI part
that we use is complex. 4 means 2, 5 means 3 and 6 means 4. Translate
and use the value correctly. Fixes SCSI5 and SCSI6 in dmesg. And
properly protects SCSI2 devices from getting SCSI3 commands.

"seems like an elegant solution to me" millert@ ok dlg@ marco@


# 1.109 23-Jul-2006 dlg

remove some scsi ioctls, most importantly the ones that can reprobe the
bus. supporting these complicates the midlayer unnecessarily.

ok krw@


# 1.108 19-Jul-2006 krw

Add cd_powerhook(). Use it to lock CD drives having open partitions
when PWR_RESUME occurs. The drives may have forgotten they were
locked.

Noted and original diff by Alexey Vatchenko.

"I agree with the intent." miod@ "Looks acceptable." deraadt@


# 1.107 11-May-2006 krw

Zap trailing whitespace.


# 1.106 15-Mar-2006 miod

Nuke dk_establish(), no longer used.


# 1.105 04-Mar-2006 miod

Typos grab bag of the month, eyeballed by jmc@


Revision tags: OPENBSD_3_9_BASE
# 1.104 21-Jan-2006 miod

Invoke disk_detach() and related cleanup work in detach(), rather than
zeroref() - just to be on the safe side, should we mess up our ref count.


# 1.103 17-Jan-2006 miod

Need to device_unreg() the implicit device_ref() done by cdlookup() in
cdminphys().


# 1.102 12-Jan-2006 krw

Don't populate the fabricated disklabel's partition info from track
information in the TOC. The partition info is just overwritten or
rendered incomplete by readdisklabel().

Just examine the TOC to determine if the cd is audio only, i.e. it has
a valid TOC but no data tracks. In this case don't call
readdisklabel(). Much simpler code. No functional change for single
data track CD's like the install media.

ok pedro@.


# 1.101 25-Dec-2005 krw

Cleanup/fix cdgetdisklabel() by

1) Using cd_load_toc() instead of replicating code.

2) Using struct cd_toc and betoh32() like other parts of cd.c.

3) Restoring pre-Sept. 26 behaviour of trying to read usable disklabel
info if there is no TOC. i.e. avoid readdisklabel() only when it is an
audio-only CD. Stop abusing spoofonly.

Tested by mjc@


# 1.100 23-Dec-2005 krw

Make cd_load_toc() take an address mode parameter, clean up a bit.
Add a check for ending_track < starting_track before calculating size
of TOC to read.

Tested by mjc@


# 1.99 22-Dec-2005 krw

Move a struct cd_toc (800 bytes) from the stack to malloc'ed memory.

bzero() all malloc'ed cd_toc structs because cd_read_toc() will only
zero as much as it is trying to read.

malloc M_TEMP memory instead of M_DEVBUF memory for the cd_toc
structs.

ok deraadt@


# 1.98 22-Dec-2005 krw

Initialize data_track before a 'goto done;' could lead to it being
used.


# 1.97 15-Oct-2005 krw

Eliminate unnecessary bzero() by only writing valid information.
Eliminate separate check/break from for() loop.

No functional change.

ok deraadt@


# 1.96 14-Oct-2005 krw

Eliminate uneeded variable 'i' and use under utilized 'data_track'
instead.

ok deraadt@


# 1.95 11-Oct-2005 hshoexer

use [bl]etohXX instead of ntoh[sl], makes the code more consistent and
better readable. actually no binary change.

ok krw@


# 1.94 11-Oct-2005 krw

Change some byte shifting to _4btol() and swap32() calls.

ok hshoexer@


# 1.93 10-Oct-2005 krw

Some KNF. malloc/free instead of MALLOC/FREE since it's a variable
sized allocation. Remove some dead code.


# 1.92 29-Sep-2005 krw

Clear SDEV_MEDIA_LOADED for cd media on the last close of a device, as
sd does. Prevents spurious label information from being seen on
devices that return NOT READY/UNABLE TO RECOVER TABLE-OF-CONTENTS
error (or other sense errors) for blank media. Burning cd's still
works.

ok marco@ dlg@ fgsch@ deraadt@


# 1.91 26-Sep-2005 krw

Use SCSI_IGNORE_ILLEGAL_REQUEST when reading a cd's table of contents.
ILLEGAL REQUEST is correctly reported for blank media, as an
informative FreeBSD comment pointed out. Ensure the returned table of
contents is always initialized to zero. Call readdisklabel with
spoofonly = 1 when no data tracks are found.

Don't try to read the DOS label from the device if spoofonly is 1.
Only done for amd64 here. More archs to follow.

Eliminates scsi error messages when attempting to open a cd containing
blank media, as pointed out by Michael Coulter.

ok deraadt@


# 1.90 21-Sep-2005 krw

Improve readability by using a variable instead of repeated
calculations. Same as sd.c r1.94.


# 1.89 21-Sep-2005 krw

Missing parenthesis. Same problem was addressed in sd.c r1.90. Could
fix devices not supporting TEST UNIT READY.


# 1.88 11-Sep-2005 krw

Simplify code by changing struct scsi_mode_sense_buf{ union {}
headers; } to just union scsi_mode_sense_buf {}. No functional change.

ok marco@


Revision tags: OPENBSD_3_8_BASE
# 1.87 23-Aug-2005 krw

Move uses of struct scsi_mode_sense_buf (255 bytes each) from the
stack into malloc'd memory.

ok deraadt@


# 1.86 03-Aug-2005 krw

Move a couple of 2048+4 byte structures from the stack to the heap.
Create structures to eliminate 2048+4 magic number everywhere. Mostly
adapted from NetBSD.

tested by sturm@, beck@. ok beck@


# 1.85 11-Jun-2005 krw

Elminate a few unnecessary casts by using union field names, bit of KNF.


# 1.84 05-Jun-2005 krw

Fix scsi_mode_select() and scsi_mode_select_big() to send just the
required number of bytes, rather than a full scsi_mode_sense_buf. Some
devices (e.g. my HP SureStore DAT/24) decline to accept such oversized
transfers. Instead, force callers to fill in the data_length field in
the header and use that information to set the size of the transfer.


# 1.83 03-Jun-2005 krw

Move definitions of struct cd_softc{} and CDRETRIES from cdvar.h into
cd.h. Remove include of cdvar.h from cd.c. cdvar.h becomes expendable.

No functional change.


# 1.82 03-Jun-2005 krw

Tweak scsi_do_mode_sense(). NetBSD was right and I was wrong. Sigh.
Add 'big' parameter to report which mode sense header type is being
returned. Eliminate icky pointer arithmetic, since it won't work if
only block descriptors are returned by the device.

No functional change.


# 1.81 27-May-2005 krw

Don't bother issuing a MODE SELECT in cd_set_pa_immed() if we aren't
going to change anything. From NetBSD.

Fixes playing music cd in ATAPI drive in USB enclosure pascoe@ is
using.

ok pascoe@.


# 1.80 27-May-2005 krw

Convert cd code to new mode sense framework. Merge cd_scsi and
cd_atapi into cd since code is now almost identical, and only affects
volume adjusting ioctl's. Minor side effect of allowing
cd_load_unload() attempts to scsi cd's as NetBSD does.


# 1.79 01-May-2005 krw

Allow RAW_PART+S_IFCHR device opens to succeed even if media not
present. A successful open is required for ioctl's to work. Mostly
from NetBSD, partly correcting previous code cleanup error.

From deraadt@, treat MTIOCTOP+MTRETEN as CDIOCCLOSE for cd devices
(i.e. close the cd drawer).

ok deraadt@.


# 1.78 06-Apr-2005 krw

De-register scsi.


# 1.77 05-Apr-2005 krw

Clean up some logic. Use better error handling for sd devices. Be
quiet if raw partition access tried. Be more careful with
SDEV_MEDIA_LOADED. Inspired by some NetBSD changes.

ok marco@


# 1.76 30-Mar-2005 krw

Comment typo, minor knf. No code change.


Revision tags: OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.75 09-May-2004 krw

Add missing <cr>'s to various SC_DEBUG() calls, along with a few other
SC_DEBUG() spacing tweaks.

ok deraadt@


Revision tags: OPENBSD_3_5_BASE
# 1.74 15-Feb-2004 tedu

new arg to disk_unbusy, to record separate read/write statistics.
looked at by various, testing henning@ mcbride@ dan weeks
mostly from netbsd via Pedro Martelletto <pbastos@rdc.puc-rio.br>


# 1.73 07-Nov-2003 jmc

adress -> address, and a few more; all from Jonathon Gray;

(mvme68k/mvme88k) vs.c and (vax) if_le.c ok miod@
isakmpd ones ok ho@


Revision tags: OPENBSD_3_4_BASE
# 1.72 30-Jul-2003 tedu

reverse booleans so it's clear what we're looking for. ok krw@


# 1.71 18-May-2003 mickey

constify the quirck tables and fix the scsi_inqmatch() proto accordingly; krw@ ok


# 1.70 17-May-2003 krw

READ_CD_CAPCITY -> READ_CD_CAPACITY in comment.


Revision tags: UBC_SYNC_A
# 1.69 16-May-2003 krw

Provide most if not all the support required for the usb changes Nate
is trying to bring in.

1) Change name of SDEV_NOCDB6 to SDEV_ONLYBIG to align it with the
same quirk in NetBSD, and make it more clear what it is trying to do.
i.e. force the use of READ_BIG/WRITE_BIG commands, not suppress all
use of 6 byte CDB's.

2) Check SDEV_ONLYBIG in cd.c as well as sd.c. i.e. both places where
a choice is made to use the 6 or 10 byte versions of READ/WRITE.

3) Actually make use of the ADEV_NOTUR (No TEST UNIT READY) quirk to
suppress the emission of TEST UNIT READY commands.

4) Add some explanatory comments from NetBSD to scsiconf.h so that the
use of the quirks is made clear.

ok miod@ tdeval@ nate@


# 1.68 06-Apr-2003 krw

The disklabel fields d_packname and d_typename are not null terminated strings
and should not be created or used as such.

This fixes some instances of both behaviours, and sets the stage for some
strcpy -> strncpy fixup.

ok tdeval@ millert@ deraadt@


Revision tags: OPENBSD_3_3_BASE
# 1.67 17-Jan-2003 jason

The end of the track is one frame before the first frame of the next track
(and right before the leadout track in the case of the last track). Some
CDROM's are evidentally picky about being asked to play the first frame
of the leadout.


# 1.66 05-Jan-2003 deraadt

spelling


# 1.65 30-Dec-2002 grange

Add new parameter to scsi_test_unit_ready(): retries number.
Use increased retries number and don't ignore SCSI_IGNORE_NOT_READY
when call scsi_test_unit_ready() for cd-rom, this makes system wait
if drive is loading media.
Tested by millert@ and fgsch@; some input and ok from krw@.
Problem reported by The lord of the CD-writers
Igor Grabin <violent@death.kiev.ua>.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.64 09-Jun-2002 art

splassert a splbio assumption.


# 1.63 08-Jun-2002 art

KISS. the spl variable doesn't have to be called s, but it make the code less confusing.


# 1.62 08-Jun-2002 art

splbio around biodone


# 1.61 23-May-2002 csapuntz

Signed/unsigned int bug caused lp->d_npartitions to be set to zero.

Should fix disklabel warnings on disks with no data track.

The old code was unnecessary complex too.


Revision tags: OPENBSD_3_1_BASE
# 1.60 14-Mar-2002 millert

Final __P removal plus some cosmetic fixups


# 1.59 14-Mar-2002 millert

First round of __P removal in sys


# 1.58 01-Feb-2002 hin

cdstrategy(): check that media is loaded before doing anything with the
cd.

ok art@


Revision tags: UBC_BASE
# 1.57 25-Oct-2001 drahn

branches: 1.57.2;
Allow an empty cd to be opened (raw device/whole disk) primarily to
allow empty CD caddies to be ejected.
Original diff from Alexander Guy. "pretty much straight from NetBSD"
Addition to allow eject (mt) to eject an empty tray.
ok csapuntz@


Revision tags: OPENBSD_3_0_BASE
# 1.56 22-Jun-2001 deraadt

KNF


Revision tags: OPENBSD_2_8_BASE OPENBSD_2_9_BASE
# 1.55 18-Jul-2000 csapuntz

Update cd_size to handle failure of READ_CD_CAPACITY by returning
some default values


Revision tags: OPENBSD_2_7_BASE
# 1.54 18-Apr-2000 csapuntz

cd detach


# 1.53 18-Apr-2000 csapuntz

sd and scsibus detach

cdlock/cdunlock now through disk_lock/disk_unlock


# 1.52 09-Apr-2000 csapuntz

Don't trust the TOC coming from the drive so much.

Be better about handling failures of SCSI CD READ TOC command.


Revision tags: SMP_BASE kame_19991208
# 1.51 12-Nov-1999 angelos

branches: 1.51.2;
Use cdio.h instead of dvdio.h


# 1.50 11-Nov-1999 csapuntz

SCSI commands do not send data in both directions in the data phase.

Fixes DMA bug Angelos was seeing with DVD stuff.

Happy ripping!


# 1.49 09-Nov-1999 angelos

Fix lengths of scsi cmds


# 1.48 03-Nov-1999 angelos

bzero the right amount of memory; I think NetBSD has this problem too.


# 1.47 03-Nov-1999 angelos

Some DVD support, from NetBSD.


Revision tags: OPENBSD_2_6_BASE
# 1.46 16-Oct-1999 deraadt

another fix form csapuntz


# 1.45 14-Oct-1999 deraadt

read disklabels only from CDs that have a data track, spoofed labels from
the audio CDs could do with a bit more work, but this makes audio cd
playing not generate disklabel read-failure messages on first open; csapuntz


# 1.44 25-Sep-1999 deraadt

sorry, but the last two changes completely broke disklabel spoofing, which we need for the release


# 1.43 21-Sep-1999 csapuntz

Bug in the disklabel calculations fixed. Offsets were calculated in
terms of 512-unit sectors, yet the disklabel said that the sector size
was 2048.

Enabled code that tries to read disklabel from first data track. I guess
this will be useful for those combination music/BSD install cds.


# 1.42 21-Sep-1999 csapuntz

For some reason unbeknownst to me, the old acd driver had a more advanced
disklabel logic than the cd driver. This patch integrates that logic into
the SCSI cd driver.

Bug fixed - we no longer try to read disklabels off of audio CDs. No more
SCSI errors when you hit play the first time on an audio CD.


# 1.41 24-Aug-1999 csapuntz

Added type field to scsi_addr to reflect bus/device type (ATAPI or SCSI).
Updated ioctls to match

Minor patches in anticipation of wd->sd translation layer


# 1.40 10-Aug-1999 deraadt

support DIOCRLDINFO


# 1.39 21-Jul-1999 csapuntz

swap16_multi by niklas@cvs.openbsd.org

Fix cd.c so it compiles on big-endian platforms


# 1.38 20-Jul-1999 csapuntz

Be more generous with timeout on cd_play_msf


# 1.37 20-Jul-1999 csapuntz

Make acd redundant.

Mostly based on NetBSD-current


Revision tags: OPENBSD_2_5_BASE
# 1.36 01-Apr-1999 millert

If READ_CD_CAPACITY fails, just use the 2048/400000 defaults since some CDR drives don't support READ_CD_CAPACITY on blank media ; downsj with modifications by me


Revision tags: OPENBSD_2_4_BASE
# 1.35 05-Oct-1998 millert

make DIOCGPDINFO equivalent to DIOCGDINFO for cd's


# 1.34 04-Oct-1998 millert

Add DIOCGPDINFO support


# 1.33 03-Oct-1998 millert

Add a "spoofonly" argument to readdisklabel() which will be used to
implement an ioctl to get a spoofed label even for disks that have
a label on them.


# 1.32 13-Jul-1998 csapuntz

CDs can have up to 99 tracks, not 65 tracks. Use kernel heap instead of stack
for temporary storage of CD table of contents


# 1.31 12-Jul-1998 deraadt

fill in d_bbsize and d_sbsize


Revision tags: OPENBSD_2_3_BASE
# 1.30 27-Mar-1998 millert

Fix strncpy usage and call a cdrom a cdrom in the fake label


# 1.29 05-Dec-1997 provos

argh. this darn little bugger made CDIOCREADSUBCHANNEL unuseable, this
should also fix some cdio problems with SCSI cdroms.


Revision tags: OPENBSD_2_2_BASE
# 1.28 18-Oct-1997 deraadt

avoid "no disklabel" error messages


# 1.27 15-Oct-1997 provos

make it compile


# 1.26 11-Sep-1997 deraadt

cd_play/acd_play() were replaced a while back


# 1.25 31-Aug-1997 downsj

* Make scsi_do_ioctl() sane again.
* Use scsi_do_ioctl() in cd.c and uk.c again.


# 1.24 08-Aug-1997 niklas

Change the bounds_check_with_label API to also take a cpu_disklabel
reference for making transferral of meta-information possible from
readdisklabel to bounds_check_with_label. The first (and maybe only)
thing that will use this is the multi-disklabel-format code on the
alpha where the labelsector is passed via cpu_disklabel so the label
write-protection can work correctly no matter what label was found.

Also use a new macro DKBAD to get at the dkbad field of the cpu_disklabel
implementations that contain it. This too is for multi-disklabel
architectures where the "bad" field can be inside a union. Use this
macro as a means for a driver to check if an architecture supports
dkbad constructs.

Remove proto of bounds_check_with_label from all MD disklabel.h as it
is in sys/disklabel.h.

I have not been able to test the changes everywhere, if I break anything
I apologize, and promise to fix it as soon as I become aware of it.


Revision tags: OPENBSD_2_1_BASE
# 1.23 14-Apr-1997 downsj

Merge in various pieces of current NetBSD scsi code, including but not limited
to:

* New changer driver.
* Better optical support.
* Different `done' semantics.
* New quirks for SCSI QIC tape driver, SCSI floppy drives.
* Better support for SCSI-I devices.

Everybody needs to test this.


# 1.22 29-Mar-1997 briggs

Increase timeout by a factor of ten in cd_size().
NetBSD PR#3409 from Koji Imada <koji@imada.math.human.nagoya-u.ac.jp>


# 1.21 26-Mar-1997 deraadt

deal with CD drives that indicate 2352 bytes per block...


# 1.20 04-Jan-1997 deraadt

readdisklabel() with correct dev_t


# 1.19 24-Dec-1996 deraadt

deal with the 2340 lie in the right place, i think


# 1.18 11-Dec-1996 deraadt

b_resid cleanups, pointed out by minoura@kw.netlaputa.or.jp in netbsd pr#3007


# 1.17 05-Dec-1996 deraadt

call readdisklabel() in the same fashion as sd.c does


# 1.16 31-Oct-1996 niklas

$OpenBSD RCSIDs + comment fix in sd.c


Revision tags: OPENBSD_2_0_BASE
# 1.15 05-Oct-1996 downsj

[a]cd_play -> [a]cd_play_big. Say hello to cdio(1).


# 1.14 16-Aug-1996 deraadt

only safe ioctl


# 1.13 07-Aug-1996 deraadt

disk_unbusy if op failed to enqueue


# 1.12 10-Jun-1996 downsj

Several changes:
* Implemented NetBSD PR#2529, adding ZIP 100.
* Added MTIOCTOP support to acd, cd, and sd.
* Implemented eject on close for acd, cd, and sd.

`mt -f /dev/rcd0d offline' now ejects a mounted {acd|cd|sd} when it is
unmounted.


# 1.11 01-Jun-1996 deraadt

all ports have dk_establish


# 1.10 16-May-1996 mickey

from NetBSD PR#812:
allow CDDA disks to be read.
not tested, anyone w/ SCSI CD is ought to.
here is the test program (not tested too ;):


#define CDDA


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/scsiio.h>
#include <sys/cdio.h>
#include <scsi/scsi_all.h>
#include <scsi/scsi_cd.h>
#include <scsi/scsi_disk.h>


extern int errno;


void
usage()
{
fprintf(stderr, "usage: cdda -d device -b blkcnt -o offset >output\n");
exit(1);
}


char databuf[CD_DA_BLKSIZ];


main(int argc, char *argv[])
{
int ch;
int fd;
off_t offset = 0;
int cnt = 0;
char *dev = 0;
struct scsi_rw_big read_cmd;
struct scsi_mode_sense sense_cmd;
struct cd_mode_data bdesc;
scsireq_t req;


while ((ch = getopt(argc, argv, "d:b:o:")) != -1) {
switch (ch) {
case 'd':
dev = optarg;
break;
case 'b':
cnt = atoi(optarg);
if (cnt <= 0)
usage();
break;
case 'o':
offset = atoi(optarg);
break;
case '?':
default:
usage();
}
}
if (dev == NULL || cnt == 0)
usage();
fd = open(dev, O_RDONLY);
if (fd == -1)
err(1,"can't open device %s", dev);
#ifdef DEBUG
ch = SC_DB_FLOW;
ioctl(fd, SCIOCDEBUG, &ch);
#endif
ch = 1;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't set CDDA mode");


read_cmd.opcode = READ_BIG; /* READ10 */
read_cmd.byte2 = 0; /* no relative */
read_cmd.reserved = 0;
read_cmd.length2 = 0;
read_cmd.length1 = 1; /* read one block at a time.
hope it caches! */
read_cmd.control = 0; /* LBA mode, leave flag & link zero */


for (; cnt > 0; cnt--, offset++) {
read_cmd.addr_3 = (offset >> 24) & 0xff;
read_cmd.addr_2 = (offset >> 16) & 0xff;
read_cmd.addr_1 = (offset >> 8) & 0xff;
read_cmd.addr_0 = offset & 0xff;
memset(&req, 0, sizeof(req));
req.flags = SCCMD_READ;
/* timeout is in milliseconds--not that it's obvious from the
include files! */
req.timeout = 10000; /* 10 sec */


bcopy(&read_cmd, req.cmd, sizeof(read_cmd));
req.cmdlen = sizeof(read_cmd);
req.databuf = databuf;
req.datalen = sizeof(databuf);
req.senselen = sizeof(req.sense); /* XXX */
if (ioctl(fd, SCIOCCOMMAND, &req) == -1) {
fprintf(stderr, "bad ioctl: %d\n", errno);
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
exit(1);
}
if (req.retsts != 0 || req.error != 0) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"return status %d, error %d\n", req.retsts, req.error);
}
if (req.datalen_used != sizeof(databuf)) {
ch = 0;
ioctl(fd, CDIOCSETCDDA, &ch);
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
errx(1,"didn't get full buffer back (%x)", req.datalen_used);
}
write(1, databuf, sizeof(databuf));
}
ch = 0;
if (ioctl(fd, CDIOCSETCDDA, &ch) == -1)
warn("can't reset CDDA mode");
#ifdef DEBUG
ioctl(fd, SCIOCDEBUG, &ch);
#endif
close(fd);
exit(0);
}


# 1.9 10-May-1996 deraadt

SC_DEBUG cleanup


# 1.8 02-May-1996 deraadt

no sys/cpu.h, fix bugs in ch


# 1.7 21-Apr-1996 deraadt

partial sync with netbsd 960418, more to come


# 1.6 20-Feb-1996 briggs

Sync w/ NetBSD:
- Accept DIOCEJECT as a synonym for CDIOCEJECT. Implement DIOCLOCK
separately from CDIOCALLOW and CDIOCPREVENT, even though they perform
basically the same function (with a different interface XXX).
- scsi prototypes


# 1.5 14-Jan-1996 briggs

From NetBSD: (required for last change to scsi_base.c in case we get
"command aborted" status)
Handle cases like the following:
- controller calls scsi_done() with error XS_TIMEOUT
- scsi_done() calls sddone()
- sddone() calls disk_unbusy()
- scsi_done() calls controller to retry command (missing the
call to disk_busy())
- controller calls scsi_done()
- scsi_done() calls sddone()
- sddone() calls disk_busy(), which panics because of the imbalance.
Bug noticed by Leo Weppleman, who also suggested this fix; pass an additional
boolean argument ("complete") to the device's "done" routine, with a
value of `0' passed from the previous call to "done", and add an additional
call to "done" when the xfer resources are freed.


# 1.4 12-Jan-1996 deraadt

from netbsd;
New generic disk framework. Highlights:
New metrics handling. Metrics are now kept in the new `struct disk'.
Busy time is now stored as a timeval, and transfer count in bytes.
Storage for disklabels is now dynamically allocated, so that the size
of the disk structure is not machine-dependent.
Several new functions for attaching and detaching disks, and handling
metrics calculation.
Old-style instrumentation is still supported in drivers that did it
before. However, old-style instrumentation is being deprecated, and
will go away once the userland utilities are updated for the new
framework.
For usage and architectural details, see the forthcoming disk(9)
manual page.


# 1.3 14-Dec-1995 deraadt

from netbsd:
If the read or write request can fit into a 6-byte cdb, then
use a 6-byte cdb, otherwise use the 10-byte as before.


# 1.2 21-Oct-1995 deraadt

mt -f /dev/rcd* offline support


# 1.1 18-Oct-1995 deraadt

branches: 1.1.1;
Initial revision