1303 lines · plain
1.. SPDX-License-Identifier: GPL-2.02 3=============================================4SCSI mid_level - lower_level driver interface5=============================================6 7Introduction8============9This document outlines the interface between the Linux SCSI mid level and10SCSI lower level drivers. Lower level drivers (LLDs) are variously called11host bus adapter (HBA) drivers and host drivers (HD). A "host" in this12context is a bridge between a computer IO bus (e.g. PCI or ISA) and a13single SCSI initiator port on a SCSI transport. An "initiator" port14(SCSI terminology, see SAM-3 at http://www.t10.org) sends SCSI commands15to "target" SCSI ports (e.g. disks). There can be many LLDs in a running16system, but only one per hardware type. Most LLDs can control one or more17SCSI HBAs. Some HBAs contain multiple hosts.18 19In some cases the SCSI transport is an external bus that already has20its own subsystem in Linux (e.g. USB and ieee1394). In such cases the21SCSI subsystem LLD is a software bridge to the other driver subsystem.22Examples are the usb-storage driver (found in the drivers/usb/storage23directory) and the ieee1394/sbp2 driver (found in the drivers/ieee139424directory).25 26For example, the aic7xxx LLD controls Adaptec SCSI parallel interface27(SPI) controllers based on that company's 7xxx chip series. The aic7xxx28LLD can be built into the kernel or loaded as a module. There can only be29one aic7xxx LLD running in a Linux system but it may be controlling many30HBAs. These HBAs might be either on PCI daughter-boards or built into31the motherboard (or both). Some aic7xxx based HBAs are dual controllers32and thus represent two hosts. Like most modern HBAs, each aic7xxx host33has its own PCI device address. [The one-to-one correspondence between34a SCSI host and a PCI device is common but not required (e.g. with35ISA adapters).]36 37The SCSI mid level isolates an LLD from other layers such as the SCSI38upper layer drivers and the block layer.39 40This version of the document roughly matches linux kernel version 2.6.8 .41 42Documentation43=============44There is a SCSI documentation directory within the kernel source tree,45typically Documentation/scsi . Most documents are in reStructuredText46format. This file is named scsi_mid_low_api.rst and can be47found in that directory. A more recent copy of this document may be found48at https://docs.kernel.org/scsi/scsi_mid_low_api.html. Many LLDs are49documented in Documentation/scsi (e.g. aic7xxx.rst). The SCSI mid-level is50briefly described in scsi.rst which contains a URL to a document describing51the SCSI subsystem in the Linux Kernel 2.4 series. Two upper level52drivers have documents in that directory: st.rst (SCSI tape driver) and53scsi-generic.rst (for the sg driver).54 55Some documentation (or URLs) for LLDs may be found in the C source code56or in the same directory as the C source code. For example to find a URL57about the USB mass storage driver see the58/usr/src/linux/drivers/usb/storage directory.59 60Driver structure61================62Traditionally an LLD for the SCSI subsystem has been at least two files in63the drivers/scsi directory. For example, a driver called "xyz" has a header64file "xyz.h" and a source file "xyz.c". [Actually there is no good reason65why this couldn't all be in one file; the header file is superfluous.] Some66drivers that have been ported to several operating systems have more than67two files. For example the aic7xxx driver has separate files for generic68and OS-specific code (e.g. FreeBSD and Linux). Such drivers tend to have69their own directory under the drivers/scsi directory.70 71When a new LLD is being added to Linux, the following files (found in the72drivers/scsi directory) will need some attention: Makefile and Kconfig .73It is probably best to study how existing LLDs are organized.74 75As the 2.5 series development kernels evolve into the 2.6 series76production series, changes are being introduced into this interface. An77example of this is driver initialization code where there are now 2 models78available. The older one, similar to what was found in the lk 2.4 series,79is based on hosts that are detected at HBA driver load time. This will be80referred to the "passive" initialization model. The newer model allows HBAs81to be hot plugged (and unplugged) during the lifetime of the LLD and will82be referred to as the "hotplug" initialization model. The newer model is83preferred as it can handle both traditional SCSI equipment that is84permanently connected as well as modern "SCSI" devices (e.g. USB or85IEEE 1394 connected digital cameras) that are hotplugged. Both86initialization models are discussed in the following sections.87 88An LLD interfaces to the SCSI subsystem several ways:89 90 a) directly invoking functions supplied by the mid level91 b) passing a set of function pointers to a registration function92 supplied by the mid level. The mid level will then invoke these93 functions at some point in the future. The LLD will supply94 implementations of these functions.95 c) direct access to instances of well known data structures maintained96 by the mid level97 98Those functions in group a) are listed in a section entitled "Mid level99supplied functions" below.100 101Those functions in group b) are listed in a section entitled "Interface102functions" below. Their function pointers are placed in the members of103"struct scsi_host_template", an instance of which is passed to104scsi_host_alloc() [#]_. Those interface functions that the LLD does not105wish to supply should have NULL placed in the corresponding member of106struct scsi_host_template. Defining an instance of struct107scsi_host_template at file scope will cause NULL to be placed in function108pointer members not explicitly initialized.109 110Those usages in group c) should be handled with care, especially in a111"hotplug" environment. LLDs should be aware of the lifetime of instances112that are shared with the mid level and other layers.113 114All functions defined within an LLD and all data defined at file scope115should be static. For example the slave_alloc() function in an LLD116called "xxx" could be defined as117``static int xxx_slave_alloc(struct scsi_device * sdev) { /* code */ }``118 119.. [#] the scsi_host_alloc() function is a replacement for the rather vaguely120 named scsi_register() function in most situations.121 122 123Hotplug initialization model124============================125In this model an LLD controls when SCSI hosts are introduced and removed126from the SCSI subsystem. Hosts can be introduced as early as driver127initialization and removed as late as driver shutdown. Typically a driver128will respond to a sysfs probe() callback that indicates an HBA has been129detected. After confirming that the new device is one that the LLD wants130to control, the LLD will initialize the HBA and then register a new host131with the SCSI mid level.132 133During LLD initialization the driver should register itself with the134appropriate IO bus on which it expects to find HBA(s) (e.g. the PCI bus).135This can probably be done via sysfs. Any driver parameters (especially136those that are writable after the driver is loaded) could also be137registered with sysfs at this point. The SCSI mid level first becomes138aware of an LLD when that LLD registers its first HBA.139 140At some later time, the LLD becomes aware of an HBA and what follows141is a typical sequence of calls between the LLD and the mid level.142This example shows the mid level scanning the newly introduced HBA for 3143scsi devices of which only the first 2 respond::144 145 HBA PROBE: assume 2 SCSI devices found in scan146 LLD mid level LLD147 ===-------------------=========--------------------===------148 scsi_host_alloc() -->149 scsi_add_host() ---->150 scsi_scan_host() -------+151 |152 slave_alloc()153 slave_configure() --> scsi_change_queue_depth()154 |155 slave_alloc()156 slave_configure()157 |158 slave_alloc() ***159 slave_destroy() ***160 161 162 *** For scsi devices that the mid level tries to scan but do not163 respond, a slave_alloc(), slave_destroy() pair is called.164 165If the LLD wants to adjust the default queue settings, it can invoke166scsi_change_queue_depth() in its slave_configure() routine.167 168When an HBA is being removed it could be as part of an orderly shutdown169associated with the LLD module being unloaded (e.g. with the "rmmod"170command) or in response to a "hot unplug" indicated by sysfs()'s171remove() callback being invoked. In either case, the sequence is the172same::173 174 HBA REMOVE: assume 2 SCSI devices attached175 LLD mid level LLD176 ===----------------------=========-----------------===------177 scsi_remove_host() ---------+178 |179 slave_destroy()180 slave_destroy()181 scsi_host_put()182 183It may be useful for a LLD to keep track of struct Scsi_Host instances184(a pointer is returned by scsi_host_alloc()). Such instances are "owned"185by the mid-level. struct Scsi_Host instances are freed from186scsi_host_put() when the reference count hits zero.187 188Hot unplugging an HBA that controls a disk which is processing SCSI189commands on a mounted file system is an interesting situation. Reference190counting logic is being introduced into the mid level to cope with many191of the issues involved. See the section on reference counting below.192 193 194The hotplug concept may be extended to SCSI devices. Currently, when an195HBA is added, the scsi_scan_host() function causes a scan for SCSI devices196attached to the HBA's SCSI transport. On newer SCSI transports the HBA197may become aware of a new SCSI device _after_ the scan has completed.198An LLD can use this sequence to make the mid level aware of a SCSI device::199 200 SCSI DEVICE hotplug201 LLD mid level LLD202 ===-------------------=========--------------------===------203 scsi_add_device() ------+204 |205 slave_alloc()206 slave_configure() [--> scsi_change_queue_depth()]207 208In a similar fashion, an LLD may become aware that a SCSI device has been209removed (unplugged) or the connection to it has been interrupted. Some210existing SCSI transports (e.g. SPI) may not become aware that a SCSI211device has been removed until a subsequent SCSI command fails which will212probably cause that device to be set offline by the mid level. An LLD that213detects the removal of a SCSI device can instigate its removal from214upper layers with this sequence::215 216 SCSI DEVICE hot unplug217 LLD mid level LLD218 ===----------------------=========-----------------===------219 scsi_remove_device() -------+220 |221 slave_destroy()222 223It may be useful for an LLD to keep track of struct scsi_device instances224(a pointer is passed as the parameter to slave_alloc() and225slave_configure() callbacks). Such instances are "owned" by the mid-level.226struct scsi_device instances are freed after slave_destroy().227 228 229Reference Counting230==================231The Scsi_Host structure has had reference counting infrastructure added.232This effectively spreads the ownership of struct Scsi_Host instances233across the various SCSI layers which use them. Previously such instances234were exclusively owned by the mid level. LLDs would not usually need to235directly manipulate these reference counts but there may be some cases236where they do.237 238There are 3 reference counting functions of interest associated with239struct Scsi_Host:240 241 - scsi_host_alloc():242 returns a pointer to new instance of struct243 Scsi_Host which has its reference count ^^ set to 1244 245 - scsi_host_get():246 adds 1 to the reference count of the given instance247 248 - scsi_host_put():249 decrements 1 from the reference count of the given250 instance. If the reference count reaches 0 then the given instance251 is freed252 253The scsi_device structure has had reference counting infrastructure added.254This effectively spreads the ownership of struct scsi_device instances255across the various SCSI layers which use them. Previously such instances256were exclusively owned by the mid level. See the access functions declared257towards the end of include/scsi/scsi_device.h . If an LLD wants to keep258a copy of a pointer to a scsi_device instance it should use scsi_device_get()259to bump its reference count. When it is finished with the pointer it can260use scsi_device_put() to decrement its reference count (and potentially261delete it).262 263.. Note::264 265 struct Scsi_Host actually has 2 reference counts which are manipulated266 in parallel by these functions.267 268 269Conventions270===========271First, Linus Torvalds's thoughts on C coding style can be found in the272Documentation/process/coding-style.rst file.273 274Also, most C99 enhancements are encouraged to the extent they are supported275by the relevant gcc compilers. So C99 style structure and array276initializers are encouraged where appropriate. Don't go too far,277VLAs are not properly supported yet. An exception to this is the use of278``//`` style comments; ``/*...*/`` comments are still preferred in Linux.279 280Well written, tested and documented code, need not be re-formatted to281comply with the above conventions. For example, the aic7xxx driver282comes to Linux from FreeBSD and Adaptec's own labs. No doubt FreeBSD283and Adaptec have their own coding conventions.284 285 286Mid level supplied functions287============================288These functions are supplied by the SCSI mid level for use by LLDs.289The names (i.e. entry points) of these functions are exported290so an LLD that is a module can access them. The kernel will291arrange for the SCSI mid level to be loaded and initialized before any LLD292is initialized. The functions below are listed alphabetically and their293names all start with ``scsi_``.294 295Summary:296 297 - scsi_add_device - creates new scsi device (lu) instance298 - scsi_add_host - perform sysfs registration and set up transport class299 - scsi_change_queue_depth - change the queue depth on a SCSI device300 - scsi_bios_ptable - return copy of block device's partition table301 - scsi_block_requests - prevent further commands being queued to given host302 - scsi_host_alloc - return a new scsi_host instance whose refcount==1303 - scsi_host_get - increments Scsi_Host instance's refcount304 - scsi_host_put - decrements Scsi_Host instance's refcount (free if 0)305 - scsi_register - create and register a scsi host adapter instance.306 - scsi_remove_device - detach and remove a SCSI device307 - scsi_remove_host - detach and remove all SCSI devices owned by host308 - scsi_report_bus_reset - report scsi _bus_ reset observed309 - scsi_scan_host - scan SCSI bus310 - scsi_track_queue_full - track successive QUEUE_FULL events311 - scsi_unblock_requests - allow further commands to be queued to given host312 - scsi_unregister - [calls scsi_host_put()]313 314 315Details::316 317 /**318 * scsi_add_device - creates new scsi device (lu) instance319 * @shost: pointer to scsi host instance320 * @channel: channel number (rarely other than 0)321 * @id: target id number322 * @lun: logical unit number323 *324 * Returns pointer to new struct scsi_device instance or325 * ERR_PTR(-ENODEV) (or some other bent pointer) if something is326 * wrong (e.g. no lu responds at given address)327 *328 * Might block: yes329 *330 * Notes: This call is usually performed internally during a scsi331 * bus scan when an HBA is added (i.e. scsi_scan_host()). So it332 * should only be called if the HBA becomes aware of a new scsi333 * device (lu) after scsi_scan_host() has completed. If successful334 * this call can lead to slave_alloc() and slave_configure() callbacks335 * into the LLD.336 *337 * Defined in: drivers/scsi/scsi_scan.c338 **/339 struct scsi_device * scsi_add_device(struct Scsi_Host *shost,340 unsigned int channel,341 unsigned int id, unsigned int lun)342 343 344 /**345 * scsi_add_host - perform sysfs registration and set up transport class346 * @shost: pointer to scsi host instance347 * @dev: pointer to struct device of type scsi class348 *349 * Returns 0 on success, negative errno of failure (e.g. -ENOMEM)350 *351 * Might block: no352 *353 * Notes: Only required in "hotplug initialization model" after a354 * successful call to scsi_host_alloc(). This function does not355 * scan the bus; this can be done by calling scsi_scan_host() or356 * in some other transport-specific way. The LLD must set up357 * the transport template before calling this function and may only358 * access the transport class data after this function has been called.359 *360 * Defined in: drivers/scsi/hosts.c361 **/362 int scsi_add_host(struct Scsi_Host *shost, struct device * dev)363 364 365 /**366 * scsi_change_queue_depth - allow LLD to change queue depth on a SCSI device367 * @sdev: pointer to SCSI device to change queue depth on368 * @tags Number of tags allowed if tagged queuing enabled,369 * or number of commands the LLD can queue up370 * in non-tagged mode (as per cmd_per_lun).371 *372 * Returns nothing373 *374 * Might block: no375 *376 * Notes: Can be invoked any time on a SCSI device controlled by this377 * LLD. [Specifically during and after slave_configure() and prior to378 * slave_destroy().] Can safely be invoked from interrupt code.379 *380 * Defined in: drivers/scsi/scsi.c [see source code for more notes]381 *382 **/383 int scsi_change_queue_depth(struct scsi_device *sdev, int tags)384 385 386 /**387 * scsi_bios_ptable - return copy of block device's partition table388 * @dev: pointer to block device389 *390 * Returns pointer to partition table, or NULL for failure391 *392 * Might block: yes393 *394 * Notes: Caller owns memory returned (free with kfree() )395 *396 * Defined in: drivers/scsi/scsicam.c397 **/398 unsigned char *scsi_bios_ptable(struct block_device *dev)399 400 401 /**402 * scsi_block_requests - prevent further commands being queued to given host403 *404 * @shost: pointer to host to block commands on405 *406 * Returns nothing407 *408 * Might block: no409 *410 * Notes: There is no timer nor any other means by which the requests411 * get unblocked other than the LLD calling scsi_unblock_requests().412 *413 * Defined in: drivers/scsi/scsi_lib.c414 **/415 void scsi_block_requests(struct Scsi_Host * shost)416 417 418 /**419 * scsi_host_alloc - create a scsi host adapter instance and perform basic420 * initialization.421 * @sht: pointer to scsi host template422 * @privsize: extra bytes to allocate in hostdata array (which is the423 * last member of the returned Scsi_Host instance)424 *425 * Returns pointer to new Scsi_Host instance or NULL on failure426 *427 * Might block: yes428 *429 * Notes: When this call returns to the LLD, the SCSI bus scan on430 * this host has _not_ yet been done.431 * The hostdata array (by default zero length) is a per host scratch432 * area for the LLD's exclusive use.433 * Both associated refcounting objects have their refcount set to 1.434 * Full registration (in sysfs) and a bus scan are performed later when435 * scsi_add_host() and scsi_scan_host() are called.436 *437 * Defined in: drivers/scsi/hosts.c .438 **/439 struct Scsi_Host * scsi_host_alloc(const struct scsi_host_template * sht,440 int privsize)441 442 443 /**444 * scsi_host_get - increment Scsi_Host instance refcount445 * @shost: pointer to struct Scsi_Host instance446 *447 * Returns nothing448 *449 * Might block: currently may block but may be changed to not block450 *451 * Notes: Actually increments the counts in two sub-objects452 *453 * Defined in: drivers/scsi/hosts.c454 **/455 void scsi_host_get(struct Scsi_Host *shost)456 457 458 /**459 * scsi_host_put - decrement Scsi_Host instance refcount, free if 0460 * @shost: pointer to struct Scsi_Host instance461 *462 * Returns nothing463 *464 * Might block: currently may block but may be changed to not block465 *466 * Notes: Actually decrements the counts in two sub-objects. If the467 * latter refcount reaches 0, the Scsi_Host instance is freed.468 * The LLD need not worry exactly when the Scsi_Host instance is469 * freed, it just shouldn't access the instance after it has balanced470 * out its refcount usage.471 *472 * Defined in: drivers/scsi/hosts.c473 **/474 void scsi_host_put(struct Scsi_Host *shost)475 476 477 /**478 * scsi_register - create and register a scsi host adapter instance.479 * @sht: pointer to scsi host template480 * @privsize: extra bytes to allocate in hostdata array (which is the481 * last member of the returned Scsi_Host instance)482 *483 * Returns pointer to new Scsi_Host instance or NULL on failure484 *485 * Might block: yes486 *487 * Notes: When this call returns to the LLD, the SCSI bus scan on488 * this host has _not_ yet been done.489 * The hostdata array (by default zero length) is a per host scratch490 * area for the LLD.491 *492 * Defined in: drivers/scsi/hosts.c .493 **/494 struct Scsi_Host * scsi_register(struct scsi_host_template * sht,495 int privsize)496 497 498 /**499 * scsi_remove_device - detach and remove a SCSI device500 * @sdev: a pointer to a scsi device instance501 *502 * Returns value: 0 on success, -EINVAL if device not attached503 *504 * Might block: yes505 *506 * Notes: If an LLD becomes aware that a scsi device (lu) has507 * been removed but its host is still present then it can request508 * the removal of that scsi device. If successful this call will509 * lead to the slave_destroy() callback being invoked. sdev is an510 * invalid pointer after this call.511 *512 * Defined in: drivers/scsi/scsi_sysfs.c .513 **/514 int scsi_remove_device(struct scsi_device *sdev)515 516 517 /**518 * scsi_remove_host - detach and remove all SCSI devices owned by host519 * @shost: a pointer to a scsi host instance520 *521 * Returns value: 0 on success, 1 on failure (e.g. LLD busy ??)522 *523 * Might block: yes524 *525 * Notes: Should only be invoked if the "hotplug initialization526 * model" is being used. It should be called _prior_ to527 * scsi_unregister().528 *529 * Defined in: drivers/scsi/hosts.c .530 **/531 int scsi_remove_host(struct Scsi_Host *shost)532 533 534 /**535 * scsi_report_bus_reset - report scsi _bus_ reset observed536 * @shost: a pointer to a scsi host involved537 * @channel: channel (within) host on which scsi bus reset occurred538 *539 * Returns nothing540 *541 * Might block: no542 *543 * Notes: This only needs to be called if the reset is one which544 * originates from an unknown location. Resets originated by the545 * mid level itself don't need to call this, but there should be546 * no harm. The main purpose of this is to make sure that a547 * CHECK_CONDITION is properly treated.548 *549 * Defined in: drivers/scsi/scsi_error.c .550 **/551 void scsi_report_bus_reset(struct Scsi_Host * shost, int channel)552 553 554 /**555 * scsi_scan_host - scan SCSI bus556 * @shost: a pointer to a scsi host instance557 *558 * Might block: yes559 *560 * Notes: Should be called after scsi_add_host()561 *562 * Defined in: drivers/scsi/scsi_scan.c563 **/564 void scsi_scan_host(struct Scsi_Host *shost)565 566 567 /**568 * scsi_track_queue_full - track successive QUEUE_FULL events on given569 * device to determine if and when there is a need570 * to adjust the queue depth on the device.571 * @sdev: pointer to SCSI device instance572 * @depth: Current number of outstanding SCSI commands on this device,573 * not counting the one returned as QUEUE_FULL.574 *575 * Returns 0 - no change needed576 * >0 - adjust queue depth to this new depth577 * -1 - drop back to untagged operation using host->cmd_per_lun578 * as the untagged command depth579 *580 * Might block: no581 *582 * Notes: LLDs may call this at any time and we will do "The Right583 * Thing"; interrupt context safe.584 *585 * Defined in: drivers/scsi/scsi.c .586 **/587 int scsi_track_queue_full(struct scsi_device *sdev, int depth)588 589 590 /**591 * scsi_unblock_requests - allow further commands to be queued to given host592 *593 * @shost: pointer to host to unblock commands on594 *595 * Returns nothing596 *597 * Might block: no598 *599 * Defined in: drivers/scsi/scsi_lib.c .600 **/601 void scsi_unblock_requests(struct Scsi_Host * shost)602 603 604 /**605 * scsi_unregister - unregister and free memory used by host instance606 * @shp: pointer to scsi host instance to unregister.607 *608 * Returns nothing609 *610 * Might block: no611 *612 * Notes: Should not be invoked if the "hotplug initialization613 * model" is being used. Called internally by exit_this_scsi_driver()614 * in the "passive initialization model". Hence a LLD has no need to615 * call this function directly.616 *617 * Defined in: drivers/scsi/hosts.c .618 **/619 void scsi_unregister(struct Scsi_Host * shp)620 621 622 623 624Interface Functions625===================626Interface functions are supplied (defined) by LLDs and their function627pointers are placed in an instance of struct scsi_host_template which628is passed to scsi_host_alloc() [or scsi_register() / init_this_scsi_driver()].629Some are mandatory. Interface functions should be declared static. The630accepted convention is that driver "xyz" will declare its slave_configure()631function as::632 633 static int xyz_slave_configure(struct scsi_device * sdev);634 635and so forth for all interface functions listed below.636 637A pointer to this function should be placed in the 'slave_configure' member638of a "struct scsi_host_template" instance. A pointer to such an instance639should be passed to the mid level's scsi_host_alloc() [or scsi_register() /640init_this_scsi_driver()].641 642The interface functions are also described in the include/scsi/scsi_host.h643file immediately above their definition point in "struct scsi_host_template".644In some cases more detail is given in scsi_host.h than below.645 646The interface functions are listed below in alphabetical order.647 648Summary:649 650 - bios_param - fetch head, sector, cylinder info for a disk651 - eh_timed_out - notify the host that a command timer expired652 - eh_abort_handler - abort given command653 - eh_bus_reset_handler - issue SCSI bus reset654 - eh_device_reset_handler - issue SCSI device reset655 - eh_host_reset_handler - reset host (host bus adapter)656 - info - supply information about given host657 - ioctl - driver can respond to ioctls658 - proc_info - supports /proc/scsi/{driver_name}/{host_no}659 - queuecommand - queue scsi command, invoke 'done' on completion660 - slave_alloc - prior to any commands being sent to a new device661 - slave_configure - driver fine tuning for given device after attach662 - slave_destroy - given device is about to be shut down663 664 665Details::666 667 /**668 * bios_param - fetch head, sector, cylinder info for a disk669 * @sdev: pointer to scsi device context (defined in670 * include/scsi/scsi_device.h)671 * @bdev: pointer to block device context (defined in fs.h)672 * @capacity: device size (in 512 byte sectors)673 * @params: three element array to place output:674 * params[0] number of heads (max 255)675 * params[1] number of sectors (max 63)676 * params[2] number of cylinders677 *678 * Return value is ignored679 *680 * Locks: none681 *682 * Calling context: process (sd)683 *684 * Notes: an arbitrary geometry (based on READ CAPACITY) is used685 * if this function is not provided. The params array is686 * pre-initialized with made up values just in case this function687 * doesn't output anything.688 *689 * Optionally defined in: LLD690 **/691 int bios_param(struct scsi_device * sdev, struct block_device *bdev,692 sector_t capacity, int params[3])693 694 695 /**696 * eh_timed_out - The timer for the command has just fired697 * @scp: identifies command timing out698 *699 * Returns:700 *701 * EH_HANDLED: I fixed the error, please complete the command702 * EH_RESET_TIMER: I need more time, reset the timer and703 * begin counting again704 * EH_NOT_HANDLED Begin normal error recovery705 *706 *707 * Locks: None held708 *709 * Calling context: interrupt710 *711 * Notes: This is to give the LLD an opportunity to do local recovery.712 * This recovery is limited to determining if the outstanding command713 * will ever complete. You may not abort and restart the command from714 * this callback.715 *716 * Optionally defined in: LLD717 **/718 int eh_timed_out(struct scsi_cmnd * scp)719 720 721 /**722 * eh_abort_handler - abort command associated with scp723 * @scp: identifies command to be aborted724 *725 * Returns SUCCESS if command aborted else FAILED726 *727 * Locks: None held728 *729 * Calling context: kernel thread730 *731 * Notes: If 'no_async_abort' is defined this callback732 * will be invoked from scsi_eh thread. No other commands733 * will then be queued on current host during eh.734 * Otherwise it will be called whenever scsi_timeout()735 * is called due to a command timeout.736 *737 * Optionally defined in: LLD738 **/739 int eh_abort_handler(struct scsi_cmnd * scp)740 741 742 /**743 * eh_bus_reset_handler - issue SCSI bus reset744 * @scp: SCSI bus that contains this device should be reset745 *746 * Returns SUCCESS if command aborted else FAILED747 *748 * Locks: None held749 *750 * Calling context: kernel thread751 *752 * Notes: Invoked from scsi_eh thread. No other commands will be753 * queued on current host during eh.754 *755 * Optionally defined in: LLD756 **/757 int eh_bus_reset_handler(struct scsi_cmnd * scp)758 759 760 /**761 * eh_device_reset_handler - issue SCSI device reset762 * @scp: identifies SCSI device to be reset763 *764 * Returns SUCCESS if command aborted else FAILED765 *766 * Locks: None held767 *768 * Calling context: kernel thread769 *770 * Notes: Invoked from scsi_eh thread. No other commands will be771 * queued on current host during eh.772 *773 * Optionally defined in: LLD774 **/775 int eh_device_reset_handler(struct scsi_cmnd * scp)776 777 778 /**779 * eh_host_reset_handler - reset host (host bus adapter)780 * @scp: SCSI host that contains this device should be reset781 *782 * Returns SUCCESS if command aborted else FAILED783 *784 * Locks: None held785 *786 * Calling context: kernel thread787 *788 * Notes: Invoked from scsi_eh thread. No other commands will be789 * queued on current host during eh.790 * With the default eh_strategy in place, if none of the _abort_,791 * _device_reset_, _bus_reset_ or this eh handler function are792 * defined (or they all return FAILED) then the device in question793 * will be set offline whenever eh is invoked.794 *795 * Optionally defined in: LLD796 **/797 int eh_host_reset_handler(struct scsi_cmnd * scp)798 799 800 /**801 * info - supply information about given host: driver name plus data802 * to distinguish given host803 * @shp: host to supply information about804 *805 * Return ASCII null terminated string. [This driver is assumed to806 * manage the memory pointed to and maintain it, typically for the807 * lifetime of this host.]808 *809 * Locks: none810 *811 * Calling context: process812 *813 * Notes: Often supplies PCI or ISA information such as IO addresses814 * and interrupt numbers. If not supplied struct Scsi_Host::name used815 * instead. It is assumed the returned information fits on one line816 * (i.e. does not included embedded newlines).817 * The SCSI_IOCTL_PROBE_HOST ioctl yields the string returned by this818 * function (or struct Scsi_Host::name if this function is not819 * available).820 * In a similar manner, init_this_scsi_driver() outputs to the console821 * each host's "info" (or name) for the driver it is registering.822 * Also if proc_info() is not supplied, the output of this function823 * is used instead.824 *825 * Optionally defined in: LLD826 **/827 const char * info(struct Scsi_Host * shp)828 829 830 /**831 * ioctl - driver can respond to ioctls832 * @sdp: device that ioctl was issued for833 * @cmd: ioctl number834 * @arg: pointer to read or write data from. Since it points to835 * user space, should use appropriate kernel functions836 * (e.g. copy_from_user() ). In the Unix style this argument837 * can also be viewed as an unsigned long.838 *839 * Returns negative "errno" value when there is a problem. 0 or a840 * positive value indicates success and is returned to the user space.841 *842 * Locks: none843 *844 * Calling context: process845 *846 * Notes: The SCSI subsystem uses a "trickle down" ioctl model.847 * The user issues an ioctl() against an upper level driver848 * (e.g. /dev/sdc) and if the upper level driver doesn't recognize849 * the 'cmd' then it is passed to the SCSI mid level. If the SCSI850 * mid level does not recognize it, then the LLD that controls851 * the device receives the ioctl. According to recent Unix standards852 * unsupported ioctl() 'cmd' numbers should return -ENOTTY.853 *854 * Optionally defined in: LLD855 **/856 int ioctl(struct scsi_device *sdp, int cmd, void *arg)857 858 859 /**860 * proc_info - supports /proc/scsi/{driver_name}/{host_no}861 * @buffer: anchor point to output to (0==writeto1_read0) or fetch from862 * (1==writeto1_read0).863 * @start: where "interesting" data is written to. Ignored when864 * 1==writeto1_read0.865 * @offset: offset within buffer 0==writeto1_read0 is actually866 * interested in. Ignored when 1==writeto1_read0 .867 * @length: maximum (or actual) extent of buffer868 * @host_no: host number of interest (struct Scsi_Host::host_no)869 * @writeto1_read0: 1 -> data coming from user space towards driver870 * (e.g. "echo some_string > /proc/scsi/xyz/2")871 * 0 -> user what data from this driver872 * (e.g. "cat /proc/scsi/xyz/2")873 *874 * Returns length when 1==writeto1_read0. Otherwise number of chars875 * output to buffer past offset.876 *877 * Locks: none held878 *879 * Calling context: process880 *881 * Notes: Driven from scsi_proc.c which interfaces to proc_fs. proc_fs882 * support can now be configured out of the scsi subsystem.883 *884 * Optionally defined in: LLD885 **/886 int proc_info(char * buffer, char ** start, off_t offset,887 int length, int host_no, int writeto1_read0)888 889 890 /**891 * queuecommand - queue scsi command, invoke scp->scsi_done on completion892 * @shost: pointer to the scsi host object893 * @scp: pointer to scsi command object894 *895 * Returns 0 on success.896 *897 * If there's a failure, return either:898 *899 * SCSI_MLQUEUE_DEVICE_BUSY if the device queue is full, or900 * SCSI_MLQUEUE_HOST_BUSY if the entire host queue is full901 *902 * On both of these returns, the mid-layer will requeue the I/O903 *904 * - if the return is SCSI_MLQUEUE_DEVICE_BUSY, only that particular905 * device will be paused, and it will be unpaused when a command to906 * the device returns (or after a brief delay if there are no more907 * outstanding commands to it). Commands to other devices continue908 * to be processed normally.909 *910 * - if the return is SCSI_MLQUEUE_HOST_BUSY, all I/O to the host911 * is paused and will be unpaused when any command returns from912 * the host (or after a brief delay if there are no outstanding913 * commands to the host).914 *915 * For compatibility with earlier versions of queuecommand, any916 * other return value is treated the same as917 * SCSI_MLQUEUE_HOST_BUSY.918 *919 * Other types of errors that are detected immediately may be920 * flagged by setting scp->result to an appropriate value,921 * invoking the scp->scsi_done callback, and then returning 0922 * from this function. If the command is not performed923 * immediately (and the LLD is starting (or will start) the given924 * command) then this function should place 0 in scp->result and925 * return 0.926 *927 * Command ownership. If the driver returns zero, it owns the928 * command and must take responsibility for ensuring the929 * scp->scsi_done callback is executed. Note: the driver may930 * call scp->scsi_done before returning zero, but after it has931 * called scp->scsi_done, it may not return any value other than932 * zero. If the driver makes a non-zero return, it must not933 * execute the command's scsi_done callback at any time.934 *935 * Locks: up to and including 2.6.36, struct Scsi_Host::host_lock936 * held on entry (with "irqsave") and is expected to be937 * held on return. From 2.6.37 onwards, queuecommand is938 * called without any locks held.939 *940 * Calling context: in interrupt (soft irq) or process context941 *942 * Notes: This function should be relatively fast. Normally it943 * will not wait for IO to complete. Hence the scp->scsi_done944 * callback is invoked (often directly from an interrupt service945 * routine) some time after this function has returned. In some946 * cases (e.g. pseudo adapter drivers that manufacture the947 * response to a SCSI INQUIRY) the scp->scsi_done callback may be948 * invoked before this function returns. If the scp->scsi_done949 * callback is not invoked within a certain period the SCSI mid950 * level will commence error processing. If a status of CHECK951 * CONDITION is placed in "result" when the scp->scsi_done952 * callback is invoked, then the LLD driver should perform953 * autosense and fill in the struct scsi_cmnd::sense_buffer954 * array. The scsi_cmnd::sense_buffer array is zeroed prior to955 * the mid level queuing a command to an LLD.956 *957 * Defined in: LLD958 **/959 int queuecommand(struct Scsi_Host *shost, struct scsi_cmnd * scp)960 961 962 /**963 * slave_alloc - prior to any commands being sent to a new device964 * (i.e. just prior to scan) this call is made965 * @sdp: pointer to new device (about to be scanned)966 *967 * Returns 0 if ok. Any other return is assumed to be an error and968 * the device is ignored.969 *970 * Locks: none971 *972 * Calling context: process973 *974 * Notes: Allows the driver to allocate any resources for a device975 * prior to its initial scan. The corresponding scsi device may not976 * exist but the mid level is just about to scan for it (i.e. send977 * and INQUIRY command plus ...). If a device is found then978 * slave_configure() will be called while if a device is not found979 * slave_destroy() is called.980 * For more details see the include/scsi/scsi_host.h file.981 *982 * Optionally defined in: LLD983 **/984 int slave_alloc(struct scsi_device *sdp)985 986 987 /**988 * slave_configure - driver fine tuning for given device just after it989 * has been first scanned (i.e. it responded to an990 * INQUIRY)991 * @sdp: device that has just been attached992 *993 * Returns 0 if ok. Any other return is assumed to be an error and994 * the device is taken offline. [offline devices will _not_ have995 * slave_destroy() called on them so clean up resources.]996 *997 * Locks: none998 *999 * Calling context: process1000 *1001 * Notes: Allows the driver to inspect the response to the initial1002 * INQUIRY done by the scanning code and take appropriate action.1003 * For more details see the include/scsi/scsi_host.h file.1004 *1005 * Optionally defined in: LLD1006 **/1007 int slave_configure(struct scsi_device *sdp)1008 1009 1010 /**1011 * slave_destroy - given device is about to be shut down. All1012 * activity has ceased on this device.1013 * @sdp: device that is about to be shut down1014 *1015 * Returns nothing1016 *1017 * Locks: none1018 *1019 * Calling context: process1020 *1021 * Notes: Mid level structures for given device are still in place1022 * but are about to be torn down. Any per device resources allocated1023 * by this driver for given device should be freed now. No further1024 * commands will be sent for this sdp instance. [However the device1025 * could be re-attached in the future in which case a new instance1026 * of struct scsi_device would be supplied by future slave_alloc()1027 * and slave_configure() calls.]1028 *1029 * Optionally defined in: LLD1030 **/1031 void slave_destroy(struct scsi_device *sdp)1032 1033 1034 1035Data Structures1036===============1037struct scsi_host_template1038-------------------------1039There is one "struct scsi_host_template" instance per LLD [#]_. It is1040typically initialized as a file scope static in a driver's header file. That1041way members that are not explicitly initialized will be set to 0 or NULL.1042Member of interest:1043 1044 name1045 - name of driver (may contain spaces, please limit to1046 less than 80 characters)1047 1048 proc_name1049 - name used in "/proc/scsi/<proc_name>/<host_no>" and1050 by sysfs in one of its "drivers" directories. Hence1051 "proc_name" should only contain characters acceptable1052 to a Unix file name.1053 1054 ``(*queuecommand)()``1055 - primary callback that the mid level uses to inject1056 SCSI commands into an LLD.1057 1058The structure is defined and commented in include/scsi/scsi_host.h1059 1060.. [#] In extreme situations a single driver may have several instances1061 if it controls several different classes of hardware (e.g. an LLD1062 that handles both ISA and PCI cards and has a separate instance of1063 struct scsi_host_template for each class).1064 1065struct Scsi_Host1066----------------1067There is one struct Scsi_Host instance per host (HBA) that an LLD1068controls. The struct Scsi_Host structure has many members in common1069with "struct scsi_host_template". When a new struct Scsi_Host instance1070is created (in scsi_host_alloc() in hosts.c) those common members are1071initialized from the driver's struct scsi_host_template instance. Members1072of interest:1073 1074 host_no1075 - system wide unique number that is used for identifying1076 this host. Issued in ascending order from 0.1077 can_queue1078 - must be greater than 0; do not send more than can_queue1079 commands to the adapter.1080 this_id1081 - scsi id of host (scsi initiator) or -1 if not known1082 sg_tablesize1083 - maximum scatter gather elements allowed by host.1084 Set this to SG_ALL or less to avoid chained SG lists.1085 Must be at least 1.1086 max_sectors1087 - maximum number of sectors (usually 512 bytes) allowed1088 in a single SCSI command. The default value of 0 leads1089 to a setting of SCSI_DEFAULT_MAX_SECTORS (defined in1090 scsi_host.h) which is currently set to 1024. So for a1091 disk the maximum transfer size is 512 KB when max_sectors1092 is not defined. Note that this size may not be sufficient1093 for disk firmware uploads.1094 cmd_per_lun1095 - maximum number of commands that can be queued on devices1096 controlled by the host. Overridden by LLD calls to1097 scsi_change_queue_depth().1098 no_async_abort1099 - 1=>Asynchronous aborts are not supported1100 - 0=>Timed-out commands will be aborted asynchronously1101 hostt1102 - pointer to driver's struct scsi_host_template from which1103 this struct Scsi_Host instance was spawned1104 hostt->proc_name1105 - name of LLD. This is the driver name that sysfs uses1106 transportt1107 - pointer to driver's struct scsi_transport_template instance1108 (if any). FC and SPI transports currently supported.1109 sh_list1110 - a double linked list of pointers to all struct Scsi_Host1111 instances (currently ordered by ascending host_no)1112 my_devices1113 - a double linked list of pointers to struct scsi_device1114 instances that belong to this host.1115 hostdata[0]1116 - area reserved for LLD at end of struct Scsi_Host. Size1117 is set by the second argument (named 'xtr_bytes') to1118 scsi_host_alloc() or scsi_register().1119 vendor_id1120 - a unique value that identifies the vendor supplying1121 the LLD for the Scsi_Host. Used most often in validating1122 vendor-specific message requests. Value consists of an1123 identifier type and a vendor-specific value.1124 See scsi_netlink.h for a description of valid formats.1125 1126The scsi_host structure is defined in include/scsi/scsi_host.h1127 1128struct scsi_device1129------------------1130Generally, there is one instance of this structure for each SCSI logical unit1131on a host. Scsi devices connected to a host are uniquely identified by a1132channel number, target id and logical unit number (lun).1133The structure is defined in include/scsi/scsi_device.h1134 1135struct scsi_cmnd1136----------------1137Instances of this structure convey SCSI commands to the LLD and responses1138back to the mid level. The SCSI mid level will ensure that no more SCSI1139commands become queued against the LLD than are indicated by1140scsi_change_queue_depth() (or struct Scsi_Host::cmd_per_lun). There will1141be at least one instance of struct scsi_cmnd available for each SCSI device.1142Members of interest:1143 1144 cmnd1145 - array containing SCSI command1146 cmnd_len1147 - length (in bytes) of SCSI command1148 sc_data_direction1149 - direction of data transfer in data phase. See1150 "enum dma_data_direction" in include/linux/dma-mapping.h1151 request_bufflen1152 - number of data bytes to transfer (0 if no data phase)1153 use_sg1154 - ==0 -> no scatter gather list, hence transfer data1155 to/from request_buffer1156 - >0 -> scatter gather list (actually an array) in1157 request_buffer with use_sg elements1158 request_buffer1159 - either contains data buffer or scatter gather list1160 depending on the setting of use_sg. Scatter gather1161 elements are defined by 'struct scatterlist' found1162 in include/linux/scatterlist.h .1163 done1164 - function pointer that should be invoked by LLD when the1165 SCSI command is completed (successfully or otherwise).1166 Should only be called by an LLD if the LLD has accepted1167 the command (i.e. queuecommand() returned or will return1168 0). The LLD may invoke 'done' prior to queuecommand()1169 finishing.1170 result1171 - should be set by LLD prior to calling 'done'. A value1172 of 0 implies a successfully completed command (and all1173 data (if any) has been transferred to or from the SCSI1174 target device). 'result' is a 32 bit unsigned integer that1175 can be viewed as 2 related bytes. The SCSI status value is1176 in the LSB. See include/scsi/scsi.h status_byte() and1177 host_byte() macros and related constants.1178 sense_buffer1179 - an array (maximum size: SCSI_SENSE_BUFFERSIZE bytes) that1180 should be written when the SCSI status (LSB of 'result')1181 is set to CHECK_CONDITION (2). When CHECK_CONDITION is1182 set, if the top nibble of sense_buffer[0] has the value 71183 then the mid level will assume the sense_buffer array1184 contains a valid SCSI sense buffer; otherwise the mid1185 level will issue a REQUEST_SENSE SCSI command to1186 retrieve the sense buffer. The latter strategy is error1187 prone in the presence of command queuing so the LLD should1188 always "auto-sense".1189 device1190 - pointer to scsi_device object that this command is1191 associated with.1192 resid1193 - an LLD should set this unsigned integer to the requested1194 transfer length (i.e. 'request_bufflen') less the number1195 of bytes that are actually transferred. 'resid' is1196 preset to 0 so an LLD can ignore it if it cannot detect1197 underruns (overruns should not be reported). An LLD1198 should set 'resid' prior to invoking 'done'. The most1199 interesting case is data transfers from a SCSI target1200 device (e.g. READs) that underrun.1201 underflow1202 - LLD should place (DID_ERROR << 16) in 'result' if1203 actual number of bytes transferred is less than this1204 figure. Not many LLDs implement this check and some that1205 do just output an error message to the log rather than1206 report a DID_ERROR. Better for an LLD to implement1207 'resid'.1208 1209It is recommended that a LLD set 'resid' on data transfers from a SCSI1210target device (e.g. READs). It is especially important that 'resid' is set1211when such data transfers have sense keys of MEDIUM ERROR and HARDWARE ERROR1212(and possibly RECOVERED ERROR). In these cases if a LLD is in doubt how much1213data has been received then the safest approach is to indicate no bytes have1214been received. For example: to indicate that no valid data has been received1215a LLD might use these helpers::1216 1217 scsi_set_resid(SCpnt, scsi_bufflen(SCpnt));1218 1219where 'SCpnt' is a pointer to a scsi_cmnd object. To indicate only three 5121220bytes blocks has been received 'resid' could be set like this::1221 1222 scsi_set_resid(SCpnt, scsi_bufflen(SCpnt) - (3 * 512));1223 1224The scsi_cmnd structure is defined in include/scsi/scsi_cmnd.h1225 1226 1227Locks1228=====1229Each struct Scsi_Host instance has a spin_lock called struct1230Scsi_Host::default_lock which is initialized in scsi_host_alloc() [found in1231hosts.c]. Within the same function the struct Scsi_Host::host_lock pointer1232is initialized to point at default_lock. Thereafter lock and unlock1233operations performed by the mid level use the struct Scsi_Host::host_lock1234pointer. Previously drivers could override the host_lock pointer but1235this is not allowed anymore.1236 1237 1238Autosense1239=========1240Autosense (or auto-sense) is defined in the SAM-2 document as "the1241automatic return of sense data to the application client coincident1242with the completion of a SCSI command" when a status of CHECK CONDITION1243occurs. LLDs should perform autosense. This should be done when the LLD1244detects a CHECK CONDITION status by either:1245 1246 a) instructing the SCSI protocol (e.g. SCSI Parallel Interface (SPI))1247 to perform an extra data in phase on such responses1248 b) or, the LLD issuing a REQUEST SENSE command itself1249 1250Either way, when a status of CHECK CONDITION is detected, the mid level1251decides whether the LLD has performed autosense by checking struct1252scsi_cmnd::sense_buffer[0] . If this byte has an upper nibble of 7 (or 0xf)1253then autosense is assumed to have taken place. If it has another value (and1254this byte is initialized to 0 before each command) then the mid level will1255issue a REQUEST SENSE command.1256 1257In the presence of queued commands the "nexus" that maintains sense1258buffer data from the command that failed until a following REQUEST SENSE1259may get out of synchronization. This is why it is best for the LLD1260to perform autosense.1261 1262 1263Changes since lk 2.4 series1264===========================1265io_request_lock has been replaced by several finer grained locks. The lock1266relevant to LLDs is struct Scsi_Host::host_lock and there is1267one per SCSI host.1268 1269The older error handling mechanism has been removed. This means the1270LLD interface functions abort() and reset() have been removed.1271The struct scsi_host_template::use_new_eh_code flag has been removed.1272 1273In the 2.4 series the SCSI subsystem configuration descriptions were1274aggregated with the configuration descriptions from all other Linux1275subsystems in the Documentation/Configure.help file. In the 2.6 series,1276the SCSI subsystem now has its own (much smaller) drivers/scsi/Kconfig1277file that contains both configuration and help information.1278 1279struct SHT has been renamed to struct scsi_host_template.1280 1281Addition of the "hotplug initialization model" and many extra functions1282to support it.1283 1284 1285Credits1286=======1287The following people have contributed to this document:1288 1289 - Mike Anderson <andmike at us dot ibm dot com>1290 - James Bottomley <James dot Bottomley at hansenpartnership dot com>1291 - Patrick Mansfield <patmans at us dot ibm dot com>1292 - Christoph Hellwig <hch at infradead dot org>1293 - Doug Ledford <dledford at redhat dot com>1294 - Andries Brouwer <Andries dot Brouwer at cwi dot nl>1295 - Randy Dunlap <rdunlap at xenotime dot net>1296 - Alan Stern <stern at rowland dot harvard dot edu>1297 1298 1299Douglas Gilbert1300dgilbert at interlog dot com1301 130221st September 20041303