Linux 2.3.0
[davej-history.git] / Documentation / scsi-generic.txt
blob17822c4ad70fcf43b8eb885622782c3396e154c9
1             Notes on Linux's SG driver version 2.1.30
2             -----------------------------------------
3                                                         990328
5 Introduction
6 ============
7 These are notes on the Linux SCSI generic packet device driver (sg)
8 describing version 2.1.30 . The original driver was written by Lawrence
9 Foard and has remained in place with minimal changes since circa 1992.
10 Version 2 of this driver remains backward compatible (binary and
11 source **) with the original. It adds scatter gather, command queuing,
12 per file descriptor sequencing, asynchronous notification and better
13 error reporting.
15 Sg is one of the four "high level" SCSI device drivers along with
16 sd, st and sr (disk, tape and CDROM respectively). Sg is more generalized
17 (but lower level) than its sibling and tends to be used on SCSI devices
18 that don't fit into the already serviced categories. Thus sg is used for
19 scanners, cd writers and reading audio cds amongst other things.
21 The interface and usage of the original sg driver has been documented
22 by Heiko Eissfeldt in a HOWTO called SCSI-Programming-HOWTO. My copy
23 of the document is version 1.5 dated 7th May 1996. It can found at
24 ftp://sunsite.unc.edu/pub/Linux/docs/HOWTO/SCSI-Programming-HOWTO .
25 Amongst other things it has a lot of tables from the SCSI-2 standard
26 that are very useful for programming this interface.
28 ** It is possible to write applications that perform differently
29 depending on whether they are using the original or this version of
30 the sg device driver. The author is not aware of any useful applications
31 that have problems with version 2 (yet).
34 Architecture
35 ============
36 The SCSI generic packet device driver (sg) is a character based device.
37 It is one of the four high level device driver in the SCSI sub-system;
38 the others are sd (for direct-access devices - disks), st (for tapes)
39 and sr (for data cdroms). The other three devices are block devices.
41 The unifying layer of the SCSI sub-system in the so-called mid-level.
42 Below that are all the drivers for the various adapters supported by
43 Linux.
45 Since sg is a character device it supports the traditional Unix
46 system calls of open(), close(), read(), write() and ioctl(). Two other
47 related system calls: poll() and fcntl() are added to this list and
48 how they interact with the sg device driver is documented later.
50 An SG device is accessed by write()ing SCSI commands plus any associated 
51 outgoing data to it; the resulting status codes and any incoming data are
52 then obtained by a read() call. The device can be opened O_NONBLOCK
53 (non-blocking) and poll() used to monitor its progress. The device may be
54 opened O_EXCL which excludes other "sg" users from this device (but not 
55 "sd", "st" or "sr" users). The buffer given to the write() call is made
56 up as follows:
57         - struct sg_header image (see below)
58         - scsi command (6, 10 or 12 bytes long)
59         - data to be written to the device (if any)
61 The buffer received from the corresponding read() call contains:
62         - struct sg_header image (check status/errors + sense_buffer)
63         - data read back from device (if any)
65 The given SCSI command has its LUN field overwritten by the LUN value of
66 the associated sg device that has been open()ed.
69 sg_header
70 =========
71 This is the name of the control structure that conveys information
72 about the length of data to be read/written by the associated SCSI
73 command. It also conveys error and status information from the
74 read() call. An instance of this structure is the first thing that
75 is placed in the data buffers of both write() and read().
77 In its original form it looked like this:
78 struct sg_header {
79     int pack_len;
80     int reply_len;
81     int pack_id;
82     int result;
83     unsigned int twelve_byte:1;
84     unsigned int other_flags:31;
85     unsigned char sense_buffer[16];
86 }; /* this structure is 36 bytes long */
88 The 'pack_len' is bizzare and ends up having the 'reply_len' put in it
89 (perhaps it had a use at some stage). 
91 The 'reply_len' is the length of the data the corresponding read()
92 will/should request (including the sg_header). 
94 The 'pack_id' is not acted upon by the sg device driver but is conveyed
95 back to the corresponding read() so it can be used for sequencing by an
96 application. 
98 The 'result' is also bizzare, turning certain types of host codes it 0 (no
99 error), EBUSY or EIO. With better error reporting now available, the
100 'result' is best ignored.
102 The 'twelve_byte' field overrides the internal SCSI command length "guessing"
103 algorithm for group 6 and 7 commands (ie when 1st byte >= 0xc0) and forces
104 a command lenth of 12 bytes.
105 The command length "guessing" algorithm is as follows:
106 Group:  0    1    2    3    4    5    6    7
107 Length: 6   10   10   12   12   12   10   10
109 'other_flags' was originally documented as "not used" but some current
110 applications assume it has 0 placed in it.
112 The 'sense_buffer' is the first 16 bytes of SCSI sense buffer that is
113 returned when the target returns a SCSI status code of CHECK_CONDITION
114 or COMMAND_TERMINATED [or (driver_status & DRIVER_SENSE) is true]. This
115 buffer should be at least 18 bytes long and arguably 32 bytes; unfortunately
116 this is unlikely to happen in the 2.2.x series of kernels.
118 The new sg_header offered in this driver is:
119 #define SG_MAX_SENSE 16
120 struct sg_header
122     int pack_len;    /* [o] reply_len (ie useless) ignored as input */
123     int reply_len;   /* [i] max length of expected reply (inc. sg_header) */
124     int pack_id;     /* [io] id number of packet (use ints >= 0) */
125     int result;      /* [o] 0==ok, else (+ve) Unix errno code (e.g. EIO) */
126     unsigned int twelve_byte:1;
127         /* [i] Force 12 byte command length for group 6 & 7 commands  */
128     unsigned int target_status:5;   /* [o] scsi status from target */
129     unsigned int host_status:8;     /* [o] host status (see "DID" codes) */
130     unsigned int driver_status:8;   /* [o] driver status+suggestion */
131     unsigned int other_flags:10;    /* unused */
132     unsigned char sense_buffer[SG_MAX_SENSE]; /* [o] when target_status is
133                CHECK_CONDITION or COMMAND_TERMINATED this is output. */
134 };      /* This structure is 36 bytes long on i386 */
136 Firstly the new header is binary compatible with the original. This is
137 important for keeping existing apps working without recompilation.
139 Only those elements (or fields) that are new or in some way different
140 from the original are documented below.
142 'pack_id' becomes input to a read() when ioctl(sg_fd, SG_SET_FORCE_PACK_ID,
143 &one) is active. A 'pack_id' of -1 is interpreted as fetch the oldest
144 waiting packet; any other value will cause the read() to wait (or yield
145 EAGAIN) until a packet with that 'pack_id' becomes available. In all cases
146 the value of 'pack_id' available after a read() is the value given to that
147 variable in the prior, corresponding write().
149 The 'target_status' field is always output and is the (masked and shifted
150 1 bit right) SCSI status code from the target device. The allowable
151 values are (found in <scsi/scsi.h>):
152 /* N.B. 1 bit offset from usual SCSI status values */
153 #define GOOD                 0x00
154 #define CHECK_CONDITION      0x01  
155 #define CONDITION_GOOD       0x02
156 #define BUSY                 0x04
157 #define INTERMEDIATE_GOOD    0x08
158 #define INTERMEDIATE_C_GOOD  0x0a
159 #define RESERVATION_CONFLICT 0x0c
160 #define COMMAND_TERMINATED   0x11
161 #define QUEUE_FULL           0x14
162 When the 'target_status' is CHECK_CONDITION or COMMAND_TERMINATED the
163 'sense_buffer' is output. Note that when (driver_status & DRIVER_SENSE)
164 is true then the 'sense_buffer' is also output (this seems to occur when
165 the scsi ide emulation is used). When the 'sense_buffer' is output the 
166 SCSI Sense Key can be found at (sense_buffer[2] & 0x0f) .
168 The 'host_status' field is always output and has the following values
169 whose "defines" are not visible outside the kernel (unfortunately):
170 #define DID_OK          0x00 /* NO error                                */
171 #define DID_NO_CONNECT  0x01 /* Couldn't connect before timeout period  */
172 #define DID_BUS_BUSY    0x02 /* BUS stayed busy through time out period */
173 #define DID_TIME_OUT    0x03 /* TIMED OUT for other reason              */
174 #define DID_BAD_TARGET  0x04 /* BAD target.                             */
175 #define DID_ABORT       0x05 /* Told to abort for some other reason     */
176 #define DID_PARITY      0x06 /* Parity error                            */
177 #define DID_ERROR       0x07 /* Internal error                          */
178 #define DID_RESET       0x08 /* Reset by somebody.                      */
179 #define DID_BAD_INTR    0x09 /* Got an interrupt we weren't expecting.  */
180 #define DID_PASSTHROUGH 0x0a /* Force command past mid-layer            */
181 #define DID_SOFT_ERROR  0x0b /* The low level driver just wish a retry  */
183 The 'driver_status' field is always output. When ('driver_status' &
184 DRIVER_SENSE) is true the 'sense_buffer' is also output. The following
185 values whose "defines" are not visible outside the kernel (unfortunately)
186 can occur:
187 #define DRIVER_OK           0x00 /* Typically no suggestion */
188 #define DRIVER_BUSY         0x01
189 #define DRIVER_SOFT         0x02
190 #define DRIVER_MEDIA        0x03
191 #define DRIVER_ERROR        0x04
192 #define DRIVER_INVALID      0x05
193 #define DRIVER_TIMEOUT      0x06
194 #define DRIVER_HARD         0x07
195 #define DRIVER_SENSE        0x08
196 /* above status 'or'ed with one of the following suggestions */
197 #define SUGGEST_RETRY       0x10
198 #define SUGGEST_ABORT       0x20
199 #define SUGGEST_REMAP       0x30
200 #define SUGGEST_DIE         0x40
201 #define SUGGEST_SENSE       0x80
203 'other_flags' still remains as a 10 bit field, so code that places 0 in it
204 will still be happy. It is not used.
207 memory
208 ======
209 Memory is a scarce resource in any computer. Sg needs to reserve memory
210 suitable for DMA roughly equal in size to the maximum of the write and
211 read data buffers for each packet. This DMA memory is obtained at the time
212 of a write() and released when the corresponding read() is called (although
213 if memory is tight it may be using the buffer reserved by the open() ).
215 Linux obtaining memory a challenge for several reasons. The memory pool
216 that sg uses is in common with all other device drivers and all user
217 processes. In this environment the only way to 99.9% guarantee a driver
218 will have memory in Linux is to build it into the kernel (ie not as a
219 module) and then reserve it on initialization before user processes get
220 a chance. [Of course, another driver initialized before sg could take
221 all available memory ...] Another problem is the biggest contiguous
222 chunk of memory that can be obtained from the kernel is 32 * PAGE_SIZE
223 (which is 128KBytes on i386). As memory gets "splintered" there is a good
224 chance that buffers won't be available (my machine has 64 MBytes of RAM
225 and has 3 available at the moment).
227 The original sg driver used the following technique: grab a SG_BIG_BUFF
228 sized buffer at driver initialization and use it for all requests greater
229 than PAGE_SIZE (4096 bytes on i386). By default SG_BIG_BUFF is set to
230 32 KBytes in the origianl driver but many applications suggest that the
231 user increases this number. Linux limits the biggest single buffer of
232 this type to 32 * PAGE_SIZE (128KBytes on i386). Unfortunately if the
233 sg driver is a module then there is a high chance a contiguous block of
234 that large size will not be available at module initialization.
236 The author has found no "silver bullet" solution but uses multiple
237 techniques hoping that at least one is able provide memory at the critical
238 time. Listed below are some of these techniques:
239         - use scatter gather: then instead of one large buffer needing to
240           be found, multiple smaller buffer can be used
241         - use memory above the 16MByte level: the original driver limited
242           itself to obtaining memory below the 16MByte level (on the i386)
243           due to the shortcomings of DMA on ISA adapters. Yet more and more
244           people use PCI adapters that don't have this problem. So make
245           the decision based on the capabilities of the host adpater
246           associated with the current SCSI device
247         - reserve some memory at open() for emergencies but otherwise
248           fetch and release it on a per packet basis
249         - if the kernel is short of memory then dip into the SCSI DMA
250           pool (maintained by the mid-level driver) to a limited amount
254 System Calls
255 ============
256 What follows are descriptions of the characteristics of the standard
257 Unix operating system calls when applied to a SCSI generic device
258 using this version of the device driver.
260 open
261 ----
262 The filename should be an 'sg' device such as
263 /dev/sg[a-z]
264 /dev/sg[0,1,2,...]
265 or a symbolic link to one of these. [Devfs has its own sub-directory for
266 sg devices.] It seems as though SCSI devices are allocated to sg minor
267 numbers in the same order as they appear in 'cat /proc/scsi/scsi'.
268 Sg is a "character" based Linux device driver. This means it has an
269 open/close/read/write/ioctl type interface.
271 Flags can be either O_RDONLY or O_RDWR or-ed with either
272 O_EXCL          waits for other opens on sg device to be closed before
273                 proceeding. If O_NONBLOCK is set then yields EBUSY when
274                 someone else has the sg device open. The combination of
275                 O_RDONLY and O_EXCL is disallowed.
276 O_NONBLOCK      Sets non-blocking mode. Calls that would otherwise block
277                 yield EAGAIN (eg read() ) or EBUSY (eg open() ).
279 The original version of sg did not allow the O_RDONLY (yielding a EACCES
280 error). This version allows it for accessing ioctls (e.g. doing an sg
281 device scan with the SG_GET_SCSI_ID ioctl) but write()s will not be
282 allowed.
284 By default, sequencing is per file descriptor in this version of sg. This
285 means, for example that 2 processes can independently manipulate the same
286 sg device at the same time. This may or may not make sense depending on
287 the application: 2 processes (logically) reading from the same direct access
288 device (ie a disk) is ok while running 2 instances of cd writing software
289 on the same device at the same time probably wouldn't be a good idea. The
290 previous version of sg supported only per device sequencing and this can
291 still be selected with the SG_SET_MERGE_FD,1 ioctl().
293 The driver will attempt to reserve SG_SCATTER_SZ bytes (32KBytes in the
294 current sg.h) on open() for "emergency" situations. If this is unavailable
295 it will halve its request and try again. It gives up if PAGE_SIZE bytes
296 (4096 bytes on i386) cannot be obtained so no memory is reserved. In this
297 case open() will still return successfully. The actual amount of memory
298 reserved can be found with the SG_GET_RESERVED_SIZE ioctl().
300 Returns a file descriptor if >= 0 , otherwise -1 implies an error.
302 Error codes (value in 'errno' after -1 returned):
303 ENODEV          sg not compiled into kernel or the kernel cannot find the
304                 sg module (or it can't initialize itself (low memory??))
305 ENXIO           either scsi sub-system is currently processing some error
306                 (eg doing a device reset) or the sg driver/module removed
307                 or corrupted
308 EBUSY           O_NONBLOCK set and some user of this sg device has O_EXCL
309                 set while someone is already using this device
310 EINTR           while waiting for an "exclusive" lock to clear, a signal
311                 is received, just try again ...        
312 ENOMEM          An attempt to get memory to store this open's context
313                 failed (this was _not_ a request to reserve DMA memory)
314 EACCES          An attempt to use both O_RDONLY and O_EXCL
317 write
318 -----
319 Even though sg is a character-based device driver it sends and receives
320 packets to/from the associated scsi device. Write() is used to send a
321 packet containing 2 mandatory parts and 1 optional part. The mandatory
322 parts are:
323   - a control block (an instance of struct sg_header)
324   - a SCSI command (6, 10 or 12 bytes long)
325 The optional part is:
326   - outgoing data (eg if a SCSI write command is being sent)
327 These should appear as one contiguous string in the buffer given to
328 write() in the above order with no pad characters.
330 If a write() accepts this packet then at some later time the user should
331 call a read() to get the result of the SCSI command. The previous sg
332 driver enforced a strict write()/read()/write()/read() regime so that a
333 second write() would block until first read() was finished. This sg
334 driver relaxes that condition and thereby allows command queuing
335 (limit is SG_MAX_QUEUE (16) outstanding packets per file descriptor).
336 However, for backward compatibility, command queuing is turned off
337 by default (#define SG_DEF_COMMAND_Q 0 in sg.h). This can be changed
338 via the the SG_SET_COMMAND_Q ioctl() [or by recompiling after changing
339 the above define to 1].
341 In this sg driver a write() should return more or less immediately.
343 Returns number of bytes written if > 0 , otherwise -1 implies an error.
345 Error codes (value in 'errno' after -1 returned):
346 ENXIO           either scsi sub-system is currently processing some error
347                 (eg doing a device reset) or the sg driver/module removed
348                 or corrupted
349 EACCES          opened with RD_ONLY flag
350 EIO             incoming buffer too short. It should be at least (6 +
351                 sizeof(struct sg_header))==42 bytes long
352 EDOM            a) command queuing off: a packet is already queued
353                 b) command queuing on: too many packets queued 
354                    (SG_MAX_QUEUE exceeded)
355 EAGAIN          SCSI mid-level out of command blocks (rare), try again.
356                 This is more likely to happen when queuing commands,
357                 so wait a bit (eg usleep(10000) ) before trying again
358 ENOMEM          can't get memory for DMA. Take evasive action ...
359                 (see section on memory)
362 read
363 ----
364 Read() is used to receive a packet containing 1 mandatory part and 1 
365 optional part. The mandatory part is:
366   - a control block (an instance of struct sg_header)
367 The optional part is:
368   - incoming data (eg if a SCSI read command was sent by earlier write() )
369 The buffer given to a read() and its corresponding count should be
370 sufficient to accommodate this packet to avoid truncation. Truncation has
371 occurred if count < sg_header::replylen .
373 By default, read() will return the oldest packet queued up. If the 
374 SG_SET_FORCE_PACK_ID,1 ioctl() is active then read() will attempt to
375 fetch the packet whose pack_id (given earlier to write()) matches the
376 sg_header::pack_id given to this read(). If not available it will either
377 wait or yield EAGAIN. As a special case, -1 in sg_header::pack_id given
378 to read() will match the oldest packet.
381 Returns number of bytes read if > 0 , otherwise -1 implies an error.
382 Unfortunately the return value in the non-error case is simply the
383 same as the count argument. It is not the actual number of bytes
384 DMA-ed by the SCSI device. This driver is currently unable to provide
385 such an underrun indication.
387 Error codes (value in 'errno' after -1 returned):
388 ENXIO           either scsi sub-system is currently processing some error
389                 (eg doing a device reset) or the sg driver/module removed
390                 or corrupted
391 EAGAIN          either no waiting packet or requested packet is not
392                 available while O_NONBLOCK flag was set
393 EINTR           while waiting for a packet, a signal is received, just
394                 try again ...        
395 EIO             if the 'count' given to read() is < sizeof(struct sg_header)
396                 and the 'result' element in sg_header is non-zero. Not a
397                 recommended error reporting technique
400 close
401 -----
402 Preferably a close() should be done after all issued write()s have had
403 their corresponding read() calls completed. Unfortunately this is not
404 always possible. The semantics of close() in Unix are to return more
405 or less immediately (ie not wait on any event) so the driver needs to
406 arrange to an orderly cleanup of those packets that are still "in
407 flight".
409 A process that has an open file descriptor to an sg device may be aborted
410 (eg by a kill signal). In this case, the kernel automatically calls close 
411 (which is called 'sg_release()' in the version 2 driver) to facilitate
412 the cleanup mentioned above.
414 A problem persists in version 2.1.8 if the sg driver is a module and is
415 removed while packets are still "in flight". Hopefully this will be soon
416 fixed.
418 Returns 0 if successful, otherwise -1 implies an error.
420 Error codes (value in 'errno' after -1 returned):
421 ENXIO           sg driver/module removed or corrupted
423 ioctl (sg specific)
424 -------------------
425 Ken Thompson (or perhaps some other Unix luminary) described ioctl() as 
426 the "garbage bin of Unix". This driver compounds the situation by adding
427 around 18 more commands. These commands either yield state information (10
428 of them), change the driver's characteristics (8 of them) or allow direct
429 communication with the common SCSI mid-level driver.
431 Those commands with an appended "+" are new in version 2.
433 Those commands with an appended "W" are only accessible from file
434 descriptors opened with O_RDWR. They will yield EACCES otherwise.
436 SG_GET_TIMEOUT:
437 Ignores its 3rd argument and _returns_ the timeout value (which will be
438 >= 0 ). The unit of this timeout is "jiffies" which are currently 10
439 millisecond intervals on i386 (less on an alpha). Linux supplies
440 a manifest constant HZ which is the number of "jiffies" in 1 second.
442 SG_SET_TIMEOUT:
443 Assumes 3rd argument points to an int containing the new timeout value
444 for this file descriptor. The unit is a "jiffy". Packets that are
445 already "in flight" will not be effected. The default value is set
446 on open() and is SG_DEFAULT_TIMEOUT (defined in sg.h).
448 SG_EMULATED_HOST:
449 Assumes 3rd argument points to an int and outputs a flag indicating
450 whether the host (adapter) is connected to a real SCSI bus or is
451 emulated one (eg ide-scsi device driver). A value of 1 means emulated
452 while 0 is not.
454 SG_SET_FORCE_LOW_DMA +:
455 Assumes 3rd argument points to an int containing 0 or 1. 0 (default)
456 means sg decides whether to use memory above 16 Mbyte level (on i386)
457 based on the host adapter being used by this SCSI device. Typically
458 PCI SCSI adapters will indicate they can DMA to the whole 32 bit address
459 space. 
460 If 1 is given then the host adapter is overridden and only memory below
461 the 16MB level is used for DMA. A requirement for this should be
462 extremely rare. If the "reserve" buffer allocated on open() is not in
463 use then it will be de-allocated and re-allocated under the 16MB level
464 (and the latter operation could fail yielding ENOMEM).
465 Only the current file descriptor is effected.
467 SG_GET_LOW_DMA +:
468 Assumes 3rd argument points to an int and places 0 or 1 in it. 0
469 indicates the whole 32 bit address space is being used for DMA transfers
470 on this file descriptor. 1 indicates the memory below the 16MB level
471 (on i386) is being used (and this may be the case because the host
472 adapters setting has been overridden by SG_SET_FORCE_LOW_DMA,1 .
474 SG_GET_SCSI_ID +:
475 Assumes 3rd argument is pointing to an object of type Sg_scsi_id and
476 populates it. That structure contains ints for host_no, channel,
477 scsi_id, lun and scsi_type. Most of this information is available from
478 other sources (eg SCSI_IOCTL_GET_IDLUN and SCSI_IOCTL_GET_BUS_NUMBER)
479 but tends to be awkward to collect.
481 SG_SET_FORCE_PACK_ID +:
482 Assumes 3rd argument is pointing to an int. 0 (default) instructs read()
483 to return the oldest (written) packet if multiple packets are
484 waiting to be read (when command queuing is being used). 
485 1 instructs read() to view the sg_header::pack_id as input and return the
486 oldest packet matching that pack_id or wait until it arrives (or yield
487 EAGAIN if O_NONBLOCK is in force). As a special case the pack_id of -1
488 given to read() in the mode will match the oldest packet.
489 Only the current file descriptor is effected by this command.
491 SG_GET_LOW_DMA +:
492 Assumes 3rd argument points to an int and places the pack_id of the
493 oldest (written) packet in it. If no packet is waiting to be read then
494 yields -1.
496 SG_GET_NUM_WAITING +:
497 Assumes 3rd argument points to an int and places the number of packets
498 waiting to be read in it.
500 SG_GET_SG_TABLESIZE +:
501 Assumes 3rd argument points to an int and places the maximum number of
502 scatter gather elements supported by the host adapter. 0 indicates that
503 the adapter does support scatter gather.
505 SG_SET_RESERVED_SIZE +W:
506 This is not currently implemented. It is intended for reserving either a
507 large buffer or scatter gather list that will be available until the
508 current file descriptor is closed. The requested amount of memory may
509 not be available so SG_GET_RESERVED_SIZE should be used after this call
510 to see how much was reserved. (EBUSY error possible)
512 SG_GET_RESERVED_SIZE +:
513 Assumes 3rd argument points to an int and places the size in bytes of
514 the DMA buffer reserved on open() for emergencies. If this is 0 then it
515 is probably not wise to attempt on operation like burning a CD on this
516 file descriptor.
518 SG_SET_MERGE_FD +W:
519 Assumes 3rd argument is pointing to an int. 0 (the default) causes all
520 subsequent sequencing to be per file descriptor. 1 causes all subsequent
521 sequencing to be per device. If this command tries to change the current
522 state and the is one or more _other_ file descriptors using this sg
523 device then an EBUSY error occurs. Also if this file descriptor was not
524 open()ed with the O_RDWR flag then an EACCES error occurs.
525 Per device sequencing was the original semantics and allowed, for example
526 different processes to "share" the device, one perhaps write()ing with
527 the other one read()ing. This command is supplied if anyone needs those
528 semantics. Per file descriptor sequencing, perhaps with the usage of
529 the O_EXCL flag, seems more sensible.
531 SG_GET_MERGE_FD +:
532 Assumes 3rd argument points to an int and places 0 or 1 in it. 0 implies
533 sequencing is per file descriptor. 1 implies sequencing is per device
534 (original sg driver's semantics).
536 SG_SET_COMMAND_Q +:
537 Assumes 3rd argument is pointing to an int. 0 (current default, set by
538 SG_DEF_COMMAND_Q in sg.h) disables command queuing. Attempts to write()
539 a packet while one is already queued will result in a EDOM error.
540 1 turns command queuing on.
541 Changing the queuing state only effects write()s done after the change.
542 Only the current file descriptor is effected by this command.
544 SG_GET_COMMAND_Q +:
545 Assumes 3rd argument points to an int and places 0 or 1 in it. 0 implies
546 that command queuing is off on this file descriptor. 1 implies command
547 queuing is on.
549 SG_SET_DEBUG +:
550 Assumes 3rd argument is pointing to an int. 0 (default) turns debugging
551 off. Values > 0 cause the SCSI sense buffer to be decoded and output
552 to the console/log when a SCSI device error occurs. Values > 8 cause
553 the current sg device driver's state to be output to the console/log
554 (this is a "one off" effect).
555 If you need a _lot_ of the SCSI sub-system debug information (mainly from
556 the mid-level) then try 'echo "scsi dump 0" > /proc/scsi/scsi' and lots of
557 debug will appear in your console/log.
559 ioctl (in common with sd, st + sr)
560 ----------------------------------
561 The following ioctl()s can be called from any high-level scsi device
562 driver (ie sd, st, sr + sg). Access permissions may differ a bit from
563 one device to another, the access information given below is specific to
564 the sg device driver.
566 SCSI_IOCTL_GET_IDLUN:
567 SCSI_IOCTL_GET_BUS_NUMBER:
569 SCSI_IOCTL_SEND_COMMAND:  W
570 If open()ed O_RDONLY yields an EACCESS error. Otherwise is forwarded onto
571 the SCSI mid-level driver for processing.
572 Don't know much about this one but it looks pretty powerful and
573 dangerous. Some comments says it is also deprecated.
575 <any_command_not matching_above>:  W
576 If open()ed O_RDONLY yields an EACCESS error. Otherwise is forwarded onto
577 the SCSI mid-level driver for processing.
580 poll
581 ----
582 This is a native call in Linux 2.2 but most of its capabilities are available
583 through the older select() call. Given a choice poll() should probably be
584 used. Typically poll() is used when a sg scsi device is open()ed O_NONBLOCK
585 for polling; or alternatively with asynchronous notification using the
586 fcntl() system call (below) and the SIGPOLL (aka SIGIO) signal.
587 Only if something drastically is wrong (eg file handle gone stale) will
588 POLLERR ever be set. POLLPRI, POLLHUP and POLLNVAL are never set.
589 POLLIN is set when there is one or more packets waiting to be read.
590 When POLLIN is set it implies that a read() will not block (or yield
591 EAGAIN in non-blocking mode) but return a packet immediately.
592 POLLOUT (aka POLLWRNORM) is set when write() is able to accept a packet
593 (ie will _not_ yield an EDOM error). The setting of POLLOUT is effected
594 by the SG_SET_COMMAND_Q state: if the state is on then POLLOUT will remain
595 set until the number of queued packets reaches SG_MAX_QUEUE, if the
596 state is off then POLLOUT is only set when no packets are queued.
597 Note that a packet can be queued after write()ing but not available to be
598 read(); this typically happens when a SCSI read command is issued while
599 the data is being retreaved.
600 Poll() is per file descriptor unless SG_SET_MERGE_FD is set in which case
601 it is per device.
604 fcntl
605 -----
606 There are several uses for this system call in association with a sg
607 file descriptor. The first pseudo code shows code that is useful for
608 scanning the sg devices, taking care not to be caught in a wait for
609 an O_EXCL lock by another process, and when the appropriate device is
610 found switching to normal blocked io. A working example of this logic
611 is in the sg_scan.c utility program.
613 open("/dev/sga", O_RDONLY | O_NONBLOCK)
614 /* check device, EBUSY means some other process has O_EXCL lock on it */
615 /* one the device you want is found then ... */
616 flags = fcntl(sg_fd, F_GETFL)
617 fcntl(sg_fd, F_SETFL, flags & (~ O_NONBLOCK))
618 /* for simple apps is is easier to use normal blocked io */
621 Some work has to be done in Linux to set up for asynchronous notification.
622 This is a non-blocking mode of operation in which when the driver receives
623 data back from a device so that a read() can be done, it sends a SIGPOLL
624 (aka SIGIO) signal to the owning process. A working example of this logic
625 is in the sg_poll.c test program.
627 sigemptyset(&sig_set)
628 sigaddset(&sig_set, SIGPOLL)
629 sigaction(SIGPOLL, &s_action, 0)
630 fcntl(sg_fd, F_SETOWN, getpid())
631 flags = fcntl(sg_fd, F_GETFL);
632 fcntl(sg_fd, F_SETFL, flags | O_ASYNC)
635 Utility and Test Programs
636 =========================