← Documents Documentation/scsi/scsi_mid_low_api.rst GitHub 원문 ↗

Linux 6.18.37 · SCSI

SCSI 중간 계층과 하위 계층 드라이버 인터페이스

SCSI 중간 계층과 LLDD 사이의 host·장치 수명 주기, 제공 함수, 콜백, 명령 소유권과 자료 구조 계약을 설명합니다.

Source pathDocumentation/scsi/scsi_mid_low_api.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

scsi_mid_low_api.rst:1-1222

SCSI 중간 계층과 LLDD 사이의 host·장치 수명 주기, 제공 함수, 콜백, 명령 소유권과 자료 구조 계약을 설명합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 =============================================
4 SCSI mid_level - lower_level driver interface
5 =============================================
6
7 Introduction
8 ============
9 This document outlines the interface between the Linux SCSI mid level and
10 SCSI lower level drivers. Lower level drivers (LLDs) are variously called
11 host bus adapter (HBA) drivers and host drivers (HD). A "host" in this
12 context is a bridge between a computer IO bus (e.g. PCI or ISA) and a
13 single SCSI initiator port on a SCSI transport. An "initiator" port
14 (SCSI terminology, see SAM-3 at http://www.t10.org) sends SCSI commands
15 to "target" SCSI ports (e.g. disks). There can be many LLDs in a running
16 system, but only one per hardware type. Most LLDs can control one or more
17 SCSI HBAs. Some HBAs contain multiple hosts.
18
19 In some cases the SCSI transport is an external bus that already has
20 its own subsystem in Linux (e.g. USB and ieee1394). In such cases the
21 SCSI subsystem LLD is a software bridge to the other driver subsystem.
22 Examples are the usb-storage driver (found in the drivers/usb/storage
23 directory) and the ieee1394/sbp2 driver (found in the drivers/ieee1394
24 directory).
25
26 For example, the aic7xxx LLD controls Adaptec SCSI parallel interface
27 (SPI) controllers based on that company's 7xxx chip series. The aic7xxx
28 LLD can be built into the kernel or loaded as a module. There can only be
29 one aic7xxx LLD running in a Linux system but it may be controlling many
30 HBAs. These HBAs might be either on PCI daughter-boards or built into
31 the motherboard (or both). Some aic7xxx based HBAs are dual controllers
32 and thus represent two hosts. Like most modern HBAs, each aic7xxx host
33 has its own PCI device address. [The one-to-one correspondence between
34 a SCSI host and a PCI device is common but not required (e.g. with
35 ISA adapters).]
36
37 The SCSI mid level isolates an LLD from other layers such as the SCSI
38 upper layer drivers and the block layer.
39
40 This version of the document roughly matches Linux kernel version 2.6.8 .
41
42 Documentation
43 =============
44 There is a SCSI documentation directory within the kernel source tree,
45 typically Documentation/scsi . Most documents are in reStructuredText
46 format. This file is named scsi_mid_low_api.rst and can be
47 found in that directory. A more recent copy of this document may be found
48 at https://docs.kernel.org/scsi/scsi_mid_low_api.html. Many LLDs are
49 documented in Documentation/scsi (e.g. aic7xxx.rst). The SCSI mid-level is
50 briefly described in scsi.rst which contains a URL to a document describing
51 the SCSI subsystem in the Linux kernel 2.4 series. Two upper level
52 drivers have documents in that directory: st.rst (SCSI tape driver) and
53 scsi-generic.rst (for the sg driver).
54
55 Some documentation (or URLs) for LLDs may be found in the C source code
56 or in the same directory as the C source code. For example to find a URL
57 about the USB mass storage driver see the
58 /usr/src/linux/drivers/usb/storage directory.
59
60 Driver structure
61 ================
62 Traditionally an LLD for the SCSI subsystem has been at least two files in
63 the drivers/scsi directory. For example, a driver called "xyz" has a header
64 file "xyz.h" and a source file "xyz.c". [Actually there is no good reason
65 why this couldn't all be in one file; the header file is superfluous.] Some
66 drivers that have been ported to several operating systems have more than
67 two files. For example the aic7xxx driver has separate files for generic
68 and OS-specific code (e.g. FreeBSD and Linux). Such drivers tend to have
69 their own directory under the drivers/scsi directory.
70
71 When a new LLD is being added to Linux, the following files (found in the
72 drivers/scsi directory) will need some attention: Makefile and Kconfig .
73 It is probably best to study how existing LLDs are organized.
74
75 As the 2.5 series development kernels evolve into the 2.6 series
76 production series, changes are being introduced into this interface. An
77 example of this is driver initialization code where there are now 2 models
78 available. The older one, similar to what was found in the Linux 2.4 series,
79 is based on hosts that are detected at HBA driver load time. This will be
80 referred to the "passive" initialization model. The newer model allows HBAs
81 to be hot plugged (and unplugged) during the lifetime of the LLD and will
82 be referred to as the "hotplug" initialization model. The newer model is
83 preferred as it can handle both traditional SCSI equipment that is
84 permanently connected as well as modern "SCSI" devices (e.g. USB or
85 IEEE 1394 connected digital cameras) that are hotplugged. Both
86 initialization models are discussed in the following sections.
87
88 An LLD interfaces to the SCSI subsystem several ways:
89
90 a) directly invoking functions supplied by the mid level
91 b) passing a set of function pointers to a registration function
92 supplied by the mid level. The mid level will then invoke these
93 functions at some point in the future. The LLD will supply
94 implementations of these functions.
95 c) direct access to instances of well known data structures maintained
96 by the mid level
97
98 Those functions in group a) are listed in a section entitled "Mid level
99 supplied functions" below.
100
101 Those functions in group b) are listed in a section entitled "Interface
102 functions" below. Their function pointers are placed in the members of
103 "struct scsi_host_template", an instance of which is passed to
104 scsi_host_alloc(). Those interface functions that the LLD does not
105 wish to supply should have NULL placed in the corresponding member of
106 struct scsi_host_template. Defining an instance of struct
107 scsi_host_template at file scope will cause NULL to be placed in function
108 pointer members not explicitly initialized.
109
110 Those usages in group c) should be handled with care, especially in a
111 "hotplug" environment. LLDs should be aware of the lifetime of instances
112 that are shared with the mid level and other layers.
113
114 All functions defined within an LLD and all data defined at file scope
115 should be static. For example the sdev_init() function in an LLD
116 called "xxx" could be defined as
117 ``static int xxx_sdev_init(struct scsi_device * sdev) { /* code */ }``
118
119
120 Hotplug initialization model
121 ============================
122 In this model an LLD controls when SCSI hosts are introduced and removed
123 from the SCSI subsystem. Hosts can be introduced as early as driver
124 initialization and removed as late as driver shutdown. Typically a driver
125 will respond to a sysfs probe() callback that indicates an HBA has been
126 detected. After confirming that the new device is one that the LLD wants
127 to control, the LLD will initialize the HBA and then register a new host
128 with the SCSI mid level.
129
130 During LLD initialization the driver should register itself with the
131 appropriate IO bus on which it expects to find HBA(s) (e.g. the PCI bus).
132 This can probably be done via sysfs. Any driver parameters (especially
133 those that are writable after the driver is loaded) could also be
134 registered with sysfs at this point. The SCSI mid level first becomes
135 aware of an LLD when that LLD registers its first HBA.
136
137 At some later time, the LLD becomes aware of an HBA and what follows
138 is a typical sequence of calls between the LLD and the mid level.
139 This example shows the mid level scanning the newly introduced HBA for 3
140 scsi devices of which only the first 2 respond::
141
142 HBA PROBE: assume 2 SCSI devices found in scan
143 LLD mid level LLD
144 ===-------------------=========--------------------===------
145 scsi_host_alloc() -->
146 scsi_add_host() ---->
147 scsi_scan_host() -------+
148 |
149 sdev_init()
150 sdev_configure() --> scsi_change_queue_depth()
151 |
152 sdev_init()
153 sdev_configure()
154 |
155 sdev_init() ***
156 sdev_destroy() ***
157
158
159 *** For scsi devices that the mid level tries to scan but do not
160 respond, a sdev_init(), sdev_destroy() pair is called.
161
162 If the LLD wants to adjust the default queue settings, it can invoke
163 scsi_change_queue_depth() in its sdev_configure() routine.
164
165 When an HBA is being removed it could be as part of an orderly shutdown
166 associated with the LLD module being unloaded (e.g. with the "rmmod"
167 command) or in response to a "hot unplug" indicated by sysfs()'s
168 remove() callback being invoked. In either case, the sequence is the
169 same::
170
171 HBA REMOVE: assume 2 SCSI devices attached
172 LLD mid level LLD
173 ===----------------------=========-----------------===------
174 scsi_remove_host() ---------+
175 |
176 sdev_destroy()
177 sdev_destroy()
178 scsi_host_put()
179
180 It may be useful for a LLD to keep track of struct Scsi_Host instances
181 (a pointer is returned by scsi_host_alloc()). Such instances are "owned"
182 by the mid-level. struct Scsi_Host instances are freed from
183 scsi_host_put() when the reference count hits zero.
184
185 Hot unplugging an HBA that controls a disk which is processing SCSI
186 commands on a mounted file system is an interesting situation. Reference
187 counting logic is being introduced into the mid level to cope with many
188 of the issues involved. See the section on reference counting below.
189
190
191 The hotplug concept may be extended to SCSI devices. Currently, when an
192 HBA is added, the scsi_scan_host() function causes a scan for SCSI devices
193 attached to the HBA's SCSI transport. On newer SCSI transports the HBA
194 may become aware of a new SCSI device _after_ the scan has completed.
195 An LLD can use this sequence to make the mid level aware of a SCSI device::
196
197 SCSI DEVICE hotplug
198 LLD mid level LLD
199 ===-------------------=========--------------------===------
200 scsi_add_device() ------+
201 |
202 sdev_init()
203 sdev_configure() [--> scsi_change_queue_depth()]
204
205 In a similar fashion, an LLD may become aware that a SCSI device has been
206 removed (unplugged) or the connection to it has been interrupted. Some
207 existing SCSI transports (e.g. SPI) may not become aware that a SCSI
208 device has been removed until a subsequent SCSI command fails which will
209 probably cause that device to be set offline by the mid level. An LLD that
210 detects the removal of a SCSI device can instigate its removal from
211 upper layers with this sequence::
212
213 SCSI DEVICE hot unplug
214 LLD mid level LLD
215 ===----------------------=========-----------------===------
216 scsi_remove_device() -------+
217 |
218 sdev_destroy()
219
220 It may be useful for an LLD to keep track of struct scsi_device instances
221 (a pointer is passed as the parameter to sdev_init() and
222 sdev_configure() callbacks). Such instances are "owned" by the mid-level.
223 struct scsi_device instances are freed after sdev_destroy().
224
225
226 Reference Counting
227 ==================
228 The Scsi_Host structure has had reference counting infrastructure added.
229 This effectively spreads the ownership of struct Scsi_Host instances
230 across the various SCSI layers which use them. Previously such instances
231 were exclusively owned by the mid level. LLDs would not usually need to
232 directly manipulate these reference counts but there may be some cases
233 where they do.
234
235 There are 3 reference counting functions of interest associated with
236 struct Scsi_Host:
237
238 - scsi_host_alloc():
239 returns a pointer to new instance of struct
240 Scsi_Host which has its reference count ^^ set to 1
241
242 - scsi_host_get():
243 adds 1 to the reference count of the given instance
244
245 - scsi_host_put():
246 decrements 1 from the reference count of the given
247 instance. If the reference count reaches 0 then the given instance
248 is freed
249
250 The scsi_device structure has had reference counting infrastructure added.
251 This effectively spreads the ownership of struct scsi_device instances
252 across the various SCSI layers which use them. Previously such instances
253 were exclusively owned by the mid level. See the access functions declared
254 towards the end of include/scsi/scsi_device.h . If an LLD wants to keep
255 a copy of a pointer to a scsi_device instance it should use scsi_device_get()
256 to bump its reference count. When it is finished with the pointer it can
257 use scsi_device_put() to decrement its reference count (and potentially
258 delete it).
259
260 .. Note::
261
262 struct Scsi_Host actually has 2 reference counts which are manipulated
263 in parallel by these functions.
264
265
266 Conventions
267 ===========
268 First, Linus Torvalds's thoughts on C coding style can be found in the
269 Documentation/process/coding-style.rst file.
270
271 Also, most C99 enhancements are encouraged to the extent they are supported
272 by the relevant gcc compilers. So C99 style structure and array
273 initializers are encouraged where appropriate. Don't go too far,
274 VLAs are not properly supported yet. An exception to this is the use of
275 ``//`` style comments; ``/*...*/`` comments are still preferred in Linux.
276
277 Well written, tested and documented code, need not be re-formatted to
278 comply with the above conventions. For example, the aic7xxx driver
279 comes to Linux from FreeBSD and Adaptec's own labs. No doubt FreeBSD
280 and Adaptec have their own coding conventions.
281
282
283 Mid level supplied functions
284 ============================
285 These functions are supplied by the SCSI mid level for use by LLDs.
286 The names (i.e. entry points) of these functions are exported
287 so an LLD that is a module can access them. The kernel will
288 arrange for the SCSI mid level to be loaded and initialized before any LLD
289 is initialized. The functions below are listed alphabetically and their
290 names all start with ``scsi_``.
291
292 Summary:
293
294 - scsi_add_device - creates new scsi device (lu) instance
295 - scsi_add_host - perform sysfs registration and set up transport class
296 - scsi_change_queue_depth - change the queue depth on a SCSI device
297 - scsi_bios_ptable - return copy of block device's partition table
298 - scsi_block_requests - prevent further commands being queued to given host
299 - scsi_host_alloc - return a new scsi_host instance whose refcount==1
300 - scsi_host_get - increments Scsi_Host instance's refcount
301 - scsi_host_put - decrements Scsi_Host instance's refcount (free if 0)
302 - scsi_remove_device - detach and remove a SCSI device
303 - scsi_remove_host - detach and remove all SCSI devices owned by host
304 - scsi_report_bus_reset - report scsi _bus_ reset observed
305 - scsi_scan_host - scan SCSI bus
306 - scsi_track_queue_full - track successive QUEUE_FULL events
307 - scsi_unblock_requests - allow further commands to be queued to given host
308
309
310 Details::
311
312 /**
313 * scsi_add_device - creates new scsi device (lu) instance
314 * @shost: pointer to scsi host instance
315 * @channel: channel number (rarely other than 0)
316 * @id: target id number
317 * @lun: logical unit number
318 *
319 * Returns pointer to new struct scsi_device instance or
320 * ERR_PTR(-ENODEV) (or some other bent pointer) if something is
321 * wrong (e.g. no lu responds at given address)
322 *
323 * Might block: yes
324 *
325 * Notes: This call is usually performed internally during a scsi
326 * bus scan when an HBA is added (i.e. scsi_scan_host()). So it
327 * should only be called if the HBA becomes aware of a new scsi
328 * device (lu) after scsi_scan_host() has completed. If successful
329 * this call can lead to sdev_init() and sdev_configure() callbacks
330 * into the LLD.
331 *
332 * Defined in: drivers/scsi/scsi_scan.c
333 **/
334 struct scsi_device * scsi_add_device(struct Scsi_Host *shost,
335 unsigned int channel,
336 unsigned int id, unsigned int lun)
337
338
339 /**
340 * scsi_add_host - perform sysfs registration and set up transport class
341 * @shost: pointer to scsi host instance
342 * @dev: pointer to struct device of type scsi class
343 *
344 * Returns 0 on success, negative errno of failure (e.g. -ENOMEM)
345 *
346 * Might block: no
347 *
348 * Notes: Only required in "hotplug initialization model" after a
349 * successful call to scsi_host_alloc(). This function does not
350 * scan the bus; this can be done by calling scsi_scan_host() or
351 * in some other transport-specific way. The LLD must set up
352 * the transport template before calling this function and may only
353 * access the transport class data after this function has been called.
354 *
355 * Defined in: drivers/scsi/hosts.c
356 **/
357 int scsi_add_host(struct Scsi_Host *shost, struct device * dev)
358
359
360 /**
361 * scsi_change_queue_depth - allow LLD to change queue depth on a SCSI device
362 * @sdev: pointer to SCSI device to change queue depth on
363 * @tags Number of tags allowed if tagged queuing enabled,
364 * or number of commands the LLD can queue up
365 * in non-tagged mode (as per cmd_per_lun).
366 *
367 * Returns nothing
368 *
369 * Might block: no
370 *
371 * Notes: Can be invoked any time on a SCSI device controlled by this
372 * LLD. [Specifically during and after sdev_configure() and prior to
373 * sdev_destroy().] Can safely be invoked from interrupt code.
374 *
375 * Defined in: drivers/scsi/scsi.c [see source code for more notes]
376 *
377 **/
378 int scsi_change_queue_depth(struct scsi_device *sdev, int tags)
379
380
381 /**
382 * scsi_bios_ptable - return copy of block device's partition table
383 * @dev: pointer to gendisk
384 *
385 * Returns pointer to partition table, or NULL for failure
386 *
387 * Might block: yes
388 *
389 * Notes: Caller owns memory returned (free with kfree() )
390 *
391 * Defined in: drivers/scsi/scsicam.c
392 **/
393 unsigned char *scsi_bios_ptable(struct gendisk *dev)
394
395
396 /**
397 * scsi_block_requests - prevent further commands being queued to given host
398 *
399 * @shost: pointer to host to block commands on
400 *
401 * Returns nothing
402 *
403 * Might block: no
404 *
405 * Notes: There is no timer nor any other means by which the requests
406 * get unblocked other than the LLD calling scsi_unblock_requests().
407 *
408 * Defined in: drivers/scsi/scsi_lib.c
409 **/
410 void scsi_block_requests(struct Scsi_Host * shost)
411
412
413 /**
414 * scsi_host_alloc - create a scsi host adapter instance and perform basic
415 * initialization.
416 * @sht: pointer to scsi host template
417 * @privsize: extra bytes to allocate in hostdata array (which is the
418 * last member of the returned Scsi_Host instance)
419 *
420 * Returns pointer to new Scsi_Host instance or NULL on failure
421 *
422 * Might block: yes
423 *
424 * Notes: When this call returns to the LLD, the SCSI bus scan on
425 * this host has _not_ yet been done.
426 * The hostdata array (by default zero length) is a per host scratch
427 * area for the LLD's exclusive use.
428 * Both associated refcounting objects have their refcount set to 1.
429 * Full registration (in sysfs) and a bus scan are performed later when
430 * scsi_add_host() and scsi_scan_host() are called.
431 *
432 * Defined in: drivers/scsi/hosts.c .
433 **/
434 struct Scsi_Host * scsi_host_alloc(const struct scsi_host_template * sht,
435 int privsize)
436
437
438 /**
439 * scsi_host_get - increment Scsi_Host instance refcount
440 * @shost: pointer to struct Scsi_Host instance
441 *
442 * Returns nothing
443 *
444 * Might block: currently may block but may be changed to not block
445 *
446 * Notes: Actually increments the counts in two sub-objects
447 *
448 * Defined in: drivers/scsi/hosts.c
449 **/
450 void scsi_host_get(struct Scsi_Host *shost)
451
452
453 /**
454 * scsi_host_put - decrement Scsi_Host instance refcount, free if 0
455 * @shost: pointer to struct Scsi_Host instance
456 *
457 * Returns nothing
458 *
459 * Might block: currently may block but may be changed to not block
460 *
461 * Notes: Actually decrements the counts in two sub-objects. If the
462 * latter refcount reaches 0, the Scsi_Host instance is freed.
463 * The LLD need not worry exactly when the Scsi_Host instance is
464 * freed, it just shouldn't access the instance after it has balanced
465 * out its refcount usage.
466 *
467 * Defined in: drivers/scsi/hosts.c
468 **/
469 void scsi_host_put(struct Scsi_Host *shost)
470
471
472 /**
473 * scsi_remove_device - detach and remove a SCSI device
474 * @sdev: a pointer to a scsi device instance
475 *
476 * Returns value: 0 on success, -EINVAL if device not attached
477 *
478 * Might block: yes
479 *
480 * Notes: If an LLD becomes aware that a scsi device (lu) has
481 * been removed but its host is still present then it can request
482 * the removal of that scsi device. If successful this call will
483 * lead to the sdev_destroy() callback being invoked. sdev is an
484 * invalid pointer after this call.
485 *
486 * Defined in: drivers/scsi/scsi_sysfs.c .
487 **/
488 int scsi_remove_device(struct scsi_device *sdev)
489
490
491 /**
492 * scsi_remove_host - detach and remove all SCSI devices owned by host
493 * @shost: a pointer to a scsi host instance
494 *
495 * Returns value: 0 on success, 1 on failure (e.g. LLD busy ??)
496 *
497 * Might block: yes
498 *
499 * Notes: Should only be invoked if the "hotplug initialization
500 * model" is being used. It should be called _prior_ to
501 * calling scsi_host_put().
502 *
503 * Defined in: drivers/scsi/hosts.c .
504 **/
505 int scsi_remove_host(struct Scsi_Host *shost)
506
507
508 /**
509 * scsi_report_bus_reset - report scsi _bus_ reset observed
510 * @shost: a pointer to a scsi host involved
511 * @channel: channel (within) host on which scsi bus reset occurred
512 *
513 * Returns nothing
514 *
515 * Might block: no
516 *
517 * Notes: This only needs to be called if the reset is one which
518 * originates from an unknown location. Resets originated by the
519 * mid level itself don't need to call this, but there should be
520 * no harm. The main purpose of this is to make sure that a
521 * CHECK_CONDITION is properly treated.
522 *
523 * Defined in: drivers/scsi/scsi_error.c .
524 **/
525 void scsi_report_bus_reset(struct Scsi_Host * shost, int channel)
526
527
528 /**
529 * scsi_scan_host - scan SCSI bus
530 * @shost: a pointer to a scsi host instance
531 *
532 * Might block: yes
533 *
534 * Notes: Should be called after scsi_add_host()
535 *
536 * Defined in: drivers/scsi/scsi_scan.c
537 **/
538 void scsi_scan_host(struct Scsi_Host *shost)
539
540
541 /**
542 * scsi_track_queue_full - track successive QUEUE_FULL events on given
543 * device to determine if and when there is a need
544 * to adjust the queue depth on the device.
545 * @sdev: pointer to SCSI device instance
546 * @depth: Current number of outstanding SCSI commands on this device,
547 * not counting the one returned as QUEUE_FULL.
548 *
549 * Returns 0 - no change needed
550 * >0 - adjust queue depth to this new depth
551 * -1 - drop back to untagged operation using host->cmd_per_lun
552 * as the untagged command depth
553 *
554 * Might block: no
555 *
556 * Notes: LLDs may call this at any time and we will do "The Right
557 * Thing"; interrupt context safe.
558 *
559 * Defined in: drivers/scsi/scsi.c .
560 **/
561 int scsi_track_queue_full(struct scsi_device *sdev, int depth)
562
563
564 /**
565 * scsi_unblock_requests - allow further commands to be queued to given host
566 *
567 * @shost: pointer to host to unblock commands on
568 *
569 * Returns nothing
570 *
571 * Might block: no
572 *
573 * Defined in: drivers/scsi/scsi_lib.c .
574 **/
575 void scsi_unblock_requests(struct Scsi_Host * shost)
576
577
578
579 Interface Functions
580 ===================
581 Interface functions are supplied (defined) by LLDs and their function
582 pointers are placed in an instance of struct scsi_host_template which
583 is passed to scsi_host_alloc().
584 Some are mandatory. Interface functions should be declared static. The
585 accepted convention is that driver "xyz" will declare its sdev_configure()
586 function as::
587
588 static int xyz_sdev_configure(struct scsi_device * sdev);
589
590 and so forth for all interface functions listed below.
591
592 A pointer to this function should be placed in the 'sdev_configure' member
593 of a "struct scsi_host_template" instance. A pointer to such an instance
594 should be passed to the mid level's scsi_host_alloc().
595 .
596
597 The interface functions are also described in the include/scsi/scsi_host.h
598 file immediately above their definition point in "struct scsi_host_template".
599 In some cases more detail is given in scsi_host.h than below.
600
601 The interface functions are listed below in alphabetical order.
602
603 Summary:
604
605 - bios_param - fetch head, sector, cylinder info for a disk
606 - eh_timed_out - notify the host that a command timer expired
607 - eh_abort_handler - abort given command
608 - eh_bus_reset_handler - issue SCSI bus reset
609 - eh_device_reset_handler - issue SCSI device reset
610 - eh_host_reset_handler - reset host (host bus adapter)
611 - info - supply information about given host
612 - ioctl - driver can respond to ioctls
613 - proc_info - supports /proc/scsi/{driver_name}/{host_no}
614 - queuecommand - queue scsi command, invoke 'done' on completion
615 - sdev_init - prior to any commands being sent to a new device
616 - sdev_configure - driver fine tuning for given device after attach
617 - sdev_destroy - given device is about to be shut down
618
619
620 Details::
621
622 /**
623 * bios_param - fetch head, sector, cylinder info for a disk
624 * @sdev: pointer to scsi device context (defined in
625 * include/scsi/scsi_device.h)
626 * @disk: pointer to gendisk (defined in blkdev.h)
627 * @capacity: device size (in 512 byte sectors)
628 * @params: three element array to place output:
629 * params[0] number of heads (max 255)
630 * params[1] number of sectors (max 63)
631 * params[2] number of cylinders
632 *
633 * Return value is ignored
634 *
635 * Locks: none
636 *
637 * Calling context: process (sd)
638 *
639 * Notes: an arbitrary geometry (based on READ CAPACITY) is used
640 * if this function is not provided. The params array is
641 * pre-initialized with made up values just in case this function
642 * doesn't output anything.
643 *
644 * Optionally defined in: LLD
645 **/
646 int bios_param(struct scsi_device * sdev, struct gendisk *disk,
647 sector_t capacity, int params[3])
648
649
650 /**
651 * eh_timed_out - The timer for the command has just fired
652 * @scp: identifies command timing out
653 *
654 * Returns:
655 *
656 * EH_HANDLED: I fixed the error, please complete the command
657 * EH_RESET_TIMER: I need more time, reset the timer and
658 * begin counting again
659 * EH_NOT_HANDLED Begin normal error recovery
660 *
661 *
662 * Locks: None held
663 *
664 * Calling context: interrupt
665 *
666 * Notes: This is to give the LLD an opportunity to do local recovery.
667 * This recovery is limited to determining if the outstanding command
668 * will ever complete. You may not abort and restart the command from
669 * this callback.
670 *
671 * Optionally defined in: LLD
672 **/
673 int eh_timed_out(struct scsi_cmnd * scp)
674
675
676 /**
677 * eh_abort_handler - abort command associated with scp
678 * @scp: identifies command to be aborted
679 *
680 * Returns SUCCESS if command aborted else FAILED
681 *
682 * Locks: None held
683 *
684 * Calling context: kernel thread
685 *
686 * Notes: This is called only for a command that has timed out.
687 *
688 * Optionally defined in: LLD
689 **/
690 int eh_abort_handler(struct scsi_cmnd * scp)
691
692
693 /**
694 * eh_bus_reset_handler - issue SCSI bus reset
695 * @scp: SCSI bus that contains this device should be reset
696 *
697 * Returns SUCCESS if command aborted else FAILED
698 *
699 * Locks: None held
700 *
701 * Calling context: kernel thread
702 *
703 * Notes: Invoked from scsi_eh thread. No other commands will be
704 * queued on current host during eh.
705 *
706 * Optionally defined in: LLD
707 **/
708 int eh_bus_reset_handler(struct scsi_cmnd * scp)
709
710
711 /**
712 * eh_device_reset_handler - issue SCSI device reset
713 * @scp: identifies SCSI device to be reset
714 *
715 * Returns SUCCESS if command aborted else FAILED
716 *
717 * Locks: None held
718 *
719 * Calling context: kernel thread
720 *
721 * Notes: Invoked from scsi_eh thread. No other commands will be
722 * queued on current host during eh.
723 *
724 * Optionally defined in: LLD
725 **/
726 int eh_device_reset_handler(struct scsi_cmnd * scp)
727
728
729 /**
730 * eh_host_reset_handler - reset host (host bus adapter)
731 * @scp: SCSI host that contains this device should be reset
732 *
733 * Returns SUCCESS if command aborted else FAILED
734 *
735 * Locks: None held
736 *
737 * Calling context: kernel thread
738 *
739 * Notes: Invoked from scsi_eh thread. No other commands will be
740 * queued on current host during eh.
741 * With the default eh_strategy in place, if none of the _abort_,
742 * _device_reset_, _bus_reset_ or this eh handler function are
743 * defined (or they all return FAILED) then the device in question
744 * will be set offline whenever eh is invoked.
745 *
746 * Optionally defined in: LLD
747 **/
748 int eh_host_reset_handler(struct scsi_cmnd * scp)
749
750
751 /**
752 * info - supply information about given host: driver name plus data
753 * to distinguish given host
754 * @shp: host to supply information about
755 *
756 * Return ASCII null terminated string. [This driver is assumed to
757 * manage the memory pointed to and maintain it, typically for the
758 * lifetime of this host.]
759 *
760 * Locks: none
761 *
762 * Calling context: process
763 *
764 * Notes: Often supplies PCI or ISA information such as IO addresses
765 * and interrupt numbers. If not supplied struct Scsi_Host::name used
766 * instead. It is assumed the returned information fits on one line
767 * (i.e. does not included embedded newlines).
768 * The SCSI_IOCTL_PROBE_HOST ioctl yields the string returned by this
769 * function (or struct Scsi_Host::name if this function is not
770 * available).
771 *
772 * Optionally defined in: LLD
773 **/
774 const char * info(struct Scsi_Host * shp)
775
776
777 /**
778 * ioctl - driver can respond to ioctls
779 * @sdp: device that ioctl was issued for
780 * @cmd: ioctl number
781 * @arg: pointer to read or write data from. Since it points to
782 * user space, should use appropriate kernel functions
783 * (e.g. copy_from_user() ). In the Unix style this argument
784 * can also be viewed as an unsigned long.
785 *
786 * Returns negative "errno" value when there is a problem. 0 or a
787 * positive value indicates success and is returned to the user space.
788 *
789 * Locks: none
790 *
791 * Calling context: process
792 *
793 * Notes: The SCSI subsystem uses a "trickle down" ioctl model.
794 * The user issues an ioctl() against an upper level driver
795 * (e.g. /dev/sdc) and if the upper level driver doesn't recognize
796 * the 'cmd' then it is passed to the SCSI mid level. If the SCSI
797 * mid level does not recognize it, then the LLD that controls
798 * the device receives the ioctl. According to recent Unix standards
799 * unsupported ioctl() 'cmd' numbers should return -ENOTTY.
800 *
801 * Optionally defined in: LLD
802 **/
803 int ioctl(struct scsi_device *sdp, int cmd, void *arg)
804
805
806 /**
807 * proc_info - supports /proc/scsi/{driver_name}/{host_no}
808 * @buffer: anchor point to output to (0==writeto1_read0) or fetch from
809 * (1==writeto1_read0).
810 * @start: where "interesting" data is written to. Ignored when
811 * 1==writeto1_read0.
812 * @offset: offset within buffer 0==writeto1_read0 is actually
813 * interested in. Ignored when 1==writeto1_read0 .
814 * @length: maximum (or actual) extent of buffer
815 * @host_no: host number of interest (struct Scsi_Host::host_no)
816 * @writeto1_read0: 1 -> data coming from user space towards driver
817 * (e.g. "echo some_string > /proc/scsi/xyz/2")
818 * 0 -> user what data from this driver
819 * (e.g. "cat /proc/scsi/xyz/2")
820 *
821 * Returns length when 1==writeto1_read0. Otherwise number of chars
822 * output to buffer past offset.
823 *
824 * Locks: none held
825 *
826 * Calling context: process
827 *
828 * Notes: Driven from scsi_proc.c which interfaces to proc_fs. proc_fs
829 * support can now be configured out of the scsi subsystem.
830 *
831 * Optionally defined in: LLD
832 **/
833 int proc_info(char * buffer, char ** start, off_t offset,
834 int length, int host_no, int writeto1_read0)
835
836
837 /**
838 * queuecommand - queue scsi command, invoke scp->scsi_done on completion
839 * @shost: pointer to the scsi host object
840 * @scp: pointer to scsi command object
841 *
842 * Returns 0 on success.
843 *
844 * If there's a failure, return either:
845 *
846 * SCSI_MLQUEUE_DEVICE_BUSY if the device queue is full, or
847 * SCSI_MLQUEUE_HOST_BUSY if the entire host queue is full
848 *
849 * On both of these returns, the mid-layer will requeue the I/O
850 *
851 * - if the return is SCSI_MLQUEUE_DEVICE_BUSY, only that particular
852 * device will be paused, and it will be unpaused when a command to
853 * the device returns (or after a brief delay if there are no more
854 * outstanding commands to it). Commands to other devices continue
855 * to be processed normally.
856 *
857 * - if the return is SCSI_MLQUEUE_HOST_BUSY, all I/O to the host
858 * is paused and will be unpaused when any command returns from
859 * the host (or after a brief delay if there are no outstanding
860 * commands to the host).
861 *
862 * For compatibility with earlier versions of queuecommand, any
863 * other return value is treated the same as
864 * SCSI_MLQUEUE_HOST_BUSY.
865 *
866 * Other types of errors that are detected immediately may be
867 * flagged by setting scp->result to an appropriate value,
868 * invoking the scp->scsi_done callback, and then returning 0
869 * from this function. If the command is not performed
870 * immediately (and the LLD is starting (or will start) the given
871 * command) then this function should place 0 in scp->result and
872 * return 0.
873 *
874 * Command ownership. If the driver returns zero, it owns the
875 * command and must take responsibility for ensuring the
876 * scp->scsi_done callback is executed. Note: the driver may
877 * call scp->scsi_done before returning zero, but after it has
878 * called scp->scsi_done, it may not return any value other than
879 * zero. If the driver makes a non-zero return, it must not
880 * execute the command's scsi_done callback at any time.
881 *
882 * Locks: up to and including 2.6.36, struct Scsi_Host::host_lock
883 * held on entry (with "irqsave") and is expected to be
884 * held on return. From 2.6.37 onwards, queuecommand is
885 * called without any locks held.
886 *
887 * Calling context: in interrupt (soft irq) or process context
888 *
889 * Notes: This function should be relatively fast. Normally it
890 * will not wait for IO to complete. Hence the scp->scsi_done
891 * callback is invoked (often directly from an interrupt service
892 * routine) some time after this function has returned. In some
893 * cases (e.g. pseudo adapter drivers that manufacture the
894 * response to a SCSI INQUIRY) the scp->scsi_done callback may be
895 * invoked before this function returns. If the scp->scsi_done
896 * callback is not invoked within a certain period the SCSI mid
897 * level will commence error processing. If a status of CHECK
898 * CONDITION is placed in "result" when the scp->scsi_done
899 * callback is invoked, then the LLD driver should perform
900 * autosense and fill in the struct scsi_cmnd::sense_buffer
901 * array. The scsi_cmnd::sense_buffer array is zeroed prior to
902 * the mid level queuing a command to an LLD.
903 *
904 * Defined in: LLD
905 **/
906 int queuecommand(struct Scsi_Host *shost, struct scsi_cmnd * scp)
907
908
909 /**
910 * sdev_init - prior to any commands being sent to a new device
911 * (i.e. just prior to scan) this call is made
912 * @sdp: pointer to new device (about to be scanned)
913 *
914 * Returns 0 if ok. Any other return is assumed to be an error and
915 * the device is ignored.
916 *
917 * Locks: none
918 *
919 * Calling context: process
920 *
921 * Notes: Allows the driver to allocate any resources for a device
922 * prior to its initial scan. The corresponding scsi device may not
923 * exist but the mid level is just about to scan for it (i.e. send
924 * and INQUIRY command plus ...). If a device is found then
925 * sdev_configure() will be called while if a device is not found
926 * sdev_destroy() is called.
927 * For more details see the include/scsi/scsi_host.h file.
928 *
929 * Optionally defined in: LLD
930 **/
931 int sdev_init(struct scsi_device *sdp)
932
933
934 /**
935 * sdev_configure - driver fine tuning for given device just after it
936 * has been first scanned (i.e. it responded to an
937 * INQUIRY)
938 * @sdp: device that has just been attached
939 *
940 * Returns 0 if ok. Any other return is assumed to be an error and
941 * the device is taken offline. [offline devices will _not_ have
942 * sdev_destroy() called on them so clean up resources.]
943 *
944 * Locks: none
945 *
946 * Calling context: process
947 *
948 * Notes: Allows the driver to inspect the response to the initial
949 * INQUIRY done by the scanning code and take appropriate action.
950 * For more details see the include/scsi/scsi_host.h file.
951 *
952 * Optionally defined in: LLD
953 **/
954 int sdev_configure(struct scsi_device *sdp)
955
956
957 /**
958 * sdev_destroy - given device is about to be shut down. All
959 * activity has ceased on this device.
960 * @sdp: device that is about to be shut down
961 *
962 * Returns nothing
963 *
964 * Locks: none
965 *
966 * Calling context: process
967 *
968 * Notes: Mid level structures for given device are still in place
969 * but are about to be torn down. Any per device resources allocated
970 * by this driver for given device should be freed now. No further
971 * commands will be sent for this sdp instance. [However the device
972 * could be re-attached in the future in which case a new instance
973 * of struct scsi_device would be supplied by future sdev_init()
974 * and sdev_configure() calls.]
975 *
976 * Optionally defined in: LLD
977 **/
978 void sdev_destroy(struct scsi_device *sdp)
979
980
981
982 Data Structures
983 ===============
984 struct scsi_host_template
985 -------------------------
986 There is one "struct scsi_host_template" instance per LLD [#]_. It is
987 typically initialized as a file scope static in a driver's header file. That
988 way members that are not explicitly initialized will be set to 0 or NULL.
989 Members of interest:
990
991 name
992 - name of driver (may contain spaces, please limit to
993 less than 80 characters)
994
995 proc_name
996 - name used in "/proc/scsi/<proc_name>/<host_no>" and
997 by sysfs in one of its "drivers" directories. Hence
998 "proc_name" should only contain characters acceptable
999 to a Unix file name.
1001 ``(*queuecommand)()``
1002 - primary callback that the mid level uses to inject
1003 SCSI commands into an LLD.
1005 vendor_id
1006 - a unique value that identifies the vendor supplying
1007 the LLD for the Scsi_Host. Used most often in validating
1008 vendor-specific message requests. Value consists of an
1009 identifier type and a vendor-specific value.
1010 See scsi_netlink.h for a description of valid formats.
1012 The structure is defined and commented in include/scsi/scsi_host.h
1014 .. [#] In extreme situations a single driver may have several instances
1015 if it controls several different classes of hardware (e.g. an LLD
1016 that handles both ISA and PCI cards and has a separate instance of
1017 struct scsi_host_template for each class).
1019 struct Scsi_Host
1020 ----------------
1021 There is one struct Scsi_Host instance per host (HBA) that an LLD
1022 controls. The struct Scsi_Host structure has many members in common
1023 with "struct scsi_host_template". When a new struct Scsi_Host instance
1024 is created (in scsi_host_alloc() in hosts.c) those common members are
1025 initialized from the driver's struct scsi_host_template instance. Members
1026 of interest:
1028 host_no
1029 - system-wide unique number that is used for identifying
1030 this host. Issued in ascending order from 0.
1031 can_queue
1032 - must be greater than 0; do not send more than can_queue
1033 commands to the adapter.
1034 this_id
1035 - scsi id of host (scsi initiator) or -1 if not known
1036 sg_tablesize
1037 - maximum scatter gather elements allowed by host.
1038 Set this to SG_ALL or less to avoid chained SG lists.
1039 Must be at least 1.
1040 max_sectors
1041 - maximum number of sectors (usually 512 bytes) allowed
1042 in a single SCSI command. The default value of 0 leads
1043 to a setting of SCSI_DEFAULT_MAX_SECTORS (defined in
1044 scsi_host.h) which is currently set to 1024. So for a
1045 disk the maximum transfer size is 512 KB when max_sectors
1046 is not defined. Note that this size may not be sufficient
1047 for disk firmware uploads.
1048 cmd_per_lun
1049 - maximum number of commands that can be queued on devices
1050 controlled by the host. Overridden by LLD calls to
1051 scsi_change_queue_depth().
1052 hostt
1053 - pointer to driver's struct scsi_host_template from which
1054 this struct Scsi_Host instance was spawned
1055 hostt->proc_name
1056 - name of LLD. This is the driver name that sysfs uses.
1057 transportt
1058 - pointer to driver's struct scsi_transport_template instance
1059 (if any). FC and SPI transports currently supported.
1060 hostdata[0]
1061 - area reserved for LLD at end of struct Scsi_Host. Size
1062 is set by the second argument (named 'privsize') to
1063 scsi_host_alloc().
1065 The scsi_host structure is defined in include/scsi/scsi_host.h
1067 struct scsi_device
1068 ------------------
1069 Generally, there is one instance of this structure for each SCSI logical unit
1070 on a host. SCSI devices connected to a host are uniquely identified by a
1071 channel number, target id and logical unit number (lun).
1072 The structure is defined in include/scsi/scsi_device.h
1074 struct scsi_cmnd
1075 ----------------
1076 Instances of this structure convey SCSI commands to the LLD and responses
1077 back to the mid level. The SCSI mid level will ensure that no more SCSI
1078 commands become queued against the LLD than are indicated by
1079 scsi_change_queue_depth() (or struct Scsi_Host::cmd_per_lun). There will
1080 be at least one instance of struct scsi_cmnd available for each SCSI device.
1081 Members of interest:
1083 cmnd
1084 - array containing SCSI command
1085 cmd_len
1086 - length (in bytes) of SCSI command
1087 sc_data_direction
1088 - direction of data transfer in data phase. See
1089 "enum dma_data_direction" in include/linux/dma-mapping.h
1090 result
1091 - should be set by LLD prior to calling 'done'. A value
1092 of 0 implies a successfully completed command (and all
1093 data (if any) has been transferred to or from the SCSI
1094 target device). 'result' is a 32-bit unsigned integer that
1095 can be viewed as 2 related bytes. The SCSI status value is
1096 in the LSB. See include/scsi/scsi.h status_byte() and
1097 host_byte() macros and related constants.
1098 sense_buffer
1099 - an array (maximum size: SCSI_SENSE_BUFFERSIZE bytes) that
1100 should be written when the SCSI status (LSB of 'result')
1101 is set to CHECK_CONDITION (2). When CHECK_CONDITION is
1102 set, if the top nibble of sense_buffer[0] has the value 7
1103 then the mid level will assume the sense_buffer array
1104 contains a valid SCSI sense buffer; otherwise the mid
1105 level will issue a REQUEST_SENSE SCSI command to
1106 retrieve the sense buffer. The latter strategy is error
1107 prone in the presence of command queuing so the LLD should
1108 always "auto-sense".
1109 device
1110 - pointer to scsi_device object that this command is
1111 associated with.
1112 resid_len (access by calling scsi_set_resid() / scsi_get_resid())
1113 - an LLD should set this unsigned integer to the requested
1114 transfer length (i.e. 'request_bufflen') less the number
1115 of bytes that are actually transferred. 'resid_len' is
1116 preset to 0 so an LLD can ignore it if it cannot detect
1117 underruns (overruns should not be reported). An LLD
1118 should set 'resid_len' prior to invoking 'done'. The most
1119 interesting case is data transfers from a SCSI target
1120 device (e.g. READs) that underrun.
1121 underflow
1122 - LLD should place (DID_ERROR << 16) in 'result' if
1123 actual number of bytes transferred is less than this
1124 figure. Not many LLDs implement this check and some that
1125 do just output an error message to the log rather than
1126 report a DID_ERROR. Better for an LLD to implement
1127 'resid_len'.
1129 It is recommended that a LLD set 'resid_len' on data transfers from a SCSI
1130 target device (e.g. READs). It is especially important that 'resid_len' is set
1131 when such data transfers have sense keys of MEDIUM ERROR and HARDWARE ERROR
1132 (and possibly RECOVERED ERROR). In these cases if a LLD is in doubt how much
1133 data has been received then the safest approach is to indicate no bytes have
1134 been received. For example: to indicate that no valid data has been received
1135 a LLD might use these helpers::
1137 scsi_set_resid(SCpnt, scsi_bufflen(SCpnt));
1139 where 'SCpnt' is a pointer to a scsi_cmnd object. To indicate only three 512
1140 bytes blocks have been received 'resid_len' could be set like this::
1142 scsi_set_resid(SCpnt, scsi_bufflen(SCpnt) - (3 * 512));
1144 The scsi_cmnd structure is defined in include/scsi/scsi_cmnd.h
1147 Locks
1148 =====
1149 Each struct Scsi_Host instance has a spin_lock called struct
1150 Scsi_Host::default_lock which is initialized in scsi_host_alloc() [found in
1151 hosts.c]. Within the same function the struct Scsi_Host::host_lock pointer
1152 is initialized to point at default_lock. Thereafter lock and unlock
1153 operations performed by the mid level use the struct Scsi_Host::host_lock
1154 pointer. Previously drivers could override the host_lock pointer but
1155 this is not allowed anymore.
1158 Autosense
1159 =========
1160 Autosense (or auto-sense) is defined in the SAM-2 document as "the
1161 automatic return of sense data to the application client coincident
1162 with the completion of a SCSI command" when a status of CHECK CONDITION
1163 occurs. LLDs should perform autosense. This should be done when the LLD
1164 detects a CHECK CONDITION status by either:
1166 a) instructing the SCSI protocol (e.g. SCSI Parallel Interface (SPI))
1167 to perform an extra data in phase on such responses
1168 b) or, the LLD issuing a REQUEST SENSE command itself
1170 Either way, when a status of CHECK CONDITION is detected, the mid level
1171 decides whether the LLD has performed autosense by checking struct
1172 scsi_cmnd::sense_buffer[0] . If this byte has an upper nibble of 7 (or 0xf)
1173 then autosense is assumed to have taken place. If it has another value (and
1174 this byte is initialized to 0 before each command) then the mid level will
1175 issue a REQUEST SENSE command.
1177 In the presence of queued commands the "nexus" that maintains sense
1178 buffer data from the command that failed until a following REQUEST SENSE
1179 may get out of synchronization. This is why it is best for the LLD
1180 to perform autosense.
1183 Changes since Linux kernel 2.4 series
1184 =====================================
1185 io_request_lock has been replaced by several finer grained locks. The lock
1186 relevant to LLDs is struct Scsi_Host::host_lock and there is
1187 one per SCSI host.
1189 The older error handling mechanism has been removed. This means the
1190 LLD interface functions abort() and reset() have been removed.
1191 The struct scsi_host_template::use_new_eh_code flag has been removed.
1193 In the 2.4 series the SCSI subsystem configuration descriptions were
1194 aggregated with the configuration descriptions from all other Linux
1195 subsystems in the Documentation/Configure.help file. In the 2.6 series,
1196 the SCSI subsystem now has its own (much smaller) drivers/scsi/Kconfig
1197 file that contains both configuration and help information.
1199 struct SHT has been renamed to struct scsi_host_template.
1201 Addition of the "hotplug initialization model" and many extra functions
1202 to support it.
1205 Credits
1206 =======
1207 The following people have contributed to this document:
1209 - Mike Anderson <andmike at us dot ibm dot com>
1210 - James Bottomley <James dot Bottomley at hansenpartnership dot com>
1211 - Patrick Mansfield <patmans at us dot ibm dot com>
1212 - Christoph Hellwig <hch at infradead dot org>
1213 - Doug Ledford <dledford at redhat dot com>
1214 - Andries Brouwer <Andries dot Brouwer at cwi dot nl>
1215 - Randy Dunlap <rdunlap at xenotime dot net>
1216 - Alan Stern <stern at rowland dot harvard dot edu>
1219 Douglas Gilbert
1220 dgilbert at interlog dot com
1222 21st September 2004

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

