📄 scsi2lib.c
字号:
/* scsi2Lib.c - Small Computer System Interface (SCSI) library (SCSI-2) *//* Copyright 1989-2002 Wind River Systems, Inc. */#include "copyright_wrs.h"/*modification history--------------------04l,07mar02,pmr SPR 73383: no division-by-zero in scsiTargetOptionsShow().04k,16oct01,pmr SPR 67310: turning off message-using options when messaging is turned off in scsiTargetOptionsSet().04j,08oct01,rcs tested for removable and medium not present in scsiPhysDevCreate() SPR# 3220304i,05oct01,rcs added display of ASCQ (Additional Sense Code Qualifier) to scsi2Transact() SCSI_DEBUG_MSGs. SPR# 29269 04h,03oct01,rcs clarified description of xferWidth in scsiTargetOptionsSet() SPR# 69003 04g,26sep01,rcs fixed scsi2PhysDevCreate() to use user specified `numBlocks' or `blockSize' SPR# 2263504f,26sep01,rcs fixed scsiTargetOptionsSet() to allow for narrow width to be explicitly set for a narrow target. SPR# 28262 04e,25sep01,rcs added routine scsiTargetOptionsShow() SPR# 6922304d,24sep01,rcs set errno for MEDIUM ERROR, HARDWARE ERROR, ILLEGAL REQUEST, BLANK CHECK, ABORTED COMMAND, and VOLUME OVERFLOW in switch statement in scsi2Transact(). SPR# 21236 04c,05oct98,jmp doc: cleanup.04b,28aug97,dds SPR 3425: "scsiFormatUnit" command, times out for disks which take a long time to format.04a,14aug97,dds Rework of SPR 8219.03z,28jul97,dds SPR 8219: switching from synch to async mode cause target to hang.03y,24jul97,dds SPR 8323 / 7838: scsiTargetOptionsGet returns "xferWidth"03x,10jul97,dds added library support for adaptec chips.03w,09jul97,dgp doc: correct fonts per SPR 785303v,28mar97,dds SPR 8220: added check for parity errors.03u,28oct96,dgp doc: editing for newly published SCSI libraries03t,21oct96,dds removed NOMANUAL for functions called from the driver interface.03s,14sep96,dds removed the scsiMgr and scsiCtrl functions. These functions are found in scsiMgrLib.c and scsiCtrlLib.c03r,30jul96,jds fixed scsiCacheSynchronize() to act on cache lines only03q,29jul96,jds added support for hardware snooping 03p,06may96,jds more doc tweaks03o,01may96,jds doc tweaks03n,22apr96,jds doc tweaks to describe WIDE transfers03m,20apr96,jds added WIDE data transfer support03l,25jan96,jds added scsiCtrl routine modifications based on SPARC/539003k,13nov95,jds minor document changes03j,08nov95,jds more doc cleanup03i,20sep95,jdi doc cleanup.03h,30aug95,jds bug fixes and cleanup. Bugs include several instances where function was returning with semaphore taken.03g,26jul95,jds added scsiReadBlockLimits in scsiPhysDevCreate for SEQ devs03f,25jul95,jds added support in scsiTransact for sequential devices. Created chkMedChangeAndWP (). Made appropriate changes in other routines as well.e.g scsiPhysDevCreate ()03e,19jul95,jds removed all SCSI direct access commands and put them in scsiDirectLib, also moved blkDev routines.03d,21mar95,ihw minor bug fixes in "scsiCtrl*()" routines03c,07oct94,ihw errno now set if sense data is unrecognised error message logged if max number of threads is reached03b,27may94,ihw documented prior to release03a,30mar94,ihw modified for enhanced SCSI library: tagged command queueing major architectural changes ... ABORT rather than REJECT used to reject invalid reselection removed redundant code for additional length in data in xfer fixed incorrect handling of ext msg in with zero length byte02b,25feb94,ihw fixed synchronous transfer message-in diagnostics02a,14jan94,ihw modified for enhanced SCSI library: multiple initiators, disconnect/reconnect and synchronous transfer supported "scsiSyncXferNegotiate()" made non-local for NCR driver01w,27nov92,jdi documentation cleanup, including SPR 1415.01v,15sep92,ccc reworked select timeout, fixed extended message to work with new drive, documentation changes.01u,10aug92,ccc added timeouts to scsiXaction for each scsi command.01t,28jul92,rrr fixed decl of scsiSyncTarget01s,22jul92,gae added correct number of parameters to logMsg().01r,20jul92,eve Remove conditional INCLUDE_SYNC_SCSI compilation.01q,18jul92,smb Changed errno.h to errnoLib.h.01p,13jul92,eve added init of the current pScsiXaction in scsiPhaseSequence().01o,08jul92,eve supplies a reqSense buffer if there is no user buffer in scsiTransact routine.01n,03jul92,eve added new sync feature with NOMANUAL01m,26may92,rrr the tree shuffle01l,16dec91,gae added includes for ANSI; added parameters to logMsg() calls.01k,19nov91,rrr shut up some ansi warnings.01j,04oct91,rrr passed through the ansification filter -changed functions to ansi style -changed READ, WRITE and UPDATE to O_RDONLY O_WRONLY and ... -changed VOID to void -changed copyright notice01i,13mar91,jcc misc. clean-up and enhancements.01h,25oct90,jcc lint.01g,18oct90,jcc removed call to printErrno() in scsiAutoConfig().01f,02oct90,jcc UTINY became UINT8; added scsiAutoConfig(), scsiPhysDevIdGet(), and scsiIoctl() option FIODISKFORMAT; changed all malloc()'s to calloc()'s in xxCreate() routines; made changes associated with SEM_ID's becoming SEMAPHORE's in created structures; enhanced scsiPhysDevCreate() to determine amount and type of REQUEST SENSE data returned by the device; miscellaneous.01e,10aug90,dnw fixed warnings caused by changing scsiBusReset to VOIDFUNCPTR.01d,18jul90,jcc made semTake() calls 5.0 compatible; clean-up.01c,08jun90,jcc modified incoming message handling; generalized scsiTransact calls to a procedure variable to allow off-board SCSI controller drivers; documentation.01b,23mar90,jcc lint.01a,05may89,jcc written.*//*DESCRIPTIONThis library implements the Small Computer System Interface (SCSI)protocol in a controller-independent manner. It implements only the SCSIinitiator function as defined in the SCSI-2 ANSI specification. This library does not support a VxWorks target acting as a SCSI target.The implementation is transaction based. A transaction is defined as theselection of a SCSI device by the initiator, the issuance of a SCSI command,and the sequence of data, status, and message phases necessary to performthe command. A transaction normally completes with a "Command Complete"message from the target, followed by disconnection from the SCSI bus. Ifthe status from the target is "Check Condition," the transactioncontinues; the initiator issues a "Request Sense" command to gain moreinformation on the exception condition reported.Many of the subroutines in scsi2Lib facilitate the transaction offrequently used SCSI commands. Individual command fields are passed asarguments from which SCSI Command Descriptor Blocks are constructed, andfields of a SCSI_TRANSACTION structure are filled in appropriately. Thisstructure, along with the SCSI_PHYS_DEV structure associated with thetarget SCSI device, is passed to the routine whose address is indicated bythe 'scsiTransact' field of the SCSI_CTRL structure associated with therelevant SCSI controller. The above mentioned structures are defined in scsi2Lib.h.The function variable 'scsiTransact' is set by the individual SCSIcontroller driver. For off-board SCSI controllers, thisroutine rearranges the fields of the SCSI_TRANSACTION structure intothe appropriate structure for the specified hardware, which then carries outthe transaction through firmware control. Drivers for an on-boardSCSI-controller chip can use the scsiTransact() routine in scsiLib (whichinvokes the scsi2Transact() routine in scsi2Lib), as long as they provide the other functions specified in the SCSI_CTRL structure.SCSI TRANSACTION TIMEOUTAssociated with each transaction is a time limit (specified in microseconds,but measured with the resolution of the system clock). If the transactionhas not completed within this time limit, the SCSI library aborts it; thecalled routine fails with a corresponding error code. The timeout periodincludes time spent waiting for the target device to become free to acceptthe command.The semantics of the timeout should guarantee that the caller waits no longer than the transaction timeout period, but in practice thismay depend on the state of the SCSI bus and the connected target device whenthe timeout occurs. If the target behaves correctly according to the SCSIspecification, proper timeout behavior results. However, in certainunusual cases--for example, when the target does not respond to an asserted ATN signal--the caller may remain blocked for longer than the timeout period.If the transaction timeout causes problems in your system, you can set thevalue of either or both the global variables "scsi{Min,Max}Timeout". Thesespecify (in microseconds) the global minimum and maximum timeout periods,which override (clip) the value specified for a transaction. They may bechanged at any time and affect all transactions issued after the newvalues are set. The range of both these variable is 0 to 0xffffffff (zero toabout 4295 seconds).SCSI TRANSACTION PRIORITYEach transaction also has an associated priority used by the SCSIlibrary when selecting the next command to issue when the SCSI system isidle. It chooses the highest priority transaction that can be dispatchedon an available physical device. If there are several equal-prioritytransactions available, the SCSI library uses a simple round-robinscheme to avoid favoring the same physical device.Priorities range from 0 (highest) to 255 (lowest), which is the same as taskpriorities. The priority SCSI_THREAD_TASK_PRIORITY can be used to give thetransaction the same priority as the calling task (this is the method usedinternally by this SCSI-2 library).SUPPORTED SCSI DEVICESThis library requires peripherals that conform to the SCSI-2 ANSIstandard; in particular, the INQUIRY, REQUEST SENSE, andTEST UNIT READY commands must be supported as specified by this standard.In general, the SCSI library is self-configuring to work with any devicethat meets these requirements.Peripherals that support identification and the SCSI message protocol arestrongly recommended as these provide maximum performance.In theory, all classes of SCSI devices are supported. The scsiLib libraryprovides the capability to transact any SCSI command on any SCSI devicethrough the FIOSCSICOMMAND function of the scsiIoctl() routine (which invokes the scsi2Ioctl() routine in scsi2Lib).Only direct-access devices (disks) are supported by file systems like dosFs, rt11Fs and rawFs. These file systems employ routines in scsiDirectLib (most of which are described in scsiLib but defined in scsiDirectLib). In the case of sequential-access devices (tapes), higher-leveltape file systems, like tapeFs, make use of scsiSeqLib. For other types of devices, additional, higher-level software is necessary to map user-levelcommands to SCSI transactions.DISCONNECT/RECONNECT SUPPORTThe target device can be disconnected from the SCSI bus while it carriesout a SCSI command; in this way, commands to multiple SCSI devices canbe overlapped to improve overall SCSI throughput. There are norestrictions on the number of pending, disconnected commands or theorder in which they are resumed. The SCSI library serializes access to thedevice according to the capabilities and status of the device (see thefollowing section).Use of the disconnect/reconnect mechanism is invisible to users of the SCSIlibrary. It can be enabled and disabled separately for each target device(see scsiTargetOptionsSet()). Note that support for disconnect/reconnectdepends on the capabilities of the controller and its driver (see below).TAGGED COMMAND QUEUEING SUPPORTIf the target device conforms to the ANSI SCSI-2 standard and indicates(using the INQUIRY command) that it supports command queuing, the SCSIlibrary allows new commands to be started on the device whenever the SCSIbus is idle. That is, it executes multiple commands concurrently on thetarget device. By default, commands are tagged with a SIMPLE QUEUE TAGmessage. Up to 256 commands can be executing concurrently.The SCSI library correctly handles contingent allegiance conditions thatarise while a device is executing tagged commands. (A contingentallegiance condition exists when a target device is maintaining sense data thatthe initiator should use to correctly recover from an error condition.) Itissues an untagged REQUEST SENSE command, and stops issuing tagged commandsuntil the sense recovery command has completed.For devices that do not support command queuing, the SCSI library onlyissues a new command when the previous one has completed. These devicescan only execute a single command at once.Use of tagged command queuing is normally invisible to users of the SCSIlibrary. If necessary, the default tag type and maximum number of tags maybe changed on a per-target basis, using scsiTargetOptionsSet().SYNCHRONOUS TRANSFER PROTOCOL SUPPORTIf the SCSI controller hardware supports the synchronous transferprotocol, scsiLib negotiates with the target device to determinewhether to use synchronous or asynchronous transfers. Either VxWorksor the target device may start a round of negotiation. Depending on thecontroller hardware, synchronous transfer rates up to the maximum allowedby the SCSI-2 standard (10 Mtransfers/second) can be used.Again, this is normally invisible to users of the SCSI library, butsynchronous transfer parameters may be set or disabled on a per-target basisby using scsiTargetOptionsSet().WIDE DATA TRANSFER SUPPORTIf the SCSI controller supports the wide data transfer protocol, scsiLibnegotiates wide data transfer parameters with the target device, ifthat device also supports wide transfers. Either VxWorks or the target devicemay start a round of negotiation. Wide data transfer parameters are negotiated prior to the synchronous data transfer parameters, as specified by the SCSI-2 ANSI specification. In conjunction withsynchronous transfer, up to a maximum of 20MB/sec. can be attained.Wide data transfer negotiation is invisible to users of this library,but it is possible to enable or disable wide data transfers and theparameters on a per-target basis by using scsiTargetOptionsSet().SCSI BUS RESETThe SCSI library implements the ANSI "hard reset" option. Any transactionsin progress when a SCSI bus reset is detected fail with an error codeindicating termination due to bus reset. Any transactions waiting to startexecuting are then started normally.CONFIGURING SCSI CONTROLLERSThe routines to create and initialize a specific SCSI controller areparticular to the controller and normally are found in its librarymodule. The normal calling sequence is:.ne 4.CS xxCtrlCreate (...); /@ parameters are controller specific @/ xxCtrlInit (...); /@ parameters are controller specific @/.CEThe conceptual difference between the two routines is that xxCtrlCreate()calloc's memory for the xx_SCSI_CTRL data structure and initializesinformation that is never expected to change (for example, clock rate). Theremaining fields in the xx_SCSI_CTRL structure are initialized byxxCtrlInit() and any necessary registers are written on the SCSIcontroller to effect the desired initialization. This routine can becalled multiple times, although this is rarely required. For example, thebus ID of the SCSI controller can be changed without rebooting the VxWorkssystem.CONFIGURING PHYSICAL SCSI DEVICESBefore a device can be used, it must be "created," that is, declared.This is done with scsiPhysDevCreate() and can only be done after aSCSI_CTRL structure exists and has been properly initialized..CSSCSI_PHYS_DEV *scsiPhysDevCreate ( SCSI_CTRL * pScsiCtrl,/@ ptr to SCSI controller info @/ int devBusId, /@ device's SCSI bus ID @/ int devLUN, /@ device's logical unit number @/ int reqSenseLength, /@ length of REQUEST SENSE data dev returns @/ int devType, /@ type of SCSI device @/ BOOL removable, /@ whether medium is removable @/ int numBlocks, /@ number of blocks on device @/ int blockSize /@ size of a block in bytes @/ ).CESeveral of these parameters can be left unspecified, as follows:.iP <reqSenseLength>If 0, issue a REQUEST_SENSE to determine a request sense length..iP <devType>This parameter is ignored: an INQUIRY command is used to ascertain thedevice type. A value of NONE (-1) is the recommended placeholder..iP "<numBlocks>, <blockSize>"If 0, issue a READ_CAPACITY to determine the number of blocks..LPThe above values are recommended, unless the device does not support therequired commands, or other non-standard conditions prevail.LOGICAL PARTITIONS ON DIRECT-ACCESS BLOCK DEVICESIt is possible to have more than one logical partition on a SCSI blockdevice. This capability is currently not supported for removable mediadevices. A partition is an array of contiguously addressed blockswith a specified starting block address and specified number of blocks.The scsiBlkDevCreate() routine is called once for each block devicepartition. Under normal usage, logical partitions should not overlap..ne 8.CSSCSI_BLK_DEV *scsiBlkDevCreate ( SCSI_PHYS_DEV * pScsiPhysDev, /@ ptr to SCSI physical device info @/ int numBlocks, /@ number of blocks in block device @/ int blockOffset /@ address of first block in volume @/ ).CENote that if <numBlocks> is 0, the rest of the device is used.ATTACHING DISK FILE SYSTEMS TO LOGICAL PARTITIONSFiles cannot be read or written to a disk partition until a file system (forexample, dosFs, rt11Fs, or rawFs) has been initialized on the partition.For more information, see the relevant documentation in dosFsLib,rt11FsLib, or rawFsLib.USING A SEQUENTIAL-ACCESS BLOCK DEVICEThe entire volume (tape) on a sequential-access block device is treated as a single raw file. This raw file is made available to higher-level layerslike tapeFs by the scsiSeqDevCreate() routine, described in scsiSeqLib. ThescsiSeqDevCreate() routine is called once for a given SCSI physical device..CSSEQ_DEV *scsiSeqDevCreate ( SCSI_PHYS_DEV *pScsiPhysDev /@ ptr to SCSI physical device info @/ ).CETRANSMITTING ARBITRARY COMMANDS TO SCSI DEVICESThe scsi2Lib, scsiCommonLib, scsiDirectLib, and scsiSeqLib libraries collectively provide routines that implement all mandatory SCSI-2 direct-access and sequential-access commands. Still, there are situations thatrequire commands that are not supported by these libraries (for example, writing software that needs to use an optional SCSI-2 command).Arbitrary commands are handled with the FIOSCSICOMMAND option toscsiIoctl(). The <arg> parameter for FIOSCSICOMMAND is a pointer to avalid SCSI_TRANSACTION structure. Typically, a call to scsiIoctl() is writtenas a subroutine of the form:.CS
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -