diff options
Diffstat (limited to 'lib/libcam')
-rw-r--r-- | lib/libcam/Makefile | 54 | ||||
-rw-r--r-- | lib/libcam/Makefile.depend | 16 | ||||
-rw-r--r-- | lib/libcam/cam.3 | 438 | ||||
-rw-r--r-- | lib/libcam/cam_cdbparse.3 | 551 | ||||
-rw-r--r-- | lib/libcam/camlib.c | 758 | ||||
-rw-r--r-- | lib/libcam/camlib.h | 180 | ||||
-rw-r--r-- | lib/libcam/scsi_cmdparse.c | 859 | ||||
-rw-r--r-- | lib/libcam/scsi_wrap.c | 178 | ||||
-rw-r--r-- | lib/libcam/scsi_wrap.h | 36 | ||||
-rw-r--r-- | lib/libcam/tests/Makefile | 6 | ||||
-rw-r--r-- | lib/libcam/tests/Makefile.depend | 19 | ||||
-rw-r--r-- | lib/libcam/tests/cam_test.c | 109 | ||||
-rw-r--r-- | lib/libcam/tests/libcam_test.c | 319 |
13 files changed, 3523 insertions, 0 deletions
diff --git a/lib/libcam/Makefile b/lib/libcam/Makefile new file mode 100644 index 000000000000..d4efbbdf4d9b --- /dev/null +++ b/lib/libcam/Makefile @@ -0,0 +1,54 @@ +PACKAGE= runtime + +LIB= cam +SHLIBDIR?= /lib +SRCS= camlib.c scsi_cmdparse.c scsi_all.c scsi_da.c scsi_sa.c cam.c \ + ata_all.c nvme_all.c nvme_util.c smp_all.c scsi_wrap.c +INCS= camlib.h scsi_wrap.h + +LIBADD= sbuf + +MAN= cam.3 cam_cdbparse.3 + +WARNS?= 2 + +MLINKS+= cam.3 cam_open_device.3 \ + cam.3 cam_open_spec_device.3 \ + cam.3 cam_open_btl.3 \ + cam.3 cam_open_pass.3 \ + cam.3 cam_close_device.3 \ + cam.3 cam_close_spec_device.3 \ + cam.3 cam_getccb.3 \ + cam.3 cam_send_ccb.3 \ + cam.3 cam_freeccb.3 \ + cam.3 cam_path_string.3 \ + cam.3 cam_device_dup.3 \ + cam.3 cam_device_copy.3 \ + cam.3 cam_get_device.3 \ + cam_cdbparse.3 csio_build.3 \ + cam_cdbparse.3 csio_build_visit.3 \ + cam_cdbparse.3 csio_decode.3 \ + cam_cdbparse.3 csio_decode_visit.3 \ + cam_cdbparse.3 buff_decode.3 \ + cam_cdbparse.3 buff_decode_visit.3 \ + cam_cdbparse.3 csio_encode.3 \ + cam_cdbparse.3 csio_encode_visit.3 \ + cam_cdbparse.3 buff_encode_visit.3 + +.PATH: ${SRCTOP}/sys/cam \ + ${SRCTOP}/sys/cam/ata \ + ${SRCTOP}/sys/cam/nvme \ + ${SRCTOP}/sys/cam/mmc \ + ${SRCTOP}/sys/cam/scsi \ + ${SRCTOP}/sys/dev/nvme + +CFLAGS+= -I${.CURDIR} -I${SRCTOP}/sys + +SHLIB_MAJOR= 7 + +.include <src.opts.mk> + +HAS_TESTS= +SUBDIR.${MK_TESTS}+= tests + +.include <bsd.lib.mk> diff --git a/lib/libcam/Makefile.depend b/lib/libcam/Makefile.depend new file mode 100644 index 000000000000..cde253fc72ce --- /dev/null +++ b/lib/libcam/Makefile.depend @@ -0,0 +1,16 @@ +# Autogenerated - do NOT edit! + +DIRDEPS = \ + include \ + include/xlocale \ + lib/${CSU_DIR} \ + lib/libc \ + lib/libcompiler_rt \ + lib/libsbuf \ + + +.include <dirdeps.mk> + +.if ${DEP_RELDIR} == ${_DEP_RELDIR} +# local dependencies - needed for -jN in clean tree +.endif diff --git a/lib/libcam/cam.3 b/lib/libcam/cam.3 new file mode 100644 index 000000000000..af10519616a8 --- /dev/null +++ b/lib/libcam/cam.3 @@ -0,0 +1,438 @@ +.\" +.\" Copyright (c) 1998 Kenneth D. Merry. +.\" All rights reserved. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 3. The name of the author may not be used to endorse or promote products +.\" derived from this software without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.Dd June 1, 2023 +.Dt CAM 3 +.Os +.Sh NAME +.Nm cam_open_device , +.Nm cam_open_spec_device , +.Nm cam_open_btl , +.Nm cam_open_pass , +.Nm cam_close_device , +.Nm cam_close_spec_device , +.Nm cam_getccb , +.Nm cam_send_ccb , +.Nm cam_freeccb , +.Nm cam_path_string , +.Nm cam_device_dup , +.Nm cam_device_copy , +.Nm cam_get_device +.Nd CAM user library +.Sh LIBRARY +.Lb libcam +.Sh SYNOPSIS +.In stdio.h +.In camlib.h +.Ft struct cam_device * +.Fo cam_open_device +.Fa "const char *path" +.Fa "int flags" +.Fc +.Ft struct cam_device * +.Fo cam_open_spec_device +.Fa "const char *dev_name" +.Fa "int unit" +.Fa "int flags" +.Fa "struct cam_device *device" +.Fc +.Ft struct cam_device * +.Fo cam_open_btl +.Fa "path_id_t path_id" +.Fa "target_id_t target_id" +.Fa "lun_id_t target_lun" +.Fa "int flags" +.Fa "struct cam_device *device" +.Fc +.Ft struct cam_device * +.Fo cam_open_pass +.Fa "const char *path" +.Fa "int flags" +.Fa "struct cam_device *device" +.Fc +.Ft void +.Fo cam_close_device +.Fa "struct cam_device *dev" +.Fc +.Ft void +.Fo cam_close_spec_device +.Fa "struct cam_device *dev" +.Fc +.Ft union ccb * +.Fo cam_getccb +.Fa "struct cam_device *dev" +.Fc +.Ft int +.Fo cam_send_ccb +.Fa "struct cam_device *device" +.Fa "union ccb *ccb" +.Fc +.Ft void +.Fo cam_freeccb +.Fa "union ccb *ccb" +.Fc +.Ft char * +.Fo cam_path_string +.Fa "struct cam_device *dev" +.Fa "char *str" +.Fa "int len" +.Fc +.Ft struct cam_device * +.Fo cam_device_dup +.Fa "struct cam_device *device" +.Fc +.Ft void +.Fo cam_device_copy +.Fa "struct cam_device *src" +.Fa "struct cam_device *dst" +.Fc +.Ft int +.Fo cam_get_device +.Fa "const char *path" +.Fa "char *dev_name" +.Fa "int devnamelen" +.Fa "int *unit" +.Fc +.Sh DESCRIPTION +The CAM library consists of a number of functions designed to aid in +programming with the CAM subsystem described in +.Xr cam 4 . +This man page covers the basic set of +library functions. +More functions are documented in the man pages listed +below. +.Pp +Many of the CAM library functions use the +.Va cam_device +structure: +.Bd -literal +struct cam_device { + char device_path[MAXPATHLEN+1];/* + * Pathname of the + * device given by the + * user. This may be + * null if the user + * states the device + * name and unit number + * separately. + */ + char given_dev_name[DEV_IDLEN+1];/* + * Device name given by + * the user. + */ + uint32_t given_unit_number; /* + * Unit number given by + * the user. + */ + char device_name[DEV_IDLEN+1];/* + * Name of the device, + * e.g., 'pass' + */ + uint32_t dev_unit_num; /* Unit number of the passthrough + * device associated with this + * particular device. + */ + + char sim_name[SIM_IDLEN+1];/* + * Controller name, e.g., 'ahc' + */ + uint32_t sim_unit_number; /* Controller unit number */ + uint32_t bus_id; /* Controller bus number */ + lun_id_t target_lun; /* Logical Unit Number */ + target_id_t target_id; /* Target ID */ + path_id_t path_id; /* System SCSI bus number */ + uint16_t pd_type; /* type of peripheral device */ + struct scsi_inquiry_data inq_data; /* SCSI Inquiry data */ + uint8_t serial_num[252]; /* device serial number */ + uint8_t serial_num_len; /* length of the serial number */ + uint8_t sync_period; /* Negotiated sync period */ + uint8_t sync_offset; /* Negotiated sync offset */ + uint8_t bus_width; /* Negotiated bus width */ + int fd; /* file descriptor for device */ +}; +.Ed +.Pp +.Fn cam_open_device +takes as arguments a string describing the device it is to open, and +.Ar flags +suitable for passing to +.Xr open 2 . +The "path" passed in may actually be most any type of string that contains +a device name and unit number to be opened. +The string will be parsed by +.Fn cam_get_device +into a device name and unit number. +Once the device name and unit number +are determined, a lookup is performed to determine the passthrough device +that corresponds to the given device. +.Pp +.Fn cam_open_spec_device +opens the +.Xr pass 4 +device that corresponds to the device name and unit number passed in. +The +.Ar flags +should be flags suitable for passing to +.Xr open 2 . +The +.Ar device +argument is optional. +The user may supply pre-allocated space for the +.Va cam_device +structure. +If the +.Ar device +argument is +.Dv NULL , +.Fn cam_open_spec_device +will allocate space for the +.Va cam_device +structure using +.Xr malloc 3 . +.Pp +.Fn cam_open_btl +is similar to +.Fn cam_open_spec_device , +except that it takes a SCSI bus, +target and logical unit instead of a device name and unit number as +arguments. +The +.Va path_id +argument is the CAM equivalent of a SCSI bus number. +It represents the logical bus number in the system. +The +.Ar flags +should be flags suitable for passing to +.Xr open 2 . +As with +.Fn cam_open_spec_device , +the +.Fa device +argument is optional. +.Pp +.Fn cam_open_pass +takes as an argument the +.Fa path +of a +.Xr pass 4 +device to open. +No translation or lookup is performed, so the path passed +in must be that of a CAM +.Xr pass 4 +device. +The +.Fa flags +should be flags suitable for passing to +.Xr open 2 . +The +.Fa device +argument, as with +.Fn cam_open_spec_device +and +.Fn cam_open_btl , +should be +.Dv NULL +if the user wants the CAM library to allocate space for the +.Va cam_device +structure. +.Pp +.Fn cam_close_device +frees the +.Va cam_device +structure allocated by one of the above +.Xr open 2 +calls, and closes the file +descriptor to the passthrough device. +This routine should not be called if +the user allocated space for the +.Va cam_device +structure. +Instead, the user should call +.Fn cam_close_spec_device . +.Pp +.Fn cam_close_spec_device +merely closes the file descriptor opened in one of the +.Xr open 2 +routines +described above. +This function should be called when the +.Va cam_device +structure was allocated by the caller, rather than the CAM library. +.Pp +.Fn cam_getccb +allocates a prezeroed CCB +using +.Xr calloc 3 +and sets fields in the CCB header using values from the +.Va cam_device +structure. +.Pp +.Fn cam_send_ccb +sends the given +.Va ccb +to the +.Fa device +described in the +.Va cam_device +structure. +.Pp +.Fn cam_freeccb +frees CCBs allocated by +.Fn cam_getccb . +If +.Va ccb +is +.Dv NULL , +no action is taken. +.Pp +.Fn cam_path_string +takes as arguments a +.Va cam_device +structure, and a string with length +.Fa len . +It creates a colon-terminated printing prefix string similar to the ones +used by the kernel. +e.g.: "(cd0:ahc1:0:4:0): ". +.Fn cam_path_string +will place at most +.Fa len Ns \-1 +characters into +.Ar str . +The +.Ar len Ns 'th +character will be the terminating +.Ql \e0 . +.Pp +.Fn cam_device_dup +operates in a fashion similar to +.Xr strdup 3 . +It allocates space for a +.Va cam_device +structure and copies the contents of the passed-in +.Fa device +structure to the newly allocated structure. +.Pp +.Fn cam_device_copy +copies the +.Fa src +structure to +.Fa dst . +.Pp +.Fn cam_get_device +takes a +.Fa path +argument containing a string with a device name followed by a unit number. +It then breaks the string down into a device name and unit number, and +passes them back in +.Fa dev_name +and +.Fa unit , +respectively. +.Fn cam_get_device +can handle strings of the following forms, at least: +.Pp +.Bl -tag -width 1234 -compact +.It /dev/foo1 +.It foo0 +.It nsa2 +.El +.Pp +.Fn cam_get_device +is provided as a convenience function for applications that need to provide +functionality similar to +.Fn cam_open_device . +.Sh RETURN VALUES +.Fn cam_open_device , +.Fn cam_open_spec_device , +.Fn cam_open_btl , +and +.Fn cam_open_pass +return a pointer to a +.Va cam_device +structure, or +.Dv NULL +if there was an error. +.Pp +.Fn cam_getccb +returns an allocated and partially initialized CCB, or +.Dv NULL +if allocation of the CCB failed. +.Pp +.Fn cam_send_ccb +returns a value of -1 if an error occurred, and +.Va errno +is set to indicate the error. +.Pp +.Fn cam_path_string +returns a filled printing prefix string as a convenience. +This is the same +.Fa str +that is passed into +.Fn cam_path_string . +.Pp +.Fn cam_device_dup +returns a copy of the +.Va device +passed in, or +.Dv NULL +if an error occurred. +.Pp +.Fn cam_get_device +returns 0 for success, and -1 to indicate failure. +.Pp +If an error is returned from one of the base CAM library functions +described here, the reason for the error is generally printed in the global +string +.Va cam_errbuf +which is +.Dv CAM_ERRBUF_SIZE +characters long. +.Sh SEE ALSO +.Xr cam_cdbparse 3 , +.Xr pass 4 , +.Xr camcontrol 8 +.Sh HISTORY +The CAM library first appeared in +.Fx 3.0 . +.Sh AUTHORS +.An Kenneth Merry Aq Mt ken@FreeBSD.org +.Sh BUGS +.Fn cam_open_device +does not check to see if the +.Fa path +passed in is a symlink to something. +It also does not check to see if the +.Fa path +passed in is an actual +.Xr pass 4 +device. +The former would be rather easy to implement, but the latter would +require a definitive way to identify a device node as a +.Xr pass 4 +device. +.Pp +Some of the functions are possibly misnamed or poorly named. diff --git a/lib/libcam/cam_cdbparse.3 b/lib/libcam/cam_cdbparse.3 new file mode 100644 index 000000000000..aaafb0db2bcb --- /dev/null +++ b/lib/libcam/cam_cdbparse.3 @@ -0,0 +1,551 @@ +.\" +.\" Copyright (c) 1998 Kenneth D. Merry. +.\" All rights reserved. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 3. The name of the author may not be used to endorse or promote products +.\" derived from this software without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" This man page borrows heavily from the old scsi(3) man page, which had +.\" the following copyright: +.\" +.\" Copyright (c) 1994 HD Associates (hd@world.std.com) +.\" All rights reserved. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 3. All advertising materials mentioning features or use of this software +.\" must display the following acknowledgement: +.\" This product includes software developed by HD Associates +.\" 4. Neither the name of the HD Associates nor the names of its contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY HD ASSOCIATES``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL HD ASSOCIATES OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" +.Dd March 13, 2017 +.Dt CAM_CDBPARSE 3 +.Os +.Sh NAME +.Nm csio_build , +.Nm csio_build_visit , +.Nm csio_decode , +.Nm csio_decode_visit , +.Nm buff_decode , +.Nm buff_decode_visit , +.Nm csio_encode , +.Nm csio_encode_visit , +.Nm buff_encode_visit +.Nd CAM user library SCSI buffer parsing routines +.Sh LIBRARY +.Lb libcam +.Sh SYNOPSIS +.In stdio.h +.In camlib.h +.Ft int +.Fo csio_build +.Fa "struct ccb_scsiio *csio" +.Fa "uint8_t *data_ptr" +.Fa "uint32_t dxfer_len" +.Fa "uint32_t flags" +.Fa "int retry_count" +.Fa "int timeout" +.Fa "const char *cmd_spec" +.Fa "..." +.Fc +.Ft int +.Fo csio_build_visit +.Fa "struct ccb_scsiio *csio" +.Fa "uint8_t *data_ptr" +.Fa "uint32_t dxfer_len" +.Fa "uint32_t flags" +.Fa "int retry_count" +.Fa "int timeout" +.Fa "const char *cmd_spec" +.Fa "int (*arg_get)(void *hook, char *field_name)" +.Fa "void *gethook" +.Fc +.Ft int +.Fo csio_decode +.Fa "struct ccb_scsiio *csio" +.Fa "const char *fmt" +.Fa "..." +.Fc +.Ft int +.Fo csio_decode_visit +.Fa "struct ccb_scsiio *csio" +.Fa "const char *fmt" +.Fa "void (*arg_put)(void *hook" +.Fa "int letter" +.Fa "void *val" +.Fa "int count" +.Fa "char *name)" +.Fa "void *puthook" +.Fc +.Ft int +.Fo buff_decode +.Fa "uint8_t *buff" +.Fa "size_t len" +.Fa "const char *fmt" +.Fa "..." +.Fc +.Ft int +.Fo buff_decode_visit +.Fa "uint8_t *buff" +.Fa "size_t len" +.Fa "const char *fmt" +.Fa "void (*arg_put)(void *, int, void *, int, char *)" +.Fa "void *puthook" +.Fc +.Ft int +.Fo csio_encode +.Fa "struct ccb_scsiio *csio" +.Fa "const char *fmt" +.Fa "..." +.Fc +.Ft int +.Fo csio_encode_visit +.Fa "struct ccb_scsiio *csio" +.Fa "const char *fmt" +.Fa "int (*arg_get)(void *hook, char *field_name)" +.Fa "void *gethook" +.Fc +.Ft int +.Fo buff_encode_visit +.Fa "uint8_t *buff" +.Fa "size_t len" +.Fa "const char *fmt" +.Fa "int (*arg_get)(void *hook, char *field_name)" +.Fa "void *gethook" +.Fc +.Sh DESCRIPTION +The CAM buffer/CDB encoding and decoding routines provide a relatively easy +migration path for userland +.Tn SCSI +applications written with the similarly-named +.Va scsireq_ Ns * +functions from the old +.Fx +.Tn SCSI +layer. +.Pp +These functions may be used in new applications, but users may find it +easier to use the various SCSI CCB building functions included with the +.Xr cam 3 +library, e.g., \& +.Fn cam_fill_csio , +.Fn scsi_start_stop , +and +.Fn scsi_read_write . +.Pp +.Fn csio_build +builds up a +.Va ccb_scsiio +structure based on the information provided in +the variable argument list. +It gracefully handles a NULL +.Fa data_ptr +argument passed to it. +.Pp +.Fa dxfer_len +is the length of the data phase; the data transfer direction is +determined by the +.Fa flags +argument. +.Pp +.Fa data_ptr +is the data buffer used during the +.Tn SCSI +data phase. +If no data is to be +transferred for the +.Tn SCSI +command in question, this should be set to NULL. +If there is data to +transfer for the command, this buffer must be at least +.Fa dxfer_len +long. +.Pp +.Fa flags +are the flags defined in +.In cam/cam_ccb.h : +.Bd -literal +/* Common CCB header */ +/* CAM CCB flags */ +typedef enum { + CAM_CDB_POINTER = 0x00000001,/* The CDB field is a pointer */ + CAM_SCATTER_VALID = 0x00000010,/* Scatter/gather list is valid */ + CAM_DIS_AUTOSENSE = 0x00000020,/* Disable autosense feature */ + CAM_DIR_RESV = 0x00000000,/* Data direction (00:reserved) */ + CAM_DIR_IN = 0x00000040,/* Data direction (01:DATA IN) */ + CAM_DIR_OUT = 0x00000080,/* Data direction (10:DATA OUT) */ + CAM_DIR_NONE = 0x000000C0,/* Data direction (11:no data) */ + CAM_DIR_MASK = 0x000000C0,/* Data direction Mask */ + CAM_DEV_QFRZDIS = 0x00000400,/* Disable DEV Q freezing */ + CAM_DEV_QFREEZE = 0x00000800,/* Freeze DEV Q on execution */ + CAM_HIGH_POWER = 0x00001000,/* Command takes a lot of power */ + CAM_SENSE_PTR = 0x00002000,/* Sense data is a pointer */ + CAM_SENSE_PHYS = 0x00004000,/* Sense pointer is physical addr*/ + CAM_TAG_ACTION_VALID = 0x00008000,/* Use the tag action in this ccb*/ + CAM_PASS_ERR_RECOVER = 0x00010000,/* Pass driver does err. recovery*/ + CAM_DIS_DISCONNECT = 0x00020000,/* Disable disconnect */ + CAM_SG_LIST_PHYS = 0x00040000,/* SG list has physical addrs. */ + CAM_DATA_PHYS = 0x00200000,/* SG/Buffer data ptrs are phys. */ + CAM_CDB_PHYS = 0x00400000,/* CDB pointer is physical */ + +/* Host target Mode flags */ + CAM_SEND_SENSE = 0x08000000,/* Send sense data with status */ + CAM_SEND_STATUS = 0x80000000,/* Send status after data phase */ +} ccb_flags; +.Ed +.Pp +Multiple flags should be ORed together. +Any of the CCB flags may be used, +although it is worth noting several important ones here: +.Bl -tag -width CAM_PASS_ERR_RECOVER +.It Dv CAM_DIR_IN +This indicates that the operation in question is a read operation. +i.e., +data is being read from the +.Tn SCSI +device to the user-supplied buffer. +.It Dv CAM_DIR_OUT +This indicates that the operation is a write operation. +i.e., data is being +written from the user-supplied buffer to the device. +.It Dv CAM_DIR_NONE +This indicates that there is no data to be transferred for this command. +.It Dv CAM_DEV_QFRZDIS +This flag disables device queue freezing as an error recovery mechanism. +.It Dv CAM_PASS_ERR_RECOVER +This flag tells the +.Xr pass 4 +driver to enable error recovery. +The default is to not perform error +recovery, which means that the retry count will not be honored without this +flag, among other things. +.It Dv CAM_DATA_PHYS +This indicates that the address contained in +.Fa data_ptr +is a physical address, not a virtual address. +.El +.Pp +The +.Fa retry_count +tells the kernel how many times to retry the command in question. +The +retry count is ignored unless the +.Xr pass 4 +driver is told to enable error recovery via the +.Dv CAM_PASS_ERR_RECOVER +flag. +.Pp +The +.Fa timeout +tells the kernel how long to wait for the given command to complete. +If +the timeout expires and the command has not completed, the CCB will be +returned from the kernel with an appropriate error status. +.Pp +.Fa cmd_spec +is a CDB format specifier used to build up the SCSI CDB. +This text string is made up of a list of field specifiers. +Field +specifiers specify the value for each CDB field (including indicating +that the value be taken from the next argument in the +variable argument list), the width +of the field in bits or bytes, and an optional name. +White space is +ignored, and the pound sign ('#') introduces a comment that ends at the +end of the current line. +.Pp +The optional name is the first part of a field specifier and +is in curly braces. +The text in curly braces in this example are +the names: +.Dl "{PS} v:b1 {Reserved} 0:b1 {Page Code} v:b6 # Mode select page" +.Pp +This field specifier has two one bit fields and one six bit field. +The second one bit field is the constant value 0 and the first +one bit field and the six bit field are taken from the variable +argument list. +Multi byte fields are swapped into the SCSI byte order in the +CDB and white space is ignored. +.Pp +When the field is a hex value or the letter v, (e.g., +.Fa "1A" +or +.Fa "v" ) +then a single byte value +is copied to the next unused byte of the CDB. +When the letter +.Fa v +is used the next integer argument is taken from the variable argument list +and that value used. +.Pp +A constant hex value followed by a field width specifier or the letter +.Fa v +followed by a field width specifier (e.g., +.Fa 3:4 , +.Fa 3:b4 , +.Fa 3:i3 , +.Fa v:i3 ) +specifies a field of a given bit or byte width. +Either the constant value or (for the V specifier) the next integer value from +the variable argument list is copied to the next unused +bits or bytes of the CDB. +.Pp +A decimal number or the letter +.Fa b +followed by a decimal number field width indicates a bit field of that width. +The bit fields are packed as tightly as possible beginning with the +high bit (so that it reads the same as the SCSI spec), and a new byte of +the CDB is started whenever a byte fills completely or when an +.Fa i +field is encountered. +.Pp +A field width specifier consisting of the letter +.Fa i +followed by either +1, 2, 3 or 4 indicates a 1, 2, 3 or 4 byte integral value that must +be swapped into SCSI byte order (MSB first). +.Pp +For the +.Fa v +field specifier the next integer argument is taken from the variable argument +list and that value is used swapped into SCSI byte order. +.Pp +.Fn csio_build_visit +operates similarly to +.Fn csio_build , +except that the values to substitute for variable arguments in +.Fa cmd_spec +are retrieved via the +.Fn arg_get +function passed in to +.Fn csio_build_visit +instead of via +.Xr stdarg 3 . +The +.Fn arg_get +function takes two arguments: +.Bl -tag -width field_name +.It Fa gethook +is passed into the +.Fn arg_get +function at each invocation. +This enables the +.Fn arg_get +function to keep some state in between calls without using global or static +variables. +.It Fa field_name +is the field name supplied in +.Fa fmt , +if any. +.El +.Pp +.Fn csio_decode +is used to decode information from the data in phase of the SCSI +transfer. +.Pp +The decoding is similar to +the command specifier processing of +.Fn csio_build +except that the data is extracted from the data pointed to by +.Fa csio->data_ptr . +The stdarg list should be pointers to integers instead of integer +values. +A seek field type and a suppression modifier are added. +The +.Fa * +suppression modifier (e.g., +.Fa *i3 +or +.Fa *b4 ) +suppresses assignment from the field and can be used to skip +over bytes or bits in the data, without having to copy +them to a dummy variable in the arg list. +.Pp +The seek field type +.Fa s +permits you to skip over data. +This seeks to an absolute position +.Pq Fa s3 +or a relative position +.Pq Fa s+3 +in the data, based on whether or not the presence of the '+' sign. +The seek value can be specified as +.Fa v +and the next integer value from the argument list will be +used as the seek value. +.Pp +.Fn csio_decode_visit +operates like +.Fn csio_decode +except that instead of placing the decoded contents of the buffer in +variadic arguments, the decoded buffer contents are returned to the user +via the +.Fn arg_put +function that is passed in. +The +.Fn arg_put +function takes several arguments: +.Bl -tag -width letter +.It Fa hook +The "hook" is a mechanism to allow the +.Fn arg_put +function to save state in between calls. +.It Fa letter +is the letter describing the format of the argument being passed into the +function. +.It Fa val +is a void pointer to the value being passed into the function. +.It Fa count +is the size of the value being passed into the +.Fn arg_put +function. +The argument format determines the unit of measure. +.It Fa name +This is a text description of the field, if one was provided in the +.Fa fmt . +.El +.Pp +.Fn buff_decode +decodes an arbitrary data buffer using the method +described above for +.Fn csio_decode . +.Pp +.Fn buff_decode_visit +decodes an arbitrary data buffer using the method described above for +.Fn csio_decode_visit . +.Pp +.Fn csio_encode +encodes the +.Fa data_ptr +portion (not the CDB!) of a +.Va ccb_scsiio +structure, using the method described above for +.Fn csio_build . +.Pp +.Fn csio_encode_visit +encodes the +.Fa data_ptr +portion (not the CDB!) of a +.Va ccb_scsiio +structure, using the method described above for +.Fn csio_build_visit . +.Pp +.Fn buff_encode_visit +encodes an arbitrary data pointer, using the method described +above for +.Fn csio_build_visit . +.Sh RETURN VALUES +.Fn csio_build , +.Fn csio_build_visit , +.Fn csio_encode , +.Fn csio_encode_visit , +and +.Fn buff_encode_visit +return the number of fields processed. +.Pp +.Fn csio_decode , +.Fn csio_decode_visit , +.Fn buff_decode , +and +.Fn buff_decode_visit +return the number of assignments performed. +.Sh SEE ALSO +.Xr cam 3 , +.Xr pass 4 , +.Xr camcontrol 8 +.Sh HISTORY +The CAM versions of these functions are based upon similar functions +implemented for the old +.Fx +.Tn SCSI +layer. +The encoding/decoding functions in the old +.Tn SCSI +code were written by +.An Peter Dufault Aq Mt dufault@hda.com . +.Pp +Many systems have comparable interfaces to permit a user to construct a +SCSI command in user space. +.Pp +The old +.Va scsireq +data structure was almost identical to the SGI /dev/scsi data structure. +If anyone knows the name of the authors it should go here; +Peter Dufault +first read about it in a 1989 Sun Expert magazine. +.Pp +The new CCB data structures are derived from the CAM-2 and CAM-3 +specifications. +.Pp +.An Peter Dufault +implemented a clone of SGI's interface in +.Bx 386 +that +led to the original +.Fx +.Tn SCSI +library and the related kernel ioctl. +If anyone needs that for compatibility, contact +.Mt dufault@hda.com . +.Sh AUTHORS +.An -nosplit +.An Kenneth Merry Aq Mt ken@FreeBSD.org +implemented the CAM versions of these encoding and decoding functions. +This current work is based upon earlier work by +.An Peter Dufault Aq Mt dufault@hda.com . +.Sh BUGS +There should probably be a function that encodes both the CDB and the data +buffer portions of a +.Tn SCSI +CCB. +I discovered this while implementing the arbitrary command execution +code in +.Xr camcontrol 8 , +but I have not yet had time to implement such a function. +.Pp +Some of the CCB flag descriptions really do not belong here. +Rather they +belong in a generic CCB man page. +Since that man page has not yet been +written, the shorter descriptions here will have to suffice. diff --git a/lib/libcam/camlib.c b/lib/libcam/camlib.c new file mode 100644 index 000000000000..6b3e62e13e6f --- /dev/null +++ b/lib/libcam/camlib.c @@ -0,0 +1,758 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 1997, 1998, 1999, 2002 Kenneth D. Merry. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/types.h> +#include <sys/param.h> +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> +#include <string.h> +#include <fcntl.h> +#include <unistd.h> +#include <errno.h> +#include <ctype.h> + +#include <cam/cam.h> +#include <cam/scsi/scsi_all.h> +#include <cam/cam_ccb.h> +#include <cam/scsi/scsi_pass.h> +#include "camlib.h" + + +static const char *nonrewind_devs[] = { + "sa" +}; + +char cam_errbuf[CAM_ERRBUF_SIZE]; + +static struct cam_device *cam_real_open_device(const char *path, int flags, + struct cam_device *device, + const char *given_path, + const char *given_dev_name, + int given_unit_number); +static struct cam_device *cam_lookup_pass(const char *dev_name, int unit, + int flags, const char *given_path, + struct cam_device *device); + +/* + * Send a ccb to a passthrough device. + */ +int +cam_send_ccb(struct cam_device *device, union ccb *ccb) +{ + return(ioctl(device->fd, CAMIOCOMMAND, ccb)); +} + +/* + * Malloc a CCB, zero out the header and set its path, target and lun ids. + */ +union ccb * +cam_getccb(struct cam_device *dev) +{ + union ccb *ccb; + + ccb = calloc(1, sizeof(*ccb)); + if (ccb != NULL) { + ccb->ccb_h.path_id = dev->path_id; + ccb->ccb_h.target_id = dev->target_id; + ccb->ccb_h.target_lun = dev->target_lun; + } + + return(ccb); +} + +/* + * Free a CCB. + */ +void +cam_freeccb(union ccb *ccb) +{ + free(ccb); +} + +/* + * Take a device name or path passed in by the user, and attempt to figure + * out the device name and unit number. Some possible device name formats are: + * /dev/foo0 + * foo0 + * nfoo0 + * + * Some peripheral drivers create separate device nodes with 'n' prefix for + * non-rewind operations. Currently only sa(4) tape driver has this feature. + * We extract pure peripheral name as device name for this special case. + * + * Input parameters: device name/path, length of devname string + * Output: device name, unit number + * Return values: returns 0 for success, -1 for failure + */ +int +cam_get_device(const char *path, char *dev_name, int devnamelen, int *unit) +{ + char *tmpstr, *tmpstr2; + char *newpath; + int unit_offset; + int i; + + if (path == NULL) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: device pathname was NULL", __func__); + return(-1); + } + + /* + * Resolve the given path to a real device path in case we are given + * an alias or other symbolic link. If the path cannot be resolved + * then try to parse it as is. + */ + newpath = realpath(path, NULL); + if (newpath == NULL) + newpath = strdup(path); + if (newpath == NULL) + return (-1); + + tmpstr = newpath; + + /* + * Check to see whether we have an absolute pathname. + */ + if (*tmpstr == '/') { + tmpstr2 = tmpstr; + tmpstr = strrchr(tmpstr2, '/'); + /* We know that tmpstr2 contains a '/', so strrchr can't fail */ + assert(tmpstr != NULL && *tmpstr != '\0'); + tmpstr++; + } + + if (*tmpstr == '\0') { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: no text after slash", __func__); + free(newpath); + return(-1); + } + + /* + * Check to see whether the user has given us a nonrewound tape + * device. + */ + if (*tmpstr == 'n' || *tmpstr == 'e') { + for (i = 0; i < sizeof(nonrewind_devs)/sizeof(char *); i++) { + int len = strlen(nonrewind_devs[i]); + if (strncmp(tmpstr + 1, nonrewind_devs[i], len) == 0) { + if (isdigit(tmpstr[len + 1])) { + tmpstr++; + break; + } + } + } + } + + /* + * We should now have just a device name and unit number. + * That means that there must be at least 2 characters. + * If we only have 1, we don't have a valid device name. + */ + if (strlen(tmpstr) < 2) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: must have both device name and unit number", + __func__); + free(newpath); + return(-1); + } + + /* + * If the first character of the string is a digit, then the user + * has probably given us all numbers. Point out the error. + */ + if (isdigit(*tmpstr)) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: device name cannot begin with a number", + __func__); + free(newpath); + return(-1); + } + + /* + * At this point, if the last character of the string isn't a + * number, we know the user either didn't give us a device number, + * or he gave us a device name/number format we don't recognize. + */ + if (!isdigit(tmpstr[strlen(tmpstr) - 1])) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: unable to find device unit number", __func__); + free(newpath); + return(-1); + } + + /* + * Attempt to figure out where the device name ends and the unit + * number begins. As long as unit_offset is at least 1 less than + * the length of the string, we can still potentially have a device + * name at the front of the string. When we get to something that + * isn't a digit, we've hit the device name. Because of the check + * above, we know that this cannot happen when unit_offset == 1. + * Therefore it is okay to decrement unit_offset -- it won't cause + * us to go past the end of the character array. + */ + for (unit_offset = 1; + (unit_offset < (strlen(tmpstr))) + && (isdigit(tmpstr[strlen(tmpstr) - unit_offset])); unit_offset++); + + unit_offset--; + + /* + * Grab the unit number. + */ + *unit = atoi(&tmpstr[strlen(tmpstr) - unit_offset]); + + /* + * Put a null in place of the first number of the unit number so + * that all we have left is the device name. + */ + tmpstr[strlen(tmpstr) - unit_offset] = '\0'; + + strlcpy(dev_name, tmpstr, devnamelen); + + /* Clean up allocated memory */ + free(newpath); + + return(0); + +} + +/* + * Backwards compatible wrapper for the real open routine. This translates + * a pathname into a device name and unit number for use with the real open + * routine. + */ +struct cam_device * +cam_open_device(const char *path, int flags) +{ + int unit; + char dev_name[DEV_IDLEN + 1]; + + /* + * cam_get_device() has already put an error message in cam_errbuf, + * so we don't need to. + */ + if (cam_get_device(path, dev_name, sizeof(dev_name), &unit) == -1) + return(NULL); + + return(cam_lookup_pass(dev_name, unit, flags, path, NULL)); +} + +/* + * Open the passthrough device for a given bus, target and lun, if the + * passthrough device exists. + */ +struct cam_device * +cam_open_btl(path_id_t path_id, target_id_t target_id, lun_id_t target_lun, + int flags, struct cam_device *device) +{ + union ccb ccb; + struct periph_match_pattern *match_pat; + int fd, bufsize; + + if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: couldn't open %s\n%s: %s", __func__, XPT_DEVICE, + __func__, strerror(errno)); + return(NULL); + } + + bzero(&ccb, sizeof(union ccb)); + ccb.ccb_h.func_code = XPT_DEV_MATCH; + ccb.ccb_h.path_id = CAM_XPT_PATH_ID; + ccb.ccb_h.target_id = CAM_TARGET_WILDCARD; + ccb.ccb_h.target_lun = CAM_LUN_WILDCARD; + + /* Setup the result buffer */ + bufsize = sizeof(struct dev_match_result); + ccb.cdm.match_buf_len = bufsize; + ccb.cdm.matches = (struct dev_match_result *)malloc(bufsize); + if (ccb.cdm.matches == NULL) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: couldn't malloc match buffer", __func__); + close(fd); + return(NULL); + } + ccb.cdm.num_matches = 0; + + /* Setup the pattern buffer */ + ccb.cdm.num_patterns = 1; + ccb.cdm.pattern_buf_len = sizeof(struct dev_match_pattern); + ccb.cdm.patterns = (struct dev_match_pattern *)malloc( + sizeof(struct dev_match_pattern)); + if (ccb.cdm.patterns == NULL) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: couldn't malloc pattern buffer", __func__); + free(ccb.cdm.matches); + ccb.cdm.matches = NULL; + close(fd); + return(NULL); + } + ccb.cdm.patterns[0].type = DEV_MATCH_PERIPH; + match_pat = &ccb.cdm.patterns[0].pattern.periph_pattern; + + /* + * We're looking for the passthrough device associated with this + * particular bus/target/lun. + */ + sprintf(match_pat->periph_name, "pass"); + match_pat->path_id = path_id; + match_pat->target_id = target_id; + match_pat->target_lun = target_lun; + /* Now set the flags to indicate what we're looking for. */ + match_pat->flags = PERIPH_MATCH_PATH | PERIPH_MATCH_TARGET | + PERIPH_MATCH_LUN | PERIPH_MATCH_NAME; + + if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: CAMIOCOMMAND ioctl failed\n" + "%s: %s", __func__, __func__, strerror(errno)); + goto btl_bailout; + } + + /* + * Check for an outright error. + */ + if ((ccb.ccb_h.status != CAM_REQ_CMP) + || ((ccb.cdm.status != CAM_DEV_MATCH_LAST) + && (ccb.cdm.status != CAM_DEV_MATCH_MORE))) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: CAM error %#x, CDM error %d " + "returned from XPT_DEV_MATCH ccb", __func__, + ccb.ccb_h.status, ccb.cdm.status); + goto btl_bailout; + } + + if (ccb.cdm.status == CAM_DEV_MATCH_MORE) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: CDM reported more than one" + " passthrough device at %d:%d:%jx!!\n", + __func__, path_id, target_id, (uintmax_t)target_lun); + goto btl_bailout; + } + + if (ccb.cdm.num_matches == 0) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: no passthrough device found at" + " %d:%d:%jx", __func__, path_id, target_id, + (uintmax_t)target_lun); + goto btl_bailout; + } + + switch(ccb.cdm.matches[0].type) { + case DEV_MATCH_PERIPH: { + int pass_unit; + char dev_path[256]; + struct periph_match_result *periph_result; + + periph_result = &ccb.cdm.matches[0].result.periph_result; + pass_unit = periph_result->unit_number; + free(ccb.cdm.matches); + ccb.cdm.matches = NULL; + free(ccb.cdm.patterns); + ccb.cdm.patterns = NULL; + close(fd); + sprintf(dev_path, "/dev/pass%d", pass_unit); + return(cam_real_open_device(dev_path, flags, device, NULL, + NULL, 0)); + break; /* NOTREACHED */ + } + default: + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: asked for a peripheral match, but" + " got a bus or device match", __func__); + goto btl_bailout; + break; /* NOTREACHED */ + } + +btl_bailout: + free(ccb.cdm.matches); + ccb.cdm.matches = NULL; + free(ccb.cdm.patterns); + ccb.cdm.patterns = NULL; + close(fd); + return(NULL); +} + +struct cam_device * +cam_open_spec_device(const char *dev_name, int unit, int flags, + struct cam_device *device) +{ + return(cam_lookup_pass(dev_name, unit, flags, NULL, device)); +} + +struct cam_device * +cam_open_pass(const char *path, int flags, struct cam_device *device) +{ + return(cam_real_open_device(path, flags, device, path, NULL, 0)); +} + +static struct cam_device * +cam_lookup_pass(const char *dev_name, int unit, int flags, + const char *given_path, struct cam_device *device) +{ + int fd; + union ccb ccb; + char dev_path[256]; + + /* + * The flags argument above only applies to the actual passthrough + * device open, not our open of the given device to find the + * passthrough device. + */ + if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: couldn't open %s\n%s: %s", __func__, XPT_DEVICE, + __func__, strerror(errno)); + return(NULL); + } + + /* This isn't strictly necessary for the GETPASSTHRU ioctl. */ + ccb.ccb_h.func_code = XPT_GDEVLIST; + + /* These two are necessary for the GETPASSTHRU ioctl to work. */ + strlcpy(ccb.cgdl.periph_name, dev_name, sizeof(ccb.cgdl.periph_name)); + ccb.cgdl.unit_number = unit; + + /* + * Attempt to get the passthrough device. This ioctl will fail if + * the device name is null, if the device doesn't exist, or if the + * passthrough driver isn't in the kernel. + */ + if (ioctl(fd, CAMGETPASSTHRU, &ccb) == -1) { + char tmpstr[256]; + + /* + * If we get ENOENT from the transport layer version of + * the CAMGETPASSTHRU ioctl, it means one of two things: + * either the device name/unit number passed in doesn't + * exist, or the passthrough driver isn't in the kernel. + */ + if (errno == ENOENT) { + snprintf(tmpstr, sizeof(tmpstr), + "\n%s: either the pass driver isn't in " + "your kernel\n%s: or %s%d doesn't exist", + __func__, __func__, dev_name, unit); + } + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: CAMGETPASSTHRU ioctl failed\n" + "%s: %s%s", __func__, __func__, strerror(errno), + (errno == ENOENT) ? tmpstr : ""); + + close(fd); + return(NULL); + } + + close(fd); + + /* + * If the ioctl returned the right status, but we got an error back + * in the ccb, that means that the kernel found the device the user + * passed in, but was unable to find the passthrough device for + * the device the user gave us. + */ + if (ccb.cgdl.status == CAM_GDEVLIST_ERROR) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: device %s%d does not exist!", + __func__, dev_name, unit); + return(NULL); + } + + sprintf(dev_path, "/dev/%s%d", ccb.cgdl.periph_name, + ccb.cgdl.unit_number); + + return(cam_real_open_device(dev_path, flags, device, NULL, + dev_name, unit)); +} + +/* + * Open a given device. The path argument isn't strictly necessary, but it + * is copied into the cam_device structure as a convenience to the user. + */ +static struct cam_device * +cam_real_open_device(const char *path, int flags, struct cam_device *device, + const char *given_path, const char *given_dev_name, + int given_unit_number) +{ + union ccb ccb; + int fd = -1, malloced_device = 0; + + /* + * See if the user wants us to malloc a device for him. + */ + if (device == NULL) { + if ((device = (struct cam_device *)malloc( + sizeof(struct cam_device))) == NULL) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: device structure malloc" + " failed\n%s: %s", __func__, __func__, + strerror(errno)); + return(NULL); + } + device->fd = -1; + malloced_device = 1; + } + + /* + * If the user passed in a path, save it for him. + */ + if (given_path != NULL) + strlcpy(device->device_path, given_path, + sizeof(device->device_path)); + else + device->device_path[0] = '\0'; + + /* + * If the user passed in a device name and unit number pair, save + * those as well. + */ + if (given_dev_name != NULL) + strlcpy(device->given_dev_name, given_dev_name, + sizeof(device->given_dev_name)); + else + device->given_dev_name[0] = '\0'; + device->given_unit_number = given_unit_number; + + if ((fd = open(path, flags)) < 0) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: couldn't open passthrough device %s\n" + "%s: %s", __func__, path, __func__, + strerror(errno)); + goto crod_bailout; + } + + device->fd = fd; + + bzero(&ccb, sizeof(union ccb)); + + /* + * Unlike the transport layer version of the GETPASSTHRU ioctl, + * we don't have to set any fields. + */ + ccb.ccb_h.func_code = XPT_GDEVLIST; + + /* + * We're only doing this to get some information on the device in + * question. Otherwise, we'd have to pass in yet another + * parameter: the passthrough driver unit number. + */ + if (ioctl(fd, CAMGETPASSTHRU, &ccb) == -1) { + /* + * At this point we know the passthrough device must exist + * because we just opened it above. The only way this + * ioctl can fail is if the ccb size is wrong. + */ + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: CAMGETPASSTHRU ioctl failed\n" + "%s: %s", __func__, __func__, strerror(errno)); + goto crod_bailout; + } + + /* + * If the ioctl returned the right status, but we got an error back + * in the ccb, that means that the kernel found the device the user + * passed in, but was unable to find the passthrough device for + * the device the user gave us. + */ + if (ccb.cgdl.status == CAM_GDEVLIST_ERROR) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: passthrough device does not exist!", __func__); + goto crod_bailout; + } + + device->dev_unit_num = ccb.cgdl.unit_number; + strlcpy(device->device_name, ccb.cgdl.periph_name, + sizeof(device->device_name)); + device->path_id = ccb.ccb_h.path_id; + device->target_id = ccb.ccb_h.target_id; + device->target_lun = ccb.ccb_h.target_lun; + + ccb.ccb_h.func_code = XPT_PATH_INQ; + if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: Path Inquiry CCB failed\n" + "%s: %s", __func__, __func__, strerror(errno)); + goto crod_bailout; + } + strlcpy(device->sim_name, ccb.cpi.dev_name, sizeof(device->sim_name)); + device->sim_unit_number = ccb.cpi.unit_number; + device->bus_id = ccb.cpi.bus_id; + + /* + * It doesn't really matter what is in the payload for a getdev + * CCB, the kernel doesn't look at it. + */ + ccb.ccb_h.func_code = XPT_GDEV_TYPE; + if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: Get Device Type CCB failed\n" + "%s: %s", __func__, __func__, strerror(errno)); + goto crod_bailout; + } + device->pd_type = SID_TYPE(&ccb.cgd.inq_data); + bcopy(&ccb.cgd.inq_data, &device->inq_data, + sizeof(struct scsi_inquiry_data)); + device->serial_num_len = ccb.cgd.serial_num_len; + bcopy(&ccb.cgd.serial_num, &device->serial_num, device->serial_num_len); + + /* + * Zero the payload, the kernel does look at the flags. + */ + CCB_CLEAR_ALL_EXCEPT_HDR(&ccb.cts); + + /* + * Get transfer settings for this device. + */ + ccb.ccb_h.func_code = XPT_GET_TRAN_SETTINGS; + + ccb.cts.type = CTS_TYPE_CURRENT_SETTINGS; + + if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: Get Transfer Settings CCB failed\n" + "%s: %s", __func__, __func__, strerror(errno)); + goto crod_bailout; + } + if (ccb.cts.transport == XPORT_SPI) { + struct ccb_trans_settings_spi *spi = + &ccb.cts.xport_specific.spi; + device->sync_period = spi->sync_period; + device->sync_offset = spi->sync_offset; + device->bus_width = spi->bus_width; + } else { + device->sync_period = 0; + device->sync_offset = 0; + device->bus_width = 0; + } + + return(device); + +crod_bailout: + + if (fd >= 0) + close(fd); + + if (malloced_device) + free(device); + + return(NULL); +} + +void +cam_close_device(struct cam_device *dev) +{ + if (dev == NULL) + return; + + cam_close_spec_device(dev); + + free(dev); +} + +void +cam_close_spec_device(struct cam_device *dev) +{ + if (dev == NULL) + return; + + if (dev->fd >= 0) { + close(dev->fd); + dev->fd = -1; + } +} + +char * +cam_path_string(struct cam_device *dev, char *str, int len) +{ + if (dev == NULL) { + snprintf(str, len, "No path"); + return(str); + } + + snprintf(str, len, "(%s%d:%s%d:%d:%d:%jx): ", + (dev->device_name[0] != '\0') ? dev->device_name : "pass", + dev->dev_unit_num, + (dev->sim_name[0] != '\0') ? dev->sim_name : "unknown", + dev->sim_unit_number, + dev->bus_id, + dev->target_id, + (uintmax_t)dev->target_lun); + + return(str); +} + +/* + * Malloc/duplicate a CAM device structure. + */ +struct cam_device * +cam_device_dup(struct cam_device *device) +{ + struct cam_device *newdev; + + if (device == NULL) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: device is NULL", __func__); + return (NULL); + } + + newdev = malloc(sizeof(struct cam_device)); + if (newdev == NULL) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: couldn't malloc CAM device structure", __func__); + return (NULL); + } + + bcopy(device, newdev, sizeof(struct cam_device)); + + return(newdev); +} + +/* + * Copy a CAM device structure. + */ +void +cam_device_copy(struct cam_device *src, struct cam_device *dst) +{ + + if (src == NULL) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: source device struct was NULL", __func__); + return; + } + + if (dst == NULL) { + snprintf(cam_errbuf, nitems(cam_errbuf), + "%s: destination device struct was NULL", __func__); + return; + } + + bcopy(src, dst, sizeof(struct cam_device)); + +} diff --git a/lib/libcam/camlib.h b/lib/libcam/camlib.h new file mode 100644 index 000000000000..c82a529181cb --- /dev/null +++ b/lib/libcam/camlib.h @@ -0,0 +1,180 @@ +/*- + * SPDX-License-Identifier: (BSD-2-Clause AND BSD-4-Clause) + * + * Copyright (c) 1997, 1998 Kenneth D. Merry. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ +/* + * Buffer encoding/decoding routines taken from the original FreeBSD SCSI + * library and slightly modified. The original header file had the following + * copyright: + */ +/* Copyright (c) 1994 HD Associates (hd@world.std.com) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by HD Associates + * 4. Neither the name of the HD Associaates nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY HD ASSOCIATES``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL HD ASSOCIATES OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + + +#ifndef _CAMLIB_H +#define _CAMLIB_H + +#include <sys/param.h> + +#include <cam/cam.h> +#include <cam/cam_ccb.h> + +#define CAM_ERRBUF_SIZE 2048 /* CAM library error string size */ + +/* + * Right now we hard code the transport layer device, but this will change + * if we ever get more than one transport layer. + */ +#define XPT_DEVICE "/dev/xpt0" + + +extern char cam_errbuf[]; + +struct cam_device { + char device_path[MAXPATHLEN];/* + * Pathname of the device + * given by the user. This + * may be null if the + * user states the device + * name and unit number + * separately. + */ + char given_dev_name[DEV_IDLEN+1];/* + * Device name given by + * the user. + */ + uint32_t given_unit_number; /* + * Unit number given by + * the user. + */ + char device_name[DEV_IDLEN+1];/* + * Name of the device, + * e.g. 'pass' + */ + uint32_t dev_unit_num; /* Unit number of the passthrough + * device associated with this + * particular device. + */ + + char sim_name[SIM_IDLEN+1]; /* Controller name, e.g. 'ahc' */ + uint32_t sim_unit_number; /* Controller unit number */ + uint32_t bus_id; /* Controller bus number */ + lun_id_t target_lun; /* Logical Unit Number */ + target_id_t target_id; /* Target ID */ + path_id_t path_id; /* System SCSI bus number */ + uint16_t pd_type; /* type of peripheral device */ + struct scsi_inquiry_data inq_data; /* SCSI Inquiry data */ + uint8_t serial_num[252]; /* device serial number */ + uint8_t serial_num_len; /* length of the serial number */ + uint8_t sync_period; /* Negotiated sync period */ + uint8_t sync_offset; /* Negotiated sync offset */ + uint8_t bus_width; /* Negotiated bus width */ + int fd; /* file descriptor for device */ +}; + +__BEGIN_DECLS +/* Basic utility commands */ +struct cam_device * cam_open_device(const char *path, int flags); +void cam_close_device(struct cam_device *dev); +void cam_close_spec_device(struct cam_device *dev); +struct cam_device * cam_open_spec_device(const char *dev_name, + int unit, int flags, + struct cam_device *device); +struct cam_device * cam_open_btl(path_id_t path_id, target_id_t target_id, + lun_id_t target_lun, int flags, + struct cam_device *device); +struct cam_device * cam_open_pass(const char *path, int flags, + struct cam_device *device); +union ccb * cam_getccb(struct cam_device *dev); +void cam_freeccb(union ccb *ccb); +int cam_send_ccb(struct cam_device *device, union ccb *ccb); +char * cam_path_string(struct cam_device *dev, char *str, + int len); +struct cam_device * cam_device_dup(struct cam_device *device); +void cam_device_copy(struct cam_device *src, + struct cam_device *dst); +int cam_get_device(const char *path, char *dev_name, + int devnamelen, int *unit); + +/* + * Buffer encoding/decoding routines, from the old SCSI library. + */ +int csio_decode(struct ccb_scsiio *csio, const char *fmt, ...) + __printflike(2, 3); +int csio_decode_visit(struct ccb_scsiio *csio, const char *fmt, + void (*arg_put)(void *, int, void *, int, char *), + void *puthook); +int buff_decode(uint8_t *buff, size_t len, const char *fmt, ...) + __printflike(3, 4); +int buff_decode_visit(uint8_t *buff, size_t len, const char *fmt, + void (*arg_put)(void *, int, void *, int, char *), + void *puthook); +int csio_build(struct ccb_scsiio *csio, uint8_t *data_ptr, + uint32_t dxfer_len, uint32_t flags, int retry_count, + int timeout, const char *cmd_spec, ...); +int csio_build_visit(struct ccb_scsiio *csio, uint8_t *data_ptr, + uint32_t dxfer_len, uint32_t flags, int retry_count, + int timeout, const char *cmd_spec, + int (*arg_get)(void *hook, char *field_name), + void *gethook); +int csio_encode(struct ccb_scsiio *csio, const char *fmt, ...) + __printflike(2, 3); +int buff_encode_visit(uint8_t *buff, size_t len, const char *fmt, + int (*arg_get)(void *hook, char *field_name), + void *gethook); +int csio_encode_visit(struct ccb_scsiio *csio, const char *fmt, + int (*arg_get)(void *hook, char *field_name), + void *gethook); +__END_DECLS + +#endif /* _CAMLIB_H */ diff --git a/lib/libcam/scsi_cmdparse.c b/lib/libcam/scsi_cmdparse.c new file mode 100644 index 000000000000..5aa69cd88fdb --- /dev/null +++ b/lib/libcam/scsi_cmdparse.c @@ -0,0 +1,859 @@ +/* + * Taken from the original FreeBSD user SCSI library. + */ +/*- + * SPDX-License-Identifier: BSD-4-Clause + * + * Copyright (c) 1994 HD Associates + * (contact: dufault@hda.com) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by HD Associates + * 4. Neither the name of the HD Associaates nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY HD ASSOCIATES``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL HD ASSOCIATES OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * From: scsi.c,v 1.8 1997/02/22 15:07:54 peter Exp $ + */ + +#include <sys/types.h> + +#include <stdlib.h> +#include <stdio.h> +#include <ctype.h> +#include <string.h> +#include <sys/errno.h> +#include <stdarg.h> +#include <fcntl.h> + +#include <cam/cam.h> +#include <cam/cam_ccb.h> +#include <cam/scsi/scsi_message.h> +#include "camlib.h" + +/* + * Decode: Decode the data section of a scsireq. This decodes + * trivial grammar: + * + * fields : field fields + * ; + * + * field : field_specifier + * | control + * ; + * + * control : 's' seek_value + * | 's' '+' seek_value + * ; + * + * seek_value : DECIMAL_NUMBER + * | 'v' // For indirect seek, i.e., value from the arg list + * ; + * + * field_specifier : type_specifier field_width + * | '{' NAME '}' type_specifier field_width + * ; + * + * field_width : DECIMAL_NUMBER + * ; + * + * type_specifier : 'i' // Integral types (i1, i2, i3, i4) + * | 'b' // Bits + * | 't' // Bits + * | 'c' // Character arrays + * | 'z' // Character arrays with zeroed trailing spaces + * ; + * + * Notes: + * 1. Integral types are swapped into host order. + * 2. Bit fields are allocated MSB to LSB to match the SCSI spec documentation. + * 3. 's' permits "seeking" in the string. "s+DECIMAL" seeks relative to + * DECIMAL; "sDECIMAL" seeks absolute to decimal. + * 4. 's' permits an indirect reference. "sv" or "s+v" will get the + * next integer value from the arg array. + * 5. Field names can be anything between the braces + * + * BUGS: + * i and b types are promoted to ints. + * + */ + +static int +do_buff_decode(uint8_t *buff, size_t len, + void (*arg_put)(void *, int , void *, int, char *), + void *puthook, const char *fmt, va_list *ap) +{ + int ind = 0; + int assigned = 0; + int width; + int suppress; + int plus; + int done = 0; + static u_char mask[] = {0, 0x01, 0x03, 0x07, 0x0f, + 0x1f, 0x3f, 0x7f, 0xff}; + int value; + char *intendp; + char letter; + char field_name[80]; + +#define ARG_PUT(ARG) \ + do { \ + if (!suppress) { \ + if (arg_put) \ + (*arg_put)(puthook, (letter == 't' ? 'b' : \ + letter), (void *)((long)(ARG)), width, \ + field_name); \ + else \ + *(va_arg(*ap, int *)) = (ARG); \ + assigned++; \ + } \ + field_name[0] = '\0'; \ + suppress = 0; \ + } while (0) + + u_char bits = 0; /* For bit fields */ + int shift = 0; /* Bits already shifted out */ + suppress = 0; + field_name[0] = '\0'; + + while (!done) { + switch(letter = *fmt) { + case ' ': /* White space */ + case '\t': + case '\r': + case '\n': + case '\f': + fmt++; + break; + + case '#': /* Comment */ + while (*fmt && (*fmt != '\n')) + fmt++; + if (fmt) + fmt++; /* Skip '\n' */ + break; + + case '*': /* Suppress assignment */ + fmt++; + suppress = 1; + break; + + case '{': /* Field Name */ + { + int i = 0; + fmt++; /* Skip '{' */ + while (*fmt && (*fmt != '}')) { + if (i < sizeof(field_name)) + field_name[i++] = *fmt; + + fmt++; + } + if (*fmt != '\0') + fmt++; /* Skip '}' */ + field_name[i] = '\0'; + break; + } + + case 't': /* Bit (field) */ + case 'b': /* Bits */ + fmt++; + width = strtol(fmt, &intendp, 10); + fmt = intendp; + if (width > 8) + done = 1; + else { + if (shift <= 0) { + if (ind >= len) { + done = 1; + break; + } + bits = buff[ind++]; + shift = 8; + } + value = (bits >> (shift - width)) & + mask[width]; + +#if 0 + printf("shift %2d bits %02x value %02x width %2d mask %02x\n", + shift, bits, value, width, mask[width]); +#endif + + ARG_PUT(value); + + shift -= width; + } + break; + + case 'i': /* Integral values */ + shift = 0; + fmt++; + width = strtol(fmt, &intendp, 10); + fmt = intendp; + if (ind + width > len) { + done = 1; + break; + } + switch(width) { + case 1: + ARG_PUT(buff[ind]); + ind++; + break; + + case 2: + ARG_PUT(buff[ind] << 8 | buff[ind + 1]); + ind += 2; + break; + + case 3: + ARG_PUT(buff[ind] << 16 | + buff[ind + 1] << 8 | buff[ind + 2]); + ind += 3; + break; + + case 4: + ARG_PUT(buff[ind] << 24 | buff[ind + 1] << 16 | + buff[ind + 2] << 8 | buff[ind + 3]); + ind += 4; + break; + + default: + done = 1; + break; + } + + break; + + case 'c': /* Characters (i.e., not swapped) */ + case 'z': /* Characters with zeroed trailing spaces */ + shift = 0; + fmt++; + width = strtol(fmt, &intendp, 10); + fmt = intendp; + if (ind + width > len) { + done = 1; + break; + } + if (!suppress) { + if (arg_put != NULL) + (*arg_put)(puthook, + (letter == 't' ? 'b' : letter), + &buff[ind], width, field_name); + else { + char *dest; + dest = va_arg(*ap, char *); + bcopy(&buff[ind], dest, width); + if (letter == 'z') { + char *p; + for (p = dest + width - 1; + p >= dest && *p == ' '; + p--) + *p = '\0'; + } + } + assigned++; + } + ind += width; + field_name[0] = 0; + suppress = 0; + break; + + case 's': /* Seek */ + shift = 0; + fmt++; + if (*fmt == '+') { + plus = 1; + fmt++; + } else + plus = 0; + + if (tolower(*fmt) == 'v') { + /* + * You can't suppress a seek value. You also + * can't have a variable seek when you are using + * "arg_put". + */ + width = (arg_put) ? 0 : va_arg(*ap, int); + fmt++; + } else { + width = strtol(fmt, &intendp, 10); + fmt = intendp; + } + + if (plus) + ind += width; /* Relative seek */ + else + ind = width; /* Absolute seek */ + + break; + + case 0: + done = 1; + break; + + default: + fprintf(stderr, "Unknown letter in format: %c\n", + letter); + fmt++; + break; + } + } + + return (assigned); +} + +/* next_field: Return the next field in a command specifier. This + * builds up a SCSI command using this trivial grammar: + * + * fields : field fields + * ; + * + * field : value + * | value ':' field_width + * ; + * + * field_width : digit + * | 'i' digit // i2 = 2 byte integer, i3 = 3 byte integer etc. + * ; + * + * value : HEX_NUMBER + * | 'v' // For indirection. + * ; + * + * Notes: + * Bit fields are specified MSB first to match the SCSI spec. + * + * Examples: + * TUR: "0 0 0 0 0 0" + * WRITE BUFFER: "38 v:3 0:2 0:3 v v:i3 v:i3 0", mode, buffer_id, list_length + * + * The function returns the value: + * 0: For reached end, with error_p set if an error was found + * 1: For valid stuff setup + * 2: For "v" was entered as the value (implies use varargs) + * + */ + +static int +next_field(const char **pp, char *fmt, int *width_p, int *value_p, char *name, + int n_name, int *error_p, int *suppress_p) +{ + const char *p = *pp; + char *intendp; + + int something = 0; + + enum { + BETWEEN_FIELDS, + START_FIELD, + GET_FIELD, + DONE, + } state; + + int value = 0; + int field_size; /* Default to byte field type... */ + int field_width; /* 1 byte wide */ + int is_error = 0; + int suppress = 0; + + field_size = 8; /* Default to byte field type... */ + *fmt = 'i'; + field_width = 1; /* 1 byte wide */ + if (name != NULL) + *name = '\0'; + + state = BETWEEN_FIELDS; + + while (state != DONE) { + switch(state) { + case BETWEEN_FIELDS: + if (*p == '\0') + state = DONE; + else if (isspace(*p)) + p++; + else if (*p == '#') { + while (*p && *p != '\n') + p++; + if (*p != '\0') + p++; + } else if (*p == '{') { + int i = 0; + + p++; + + while (*p && *p != '}') { + if(name && i < n_name) { + name[i] = *p; + i++; + } + p++; + } + + if(name && i < n_name) + name[i] = '\0'; + + if (*p == '}') + p++; + } else if (*p == '*') { + p++; + suppress = 1; + } else if (isxdigit(*p)) { + something = 1; + value = strtol(p, &intendp, 16); + p = intendp; + state = START_FIELD; + } else if (tolower(*p) == 'v') { + p++; + something = 2; + value = *value_p; + state = START_FIELD; + } else if (tolower(*p) == 'i') { + /* + * Try to work without the "v". + */ + something = 2; + value = *value_p; + p++; + + *fmt = 'i'; + field_size = 8; + field_width = strtol(p, &intendp, 10); + p = intendp; + state = DONE; + + } else if (tolower(*p) == 't') { + /* + * XXX: B can't work: Sees the 'b' as a + * hex digit in "isxdigit". try "t" for + * bit field. + */ + something = 2; + value = *value_p; + p++; + + *fmt = 'b'; + field_size = 1; + field_width = strtol(p, &intendp, 10); + p = intendp; + state = DONE; + } else if (tolower(*p) == 's') { + /* Seek */ + *fmt = 's'; + p++; + if (tolower(*p) == 'v') { + p++; + something = 2; + value = *value_p; + } else { + something = 1; + value = strtol(p, &intendp, 0); + p = intendp; + } + state = DONE; + } else { + fprintf(stderr, "Invalid starting " + "character: %c\n", *p); + is_error = 1; + state = DONE; + } + break; + + case START_FIELD: + if (*p == ':') { + p++; + field_size = 1; /* Default to bits + when specified */ + state = GET_FIELD; + } else + state = DONE; + break; + + case GET_FIELD: + if (isdigit(*p)) { + *fmt = 'b'; + field_size = 1; + field_width = strtol(p, &intendp, 10); + p = intendp; + state = DONE; + } else if (*p == 'i') { + + /* Integral (bytes) */ + p++; + + *fmt = 'i'; + field_size = 8; + field_width = strtol(p, &intendp, 10); + p = intendp; + state = DONE; + } else if (*p == 'b') { + + /* Bits */ + p++; + + *fmt = 'b'; + field_size = 1; + field_width = strtol(p, &intendp, 10); + p = intendp; + state = DONE; + } else { + fprintf(stderr, "Invalid startfield %c " + "(%02x)\n", *p, *p); + is_error = 1; + state = DONE; + } + break; + + case DONE: + break; + } + } + + if (is_error) { + *error_p = 1; + return (0); + } + + *error_p = 0; + *pp = p; + *width_p = field_width * field_size; + *value_p = value; + *suppress_p = suppress; + + return (something); +} + +static int +do_encode(u_char *buff, size_t vec_max, size_t *used, + int (*arg_get)(void *, char *), void *gethook, const char *fmt, + va_list *ap) +{ + int ind; + int shift; + u_char val; + int ret; + int width, value, error, suppress; + char c; + int encoded = 0; + char field_name[80]; + + ind = 0; + shift = 0; + val = 0; + + while ((ret = next_field(&fmt, &c, &width, &value, field_name, + sizeof(field_name), &error, &suppress))) { + encoded++; + + if (ret == 2) { + if (suppress) + value = 0; + else + value = arg_get != NULL ? + (*arg_get)(gethook, field_name) : + va_arg(*ap, int); + } + +#if 0 + printf( +"do_encode: ret %d fmt %c width %d value %d name \"%s\" error %d suppress %d\n", + ret, c, width, value, field_name, error, suppress); +#endif + /* Absolute seek */ + if (c == 's') { + ind = value; + continue; + } + + /* A width of < 8 is a bit field. */ + if (width < 8) { + + /* This is a bit field. We start with the high bits + * so it reads the same as the SCSI spec. + */ + + shift += width; + + val |= (value << (8 - shift)); + + if (shift == 8) { + if (ind < vec_max) { + buff[ind++] = val; + val = 0; + } + shift = 0; + } + } else { + if (shift) { + if (ind < vec_max) { + buff[ind++] = val; + val = 0; + } + shift = 0; + } + switch(width) { + case 8: /* 1 byte integer */ + if (ind < vec_max) + buff[ind++] = value; + break; + + case 16: /* 2 byte integer */ + if (ind < vec_max - 2 + 1) { + buff[ind++] = value >> 8; + buff[ind++] = value; + } + break; + + case 24: /* 3 byte integer */ + if (ind < vec_max - 3 + 1) { + buff[ind++] = value >> 16; + buff[ind++] = value >> 8; + buff[ind++] = value; + } + break; + + case 32: /* 4 byte integer */ + if (ind < vec_max - 4 + 1) { + buff[ind++] = value >> 24; + buff[ind++] = value >> 16; + buff[ind++] = value >> 8; + buff[ind++] = value; + } + break; + + default: + fprintf(stderr, "do_encode: Illegal width\n"); + break; + } + } + } + + /* Flush out any remaining bits + */ + if (shift && ind < vec_max) { + buff[ind++] = val; + val = 0; + } + + + if (used) + *used = ind; + + if (error) + return (-1); + + return (encoded); +} + +int +csio_decode(struct ccb_scsiio *csio, const char *fmt, ...) +{ + va_list ap; + int retval; + + va_start(ap, fmt); + + retval = do_buff_decode(csio->data_ptr, (size_t)csio->dxfer_len, + NULL, NULL, fmt, &ap); + + va_end(ap); + + return (retval); +} + +int +csio_decode_visit(struct ccb_scsiio *csio, const char *fmt, + void (*arg_put)(void *, int, void *, int, char *), + void *puthook) +{ + + /* + * We need some way to output things; we can't do it without + * the arg_put function. + */ + if (arg_put == NULL) + return (-1); + + return (do_buff_decode(csio->data_ptr, (size_t)csio->dxfer_len, + arg_put, puthook, fmt, NULL)); +} + +int +buff_decode(uint8_t *buff, size_t len, const char *fmt, ...) +{ + va_list ap; + int retval; + + va_start(ap, fmt); + + retval = do_buff_decode(buff, len, NULL, NULL, fmt, &ap); + + va_end(ap); + + return (retval); +} + +int +buff_decode_visit(uint8_t *buff, size_t len, const char *fmt, + void (*arg_put)(void *, int, void *, int, char *), + void *puthook) +{ + + /* + * We need some way to output things; we can't do it without + * the arg_put function. + */ + if (arg_put == NULL) + return (-1); + + return (do_buff_decode(buff, len, arg_put, puthook, fmt, NULL)); +} + +/* + * Build a SCSI CCB, given the command and data pointers and a format + * string describing the + */ +int +csio_build(struct ccb_scsiio *csio, uint8_t *data_ptr, uint32_t dxfer_len, + uint32_t flags, int retry_count, int timeout, const char *cmd_spec, + ...) +{ + size_t cmdlen; + int retval; + va_list ap; + + if (csio == NULL) + return (0); + + bzero(csio, sizeof(struct ccb_scsiio)); + + va_start(ap, cmd_spec); + + if ((retval = do_encode(csio->cdb_io.cdb_bytes, SCSI_MAX_CDBLEN, + &cmdlen, NULL, NULL, cmd_spec, &ap)) == -1) + goto done; + + cam_fill_csio(csio, + /* retries */ retry_count, + /* cbfcnp */ NULL, + /* flags */ flags, + /* tag_action */ MSG_SIMPLE_Q_TAG, + /* data_ptr */ data_ptr, + /* dxfer_len */ dxfer_len, + /* sense_len */ SSD_FULL_SIZE, + /* cdb_len */ cmdlen, + /* timeout */ timeout ? timeout : 5000); + +done: + va_end(ap); + + return (retval); +} + +int +csio_build_visit(struct ccb_scsiio *csio, uint8_t *data_ptr, + uint32_t dxfer_len, uint32_t flags, int retry_count, + int timeout, const char *cmd_spec, + int (*arg_get)(void *hook, char *field_name), void *gethook) +{ + size_t cmdlen; + int retval; + + if (csio == NULL) + return (0); + + /* + * We need something to encode, but we can't get it without the + * arg_get function. + */ + if (arg_get == NULL) + return (-1); + + bzero(csio, sizeof(struct ccb_scsiio)); + + if ((retval = do_encode(csio->cdb_io.cdb_bytes, SCSI_MAX_CDBLEN, + &cmdlen, arg_get, gethook, cmd_spec, NULL)) == -1) + return (retval); + + cam_fill_csio(csio, + /* retries */ retry_count, + /* cbfcnp */ NULL, + /* flags */ flags, + /* tag_action */ MSG_SIMPLE_Q_TAG, + /* data_ptr */ data_ptr, + /* dxfer_len */ dxfer_len, + /* sense_len */ SSD_FULL_SIZE, + /* cdb_len */ cmdlen, + /* timeout */ timeout ? timeout : 5000); + + return (retval); +} + +int +csio_encode(struct ccb_scsiio *csio, const char *fmt, ...) +{ + va_list ap; + int retval; + + if (csio == NULL) + return (0); + + va_start(ap, fmt); + + retval = do_encode(csio->data_ptr, csio->dxfer_len, NULL, NULL, NULL, + fmt, &ap); + + va_end(ap); + + return (retval); +} + +int +buff_encode_visit(uint8_t *buff, size_t len, const char *fmt, + int (*arg_get)(void *hook, char *field_name), void *gethook) +{ + + /* + * We need something to encode, but we can't get it without the + * arg_get function. + */ + if (arg_get == NULL) + return (-1); + + return (do_encode(buff, len, NULL, arg_get, gethook, fmt, NULL)); +} + +int +csio_encode_visit(struct ccb_scsiio *csio, const char *fmt, + int (*arg_get)(void *hook, char *field_name), void *gethook) +{ + + /* + * We need something to encode, but we can't get it without the + * arg_get function. + */ + if (arg_get == NULL) + return (-1); + + return (do_encode(csio->data_ptr, csio->dxfer_len, NULL, arg_get, + gethook, fmt, NULL)); +} diff --git a/lib/libcam/scsi_wrap.c b/lib/libcam/scsi_wrap.c new file mode 100644 index 000000000000..584f760bcc42 --- /dev/null +++ b/lib/libcam/scsi_wrap.c @@ -0,0 +1,178 @@ +/*- + * Copyright (c) 2021 Netflix, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* + * Wrapper functions to make requests and get answers w/o managing the + * details. + */ + +#include <sys/types.h> + +#include <err.h> +#include <stdio.h> +#include <stdlib.h> +#include <strings.h> + +#include <cam/cam.h> +#include <cam/cam_ccb.h> +#include <cam/scsi/scsi_all.h> +#include <cam/scsi/scsi_pass.h> +#include <cam/scsi/scsi_message.h> +#include "camlib.h" +#include "scsi_wrap.h" + +void * +scsi_wrap_get_physical_element_status(struct cam_device *device, int task_attr, int retry_count, + int timeout, uint8_t report_type, uint32_t start_element) +{ + uint32_t allocation_length; + union ccb *ccb = NULL; + struct scsi_get_physical_element_hdr *hdr = NULL; + uint32_t dtors; + uint32_t reported; + + ccb = cam_getccb(device); + if (ccb == NULL) { + warnx("Can't allocate ccb"); + return (NULL); + } + + /* + * Do the request up to twice. Once to get the length and once to get + * the data. We'll guess that 4096 is enough to almost always long + * enough since that's 127 entries and most drives have < 20 heads. If + * by chance it's not, then we'll loop once as we'll then know the + * proper length. + */ + allocation_length = MAX(sizeof(*hdr), 4096); +again: + free(hdr); + hdr = calloc(allocation_length, 1); + if (hdr == NULL) { + warnx("Can't allocate memory for physical element list"); + return (NULL); + } + + scsi_get_physical_element_status(&ccb->csio, + retry_count, + NULL, + task_attr, + (uint8_t *)hdr, + allocation_length, + report_type, + start_element, + SSD_FULL_SIZE, + timeout); + + /* Disable freezing the device queue */ + ccb->ccb_h.flags |= CAM_DEV_QFRZDIS; + + if (cam_send_ccb(device, ccb) < 0) { + warn("error sending GET PHYSICAL ELEMENT STATUS command"); + goto errout; + } + + if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) { + cam_error_print(device, ccb, CAM_ESF_ALL, + CAM_EPF_ALL, stderr); + goto errout; + } + + dtors = scsi_4btoul(hdr->num_descriptors); + reported = scsi_4btoul(hdr->num_returned); + if (dtors != 0 && dtors != reported) { + /* + * Get all the data... in the future we may need to step through + * a long list, but so far all drives I've found fit into one + * response. A 4k transfer can do 128 heads and current designs + * have 16. + */ + allocation_length = dtors * sizeof(struct scsi_get_physical_element_descriptor) + + sizeof(*hdr); + goto again; + } + cam_freeccb(ccb); + return (hdr); +errout: + cam_freeccb(ccb); + free(hdr); + return (NULL); +} + +void * +scsi_wrap_inquiry(struct cam_device *device, uint32_t page, uint32_t length) +{ + union ccb *ccb; + uint8_t *buf; + + ccb = cam_getccb(device); + + if (ccb == NULL) + return (NULL); + + buf = malloc(length); + + if (buf == NULL) { + cam_freeccb(ccb); + return (NULL); + } + + scsi_inquiry(&ccb->csio, + /*retries*/ 0, + /*cbfcnp*/ NULL, + /* tag_action */ MSG_SIMPLE_Q_TAG, + /* inq_buf */ (uint8_t *)buf, + /* inq_len */ length, + /* evpd */ 1, + /* page_code */ page, + /* sense_len */ SSD_FULL_SIZE, + /* timeout */ 5000); + + /* Disable freezing the device queue */ + ccb->ccb_h.flags |= CAM_DEV_QFRZDIS; + // ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER; + + if (cam_send_ccb(device, ccb) < 0) { + warn("error sending INQUIRY command"); + cam_freeccb(ccb); + free(buf); + return (NULL); + } + + if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) { + free(buf); + buf = NULL; + } + cam_freeccb(ccb); + return (buf); +} + +struct scsi_vpd_block_device_characteristics * +scsi_wrap_vpd_block_device_characteristics(struct cam_device *device) +{ + + return ((struct scsi_vpd_block_device_characteristics *)scsi_wrap_inquiry( + device, SVPD_BDC, sizeof(struct scsi_vpd_block_device_characteristics))); +} diff --git a/lib/libcam/scsi_wrap.h b/lib/libcam/scsi_wrap.h new file mode 100644 index 000000000000..f61cafd60ec1 --- /dev/null +++ b/lib/libcam/scsi_wrap.h @@ -0,0 +1,36 @@ +/*- + * Copyright (c) 2021 Netflix, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#ifndef _CAM_SCSI_WRAP_H +#define _CAM_SCSI_WRAP_H + +void *scsi_wrap_get_physical_element_status(struct cam_device *device, + int task_attr, int retry_count, int timeout, uint8_t report_type, + uint32_t start_element); +void *scsi_wrap_inquiry(struct cam_device *device, uint32_t page, uint32_t length); +struct scsi_vpd_block_device_characteristics *scsi_wrap_vpd_block_device_characteristics( + struct cam_device *device); + +#endif /* _CAM_SCSI_WRAP_H */ diff --git a/lib/libcam/tests/Makefile b/lib/libcam/tests/Makefile new file mode 100644 index 000000000000..a1726638fdc9 --- /dev/null +++ b/lib/libcam/tests/Makefile @@ -0,0 +1,6 @@ +ATF_TESTS_C+= libcam_test +ATF_TESTS_C+= cam_test + +LIBADD+= cam + +.include <bsd.test.mk> diff --git a/lib/libcam/tests/Makefile.depend b/lib/libcam/tests/Makefile.depend new file mode 100644 index 000000000000..be9c511c0669 --- /dev/null +++ b/lib/libcam/tests/Makefile.depend @@ -0,0 +1,19 @@ +# Autogenerated - do NOT edit! + +DIRDEPS = \ + gnu/lib/csu \ + include \ + include/xlocale \ + lib/${CSU_DIR} \ + lib/atf/libatf-c \ + lib/libc \ + lib/libcam \ + lib/libcompiler_rt \ + lib/libsbuf \ + + +.include <dirdeps.mk> + +.if ${DEP_RELDIR} == ${_DEP_RELDIR} +# local dependencies - needed for -jN in clean tree +.endif diff --git a/lib/libcam/tests/cam_test.c b/lib/libcam/tests/cam_test.c new file mode 100644 index 000000000000..6c9fda40d43c --- /dev/null +++ b/lib/libcam/tests/cam_test.c @@ -0,0 +1,109 @@ +/*- + * Copyright (c) 2017 Spectra Logic Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* Tests functions in sys/cam/cam.c */ + +#include <sys/cdefs.h> +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <camlib.h> + +#include <atf-c.h> + +#define ATF_CHECK_NE(x, y) ATF_CHECK((x) != (y)) + +ATF_TC_WITHOUT_HEAD(cam_strmatch); +ATF_TC_BODY(cam_strmatch, tc) +{ + /* Basic fixed patterns */ + ATF_CHECK_EQ(0, cam_strmatch("foo", "foo", 3)); + ATF_CHECK_NE(0, cam_strmatch("foo", "bar", 3)); + ATF_CHECK_NE(0, cam_strmatch("foo", "foobar", 3)); + + /* The str is not necessarily null-terminated */ + ATF_CHECK_EQ(0, cam_strmatch("fooxuehfxeuf", "foo", 3)); + ATF_CHECK_NE(0, cam_strmatch("foo\0bar", "foo", 7)); + + /* Eat trailing spaces, which get added by SAT */ + ATF_CHECK_EQ(0, cam_strmatch("foo ", "foo", 16)); + + /* '*' matches everything, like shell globbing */ + ATF_CHECK_EQ(0, cam_strmatch("foobar", "foo*", 6)); + ATF_CHECK_EQ(0, cam_strmatch("foobar", "*bar", 6)); + ATF_CHECK_NE(0, cam_strmatch("foobar", "foo*x", 6)); + ATF_CHECK_EQ(0, cam_strmatch("foobarbaz", "*bar*", 9)); + /* Even NUL */ + ATF_CHECK_EQ(0, cam_strmatch("foo\0bar", "foo*", 7)); + /* Or nothing */ + ATF_CHECK_EQ(0, cam_strmatch("foo", "foo*", 3)); + /* But stuff after the * still must match */ + ATF_CHECK_NE(0, cam_strmatch("foo", "foo*x", 3)); + + /* '?' matches exactly one single character */ + ATF_CHECK_EQ(0, cam_strmatch("foobar", "foo?ar", 6)); + ATF_CHECK_NE(0, cam_strmatch("foo", "foo?", 3)); + /* Even NUL */ + ATF_CHECK_EQ(0, cam_strmatch("foo\0bar", "foo?bar", 7)); + + /* '[]' contains a set of characters */ + ATF_CHECK_EQ(0, cam_strmatch("foobar", "foo[abc]ar", 6)); + ATF_CHECK_EQ(0, cam_strmatch("foobar", "foo[b]ar", 6)); + ATF_CHECK_NE(0, cam_strmatch("foobar", "foo[ac]ar", 6)); + + /* '[]' can contain a range of characters, too */ + ATF_CHECK_EQ(0, cam_strmatch("foobar", "foo[a-c]ar", 6)); + ATF_CHECK_EQ(0, cam_strmatch("fooxar", "foo[a-cx]ar", 6)); + ATF_CHECK_NE(0, cam_strmatch("foodar", "foo[a-c]ar", 6)); + + /* Back-to-back '[]' character sets */ + ATF_CHECK_EQ(0, cam_strmatch("foobar", "fo[a-z][abc]ar", 6)); + ATF_CHECK_NE(0, cam_strmatch("foAbar", "fo[a-z][abc]ar", 6)); + ATF_CHECK_NE(0, cam_strmatch("foodar", "fo[a-z][abc]ar", 6)); + + /* A '^' negates a set of characters */ + ATF_CHECK_NE(0, cam_strmatch("foobar", "foo[^abc]ar", 6)); + ATF_CHECK_NE(0, cam_strmatch("foobar", "foo[^b]ar", 6)); + ATF_CHECK_EQ(0, cam_strmatch("foobar", "foo[^ac]ar", 6)); + ATF_CHECK_NE(0, cam_strmatch("foobar", "foo[^a-c]ar", 6)); + ATF_CHECK_NE(0, cam_strmatch("fooxar", "foo[^a-cx]ar", 6)); + ATF_CHECK_EQ(0, cam_strmatch("foodar", "foo[^a-c]ar", 6)); + + /* Outside of '[]' a ']' is just an ordinary character */ + ATF_CHECK_EQ(0, cam_strmatch("f]o", "f]o", 3)); + ATF_CHECK_NE(0, cam_strmatch("foo", "f]o", 3)); + + /* Matching a literal '[' requires specifying a range */ + ATF_CHECK_EQ(0, cam_strmatch("f[o", "f[[]o", 3)); + ATF_CHECK_NE(0, cam_strmatch("foo", "f[[]o", 3)); +} + +ATF_TP_ADD_TCS(tp) +{ + ATF_TP_ADD_TC(tp, cam_strmatch); + + return (atf_no_error()); +} diff --git a/lib/libcam/tests/libcam_test.c b/lib/libcam/tests/libcam_test.c new file mode 100644 index 000000000000..912f62c42c6c --- /dev/null +++ b/lib/libcam/tests/libcam_test.c @@ -0,0 +1,319 @@ +/*- + * Copyright (c) 2017 Enji Cooper <ngie@freebsd.org> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* Tests functions in lib/libcam/camlib.c */ + +#include <sys/cdefs.h> +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <camlib.h> + +#include <atf-c.h> + +static const char * +get_cam_test_device(const atf_tc_t *tc) +{ + const char *cam_test_device; + + cam_test_device = atf_tc_get_config_var(tc, "cam_test_device"); + + return (cam_test_device); +} + +static void +cam_clear_error(void) +{ + + strcpy(cam_errbuf, ""); +} + +static bool +cam_has_error(void) +{ + + return (strlen(cam_errbuf) != 0); +} + +ATF_TC_WITHOUT_HEAD(cam_get_device_negative_test_NULL_path); +ATF_TC_BODY(cam_get_device_negative_test_NULL_path, tc) +{ + char parsed_dev_name[DEV_IDLEN + 1]; + int parsed_unit; + + ATF_REQUIRE_MSG(cam_get_device(NULL, parsed_dev_name, + nitems(parsed_dev_name), &parsed_unit) == -1, + "cam_get_device succeeded unexpectedly"); +} + +ATF_TC_WITHOUT_HEAD(cam_get_device_negative_test_bad_path); +ATF_TC_BODY(cam_get_device_negative_test_bad_path, tc) +{ + char parsed_dev_name[DEV_IDLEN + 1]; + int parsed_unit; + + ATF_REQUIRE_MSG(cam_get_device("1ada", parsed_dev_name, + nitems(parsed_dev_name), &parsed_unit) == -1, + "cam_get_device succeeded unexpectedly"); +} + +ATF_TC_WITHOUT_HEAD(cam_get_device_negative_test_nul_path); +ATF_TC_BODY(cam_get_device_negative_test_nul_path, tc) +{ + char parsed_dev_name[DEV_IDLEN + 1]; + int parsed_unit; + + ATF_REQUIRE_MSG(cam_get_device("", parsed_dev_name, + nitems(parsed_dev_name), &parsed_unit) == -1, + "cam_get_device succeeded unexpectedly"); +} + +ATF_TC_WITHOUT_HEAD(cam_get_device_negative_test_root); +ATF_TC_BODY(cam_get_device_negative_test_root, tc) +{ + char parsed_dev_name[DEV_IDLEN + 1]; + int parsed_unit; + + ATF_REQUIRE_MSG(cam_get_device("/", parsed_dev_name, + nitems(parsed_dev_name), &parsed_unit) == -1, + "cam_get_device succeeded unexpectedly"); +} + +ATF_TC_WITHOUT_HEAD(cam_get_device_positive_test); +ATF_TC_BODY(cam_get_device_positive_test, tc) +{ + char expected_dev_name[] = "foo"; + char parsed_dev_name[DEV_IDLEN + 1]; + int expected_unit, parsed_unit; + + expected_unit = 1; + + ATF_REQUIRE_MSG(cam_get_device("/dev/foo1", parsed_dev_name, + nitems(parsed_dev_name), &parsed_unit) == 0, + "cam_get_device failed"); + ATF_REQUIRE_STREQ(parsed_dev_name, expected_dev_name); + ATF_REQUIRE(parsed_unit == expected_unit); + + strcpy(parsed_dev_name, ""); + parsed_unit = -1; + + ATF_REQUIRE_MSG(cam_get_device("foo1", parsed_dev_name, + nitems(parsed_dev_name), &parsed_unit) == 0, + "cam_get_device failed"); + ATF_REQUIRE_STREQ(parsed_dev_name, expected_dev_name); + ATF_REQUIRE(parsed_unit == expected_unit); +} + +/* + * sa(4) uniquely creates nsa and esa device nodes for non-rewind operations + * and eject-on-close operations. cam_get_device must special case these nodes + * to always return the base device. + */ +ATF_TC_WITHOUT_HEAD(cam_get_device_sa_test); +ATF_TC_BODY(cam_get_device_sa_test, tc) +{ + char parsed_dev_name[DEV_IDLEN + 1]; + int parsed_unit; + + ATF_REQUIRE_MSG(cam_get_device("nsa99", parsed_dev_name, + nitems(parsed_dev_name), &parsed_unit) == 0, + "cam_get_device failed"); + ATF_REQUIRE_STREQ(parsed_dev_name, "sa"); + ATF_REQUIRE(parsed_unit == 99); + + strcpy(parsed_dev_name, ""); + parsed_unit = -1; + + ATF_REQUIRE_MSG(cam_get_device("esa99", parsed_dev_name, + nitems(parsed_dev_name), &parsed_unit) == 0, + "cam_get_device failed"); + ATF_REQUIRE_STREQ(parsed_dev_name, "sa"); + ATF_REQUIRE(parsed_unit == 99); +} + +ATF_TC(cam_open_device_negative_test_O_RDONLY); +ATF_TC_HEAD(cam_open_device_negative_test_O_RDONLY, tc) +{ + + atf_tc_set_md_var(tc, "descr", + "test that cam_open_device(`cam_device`, O_RDONLY) fails to open " + "the underlying pass(4) device (bug 217649)"); + atf_tc_set_md_var(tc, "require.config", "cam_test_device"); + atf_tc_set_md_var(tc, "require.user", "root"); +} + +ATF_TC_BODY(cam_open_device_negative_test_O_RDONLY, tc) +{ + const char *cam_test_device; + + cam_test_device = get_cam_test_device(tc); + + cam_clear_error(); + ATF_CHECK(cam_open_device(cam_test_device, O_RDONLY) == NULL); + ATF_REQUIRE(cam_has_error()); +} + +ATF_TC(cam_open_device_negative_test_nonexistent); +ATF_TC_HEAD(cam_open_device_negative_test_nonexistent, tc) +{ + + atf_tc_set_md_var(tc, "require.user", "root"); +} + +ATF_TC_BODY(cam_open_device_negative_test_nonexistent, tc) +{ + + cam_clear_error(); + ATF_REQUIRE(cam_open_device("/nonexistent", O_RDWR) == NULL); + ATF_REQUIRE(cam_has_error()); +} + +ATF_TC(cam_open_device_negative_test_unprivileged); +ATF_TC_HEAD(cam_open_device_negative_test_unprivileged, tc) +{ + + atf_tc_set_md_var(tc, "require.config", "cam_test_device"); + atf_tc_set_md_var(tc, "require.user", "unprivileged"); +} + +ATF_TC_BODY(cam_open_device_negative_test_unprivileged, tc) +{ + const char *cam_test_device; + + cam_test_device = get_cam_test_device(tc); + + cam_clear_error(); + ATF_CHECK(cam_open_device(cam_test_device, O_RDONLY) == NULL); + ATF_REQUIRE(cam_has_error()); + + cam_clear_error(); + ATF_CHECK(cam_open_device(cam_test_device, O_RDWR) == NULL); + ATF_REQUIRE(cam_has_error()); +} + +ATF_TC(cam_open_device_positive_test); +ATF_TC_HEAD(cam_open_device_positive_test, tc) +{ + + atf_tc_set_md_var(tc, "require.config", "cam_test_device"); + atf_tc_set_md_var(tc, "require.user", "root"); +} + +ATF_TC_BODY(cam_open_device_positive_test, tc) +{ + struct cam_device *cam_dev; + const char *cam_test_device; + + cam_test_device = get_cam_test_device(tc); + + cam_clear_error(); + cam_dev = cam_open_device(cam_test_device, O_RDWR); + ATF_CHECK_MSG(cam_dev != NULL, "cam_open_device failed: %s", + cam_errbuf); + ATF_REQUIRE(!cam_has_error()); + cam_close_device(cam_dev); +} + +ATF_TC(cam_close_device_negative_test_NULL); +ATF_TC_HEAD(cam_close_device_negative_test_NULL, tc) +{ + + atf_tc_set_md_var(tc, "descr", + "test that cam_close_device(NULL) succeeds without error"); + atf_tc_set_md_var(tc, "require.user", "root"); +} + +ATF_TC_BODY(cam_close_device_negative_test_NULL, tc) +{ + + cam_clear_error(); + cam_close_device(NULL); + ATF_REQUIRE(!cam_has_error()); +} + +ATF_TC(cam_getccb_positive_test); +ATF_TC_HEAD(cam_getccb_positive_test, tc) +{ + + atf_tc_set_md_var(tc, "require.config", "cam_test_device"); + atf_tc_set_md_var(tc, "require.user", "root"); +} + +ATF_TC_BODY(cam_getccb_positive_test, tc) +{ + union ccb *cam_ccb; + struct cam_device *cam_dev; + const char *cam_test_device; + + cam_test_device = get_cam_test_device(tc); + + cam_clear_error(); + cam_dev = cam_open_device(cam_test_device, O_RDWR); + ATF_CHECK_MSG(cam_dev != NULL, "cam_open_device failed: %s", + cam_errbuf); + ATF_REQUIRE(!cam_has_error()); + cam_ccb = cam_getccb(cam_dev); + ATF_CHECK_MSG(cam_ccb != NULL, "get_camccb failed: %s", cam_errbuf); + ATF_REQUIRE(!cam_has_error()); + cam_freeccb(cam_ccb); + cam_close_device(cam_dev); +} + +ATF_TC(cam_freeccb_negative_test_NULL); +ATF_TC_HEAD(cam_freeccb_negative_test_NULL, tc) +{ + + atf_tc_set_md_var(tc, "descr", + "test that cam_freeccb(NULL) succeeds without error"); + atf_tc_set_md_var(tc, "require.user", "root"); +} + +ATF_TC_BODY(cam_freeccb_negative_test_NULL, tc) +{ + + cam_clear_error(); + cam_freeccb(NULL); + ATF_REQUIRE(!cam_has_error()); +} + +ATF_TP_ADD_TCS(tp) +{ + + ATF_TP_ADD_TC(tp, cam_get_device_negative_test_NULL_path); + ATF_TP_ADD_TC(tp, cam_get_device_negative_test_bad_path); + ATF_TP_ADD_TC(tp, cam_get_device_negative_test_nul_path); + ATF_TP_ADD_TC(tp, cam_get_device_negative_test_root); + ATF_TP_ADD_TC(tp, cam_get_device_positive_test); + ATF_TP_ADD_TC(tp, cam_get_device_sa_test); + ATF_TP_ADD_TC(tp, cam_open_device_negative_test_O_RDONLY); + ATF_TP_ADD_TC(tp, cam_open_device_negative_test_nonexistent); + ATF_TP_ADD_TC(tp, cam_open_device_negative_test_unprivileged); + ATF_TP_ADD_TC(tp, cam_open_device_positive_test); + ATF_TP_ADD_TC(tp, cam_close_device_negative_test_NULL); + ATF_TP_ADD_TC(tp, cam_getccb_positive_test); + ATF_TP_ADD_TC(tp, cam_freeccb_negative_test_NULL); + + return (atf_no_error()); +} |