SCSI host, initiator와 LLD의 역할

1-41

이 문서는 Linux SCSI 중간 계층과 하위 계층 드라이버(LLD)의 인터페이스를 설명한다. LLD는 host bus adapter(HBA) 드라이버 또는 host driver(HD)라고도 부른다. 여기서 host는 PCI나 ISA 같은 컴퓨터 I/O 버스와 SCSI transport의 단일 initiator port 사이를 잇는 다리다. initiator는 disk 같은 target port에 SCSI 명령을 보낸다.

실행 중인 시스템에는 하드웨어 종류마다 하나씩 여러 LLD가 있을 수 있다. 대부분의 LLD는 하나 이상의 HBA를 제어하며 HBA 하나가 여러 host를 포함하기도 한다. USB나 IEEE 1394처럼 transport 자체에 Linux 하위 시스템이 있으면 `usb-storage`나 `ieee1394/sbp2` 같은 SCSI LLD가 두 드라이버 하위 시스템 사이의 소프트웨어 bridge 역할을 한다.

`aic7xxx`는 Adaptec 7xxx 계열 SPI controller를 제어하는 예다. 커널 내장 또는 module로 실행할 수 있고, 단 하나의 드라이버 인스턴스가 여러 PCI daughter-board 또는 motherboard 내장 HBA를 관리할 수 있다. dual controller HBA는 host 두 개로 나타난다. host와 PCI device가 일대일인 경우가 흔하지만 ISA adapter처럼 필수 조건은 아니다.

SCSI 중간 계층은 LLD를 SCSI 상위 계층 드라이버와 block layer 같은 다른 계층으로부터 격리한다. 원문은 대략 Linux 2.6.8의 인터페이스를 기준으로 작성되었다.

.. SPDX-License-Identifier: GPL-2.0

=============================================
SCSI mid_level - lower_level driver interface
=============================================

Introduction
============
This document outlines the interface between the Linux SCSI mid level and
SCSI lower level drivers. Lower level drivers (LLDs) are variously called
host bus adapter (HBA) drivers and host drivers (HD). A "host" in this
context is a bridge between a computer IO bus (e.g. PCI or ISA) and a
single SCSI initiator port on a SCSI transport. An "initiator" port
(SCSI terminology, see SAM-3 at http://www.t10.org) sends SCSI commands
to "target" SCSI ports (e.g. disks). There can be many LLDs in a running
system, but only one per hardware type. Most LLDs can control one or more
SCSI HBAs. Some HBAs contain multiple hosts.

In some cases the SCSI transport is an external bus that already has
its own subsystem in Linux (e.g. USB and ieee1394). In such cases the
SCSI subsystem LLD is a software bridge to the other driver subsystem.
Examples are the usb-storage driver (found in the drivers/usb/storage
directory) and the ieee1394/sbp2 driver (found in the drivers/ieee1394
directory).

For example, the aic7xxx LLD controls Adaptec SCSI parallel interface
(SPI) controllers based on that company's 7xxx chip series. The aic7xxx
LLD can be built into the kernel or loaded as a module. There can only be
one aic7xxx LLD running in a Linux system but it may be controlling many
HBAs. These HBAs might be either on PCI daughter-boards or built into
the motherboard (or both). Some aic7xxx based HBAs are dual controllers
and thus represent two hosts. Like most modern HBAs, each aic7xxx host
has its own PCI device address. [The one-to-one correspondence between
a SCSI host and a PCI device is common but not required (e.g. with
ISA adapters).]

The SCSI mid level isolates an LLD from other layers such as the SCSI
upper layer drivers and the block layer.

This version of the document roughly matches Linux kernel version 2.6.8 .

관련 문서와 드라이버 구성

42-119

커널 소스의 `Documentation/scsi`에는 이 문서 `scsi_mid_low_api.rst`, LLD별 문서, `scsi.rst`, tape용 `st.rst`, sg용 `scsi-generic.rst`가 있다. 최신 렌더링 주소로 `https://docs.kernel.org/scsi/scsi_mid_low_api.html`을 제시한다. 일부 LLD 자료와 URL은 C 소스 또는 같은 소스 디렉터리에 있으며 USB mass storage의 예는 `/usr/src/linux/drivers/usb/storage`에서 찾는다.

전통적인 LLD는 `drivers/scsi` 아래 `xyz.h`와 `xyz.c` 같은 두 파일로 구성했지만 헤더가 반드시 필요한 것은 아니다. 여러 운영체제로 이식된 드라이버는 generic 코드와 OS별 코드를 분리하며 자체 하위 디렉터리를 쓰기도 한다. 새 LLD를 추가할 때는 `drivers/scsi/Makefile`과 `drivers/scsi/Kconfig`를 갱신하고 기존 드라이버 구성을 참고한다.

초기화 방식은 두 가지다. Linux 2.4와 비슷한 passive 모델은 드라이버를 load할 때 HBA를 검출한다. 권장되는 hotplug 모델은 LLD의 수명 동안 HBA를 추가하거나 제거할 수 있어 영구 연결 장치와 USB·IEEE 1394 카메라 같은 hotplug 장치를 함께 처리한다.

LLD는 세 방식으로 중간 계층과 접촉한다. 첫째 중간 계층 제공 함수를 직접 호출하고, 둘째 `struct scsi_host_template`의 함수 포인터로 콜백을 등록하며, 셋째 공유 자료 구조 인스턴스에 직접 접근한다. 제공하지 않는 콜백 포인터는 `NULL`이어야 한다. file scope에서 template을 정의하면 명시하지 않은 멤버가 자동으로 0 또는 NULL이 된다.

공유 자료 구조는 특히 hotplug 환경에서 수명을 주의해야 한다. LLD 내부 함수와 file-scope 데이터는 모두 `static`으로 정의한다. 예를 들어 `static int xxx_sdev_init(struct scsi_device *sdev) { /* code */ }`처럼 드라이버 이름을 접두사로 붙인다.

LLD와 중간 계층의 접점
방식인터페이스
직접 호출scsi_* 중간 계층 제공 함수
콜백 등록struct scsi_host_template 함수 포인터
자료 구조 접근Scsi_Host, scsi_device, scsi_cmnd 인스턴스

드라이버가 SCSI 중간 계층을 사용하는 세 방식이다.

Documentation
=============
There is a SCSI documentation directory within the kernel source tree,
typically Documentation/scsi . Most documents are in reStructuredText
format. This file is named scsi_mid_low_api.rst and can be
found in that directory. A more recent copy of this document may be found
at https://docs.kernel.org/scsi/scsi_mid_low_api.html. Many LLDs are
documented in Documentation/scsi (e.g. aic7xxx.rst). The SCSI mid-level is
briefly described in scsi.rst which contains a URL to a document describing
the SCSI subsystem in the Linux kernel 2.4 series. Two upper level
drivers have documents in that directory: st.rst (SCSI tape driver) and
scsi-generic.rst (for the sg driver).

Some documentation (or URLs) for LLDs may be found in the C source code
or in the same directory as the C source code. For example to find a URL
about the USB mass storage driver see the
/usr/src/linux/drivers/usb/storage directory.

Driver structure
================
Traditionally an LLD for the SCSI subsystem has been at least two files in
the drivers/scsi directory. For example, a driver called "xyz" has a header
file "xyz.h" and a source file "xyz.c". [Actually there is no good reason
why this couldn't all be in one file; the header file is superfluous.] Some
drivers that have been ported to several operating systems have more than
two files. For example the aic7xxx driver has separate files for generic
and OS-specific code (e.g. FreeBSD and Linux). Such drivers tend to have
their own directory under the drivers/scsi directory.

When a new LLD is being added to Linux, the following files (found in the
drivers/scsi directory) will need some attention: Makefile and Kconfig .
It is probably best to study how existing LLDs are organized.

As the 2.5 series development kernels evolve into the 2.6 series
production series, changes are being introduced into this interface. An
example of this is driver initialization code where there are now 2 models
available. The older one, similar to what was found in the Linux 2.4 series,
is based on hosts that are detected at HBA driver load time. This will be
referred to the "passive" initialization model. The newer model allows HBAs
to be hot plugged (and unplugged) during the lifetime of the LLD and will
be referred to as the "hotplug" initialization model. The newer model is
preferred as it can handle both traditional SCSI equipment that is
permanently connected as well as modern "SCSI" devices (e.g. USB or
IEEE 1394 connected digital cameras) that are hotplugged. Both
initialization models are discussed in the following sections.

An LLD interfaces to the SCSI subsystem several ways:

  a) directly invoking functions supplied by the mid level
  b) passing a set of function pointers to a registration function
     supplied by the mid level. The mid level will then invoke these
     functions at some point in the future. The LLD will supply
     implementations of these functions.
  c) direct access to instances of well known data structures maintained
     by the mid level

Those functions in group a) are listed in a section entitled "Mid level
supplied functions" below.

Those functions in group b) are listed in a section entitled "Interface
functions" below. Their function pointers are placed in the members of
"struct scsi_host_template", an instance of which is passed to
scsi_host_alloc().  Those interface functions that the LLD does not
wish to supply should have NULL placed in the corresponding member of
struct scsi_host_template.  Defining an instance of struct
scsi_host_template at file scope will cause NULL to be  placed in function
pointer members not explicitly initialized.

Those usages in group c) should be handled with care, especially in a
"hotplug" environment. LLDs should be aware of the lifetime of instances
that are shared with the mid level and other layers.

All functions defined within an LLD and all data defined at file scope
should be static. For example the sdev_init() function in an LLD
called "xxx" could be defined as
``static int xxx_sdev_init(struct scsi_device * sdev) { /* code */ }``

HBA hotplug 등록과 제거

120-190

hotplug 모델에서는 LLD가 SCSI host를 중간 계층에 넣고 빼는 시점을 제어한다. 보통 sysfs `probe()`가 HBA 검출을 알리면 LLD가 지원 장치인지 확인하고 HBA를 초기화한 뒤 새 host를 등록한다. 드라이버 초기화 때 예상 I/O 버스에 자신을 등록하고, 쓰기 가능한 parameter를 포함한 드라이버 속성도 sysfs에 등록할 수 있다. 중간 계층은 첫 HBA가 등록될 때 LLD를 처음 인식한다.

HBA 추가 순서는 `scsi_host_alloc()`, `scsi_add_host()`, `scsi_scan_host()`다. scan 중 응답하는 장치마다 `sdev_init()` 뒤 `sdev_configure()`를 호출하며, LLD는 그 안에서 `scsi_change_queue_depth()`로 기본 queue를 조정할 수 있다. 주소를 조사했지만 응답하지 않는 장치에도 `sdev_init()`과 `sdev_destroy()` 쌍이 호출된다.

module `rmmod`에 따른 정상 종료든 sysfs `remove()`에 따른 hot unplug이든 HBA 제거 순서는 같다. `scsi_remove_host()`가 소속 장치마다 `sdev_destroy()`를 호출하고, 마지막에 LLD가 `scsi_host_put()`으로 참조를 놓는다. `scsi_host_alloc()`이 돌려준 `Scsi_Host`는 중간 계층이 소유하며 참조 수가 0이 될 때 해제된다.

마운트된 파일 시스템에서 명령을 처리 중인 disk의 HBA를 뽑는 상황은 복잡하다. 원문은 이런 수명 문제를 처리하기 위해 중간 계층에 reference counting이 도입되고 있다고 설명한다.

HBA probe 흐름
scsi_host_allocscsi_add_hostscsi_scan_host장치 1: sdev_init -> sdev_configure장치 2: sdev_init -> sdev_configure미응답 주소: sdev_init -> sdev_destroy

응답하는 두 장치와 응답하지 않는 한 주소를 조사하는 원문 흐름이다.

HBA remove 흐름
scsi_remove_host각 장치 sdev_destroyscsi_host_put참조 수 0이면 Scsi_Host 해제

host 제거 뒤 참조를 놓는 순서를 보존했다.

Hotplug initialization model
============================
In this model an LLD controls when SCSI hosts are introduced and removed
from the SCSI subsystem. Hosts can be introduced as early as driver
initialization and removed as late as driver shutdown. Typically a driver
will respond to a sysfs probe() callback that indicates an HBA has been
detected. After confirming that the new device is one that the LLD wants
to control, the LLD will initialize the HBA and then register a new host
with the SCSI mid level.

During LLD initialization the driver should register itself with the
appropriate IO bus on which it expects to find HBA(s) (e.g. the PCI bus).
This can probably be done via sysfs. Any driver parameters (especially
those that are writable after the driver is loaded) could also be
registered with sysfs at this point. The SCSI mid level first becomes
aware of an LLD when that LLD registers its first HBA.

At some later time, the LLD becomes aware of an HBA and what follows
is a typical sequence of calls between the LLD and the mid level.
This example shows the mid level scanning the newly introduced HBA for 3
scsi devices of which only the first 2 respond::

        HBA PROBE: assume 2 SCSI devices found in scan
    LLD                   mid level                    LLD
    ===-------------------=========--------------------===------
    scsi_host_alloc()  -->
    scsi_add_host()  ---->
    scsi_scan_host()  -------+
                            |
                        sdev_init()
                        sdev_configure() -->  scsi_change_queue_depth()
                            |
                        sdev_init()
                        sdev_configure()
                            |
                        sdev_init()   ***
                        sdev_destroy() ***


    *** For scsi devices that the mid level tries to scan but do not
        respond, a sdev_init(), sdev_destroy() pair is called.

If the LLD wants to adjust the default queue settings, it can invoke
scsi_change_queue_depth() in its sdev_configure() routine.

When an HBA is being removed it could be as part of an orderly shutdown
associated with the LLD module being unloaded (e.g. with the "rmmod"
command) or in response to a "hot unplug" indicated by sysfs()'s
remove() callback being invoked. In either case, the sequence is the
same::

            HBA REMOVE: assume 2 SCSI devices attached
    LLD                      mid level                 LLD
    ===----------------------=========-----------------===------
    scsi_remove_host() ---------+
                                |
                        sdev_destroy()
                        sdev_destroy()
    scsi_host_put()

It may be useful for a LLD to keep track of struct Scsi_Host instances
(a pointer is returned by scsi_host_alloc()). Such instances are "owned"
by the mid-level.  struct Scsi_Host instances are freed from
scsi_host_put() when the reference count hits zero.

Hot unplugging an HBA that controls a disk which is processing SCSI
commands on a mounted file system is an interesting situation. Reference
counting logic is being introduced into the mid level to cope with many
of the issues involved. See the section on reference counting below.

SCSI 장치의 동적 추가와 제거

191-225

HBA scan이 끝난 뒤 새 장치를 알게 되는 transport에서는 LLD가 `scsi_add_device()`를 호출한다. 중간 계층은 `sdev_init()`과 `sdev_configure()`를 호출하고, 필요하면 configure 단계에서 `scsi_change_queue_depth()`를 사용할 수 있다.

장치가 빠지거나 연결이 끊겼음을 LLD가 검출하면 `scsi_remove_device()`로 상위 계층에서 제거를 시작하고 중간 계층이 `sdev_destroy()`를 호출한다. SPI처럼 제거를 즉시 알 수 없는 transport는 뒤의 명령 실패를 통해 중간 계층이 장치를 offline으로 만들 수 있다.

LLD가 보관할 수 있는 `struct scsi_device` 포인터는 중간 계층 소유다. 인스턴스는 `sdev_destroy()` 뒤 해제되므로 수명 규칙을 지켜야 한다.

SCSI 장치 hotplug
LLD: scsi_add_device중간 계층: sdev_init중간 계층: sdev_configure선택: scsi_change_queue_depth

scan 뒤 발견된 논리 장치를 추가하는 흐름이다.

SCSI 장치 hot unplug
LLD: 제거 또는 연결 단절 검출scsi_remove_devicesdev_destroy상위 계층에서 장치 제거

host는 유지하면서 논리 장치만 제거한다.

The hotplug concept may be extended to SCSI devices. Currently, when an
HBA is added, the scsi_scan_host() function causes a scan for SCSI devices
attached to the HBA's SCSI transport. On newer SCSI transports the HBA
may become aware of a new SCSI device _after_ the scan has completed.
An LLD can use this sequence to make the mid level aware of a SCSI device::

                    SCSI DEVICE hotplug
    LLD                   mid level                    LLD
    ===-------------------=========--------------------===------
    scsi_add_device()  ------+
                            |
                        sdev_init()
                        sdev_configure()   [--> scsi_change_queue_depth()]

In a similar fashion, an LLD may become aware that a SCSI device has been
removed (unplugged) or the connection to it has been interrupted. Some
existing SCSI transports (e.g. SPI) may not become aware that a SCSI
device has been removed until a subsequent SCSI command fails which will
probably cause that device to be set offline by the mid level. An LLD that
detects the removal of a SCSI device can instigate its removal from
upper layers with this sequence::

                    SCSI DEVICE hot unplug
    LLD                      mid level                 LLD
    ===----------------------=========-----------------===------
    scsi_remove_device() -------+
                                |
                        sdev_destroy()

It may be useful for an LLD to keep track of struct scsi_device instances
(a pointer is passed as the parameter to sdev_init() and
sdev_configure() callbacks). Such instances are "owned" by the mid-level.
struct scsi_device instances are freed after sdev_destroy().

Scsi_Host와 scsi_device 참조 수

226-265

`Scsi_Host`의 reference counting은 인스턴스 소유를 사용하는 여러 SCSI 계층에 분산한다. LLD가 직접 조작할 일은 보통 없지만 필요한 경우 `scsi_host_alloc()`은 참조 수 1인 새 host를 반환하고, `scsi_host_get()`은 1을 더하며, `scsi_host_put()`은 1을 빼고 0이면 해제한다.

`scsi_device`도 같은 이유로 reference counting을 사용한다. LLD가 장치 포인터 복사본을 보관하려면 `scsi_device_get()`으로 참조를 올리고, 사용을 마치면 `scsi_device_put()`으로 내려 잠재적으로 인스턴스를 삭제하게 한다. 관련 접근 함수는 `include/scsi/scsi_device.h` 끝부분에 선언되어 있다.

주의할 점은 `struct Scsi_Host`에 실제로 두 reference count가 있고 host 참조 함수들이 이를 병렬로 조작한다는 것이다.

참조 수 함수
함수효과
scsi_host_alloc참조 수 1인 Scsi_Host 생성
scsi_host_gethost 참조 수 증가
scsi_host_puthost 참조 수 감소, 0이면 해제
scsi_device_getdevice 참조 수 증가
scsi_device_putdevice 참조 수 감소, 0이면 해제 가능

LLD가 공유 인스턴스의 수명을 연장하거나 끝낼 때 쓰는 함수다.

Reference Counting
==================
The Scsi_Host structure has had reference counting infrastructure added.
This effectively spreads the ownership of struct Scsi_Host instances
across the various SCSI layers which use them. Previously such instances
were exclusively owned by the mid level. LLDs would not usually need to
directly manipulate these reference counts but there may be some cases
where they do.

There are 3 reference counting functions of interest associated with
struct Scsi_Host:

  - scsi_host_alloc():
        returns a pointer to new instance of struct
        Scsi_Host which has its reference count ^^ set to 1

  - scsi_host_get():
        adds 1 to the reference count of the given instance

  - scsi_host_put():
        decrements 1 from the reference count of the given
        instance. If the reference count reaches 0 then the given instance
        is freed

The scsi_device structure has had reference counting infrastructure added.
This effectively spreads the ownership of struct scsi_device instances
across the various SCSI layers which use them. Previously such instances
were exclusively owned by the mid level. See the access functions declared
towards the end of include/scsi/scsi_device.h . If an LLD wants to keep
a copy of a pointer to a scsi_device instance it should use scsi_device_get()
to bump its reference count. When it is finished with the pointer it can
use scsi_device_put() to decrement its reference count (and potentially
delete it).

.. Note::

   struct Scsi_Host actually has 2 reference counts which are manipulated
   in parallel by these functions.

코딩 규칙과 제공 함수 요약

266-310

C 코드는 `Documentation/process/coding-style.rst`를 따른다. 관련 gcc가 지원하는 범위에서 C99 구조체와 배열 initializer를 권장하지만 VLA는 적절히 지원되지 않으므로 지나치게 사용하지 않는다. `//`보다 `/* ... */` 주석을 선호한다. 다만 잘 작성되고 시험·문서화된 외부 유래 코드를 규칙에 맞추려고 기계적으로 다시 포맷할 필요는 없다.

SCSI 중간 계층이 LLD에 제공하는 함수 이름은 module에서도 접근하도록 export되며 모두 `scsi_`로 시작한다. 커널은 LLD 초기화 전에 SCSI 중간 계층을 load하고 초기화한다.

중간 계층 제공 함수
함수기능
scsi_add_device새 논리 장치 인스턴스 생성
scsi_add_hostsysfs 등록과 transport class 설정
scsi_change_queue_depth장치 queue depth 변경
scsi_bios_ptableblock 장치 partition table 복사
scsi_block_requestshost의 추가 명령 queueing 차단
scsi_host_alloc/get/puthost 생성과 참조 수 관리
scsi_remove_deviceSCSI 장치 분리 및 제거
scsi_remove_hosthost 소속 장치 전체 제거
scsi_report_bus_reset관측한 SCSI bus reset 보고
scsi_scan_hostSCSI bus scan
scsi_track_queue_full연속 QUEUE_FULL 추적
scsi_unblock_requestshost queueing 재개

원문 요약 목록의 기능을 보존했다.

Conventions
===========
First, Linus Torvalds's thoughts on C coding style can be found in the
Documentation/process/coding-style.rst file.

Also, most C99 enhancements are encouraged to the extent they are supported
by the relevant gcc compilers. So C99 style structure and array
initializers are encouraged where appropriate. Don't go too far,
VLAs are not properly supported yet.  An exception to this is the use of
``//`` style comments; ``/*...*/`` comments are still preferred in Linux.

Well written, tested and documented code, need not be re-formatted to
comply with the above conventions. For example, the aic7xxx driver
comes to Linux from FreeBSD and Adaptec's own labs. No doubt FreeBSD
and Adaptec have their own coding conventions.


Mid level supplied functions
============================
These functions are supplied by the SCSI mid level for use by LLDs.
The names (i.e. entry points) of these functions are exported
so an LLD that is a module can access them. The kernel will
arrange for the SCSI mid level to be loaded and initialized before any LLD
is initialized. The functions below are listed alphabetically and their
names all start with ``scsi_``.

Summary:

  - scsi_add_device - creates new scsi device (lu) instance
  - scsi_add_host - perform sysfs registration and set up transport class
  - scsi_change_queue_depth - change the queue depth on a SCSI device
  - scsi_bios_ptable - return copy of block device's partition table
  - scsi_block_requests - prevent further commands being queued to given host
  - scsi_host_alloc - return a new scsi_host instance whose refcount==1
  - scsi_host_get - increments Scsi_Host instance's refcount
  - scsi_host_put - decrements Scsi_Host instance's refcount (free if 0)
  - scsi_remove_device - detach and remove a SCSI device
  - scsi_remove_host - detach and remove all SCSI devices owned by host
  - scsi_report_bus_reset - report scsi _bus_ reset observed
  - scsi_scan_host - scan SCSI bus
  - scsi_track_queue_full - track successive QUEUE_FULL events
  - scsi_unblock_requests - allow further commands to be queued to given host


Details::

장치·host 추가와 queue depth 변경

311-379

`scsi_add_device(shost, channel, id, lun)`은 새 `struct scsi_device`를 반환하며 지정 주소에 논리 장치가 없거나 오류가 나면 `ERR_PTR(-ENODEV)` 같은 오류 포인터를 반환한다. 차단될 수 있다. 보통 `scsi_scan_host()` 내부에서 사용하므로 scan 완료 뒤 HBA가 새 장치를 알게 된 경우에만 직접 호출한다. 성공하면 LLD의 `sdev_init()`과 `sdev_configure()`가 호출될 수 있다. 구현은 `drivers/scsi/scsi_scan.c`에 있다.

`scsi_add_host(shost, dev)`는 sysfs 등록과 transport class 설정을 수행한다. 성공 시 0, 실패 시 `-ENOMEM` 같은 음수 errno를 반환하고 차단되지 않는다. hotplug 모델에서 `scsi_host_alloc()` 성공 뒤 사용한다. bus scan은 별도이므로 `scsi_scan_host()` 또는 transport 고유 방식으로 실행해야 한다. transport template은 호출 전에 설정하고 transport class 데이터는 호출 뒤에만 접근한다. 구현은 `drivers/scsi/hosts.c`에 있다.

`scsi_change_queue_depth(sdev, tags)`는 tagged mode이면 허용 tag 수, non-tagged mode이면 `cmd_per_lun` 기준 LLD queue 수를 바꾼다. 반환값이 없고 차단되지 않으며 interrupt 문맥에서도 안전하다. `sdev_configure()` 중·이후부터 `sdev_destroy()` 전까지 언제든 호출할 수 있다. 구현은 `drivers/scsi/scsi.c`에 있다.

추가 API 계약
함수반환차단
scsi_add_devicescsi_device* 또는 ERR_PTR
scsi_add_host0 또는 음수 errno아니요
scsi_change_queue_depth없음아니요

반환값과 차단 가능성을 한눈에 정리했다.


    /**
    * scsi_add_device - creates new scsi device (lu) instance
    * @shost:   pointer to scsi host instance
    * @channel: channel number (rarely other than 0)
    * @id:      target id number
    * @lun:     logical unit number
    *
    *      Returns pointer to new struct scsi_device instance or
    *      ERR_PTR(-ENODEV) (or some other bent pointer) if something is
    *      wrong (e.g. no lu responds at given address)
    *
    *      Might block: yes
    *
    *      Notes: This call is usually performed internally during a scsi
    *      bus scan when an HBA is added (i.e. scsi_scan_host()). So it
    *      should only be called if the HBA becomes aware of a new scsi
    *      device (lu) after scsi_scan_host() has completed. If successful
    *      this call can lead to sdev_init() and sdev_configure() callbacks
    *      into the LLD.
    *
    *      Defined in: drivers/scsi/scsi_scan.c
    **/
    struct scsi_device * scsi_add_device(struct Scsi_Host *shost,
                                        unsigned int channel,
                                        unsigned int id, unsigned int lun)


    /**
    * scsi_add_host - perform sysfs registration and set up transport class
    * @shost:   pointer to scsi host instance
    * @dev:     pointer to struct device of type scsi class
    *
    *      Returns 0 on success, negative errno of failure (e.g. -ENOMEM)
    *
    *      Might block: no
    *
    *      Notes: Only required in "hotplug initialization model" after a
    *      successful call to scsi_host_alloc().  This function does not
    *        scan the bus; this can be done by calling scsi_scan_host() or
    *        in some other transport-specific way.  The LLD must set up
    *        the transport template before calling this function and may only
    *        access the transport class data after this function has been called.
    *
    *      Defined in: drivers/scsi/hosts.c
    **/
    int scsi_add_host(struct Scsi_Host *shost, struct device * dev)


    /**
    * scsi_change_queue_depth - allow LLD to change queue depth on a SCSI device
    * @sdev:       pointer to SCSI device to change queue depth on
    * @tags        Number of tags allowed if tagged queuing enabled,
    *              or number of commands the LLD can queue up
    *              in non-tagged mode (as per cmd_per_lun).
    *
    *      Returns nothing
    *
    *      Might block: no
    *
    *      Notes: Can be invoked any time on a SCSI device controlled by this
    *      LLD. [Specifically during and after sdev_configure() and prior to
    *      sdev_destroy().] Can safely be invoked from interrupt code.
    *
    *      Defined in: drivers/scsi/scsi.c [see source code for more notes]
    *
    **/
    int scsi_change_queue_depth(struct scsi_device *sdev, int tags)

partition table, 요청 차단과 host 할당

380-436

`scsi_bios_ptable(gendisk)`은 partition table 복사본을 반환하고 실패하면 NULL을 반환한다. 차단될 수 있으며 반환 메모리는 호출자가 소유하므로 `kfree()`해야 한다. 구현은 `drivers/scsi/scsicam.c`에 있다.

`scsi_block_requests(shost)`는 지정 host에 추가 명령이 queue되는 것을 막는다. 반환값이 없고 차단되지 않는다. 자동 timer나 해제 경로는 없으므로 LLD가 반드시 `scsi_unblock_requests()`를 호출해야 한다. 구현은 `drivers/scsi/scsi_lib.c`에 있다.

`scsi_host_alloc(sht, privsize)`은 host adapter 인스턴스를 만들고 기본 초기화한다. 실패 시 NULL, 성공 시 새 `Scsi_Host`를 반환하며 차단될 수 있다. 반환 시 bus scan은 아직 수행하지 않았다. 구조체 끝의 `hostdata`에 LLD 전용 per-host scratch area를 `privsize` byte만큼 할당하고 0으로 초기화한다. 연관된 두 reference object의 참조 수는 각각 1이다. sysfs 등록과 scan은 뒤의 `scsi_add_host()`와 `scsi_scan_host()`가 수행한다.

할당과 차단 API
함수핵심 소유권
scsi_bios_ptable호출자가 반환 메모리를 kfree
scsi_block_requestsLLD가 unblock을 반드시 호출
scsi_host_alloc참조 수 1, hostdata는 LLD 전용

소유권과 해제 책임이 중요한 함수들이다.


    /**
    * scsi_bios_ptable - return copy of block device's partition table
    * @dev:        pointer to gendisk
    *
    *      Returns pointer to partition table, or NULL for failure
    *
    *      Might block: yes
    *
    *      Notes: Caller owns memory returned (free with kfree() )
    *
    *      Defined in: drivers/scsi/scsicam.c
    **/
    unsigned char *scsi_bios_ptable(struct gendisk *dev)


    /**
    * scsi_block_requests - prevent further commands being queued to given host
    *
    * @shost: pointer to host to block commands on
    *
    *      Returns nothing
    *
    *      Might block: no
    *
    *      Notes: There is no timer nor any other means by which the requests
    *      get unblocked other than the LLD calling scsi_unblock_requests().
    *
    *      Defined in: drivers/scsi/scsi_lib.c
    **/
    void scsi_block_requests(struct Scsi_Host * shost)


    /**
    * scsi_host_alloc - create a scsi host adapter instance and perform basic
    *                   initialization.
    * @sht:        pointer to scsi host template
    * @privsize:   extra bytes to allocate in hostdata array (which is the
    *              last member of the returned Scsi_Host instance)
    *
    *      Returns pointer to new Scsi_Host instance or NULL on failure
    *
    *      Might block: yes
    *
    *      Notes: When this call returns to the LLD, the SCSI bus scan on
    *      this host has _not_ yet been done.
    *      The hostdata array (by default zero length) is a per host scratch
    *      area for the LLD's exclusive use.
    *      Both associated refcounting objects have their refcount set to 1.
    *      Full registration (in sysfs) and a bus scan are performed later when
    *      scsi_add_host() and scsi_scan_host() are called.
    *
    *      Defined in: drivers/scsi/hosts.c .
    **/
    struct Scsi_Host * scsi_host_alloc(const struct scsi_host_template * sht,
                                    int privsize)

host 참조와 장치·host 제거

437-506

`scsi_host_get(shost)`은 내부 두 sub-object 참조 수를 올린다. `scsi_host_put(shost)`은 둘을 내리고 마지막 참조가 0이면 `Scsi_Host`를 해제한다. 현재 두 함수는 차단될 수 있지만 향후 바뀔 수 있다. LLD는 정확한 해제 시점보다 get/put 균형을 지키고 마지막 put 뒤 인스턴스에 접근하지 않는 것이 중요하다.

`scsi_remove_device(sdev)`는 host를 유지한 채 논리 장치를 분리·제거한다. 성공 시 0, attach되지 않은 장치면 `-EINVAL`이며 차단될 수 있다. 성공하면 `sdev_destroy()`가 호출되고 함수 반환 뒤 `sdev` 포인터는 무효다. 구현은 `drivers/scsi/scsi_sysfs.c`에 있다.

`scsi_remove_host(shost)`는 해당 host가 소유한 모든 SCSI 장치를 분리·제거한다. 성공 시 0, 실패 시 1을 반환하고 차단될 수 있다. hotplug 모델에서만 사용하며 반드시 `scsi_host_put()`보다 먼저 호출한다. 구현은 `drivers/scsi/hosts.c`에 있다.

제거 API 이후 포인터 상태
함수호출 뒤
scsi_host_put균형을 맞춘 마지막 put 뒤 host 접근 금지
scsi_remove_devicesdev 포인터 무효
scsi_remove_host소속 장치 제거, 이후 scsi_host_put

호출 순서와 포인터 유효성을 보존했다.


    /**
    * scsi_host_get - increment Scsi_Host instance refcount
    * @shost:   pointer to struct Scsi_Host instance
    *
    *      Returns nothing
    *
    *      Might block: currently may block but may be changed to not block
    *
    *      Notes: Actually increments the counts in two sub-objects
    *
    *      Defined in: drivers/scsi/hosts.c
    **/
    void scsi_host_get(struct Scsi_Host *shost)


    /**
    * scsi_host_put - decrement Scsi_Host instance refcount, free if 0
    * @shost:   pointer to struct Scsi_Host instance
    *
    *      Returns nothing
    *
    *      Might block: currently may block but may be changed to not block
    *
    *      Notes: Actually decrements the counts in two sub-objects. If the
    *      latter refcount reaches 0, the Scsi_Host instance is freed.
    *      The LLD need not worry exactly when the Scsi_Host instance is
    *      freed, it just shouldn't access the instance after it has balanced
    *      out its refcount usage.
    *
    *      Defined in: drivers/scsi/hosts.c
    **/
    void scsi_host_put(struct Scsi_Host *shost)


    /**
    * scsi_remove_device - detach and remove a SCSI device
    * @sdev:      a pointer to a scsi device instance
    *
    *      Returns value: 0 on success, -EINVAL if device not attached
    *
    *      Might block: yes
    *
    *      Notes: If an LLD becomes aware that a scsi device (lu) has
    *      been removed but its host is still present then it can request
    *      the removal of that scsi device. If successful this call will
    *      lead to the sdev_destroy() callback being invoked. sdev is an
    *      invalid pointer after this call.
    *
    *      Defined in: drivers/scsi/scsi_sysfs.c .
    **/
    int scsi_remove_device(struct scsi_device *sdev)


    /**
    * scsi_remove_host - detach and remove all SCSI devices owned by host
    * @shost:      a pointer to a scsi host instance
    *
    *      Returns value: 0 on success, 1 on failure (e.g. LLD busy ??)
    *
    *      Might block: yes
    *
    *      Notes: Should only be invoked if the "hotplug initialization
    *      model" is being used. It should be called _prior_ to
    *      calling scsi_host_put().
    *
    *      Defined in: drivers/scsi/hosts.c .
    **/
    int scsi_remove_host(struct Scsi_Host *shost)

bus reset 보고, scan과 QUEUE_FULL 추적

507-578

`scsi_report_bus_reset(shost, channel)`은 알 수 없는 위치에서 발생한 SCSI bus reset을 보고해 `CHECK_CONDITION`을 올바르게 처리하게 한다. 중간 계층이 시작한 reset은 보고할 필요가 없지만 호출해도 해롭지 않다. 반환값이 없고 차단되지 않으며 `drivers/scsi/scsi_error.c`에 구현되어 있다.

`scsi_scan_host(shost)`는 SCSI bus를 조사하며 차단될 수 있다. `scsi_add_host()` 뒤 호출해야 하고 구현은 `drivers/scsi/scsi_scan.c`에 있다.

`scsi_track_queue_full(sdev, depth)`는 연속 `QUEUE_FULL`을 추적한다. `depth`는 QUEUE_FULL로 돌아온 명령을 제외한 현재 outstanding 명령 수다. 0은 변경 없음, 양수는 새 queue depth, -1은 `host->cmd_per_lun`을 depth로 쓰는 untagged mode 전환을 뜻한다. interrupt 문맥에서 안전하고 차단되지 않는다.

`scsi_unblock_requests(shost)`는 지정 host의 명령 queueing을 재개한다. 반환값이 없고 차단되지 않으며 `drivers/scsi/scsi_lib.c`에 구현되어 있다.

QUEUE_FULL 반환 해석
반환동작
0queue depth 유지
> 0반환값으로 depth 조정
-1cmd_per_lun 기반 untagged mode

scsi_track_queue_full의 반환 계약이다.


    /**
    * scsi_report_bus_reset - report scsi _bus_ reset observed
    * @shost: a pointer to a scsi host involved
    * @channel: channel (within) host on which scsi bus reset occurred
    *
    *      Returns nothing
    *
    *      Might block: no
    *
    *      Notes: This only needs to be called if the reset is one which
    *      originates from an unknown location.  Resets originated by the
    *      mid level itself don't need to call this, but there should be
    *      no harm.  The main purpose of this is to make sure that a
    *      CHECK_CONDITION is properly treated.
    *
    *      Defined in: drivers/scsi/scsi_error.c .
    **/
    void scsi_report_bus_reset(struct Scsi_Host * shost, int channel)


    /**
    * scsi_scan_host - scan SCSI bus
    * @shost: a pointer to a scsi host instance
    *
    *        Might block: yes
    *
    *        Notes: Should be called after scsi_add_host()
    *
    *        Defined in: drivers/scsi/scsi_scan.c
    **/
    void scsi_scan_host(struct Scsi_Host *shost)


    /**
    * scsi_track_queue_full - track successive QUEUE_FULL events on given
    *                      device to determine if and when there is a need
    *                      to adjust the queue depth on the device.
    * @sdev:  pointer to SCSI device instance
    * @depth: Current number of outstanding SCSI commands on this device,
    *         not counting the one returned as QUEUE_FULL.
    *
    *      Returns 0  - no change needed
    *              >0 - adjust queue depth to this new depth
    *              -1 - drop back to untagged operation using host->cmd_per_lun
    *                   as the untagged command depth
    *
    *      Might block: no
    *
    *      Notes: LLDs may call this at any time and we will do "The Right
    *              Thing"; interrupt context safe.
    *
    *      Defined in: drivers/scsi/scsi.c .
    **/
    int scsi_track_queue_full(struct scsi_device *sdev, int depth)


    /**
    * scsi_unblock_requests - allow further commands to be queued to given host
    *
    * @shost: pointer to host to unblock commands on
    *
    *      Returns nothing
    *
    *      Might block: no
    *
    *      Defined in: drivers/scsi/scsi_lib.c .
    **/
    void scsi_unblock_requests(struct Scsi_Host * shost)


LLDD 인터페이스 콜백 등록

579-620

interface function은 LLD가 정의하고 그 포인터를 `struct scsi_host_template`에 넣어 `scsi_host_alloc()`에 전달한다. 일부는 필수이며 모두 `static`으로 선언하는 관례를 따른다. 예를 들어 `static int xyz_sdev_configure(struct scsi_device *sdev);`의 포인터를 template의 `sdev_configure` 멤버에 넣는다.

함수 포인터 정의점 바로 위의 `include/scsi/scsi_host.h`에도 설명이 있으며 경우에 따라 이 문서보다 자세하다. 원문은 콜백을 알파벳순으로 나열한다.

LLDD 콜백 목록
콜백역할
bios_paramdisk geometry 제공
eh_timed_out명령 timer 만료 통지
eh_abort_handler명령 abort
eh_bus_reset_handlerSCSI bus reset
eh_device_reset_handlerSCSI device reset
eh_host_reset_handlerHBA reset
infohost 정보 문자열
ioctlLLD ioctl 처리
proc_info/proc/scsi 인터페이스
queuecommand명령 queue와 완료
sdev_init/configure/destroy장치 수명 주기

host template에 등록할 수 있는 인터페이스 함수다.

Interface Functions
===================
Interface functions are supplied (defined) by LLDs and their function
pointers are placed in an instance of struct scsi_host_template which
is passed to scsi_host_alloc().
Some are mandatory. Interface functions should be declared static. The
accepted convention is that driver "xyz" will declare its sdev_configure()
function as::

    static int xyz_sdev_configure(struct scsi_device * sdev);

and so forth for all interface functions listed below.

A pointer to this function should be placed in the 'sdev_configure' member
of a "struct scsi_host_template" instance. A pointer to such an instance
should be passed to the mid level's scsi_host_alloc().
.

The interface functions are also described in the include/scsi/scsi_host.h
file immediately above their definition point in "struct scsi_host_template".
In some cases more detail is given in scsi_host.h than below.

The interface functions are listed below in alphabetical order.

Summary:

  - bios_param - fetch head, sector, cylinder info for a disk
  - eh_timed_out - notify the host that a command timer expired
  - eh_abort_handler - abort given command
  - eh_bus_reset_handler - issue SCSI bus reset
  - eh_device_reset_handler - issue SCSI device reset
  - eh_host_reset_handler - reset host (host bus adapter)
  - info - supply information about given host
  - ioctl - driver can respond to ioctls
  - proc_info - supports /proc/scsi/{driver_name}/{host_no}
  - queuecommand - queue scsi command, invoke 'done' on completion
  - sdev_init - prior to any commands being sent to a new device
  - sdev_configure - driver fine tuning for given device after attach
  - sdev_destroy - given device is about to be shut down


Details::

bios_param과 eh_timed_out

621-674

`bios_param(sdev, disk, capacity, params)`는 512-byte sector 단위 용량을 받아 `params[0]` head 수(최대 255), `params[1]` sector 수(최대 63), `params[2]` cylinder 수를 채운다. 반환값은 무시되고 lock 없이 process 문맥에서 호출된다. 콜백이 없으면 READ CAPACITY를 바탕으로 임의 geometry를 쓰며 배열은 미리 가상 값으로 초기화된다. 선택 콜백이다.

`eh_timed_out(scp)`은 명령 timer가 만료될 때 interrupt 문맥에서 lock 없이 호출된다. `EH_HANDLED`는 로컬 복구가 끝났으니 명령을 완료하라는 뜻이고, `EH_RESET_TIMER`는 시간이 더 필요하니 timer를 다시 시작하라는 뜻이며, `EH_NOT_HANDLED`는 일반 오류 복구를 시작하라는 뜻이다. outstanding 명령이 끝날 가능성을 판정하는 제한된 로컬 복구 기회이며 이 콜백 안에서 명령을 abort하고 재시작하면 안 된다.

eh_timed_out 반환
반환처리
EH_HANDLED오류 해결, 명령 완료
EH_RESET_TIMERtimer 재설정
EH_NOT_HANDLED일반 EH 시작

timeout 콜백이 중간 계층에 지시하는 처리다.


    /**
    *      bios_param - fetch head, sector, cylinder info for a disk
    *      @sdev: pointer to scsi device context (defined in
    *             include/scsi/scsi_device.h)
    *      @disk: pointer to gendisk (defined in blkdev.h)
    *      @capacity:  device size (in 512 byte sectors)
    *      @params: three element array to place output:
    *              params[0] number of heads (max 255)
    *              params[1] number of sectors (max 63)
    *              params[2] number of cylinders
    *
    *      Return value is ignored
    *
    *      Locks: none
    *
    *      Calling context: process (sd)
    *
    *      Notes: an arbitrary geometry (based on READ CAPACITY) is used
    *      if this function is not provided. The params array is
    *      pre-initialized with made up values just in case this function
    *      doesn't output anything.
    *
    *      Optionally defined in: LLD
    **/
        int bios_param(struct scsi_device * sdev, struct gendisk *disk,
                    sector_t capacity, int params[3])


    /**
    *      eh_timed_out - The timer for the command has just fired
    *      @scp: identifies command timing out
    *
    *      Returns:
    *
    *      EH_HANDLED:             I fixed the error, please complete the command
    *      EH_RESET_TIMER:         I need more time, reset the timer and
    *                              begin counting again
    *      EH_NOT_HANDLED          Begin normal error recovery
    *
    *
    *      Locks: None held
    *
    *      Calling context: interrupt
    *
    *      Notes: This is to give the LLD an opportunity to do local recovery.
    *      This recovery is limited to determining if the outstanding command
    *      will ever complete.  You may not abort and restart the command from
    *      this callback.
    *
    *      Optionally defined in: LLD
    **/
        int eh_timed_out(struct scsi_cmnd * scp)

abort, device, bus와 host reset 콜백

675-749

`eh_abort_handler(scp)`는 시간 초과된 명령만 대상으로 abort를 시도하고 성공 시 `SUCCESS`, 아니면 `FAILED`를 반환한다. lock 없이 kernel thread 문맥에서 호출된다.

`eh_device_reset_handler(scp)`는 해당 SCSI device, `eh_bus_reset_handler(scp)`는 해당 device가 속한 bus, `eh_host_reset_handler(scp)`는 해당 host adapter를 reset한다. 모두 SCSI EH thread가 lock 없이 호출하며 `SUCCESS` 또는 `FAILED`를 반환한다. EH 동안 현재 host에는 다른 명령이 queue되지 않는다.

기본 EH strategy에서 abort, device reset, bus reset, host reset 콜백이 모두 없거나 모두 실패하면 문제가 된 device를 offline으로 만든다.

기본 EH 단계
eh_abort_handlereh_device_reset_handlereh_bus_reset_handlereh_host_reset_handler모두 실패: device offline

세분화된 handler가 점점 넓은 범위를 reset한다.


    /**
    *      eh_abort_handler - abort command associated with scp
    *      @scp: identifies command to be aborted
    *
    *      Returns SUCCESS if command aborted else FAILED
    *
    *      Locks: None held
    *
    *      Calling context: kernel thread
    *
    *      Notes: This is called only for a command that has timed out.
    *
    *      Optionally defined in: LLD
    **/
        int eh_abort_handler(struct scsi_cmnd * scp)


    /**
    *      eh_bus_reset_handler - issue SCSI bus reset
    *      @scp: SCSI bus that contains this device should be reset
    *
    *      Returns SUCCESS if command aborted else FAILED
    *
    *      Locks: None held
    *
    *      Calling context: kernel thread
    *
    *      Notes: Invoked from scsi_eh thread. No other commands will be
    *      queued on current host during eh.
    *
    *      Optionally defined in: LLD
    **/
        int eh_bus_reset_handler(struct scsi_cmnd * scp)


    /**
    *      eh_device_reset_handler - issue SCSI device reset
    *      @scp: identifies SCSI device to be reset
    *
    *      Returns SUCCESS if command aborted else FAILED
    *
    *      Locks: None held
    *
    *      Calling context: kernel thread
    *
    *      Notes: Invoked from scsi_eh thread. No other commands will be
    *      queued on current host during eh.
    *
    *      Optionally defined in: LLD
    **/
        int eh_device_reset_handler(struct scsi_cmnd * scp)


    /**
    *      eh_host_reset_handler - reset host (host bus adapter)
    *      @scp: SCSI host that contains this device should be reset
    *
    *      Returns SUCCESS if command aborted else FAILED
    *
    *      Locks: None held
    *
    *      Calling context: kernel thread
    *
    *      Notes: Invoked from scsi_eh thread. No other commands will be
    *      queued on current host during eh.
    *      With the default eh_strategy in place, if none of the _abort_,
    *      _device_reset_, _bus_reset_ or this eh handler function are
    *      defined (or they all return FAILED) then the device in question
    *      will be set offline whenever eh is invoked.
    *
    *      Optionally defined in: LLD
    **/
        int eh_host_reset_handler(struct scsi_cmnd * scp)

host 정보와 ioctl 전달

750-804

`info(shp)`는 driver 이름과 해당 host를 구분하는 PCI/ISA I/O 주소, interrupt 번호 같은 정보를 한 줄짜리 NUL-terminated ASCII 문자열로 반환한다. 드라이버가 반환 메모리를 host 수명 동안 유지한다고 가정한다. 콜백이 없으면 `Scsi_Host::name`을 사용하며 `SCSI_IOCTL_PROBE_HOST`도 같은 문자열을 돌려준다. lock 없이 process 문맥에서 호출되는 선택 콜백이다.

`ioctl(sdp, cmd, arg)`의 `arg`는 user space를 가리키므로 `copy_from_user()` 같은 적절한 kernel 함수를 써야 한다. 오류는 음수 errno, 성공은 0 또는 양수로 user space에 반환한다. SCSI의 ioctl은 상위 드라이버에서 중간 계층, 다시 LLD로 내려오는 trickle-down 모델이다. 어느 계층도 `cmd`를 알지 못하면 최근 Unix 규칙에 따라 `-ENOTTY`를 반환한다. lock 없이 process 문맥에서 호출되는 선택 콜백이다.

SCSI ioctl 전달
user ioctl on /dev/sdc상위 계층 드라이버SCSI 중간 계층장치 담당 LLD미지원: -ENOTTY

인식하지 못한 명령이 하위 계층으로 전달된다.


    /**
    *      info - supply information about given host: driver name plus data
    *             to distinguish given host
    *      @shp: host to supply information about
    *
    *      Return ASCII null terminated string. [This driver is assumed to
    *      manage the memory pointed to and maintain it, typically for the
    *      lifetime of this host.]
    *
    *      Locks: none
    *
    *      Calling context: process
    *
    *      Notes: Often supplies PCI or ISA information such as IO addresses
    *      and interrupt numbers. If not supplied struct Scsi_Host::name used
    *      instead. It is assumed the returned information fits on one line
    *      (i.e. does not included embedded newlines).
    *      The SCSI_IOCTL_PROBE_HOST ioctl yields the string returned by this
    *      function (or struct Scsi_Host::name if this function is not
    *      available).
    *
    *      Optionally defined in: LLD
    **/
        const char * info(struct Scsi_Host * shp)


    /**
    *      ioctl - driver can respond to ioctls
    *      @sdp: device that ioctl was issued for
    *      @cmd: ioctl number
    *      @arg: pointer to read or write data from. Since it points to
    *            user space, should use appropriate kernel functions
    *            (e.g. copy_from_user() ). In the Unix style this argument
    *            can also be viewed as an unsigned long.
    *
    *      Returns negative "errno" value when there is a problem. 0 or a
    *      positive value indicates success and is returned to the user space.
    *
    *      Locks: none
    *
    *      Calling context: process
    *
    *      Notes: The SCSI subsystem uses a "trickle down" ioctl model.
    *      The user issues an ioctl() against an upper level driver
    *      (e.g. /dev/sdc) and if the upper level driver doesn't recognize
    *      the 'cmd' then it is passed to the SCSI mid level. If the SCSI
    *      mid level does not recognize it, then the LLD that controls
    *      the device receives the ioctl. According to recent Unix standards
    *      unsupported ioctl() 'cmd' numbers should return -ENOTTY.
    *
    *      Optionally defined in: LLD
    **/
        int ioctl(struct scsi_device *sdp, int cmd, void *arg)

proc_info 인터페이스

805-836

`proc_info(buffer, start, offset, length, host_no, writeto1_read0)`는 `/proc/scsi/{driver_name}/{host_no}` 읽기와 쓰기를 지원한다. `writeto1_read0`이 1이면 user space에서 driver로 쓰는 경로이고, 0이면 driver 정보를 읽는 경로다. `buffer`는 입출력 anchor, `start`와 `offset`은 읽기에서 관심 범위를 나타내며, `length`는 최대 또는 실제 buffer 범위다.

쓰기에서는 길이를 반환하고 읽기에서는 offset 뒤 buffer에 출력한 문자 수를 반환한다. lock 없이 process 문맥에서 호출된다. `scsi_proc.c`와 proc_fs가 구동하며 SCSI subsystem에서 proc_fs 지원을 빌드 시 제외할 수 있다. 선택 콜백이다.


    /**
    *      proc_info - supports /proc/scsi/{driver_name}/{host_no}
    *      @buffer: anchor point to output to (0==writeto1_read0) or fetch from
    *               (1==writeto1_read0).
    *      @start: where "interesting" data is written to. Ignored when
    *              1==writeto1_read0.
    *      @offset: offset within buffer 0==writeto1_read0 is actually
    *               interested in. Ignored when 1==writeto1_read0 .
    *      @length: maximum (or actual) extent of buffer
    *      @host_no: host number of interest (struct Scsi_Host::host_no)
    *      @writeto1_read0: 1 -> data coming from user space towards driver
    *                            (e.g. "echo some_string > /proc/scsi/xyz/2")
    *                       0 -> user what data from this driver
    *                            (e.g. "cat /proc/scsi/xyz/2")
    *
    *      Returns length when 1==writeto1_read0. Otherwise number of chars
    *      output to buffer past offset.
    *
    *      Locks: none held
    *
    *      Calling context: process
    *
    *      Notes: Driven from scsi_proc.c which interfaces to proc_fs. proc_fs
    *      support can now be configured out of the scsi subsystem.
    *
    *      Optionally defined in: LLD
    **/
        int proc_info(char * buffer, char ** start, off_t offset,
                    int length, int host_no, int writeto1_read0)

queuecommand 반환과 명령 소유권

837-907

필수 `queuecommand(shost, scp)`는 명령을 LLD에 넣고 완료 때 `scp->scsi_done`을 호출한다. 성공은 0이다. device queue가 차면 `SCSI_MLQUEUE_DEVICE_BUSY`, host 전체 queue가 차면 `SCSI_MLQUEUE_HOST_BUSY`를 반환하고 중간 계층이 I/O를 다시 queue한다. 전자는 해당 device만 멈췄다가 그 장치의 명령 완료 또는 짧은 지연 뒤 재개하고, 후자는 host의 모든 I/O를 멈췄다가 host의 아무 명령이든 완료되면 재개한다. 호환성을 위해 그 밖의 nonzero 반환도 HOST_BUSY처럼 취급한다.

즉시 검출한 다른 오류는 `scp->result`를 설정하고 `scp->scsi_done`을 호출한 뒤 0을 반환한다. 비동기 실행을 시작하거나 시작할 예정이면 `scp->result=0`으로 두고 0을 반환한다.

반환 0이면 명령 소유권은 driver로 넘어가므로 반드시 `scsi_done` 호출을 보장해야 한다. 함수 반환 전에 완료 콜백을 호출할 수 있지만 그 뒤에는 반드시 0만 반환한다. nonzero를 반환했다면 어느 때도 해당 명령의 `scsi_done`을 호출하면 안 된다.

2.6.36까지는 진입 시 `Scsi_Host::host_lock`이 irqsave 상태로 잡혀 있고 반환할 때도 유지해야 했다. 2.6.37부터는 lock 없이 호출된다. soft IRQ 또는 process 문맥에서 실행되며 보통 I/O 완료를 기다리지 않고 빨리 반환해야 한다. 정해진 시간 안에 `scsi_done`이 없으면 중간 계층이 EH를 시작한다.

`CHECK_CONDITION`을 `result`에 넣어 완료하면 LLD가 autosense를 수행해 `scsi_cmnd::sense_buffer`를 채워야 한다. 중간 계층은 LLD에 명령을 queue하기 전에 이 배열을 0으로 지운다.

queuecommand 반환과 소유권
반환중간 계층 동작LLD 소유권
0실행 또는 즉시 완료명령 소유, 반드시 scsi_done
SCSI_MLQUEUE_DEVICE_BUSY해당 device만 재큐잉소유하지 않음, scsi_done 금지
SCSI_MLQUEUE_HOST_BUSYhost 전체 재큐잉소유하지 않음, scsi_done 금지
그 밖 nonzeroHOST_BUSY로 취급소유하지 않음

반환값이 명령과 완료 콜백의 책임을 결정한다.

    /**
    *      queuecommand - queue scsi command, invoke scp->scsi_done on completion
    *      @shost: pointer to the scsi host object
    *      @scp: pointer to scsi command object
    *
    *      Returns 0 on success.
    *
    *      If there's a failure, return either:
    *
    *      SCSI_MLQUEUE_DEVICE_BUSY if the device queue is full, or
    *      SCSI_MLQUEUE_HOST_BUSY if the entire host queue is full
    *
    *      On both of these returns, the mid-layer will requeue the I/O
    *
    *      - if the return is SCSI_MLQUEUE_DEVICE_BUSY, only that particular
    *      device will be paused, and it will be unpaused when a command to
    *      the device returns (or after a brief delay if there are no more
    *      outstanding commands to it).  Commands to other devices continue
    *      to be processed normally.
    *
    *      - if the return is SCSI_MLQUEUE_HOST_BUSY, all I/O to the host
    *      is paused and will be unpaused when any command returns from
    *      the host (or after a brief delay if there are no outstanding
    *      commands to the host).
    *
    *      For compatibility with earlier versions of queuecommand, any
    *      other return value is treated the same as
    *      SCSI_MLQUEUE_HOST_BUSY.
    *
    *      Other types of errors that are detected immediately may be
    *      flagged by setting scp->result to an appropriate value,
    *      invoking the scp->scsi_done callback, and then returning 0
    *      from this function. If the command is not performed
    *      immediately (and the LLD is starting (or will start) the given
    *      command) then this function should place 0 in scp->result and
    *      return 0.
    *
    *      Command ownership.  If the driver returns zero, it owns the
    *      command and must take responsibility for ensuring the
    *      scp->scsi_done callback is executed.  Note: the driver may
    *      call scp->scsi_done before returning zero, but after it has
    *      called scp->scsi_done, it may not return any value other than
    *      zero.  If the driver makes a non-zero return, it must not
    *      execute the command's scsi_done callback at any time.
    *
    *      Locks: up to and including 2.6.36, struct Scsi_Host::host_lock
    *             held on entry (with "irqsave") and is expected to be
    *             held on return. From 2.6.37 onwards, queuecommand is
    *             called without any locks held.
    *
    *      Calling context: in interrupt (soft irq) or process context
    *
    *      Notes: This function should be relatively fast. Normally it
    *      will not wait for IO to complete. Hence the scp->scsi_done
    *      callback is invoked (often directly from an interrupt service
    *      routine) some time after this function has returned. In some
    *      cases (e.g. pseudo adapter drivers that manufacture the
    *      response to a SCSI INQUIRY) the scp->scsi_done callback may be
    *      invoked before this function returns.  If the scp->scsi_done
    *      callback is not invoked within a certain period the SCSI mid
    *      level will commence error processing.  If a status of CHECK
    *      CONDITION is placed in "result" when the scp->scsi_done
    *      callback is invoked, then the LLD driver should perform
    *      autosense and fill in the struct scsi_cmnd::sense_buffer
    *      array. The scsi_cmnd::sense_buffer array is zeroed prior to
    *      the mid level queuing a command to an LLD.
    *
    *      Defined in: LLD
    **/
        int queuecommand(struct Scsi_Host *shost, struct scsi_cmnd * scp)

sdev_init, configure와 destroy

908-981

`sdev_init(sdp)`는 새 주소를 scan하기 직전, 어떤 명령도 보내기 전에 호출된다. driver가 per-device 자원을 미리 할당할 수 있다. 0이면 계속하고 다른 값이면 오류로 보아 장치를 무시한다. 실제 장치가 응답하면 `sdev_configure()`, 없으면 `sdev_destroy()`가 이어진다. lock 없이 process 문맥에서 호출되는 선택 콜백이다.

`sdev_configure(sdp)`는 첫 INQUIRY 응답 뒤 장치를 세밀하게 조정한다. 0이 아니면 장치를 offline으로 만든다. offline device에는 `sdev_destroy()`를 호출하지 않으므로 configure에서 실패를 반환하기 전에 자체 자원을 정리해야 한다. 초기 INQUIRY 내용을 검사해 적절한 조치를 취할 수 있고 lock 없이 process 문맥에서 호출된다.

`sdev_destroy(sdp)`는 장치의 모든 활동이 끝나고 중간 계층 구조를 해체하기 직전에 호출된다. LLD가 할당한 per-device 자원을 이때 해제하며 이 인스턴스에는 더 이상 명령이 오지 않는다. 나중에 같은 물리 장치를 다시 attach하면 새 `scsi_device` 인스턴스로 init과 configure를 다시 호출한다.

장치 수명 콜백
콜백시점오류/정리
sdev_initscan 직전nonzero면 무시, destroy 호출
sdev_configureINQUIRY 성공 뒤nonzero면 offline, 자체 자원 즉시 정리
sdev_destroy장치 해체 직전per-device 자원 해제

scan 결과에 따라 호출되는 단계와 정리 책임이다.


    /**
    *      sdev_init -   prior to any commands being sent to a new device
    *                      (i.e. just prior to scan) this call is made
    *      @sdp: pointer to new device (about to be scanned)
    *
    *      Returns 0 if ok. Any other return is assumed to be an error and
    *      the device is ignored.
    *
    *      Locks: none
    *
    *      Calling context: process
    *
    *      Notes: Allows the driver to allocate any resources for a device
    *      prior to its initial scan. The corresponding scsi device may not
    *      exist but the mid level is just about to scan for it (i.e. send
    *      and INQUIRY command plus ...). If a device is found then
    *      sdev_configure() will be called while if a device is not found
    *      sdev_destroy() is called.
    *      For more details see the include/scsi/scsi_host.h file.
    *
    *      Optionally defined in: LLD
    **/
        int sdev_init(struct scsi_device *sdp)


    /**
    *      sdev_configure - driver fine tuning for given device just after it
    *                     has been first scanned (i.e. it responded to an
    *                     INQUIRY)
    *      @sdp: device that has just been attached
    *
    *      Returns 0 if ok. Any other return is assumed to be an error and
    *      the device is taken offline. [offline devices will _not_ have
    *      sdev_destroy() called on them so clean up resources.]
    *
    *      Locks: none
    *
    *      Calling context: process
    *
    *      Notes: Allows the driver to inspect the response to the initial
    *      INQUIRY done by the scanning code and take appropriate action.
    *      For more details see the include/scsi/scsi_host.h file.
    *
    *      Optionally defined in: LLD
    **/
        int sdev_configure(struct scsi_device *sdp)


    /**
    *      sdev_destroy - given device is about to be shut down. All
    *                      activity has ceased on this device.
    *      @sdp: device that is about to be shut down
    *
    *      Returns nothing
    *
    *      Locks: none
    *
    *      Calling context: process
    *
    *      Notes: Mid level structures for given device are still in place
    *      but are about to be torn down. Any per device resources allocated
    *      by this driver for given device should be freed now. No further
    *      commands will be sent for this sdp instance. [However the device
    *      could be re-attached in the future in which case a new instance
    *      of struct scsi_device would be supplied by future sdev_init()
    *      and sdev_configure() calls.]
    *
    *      Optionally defined in: LLD
    **/
        void sdev_destroy(struct scsi_device *sdp)


struct scsi_host_template

982-1018

보통 LLD마다 `struct scsi_host_template` 인스턴스 하나를 file-scope static으로 둔다. 명시하지 않은 멤버가 0 또는 NULL이 되기 때문이다. 여러 하드웨어 class를 제어하는 극단적인 경우에는 ISA와 PCI용처럼 template을 여러 개 둘 수 있다.

`name`은 80자 미만 권장 driver 이름이며 공백을 포함할 수 있다. `proc_name`은 `/proc/scsi/<proc_name>/<host_no>`와 sysfs driver 디렉터리에 쓰이므로 Unix 파일 이름에 허용되는 문자만 써야 한다. `queuecommand`는 중간 계층이 명령을 주입하는 주 콜백이다. `vendor_id`는 vendor 고유 message 검증 등에 쓰는 식별 type과 vendor-specific 값의 조합이며 형식은 `scsi_netlink.h`를 참고한다. 구조체 정의는 `include/scsi/scsi_host.h`에 있다.

scsi_host_template 핵심 멤버
멤버의미
namedriver 표시 이름
proc_nameproc/sysfs 파일 이름
queuecommand주 명령 제출 콜백
vendor_idvendor 식별 type과 값

LLD 전체에 공통인 식별자와 콜백이다.

Data Structures
===============
struct scsi_host_template
-------------------------
There is one "struct scsi_host_template" instance per LLD [#]_. It is
typically initialized as a file scope static in a driver's header file. That
way members that are not explicitly initialized will be set to 0 or NULL.
Members of interest:

    name
                 - name of driver (may contain spaces, please limit to
                   less than 80 characters)

    proc_name
                 - name used in "/proc/scsi/<proc_name>/<host_no>" and
                   by sysfs in one of its "drivers" directories. Hence
                   "proc_name" should only contain characters acceptable
                   to a Unix file name.

   ``(*queuecommand)()``
                 - primary callback that the mid level uses to inject
                   SCSI commands into an LLD.

    vendor_id
                 - a unique value that identifies the vendor supplying
                   the LLD for the Scsi_Host.  Used most often in validating
                   vendor-specific message requests.  Value consists of an
                   identifier type and a vendor-specific value.
                   See scsi_netlink.h for a description of valid formats.

The structure is defined and commented in include/scsi/scsi_host.h

.. [#] In extreme situations a single driver may have several instances
       if it controls several different classes of hardware (e.g. an LLD
       that handles both ISA and PCI cards and has a separate instance of
       struct scsi_host_template for each class).

struct Scsi_Host

1019-1066

LLD가 제어하는 host(HBA)마다 `struct Scsi_Host` 인스턴스가 하나 있다. `scsi_host_alloc()`이 만들 때 template과 공통인 멤버를 복사해 초기화한다. `host_no`는 0부터 증가하는 시스템 전체 고유 번호다. `can_queue`는 반드시 0보다 크며 adapter에 동시에 보낼 수 있는 최대 명령 수다.

`this_id`는 initiator SCSI ID 또는 모르면 -1이다. `sg_tablesize`는 허용 scatter-gather element 최대값이며 chained SG list를 피하려면 `SG_ALL` 이하, 최소 1이어야 한다. `max_sectors`는 명령 하나의 최대 sector 수다. 0이면 현재 1024인 `SCSI_DEFAULT_MAX_SECTORS`가 적용되어 512-byte disk sector 기준 최대 512KB가 되며 firmware upload에는 부족할 수 있다.

`cmd_per_lun`은 host 소속 장치마다 queue할 명령 최대값이며 `scsi_change_queue_depth()`로 덮어쓸 수 있다. `hostt`는 생성에 사용한 `scsi_host_template`, `hostt->proc_name`은 sysfs가 쓰는 LLD 이름, `transportt`는 FC나 SPI용 `scsi_transport_template` 포인터다. 구조체 끝 `hostdata[0]`은 `scsi_host_alloc()`의 `privsize`로 정한 LLD 전용 공간이다. 정의는 `include/scsi/scsi_host.h`에 있다.

Scsi_Host 용량 제한
멤버제약
can_queue> 0, adapter 전체 명령 수
sg_tablesize>= 1, scatter-gather 최대
max_sectors0이면 1024 sector
cmd_per_lun장치별 queue 수
hostdataprivsize byte LLD 전용

host가 중간 계층에 알리는 주요 queue와 전송 한계다.

struct Scsi_Host
----------------
There is one struct Scsi_Host instance per host (HBA) that an LLD
controls. The struct Scsi_Host structure has many members in common
with "struct scsi_host_template". When a new struct Scsi_Host instance
is created (in scsi_host_alloc() in hosts.c) those common members are
initialized from the driver's struct scsi_host_template instance. Members
of interest:

    host_no
                 - system-wide unique number that is used for identifying
                   this host. Issued in ascending order from 0.
    can_queue
                 - must be greater than 0; do not send more than can_queue
                   commands to the adapter.
    this_id
                 - scsi id of host (scsi initiator) or -1 if not known
    sg_tablesize
                 - maximum scatter gather elements allowed by host.
                   Set this to SG_ALL or less to avoid chained SG lists.
                   Must be at least 1.
    max_sectors
                 - maximum number of sectors (usually 512 bytes) allowed
                   in a single SCSI command. The default value of 0 leads
                   to a setting of SCSI_DEFAULT_MAX_SECTORS (defined in
                   scsi_host.h) which is currently set to 1024. So for a
                   disk the maximum transfer size is 512 KB when max_sectors
                   is not defined. Note that this size may not be sufficient
                   for disk firmware uploads.
    cmd_per_lun
                 - maximum number of commands that can be queued on devices
                   controlled by the host. Overridden by LLD calls to
                   scsi_change_queue_depth().
    hostt
                 - pointer to driver's struct scsi_host_template from which
                   this struct Scsi_Host instance was spawned
    hostt->proc_name
                 - name of LLD. This is the driver name that sysfs uses.
    transportt
                 - pointer to driver's struct scsi_transport_template instance
                   (if any). FC and SPI transports currently supported.
    hostdata[0]
                 - area reserved for LLD at end of struct Scsi_Host. Size
                   is set by the second argument (named 'privsize') to
                   scsi_host_alloc().

The scsi_host structure is defined in include/scsi/scsi_host.h

struct scsi_device와 scsi_cmnd

1067-1128

일반적으로 host의 각 SCSI logical unit마다 `struct scsi_device`가 하나 있으며 channel, target ID, LUN의 조합으로 고유하게 식별한다. 정의는 `include/scsi/scsi_device.h`에 있다.

`struct scsi_cmnd`는 SCSI 명령을 LLD로 전달하고 응답을 중간 계층으로 돌려준다. 중간 계층은 `scsi_change_queue_depth()` 또는 `Scsi_Host::cmd_per_lun`이 정한 수보다 많은 명령을 LLD에 queue하지 않는다. 각 장치에는 최소 하나의 command 인스턴스가 있다.

`cmnd` 배열은 SCSI CDB, `cmd_len`은 byte 길이, `sc_data_direction`은 `include/linux/dma-mapping.h`의 `enum dma_data_direction` 값이다. LLD는 `done` 전에 `result`를 설정한다. 0은 모든 데이터까지 성공적으로 전송했다는 뜻이다. 32-bit `result`의 LSB에는 SCSI status가 있고 `status_byte()`, `host_byte()` macro로 해석한다.

status가 `CHECK_CONDITION(2)`이면 최대 `SCSI_SENSE_BUFFERSIZE`인 `sense_buffer`를 채운다. 첫 byte의 상위 nibble이 7이면 유효 sense로 보고, 아니면 중간 계층이 `REQUEST_SENSE`를 보낸다. queueing에서는 이 후속 명령이 오류에 취약하므로 LLD가 항상 autosense해야 한다. `device`는 연결된 `scsi_device` 포인터다.

`resid_len`은 `scsi_set_resid()`와 `scsi_get_resid()`로 접근하며 요청 길이에서 실제 전송 byte 수를 뺀 값이다. 기본 0이므로 underrun을 알 수 없는 LLD는 무시할 수 있고 overrun은 보고하면 안 된다. `done` 전에 설정해야 한다. 실제 전송량이 `underflow`보다 작으면 LLD는 `result`에 `(DID_ERROR << 16)`을 넣어야 하지만, 잔여 길이를 정확히 보고하는 편이 더 낫다.

scsi_cmnd 핵심 멤버
멤버LLD 책임
cmnd / cmd_lenCDB와 길이 읽기
sc_data_directionDMA 방향 준수
resultdone 전에 상태 설정
sense_bufferCHECK_CONDITION에서 autosense 기록
device대상 scsi_device
resid_len요청량 - 실제 전송량
underflow미달 시 DID_ERROR 판단 기준

명령, 결과, sense와 전송 잔여량의 계약이다.

struct scsi_device
------------------
Generally, there is one instance of this structure for each SCSI logical unit
on a host. SCSI devices connected to a host are uniquely identified by a
channel number, target id and logical unit number (lun).
The structure is defined in include/scsi/scsi_device.h

struct scsi_cmnd
----------------
Instances of this structure convey SCSI commands to the LLD and responses
back to the mid level. The SCSI mid level will ensure that no more SCSI
commands become queued against the LLD than are indicated by
scsi_change_queue_depth() (or struct Scsi_Host::cmd_per_lun). There will
be at least one instance of struct scsi_cmnd available for each SCSI device.
Members of interest:

    cmnd
                 - array containing SCSI command
    cmd_len
                 - length (in bytes) of SCSI command
    sc_data_direction
                 - direction of data transfer in data phase. See
                   "enum dma_data_direction" in include/linux/dma-mapping.h
    result
                 - should be set by LLD prior to calling 'done'. A value
                   of 0 implies a successfully completed command (and all
                   data (if any) has been transferred to or from the SCSI
                   target device). 'result' is a 32-bit unsigned integer that
                   can be viewed as 2 related bytes. The SCSI status value is
                   in the LSB. See include/scsi/scsi.h status_byte() and
                   host_byte() macros and related constants.
    sense_buffer
                 - an array (maximum size: SCSI_SENSE_BUFFERSIZE bytes) that
                   should be written when the SCSI status (LSB of 'result')
                   is set to CHECK_CONDITION (2). When CHECK_CONDITION is
                   set, if the top nibble of sense_buffer[0] has the value 7
                   then the mid level will assume the sense_buffer array
                   contains a valid SCSI sense buffer; otherwise the mid
                   level will issue a REQUEST_SENSE SCSI command to
                   retrieve the sense buffer. The latter strategy is error
                   prone in the presence of command queuing so the LLD should
                   always "auto-sense".
    device
                 - pointer to scsi_device object that this command is
                   associated with.
    resid_len   (access by calling scsi_set_resid() / scsi_get_resid())
                 - an LLD should set this unsigned integer to the requested
                   transfer length (i.e. 'request_bufflen') less the number
                   of bytes that are actually transferred. 'resid_len' is
                   preset to 0 so an LLD can ignore it if it cannot detect
                   underruns (overruns should not be reported). An LLD
                   should set 'resid_len' prior to invoking 'done'. The most
                   interesting case is data transfers from a SCSI target
                   device (e.g. READs) that underrun.
    underflow
                 - LLD should place (DID_ERROR << 16) in 'result' if
                   actual number of bytes transferred is less than this
                   figure. Not many LLDs implement this check and some that
                   do just output an error message to the log rather than
                   report a DID_ERROR. Better for an LLD to implement
                   'resid_len'.

READ 잔여 길이 보고

1129-1146

target에서 데이터를 받는 READ에서는 LLD가 `resid_len`을 설정하는 것이 권장된다. 특히 sense key가 `MEDIUM ERROR`, `HARDWARE ERROR`, 경우에 따라 `RECOVERED ERROR`이면 중요하다. 받은 유효 byte 수가 불확실하면 아무 byte도 받지 못한 것으로 보고하는 것이 가장 안전하다.

유효 데이터가 전혀 없으면 `scsi_set_resid(SCpnt, scsi_bufflen(SCpnt));`를 사용한다. 512-byte block 세 개만 받았다면 `scsi_set_resid(SCpnt, scsi_bufflen(SCpnt) - (3 * 512));`로 설정한다. `SCpnt`는 `scsi_cmnd` 포인터다. 구조체 정의는 `include/scsi/scsi_cmnd.h`에 있다.

It is recommended that a LLD set 'resid_len' on data transfers from a SCSI
target device (e.g. READs). It is especially important that 'resid_len' is set
when such data transfers have sense keys of MEDIUM ERROR and HARDWARE ERROR
(and possibly RECOVERED ERROR). In these cases if a LLD is in doubt how much
data has been received then the safest approach is to indicate no bytes have
been received. For example: to indicate that no valid data has been received
a LLD might use these helpers::

    scsi_set_resid(SCpnt, scsi_bufflen(SCpnt));

where 'SCpnt' is a pointer to a scsi_cmnd object. To indicate only three 512
bytes blocks have been received 'resid_len' could be set like this::

    scsi_set_resid(SCpnt, scsi_bufflen(SCpnt) - (3 * 512));

The scsi_cmnd structure is defined in include/scsi/scsi_cmnd.h

host lock과 autosense

1147-1182

각 `Scsi_Host`에는 `scsi_host_alloc()`이 초기화하는 `default_lock` spinlock이 있다. 같은 함수에서 `host_lock` 포인터가 이 lock을 가리키게 하고, 이후 중간 계층은 `host_lock`을 통해 잠금과 해제를 수행한다. 과거에는 driver가 포인터를 바꿀 수 있었지만 지금은 허용하지 않는다.

SAM-2에서 autosense는 `CHECK CONDITION` 발생 시 SCSI 명령 완료와 동시에 sense data를 application client에 자동 반환하는 것이다. LLD는 protocol에 추가 data-in phase를 지시하거나 직접 `REQUEST SENSE`를 발행하는 방식으로 autosense를 수행해야 한다.

중간 계층은 `sense_buffer[0]` 상위 nibble이 7 또는 0xf이면 autosense가 수행되었다고 본다. 다른 값이면, 명령 전 0으로 초기화되어 있으므로 중간 계층이 `REQUEST SENSE`를 발행한다. queue된 명령에서는 실패 명령의 sense를 보존하는 nexus와 후속 REQUEST SENSE가 어긋날 수 있으므로 LLD autosense가 가장 안전하다.

CHECK CONDITION 처리
CHECK CONDITION 검출protocol 추가 data-in 또는 LLD REQUEST SENSEsense_buffer[0] 상위 nibble 7/0xfscsi_done과 함께 sense 반환

LLD autosense가 후속 명령과의 동기화 위험을 없앤다.

Locks
=====
Each struct Scsi_Host instance has a spin_lock called struct
Scsi_Host::default_lock which is initialized in scsi_host_alloc() [found in
hosts.c]. Within the same function the struct Scsi_Host::host_lock pointer
is initialized to point at default_lock.  Thereafter lock and unlock
operations performed by the mid level use the struct Scsi_Host::host_lock
pointer.  Previously drivers could override the host_lock pointer but
this is not allowed anymore.


Autosense
=========
Autosense (or auto-sense) is defined in the SAM-2 document as "the
automatic return of sense data to the application client coincident
with the completion of a SCSI command" when a status of CHECK CONDITION
occurs. LLDs should perform autosense. This should be done when the LLD
detects a CHECK CONDITION status by either:

    a) instructing the SCSI protocol (e.g. SCSI Parallel Interface (SPI))
       to perform an extra data in phase on such responses
    b) or, the LLD issuing a REQUEST SENSE command itself

Either way, when a status of CHECK CONDITION is detected, the mid level
decides whether the LLD has performed autosense by checking struct
scsi_cmnd::sense_buffer[0] . If this byte has an upper nibble of 7 (or 0xf)
then autosense is assumed to have taken place. If it has another value (and
this byte is initialized to 0 before each command) then the mid level will
issue a REQUEST SENSE command.

In the presence of queued commands the "nexus" that maintains sense
buffer data from the command that failed until a following REQUEST SENSE
may get out of synchronization. This is why it is best for the LLD
to perform autosense.

Linux 2.4 이후 변경과 기여자

1183-1222

Linux 2.4의 전역 `io_request_lock`은 더 세분화된 lock들로 바뀌었고 LLD 관련 lock은 host마다 하나인 `Scsi_Host::host_lock`이다. 이전 오류 처리의 `abort()`와 `reset()` 콜백, `scsi_host_template::use_new_eh_code` flag는 제거되었다.

2.4의 `Documentation/Configure.help`에 모여 있던 설정 설명은 2.6에서 SCSI 전용 `drivers/scsi/Kconfig`로 이동했다. `struct SHT` 이름은 `struct scsi_host_template`으로 바뀌었고 hotplug 초기화 모델과 이를 지원하는 함수들이 추가되었다.

기여자는 Mike Anderson, James Bottomley, Patrick Mansfield, Christoph Hellwig, Doug Ledford, Andries Brouwer, Randy Dunlap, Alan Stern이다. 문서 작성자는 Douglas Gilbert이며 날짜는 2004년 9월 21일이다.

Changes since Linux kernel 2.4 series
=====================================
io_request_lock has been replaced by several finer grained locks. The lock
relevant to LLDs is struct Scsi_Host::host_lock and there is
one per SCSI host.

The older error handling mechanism has been removed. This means the
LLD interface functions abort() and reset() have been removed.
The struct scsi_host_template::use_new_eh_code flag has been removed.

In the 2.4 series the SCSI subsystem configuration descriptions were
aggregated with the configuration descriptions from all other Linux
subsystems in the Documentation/Configure.help file. In the 2.6 series,
the SCSI subsystem now has its own (much smaller) drivers/scsi/Kconfig
file that contains both configuration and help information.

struct SHT has been renamed to struct scsi_host_template.

Addition of the "hotplug initialization model" and many extra functions
to support it.


Credits
=======
The following people have contributed to this document:

        - Mike Anderson <andmike at us dot ibm dot com>
        - James Bottomley <James dot Bottomley at hansenpartnership dot com>
        - Patrick Mansfield <patmans at us dot ibm dot com>
        - Christoph Hellwig <hch at infradead dot org>
        - Doug Ledford <dledford at redhat dot com>
        - Andries Brouwer <Andries dot Brouwer at cwi dot nl>
        - Randy Dunlap <rdunlap at xenotime dot net>
        - Alan Stern <stern at rowland dot harvard dot edu>


Douglas Gilbert
dgilbert at interlog dot com

21st September 2004