Import changeset
[linux-flexiantxendom0-3.2.10.git] / Documentation / scsi-generic.txt
1             Notes on Linux's SG driver version 2.1.36
2             -----------------------------------------
3                                                         20000110
4
5 Introduction
6 ============
7 The SCSI Generic driver (sg) is one of the four "high level" SCSI device
8 drivers along with sd, st and sr (disk, tape and CDROM respectively). Sg
9 is more generalized (but lower level) than its siblings and tends to be
10 used on SCSI devices that don't fit into the already serviced categories.
11 Thus sg is used for scanners, cd writers and reading audio cds digitally
12 amongst other things.
13
14 These are notes on the Linux SCSI generic packet device driver (sg)
15 describing version 2.1.36 . The original driver was written by Lawrence
16 Foard and remained in place with minimal changes since circa 1992.
17 Version 2 of this driver remains backward compatible (binary and
18 source **) with the original. It adds scatter gather, command queuing,
19 per file descriptor sequencing, asynchronous notification and better
20 error reporting.
21
22 This is an abridged version of the sg documentation that is targeted
23 at the linux/Documentation directory. The full document can be found
24 at http://www.torque.net/sg/p/scsi-generic_long.txt .
25
26 The interface and usage of the original sg driver have been documented
27 by Heiko Eissfeldt in a HOWTO called SCSI-Programming-HOWTO. My copy
28 of the document is version 1.5 dated 7th May 1996. It can found at
29 ftp://sunsite.unc.edu/pub/Linux/docs/HOWTO-SCSI-Programming-HOWTO .
30 A copy of this document can be found at:
31 http://www.torque.net/sg/p/original/HOWTO-SCSI-Programming-HOWTO.txt .
32
33 ** It is possible to write applications that perform differently
34 depending on whether they are using the original or this version of
35 the sg device driver. The author is not aware of any useful
36 pre-existing applications that have problems with version 2.
37
38
39 Architecture
40 ============
41 The SCSI generic packet device driver (sg) is a character based device.
42 It is one of the four high level device driver in the SCSI sub-system;
43 the others are sd (for direct-access devices - disks), st (for tapes)
44 and sr (for data cdroms). The other three devices are block devices.
45
46 The unifying layer of the SCSI sub-system is the so-called mid-level.
47 Below that are the "low level" drivers which are the drivers for the
48 various adapters supported by Linux. Also at this level are pseudo
49 adapter drivers such as ide-scsi which converts the SCSI protocol to
50 ATAPI (which are similar to one another) for use by IDE devices.
51
52 Since sg is a character device it supports the traditional Unix
53 system calls of open(), close(), read(), write() and ioctl(). Two other
54 related system calls: poll() and fcntl() are added to this list and
55 how they interact with the sg device driver is documented later.
56
57 An SG device is accessed by write()ing SCSI commands plus any associated
58 outgoing data to it; the resulting status codes and any incoming data are
59 then obtained by a read() call. The device can be opened O_NONBLOCK
60 (non-blocking) and poll() used to monitor its progress. The device may be
61 opened O_EXCL which excludes other "sg" users from this device (but not
62 "sd", "st" or "sr" users). The buffer given to the write() call is made
63 up as follows:
64         - struct sg_header image (see below)
65         - scsi command (6, 10 or 12 bytes long)
66         - data to be written to the device (if any)
67
68 The buffer received from the corresponding read() call contains:
69         - struct sg_header image (check status/errors + sense_buffer)
70         - data read back from device (if any)
71
72 The given SCSI command has its LUN field overwritten by the LUN value of
73 the associated sg device that has been open()ed.
74
75 SCSI commands are only attempted once (i.e. there are no internal
76 retries). If appropriate (e.g. a SCSI READ) the data buffer is copied back
77 to user space irrespective of the values of the various SCSI related
78 error/status codes. [Some adapters that use an old error interface in
79 the SCSI mid level ignore the retry count and retry certain errors.]
80
81
82 sg_header
83 =========
84 This is the name of the control structure that conveys information
85 about the length of data to be read/written by the associated SCSI
86 command. It also conveys error and status information from the
87 read() call. An instance of this structure is the first thing that
88 is placed in the data buffers of both write() and read().
89
90 In its original form it looked like this:
91 struct sg_header {
92     int pack_len;
93     int reply_len;
94     int pack_id;
95     int result;
96     unsigned int twelve_byte:1;
97     unsigned int other_flags:31;
98     unsigned char sense_buffer[16];
99 }; /* this structure is 36 bytes long */
100
101 The 'pack_len' is bizarre and ends up having the 'reply_len' put in it
102 (perhaps it had a use at some stage). Even though it looks like an
103 input variable, it is not read by sg internally (only written).
104
105 The 'reply_len' is the length of the data the corresponding read()
106 will/should request (including the sg_header).
107
108 The 'pack_id' is not acted upon by the sg device driver but is conveyed
109 back to the corresponding read() so it can be used for sequencing by an
110 application.
111
112 The 'result' is also bizarre, turning certain types of host codes to 0 (no
113 error), EBUSY or EIO. With better error reporting now available, the
114 'result' is best ignored.
115
116 The 'twelve_byte' field overrides the internal SCSI command length detection
117 algorithm for group 6 and 7 commands (ie when 1st byte >= 0xc0) and forces
118 a command length of 12 bytes.
119 The command length detection algorithm is as follows:
120 Group:  0    1    2    3    4    5    6    7
121 Length: 6   10   10   12   12   12   10   10
122
123 'other_flags' was originally documented as "not used" but some current
124 applications assume it has 0 placed in it.
125
126 The 'sense_buffer' is the first 16 bytes of SCSI sense buffer that is
127 returned when the target returns a SCSI status code of CHECK_CONDITION
128 or COMMAND_TERMINATED [or (driver_status & DRIVER_SENSE) is true]. This
129 buffer should be at least 18 bytes long and arguably 32 bytes; unfortunately
130 this is unlikely to happen in the 2.2.x series of kernels.
131
132
133 The new sg_header offered in this driver is:
134 #define SG_MAX_SENSE 16
135 struct sg_header
136 {
137     int pack_len;    /* [o] reply_len (ie useless) ignored as input */
138     int reply_len;   /* [i] max length of expected reply (inc. sg_header) */
139     int pack_id;     /* [io] id number of packet (use ints >= 0) */
140     int result;      /* [o] 0==ok, else (+ve) Unix errno (best ignored) */
141     unsigned int twelve_byte:1;
142         /* [i] Force 12 byte command length for group 6 & 7 commands  */
143     unsigned int target_status:5;   /* [o] scsi status from target */
144     unsigned int host_status:8;     /* [o] host status (see "DID" codes) */
145     unsigned int driver_status:8;   /* [o] driver status+suggestion */
146     unsigned int other_flags:10;    /* unused */
147     unsigned char sense_buffer[SG_MAX_SENSE]; /* [o] Output in 3 cases:
148            when target_status is CHECK_CONDITION or
149            when target_status is COMMAND_TERMINATED or
150            when (driver_status & DRIVER_SENSE) is true. */
151 };      /* This structure is 36 bytes long on i386 */
152
153 Firstly the new header is binary compatible with the original. This is
154 important for keeping existing apps working without recompilation.
155
156 Only those elements (or fields) that are new or in some way different
157 from the original are documented below.
158
159 'pack_id' becomes input to a read() when ioctl(sg_fd, SG_SET_FORCE_PACK_ID,
160 &one) is active. A 'pack_id' of -1 is interpreted as fetch the oldest
161 waiting packet; any other value will cause the read() to wait (or yield
162 EAGAIN) until a packet with that 'pack_id' becomes available. In all cases
163 the value of 'pack_id' available after a read() is the value given to that
164 variable in the prior, corresponding write().
165
166 The SCSI command length can now be given directly using the SG_NEXT_CMD_LEN
167 ioctl().
168
169 The 'target_status' field is always output and is the (masked and shifted
170 1 bit right) SCSI status code from the target device. The allowable
171 values are (found in <scsi/scsi.h>):
172 /* N.B. 1 bit offset from usual SCSI status values */
173 #define GOOD                 0x00
174 #define CHECK_CONDITION      0x01
175 #define CONDITION_GOOD       0x02
176 #define BUSY                 0x04
177 #define INTERMEDIATE_GOOD    0x08
178 #define INTERMEDIATE_C_GOOD  0x0a
179 #define RESERVATION_CONFLICT 0x0c
180 #define COMMAND_TERMINATED   0x11
181 #define QUEUE_FULL           0x14
182 When the 'target_status' is CHECK_CONDITION or COMMAND_TERMINATED the
183 'sense_buffer' is output. Note that when (driver_status & DRIVER_SENSE)
184 is true then the 'sense_buffer' is also output (this seems to occur when
185 the ide-scsi emulation is used). When the 'sense_buffer' is output the
186 SCSI Sense Key can be found at (sense_buffer[2] & 0x0f) .
187
188 The 'host_status' field is always output and has the following values
189 whose "defines" are not visible outside the kernel. A copy of these
190 defines can be found in sg_err.h (see the utilities section):
191 #define DID_OK          0x00 /* NO error                                */
192 #define DID_NO_CONNECT  0x01 /* Couldn't connect before timeout period  */
193 #define DID_BUS_BUSY    0x02 /* BUS stayed busy through time out period */
194 #define DID_TIME_OUT    0x03 /* TIMED OUT for other reason              */
195 #define DID_BAD_TARGET  0x04 /* BAD target, device not responding?      */
196 #define DID_ABORT       0x05 /* Told to abort for some other reason     */
197 #define DID_PARITY      0x06 /* Parity error                            */
198 #define DID_ERROR       0x07 /* Internal error [DMA underrun on aic7xxx]*/
199 #define DID_RESET       0x08 /* Reset by somebody.                      */
200 #define DID_BAD_INTR    0x09 /* Got an interrupt we weren't expecting.  */
201 #define DID_PASSTHROUGH 0x0a /* Force command past mid-layer            */
202 #define DID_SOFT_ERROR  0x0b /* The low level driver wants a retry      */
203
204 The 'driver_status' field is always output. When ('driver_status' &
205 DRIVER_SENSE) is true the 'sense_buffer' is also output. A copy of these
206 defines can be found in sg_err.h (see the utilities section):
207 #define DRIVER_OK           0x00 /* Typically no suggestion */
208 #define DRIVER_BUSY         0x01
209 #define DRIVER_SOFT         0x02
210 #define DRIVER_MEDIA        0x03
211 #define DRIVER_ERROR        0x04
212 #define DRIVER_INVALID      0x05
213 #define DRIVER_TIMEOUT      0x06
214 #define DRIVER_HARD         0x07
215 #define DRIVER_SENSE        0x08 /* Implies sense_buffer output */
216 /* above status 'or'ed with one of the following suggestions */
217 #define SUGGEST_RETRY       0x10
218 #define SUGGEST_ABORT       0x20
219 #define SUGGEST_REMAP       0x30
220 #define SUGGEST_DIE         0x40
221 #define SUGGEST_SENSE       0x80
222
223 'other_flags' still remains as a 10 bit field (reduced from 31 bits), so
224 code that places 0 in it will still be happy. It is not used.
225
226
227 System Calls
228 ============
229 What follows are descriptions of the characteristics of the standard
230 Unix operating system calls when applied to a SCSI generic device
231 using this version of the device driver.
232
233 open(const char * filename, int flags)
234 --------------------------------------
235 The filename should be an 'sg' device such as
236 /dev/sg[a-z]
237 /dev/sg[0,1,2,...]
238 or a symbolic link to one of these. [Devfs has its own sub-directory for
239 sg devices with entries like: /dev/sg/c1b2t3u4 .] It seems as though SCSI
240 devices are allocated to sg minor numbers in the same order as they appear
241 in 'cat /proc/scsi/scsi'. Sg is a "character" based Linux device driver.
242 This means it has an open/close/read/write/ioctl type interface.
243
244 Flags can be either O_RDONLY or O_RDWR or-ed with either
245 O_EXCL          waits for other opens on sg device to be closed before
246                 proceeding. If O_NONBLOCK is set then yields EBUSY when
247                 someone else has the sg device open. The combination of
248                 O_RDONLY and O_EXCL is disallowed.
249 O_NONBLOCK      Sets non-blocking mode. Calls that would otherwise block
250                 yield EAGAIN (eg read() ) or EBUSY (eg open() ).
251
252 The original version of sg did not allow the O_RDONLY (yielding a EACCES
253 error). This version allows it for accessing ioctls (e.g. doing an sg
254 device scan with the SG_GET_SCSI_ID ioctl) but write()s will not be
255 allowed. These flags are found in <fcntl.h> .
256
257 By default, sequencing is per file descriptor in this version of sg. This
258 means, for example that 2 processes can independently manipulate the same
259 sg device at the same time. This may or may not make sense depending on
260 the application: 2 processes (logically) reading from the same direct access
261 device (ie a disk) is ok while running 2 instances of cd writing software
262 on the same device at the same time probably wouldn't be a good idea. The
263 previous version of sg supported only per device sequencing and this can
264 still be selected with the SG_SET_MERGE_FD,1 ioctl().
265
266 The driver will attempt to reserve SG_DEF_RESERVED_SIZE bytes (32KBytes in
267 the current sg.h) on open(). The size of this reserved buffer can
268 subsequently be modified with the SG_SET_RESERVED_SIZE ioctl(). In both
269 cases these are requests subject to various dynamic constraints. The actual
270 amount of memory obtained can be found by the SG_GET_RESERVED_SIZE ioctl().
271 The reserved buffer will be used if:
272     -  it is not already in use (eg when command queuing is in use)
273     -  a write() does not call for a buffer size larger than the
274        reserved size.
275
276 Returns a file descriptor if >= 0 , otherwise -1 implies an error.
277
278 Error codes (value in 'errno' after -1 returned):
279 EACCES          Either the user doesn't have appropriate permissions on
280                 'filename' or attempted to use both O_RDONLY and O_EXCL
281 EBUSY           O_NONBLOCK set and some user of this sg device has O_EXCL
282                 set while someone is already using this device
283 EINTR           while waiting for an "exclusive" lock to clear, a signal
284                 is received, just try again ...
285 ENODEV          sg not compiled into kernel or the kernel cannot find the
286                 sg module (or it can't initialize itself (low memory??))
287 ENOENT          given filename not found
288 ENOMEM          An attempt to get memory to store this open's context
289                 failed (this was _not_ a request to reserve DMA memory)
290 ENXIO           either there is no attached device corresponding to given
291                 filename or scsi sub-system is currently processing some
292                 error (eg doing a device reset) or the sg driver/module
293                 removed or corrupted
294
295
296 write(int sg_fd, const void * buffer, size_t count)
297 ---------------------------------------------------
298 Even though sg is a character-based device driver it sends and receives
299 packets to/from the associated scsi device. Write() is used to send a
300 packet containing 2 mandatory parts and 1 optional part. The mandatory
301 parts are:
302   - a control block (an instance of struct sg_header)
303   - a SCSI command (6, 10 or 12 bytes long)
304 The optional part is:
305   - outgoing data (eg if a SCSI write command is being sent)
306 These should appear as one contiguous string in the buffer given to
307 write() in the above order with no pad characters.
308
309 If a write() accepts this packet then at some later time the user should
310 call a read() to get the result of the SCSI command. The previous sg
311 driver enforced a strict write()/read()/write()/read() regime so that a
312 second write() would block until first read() was finished. This sg
313 driver relaxes that condition and thereby allows command queuing
314 (limit is SG_MAX_QUEUE (16) outstanding packets per file descriptor).
315 However, for backward compatibility, command queuing is turned off
316 by default (#define SG_DEF_COMMAND_Q 0 in sg.h). This can be changed
317 via the the SG_SET_COMMAND_Q ioctl() [or by recompiling after changing
318 the above define to 1].
319
320 In this sg driver a write() should return more or less immediately.
321
322 Returns number of bytes written if > 0 , otherwise -1 implies an error.
323
324 Error codes (value in 'errno' after -1 returned):
325 EACCES          opened with RD_ONLY flag
326 EAGAIN          SCSI mid-level out of command blocks (rare), try again.
327                 This is more likely to happen when queuing commands,
328                 so wait a bit (eg usleep(10000) ) before trying again
329 EDOM            a) command queuing off: a packet is already queued
330                 b) command queuing on: too many packets queued
331                    (SG_MAX_QUEUE exceeded)
332 EFAULT          'buffer' for 'count' bytes is an invalid memory range
333 EIO             a) incoming buffer too short. It should be at least
334                    (6 + sizeof(struct sg_header))==42 bytes long
335                 b) SCSI command length given in SG_NEXT_CMD_LEN too long
336                 c) reply_len negative
337 ENOMEM          can't get memory for DMA. Take evasive action ...
338 ENXIO           either scsi sub-system is currently processing some error
339                 (eg doing a device reset) or the sg driver/module removed
340                 or corrupted
341
342
343 read(int sg_fd, void * buffer, size_t count)
344 --------------------------------------------
345 Read() is used to receive a packet containing 1 mandatory part and 1
346 optional part. The mandatory part is:
347   - a control block (an instance of struct sg_header)
348 The optional part is:
349   - incoming data (eg if a SCSI read command was sent by earlier write() )
350 The buffer given to a read() and its corresponding count should be
351 sufficient to accommodate this packet to avoid truncation. Truncation occurs
352 if count < sg_header::replylen .
353
354 By default, read() will return the oldest packet queued up. If the
355 SG_SET_FORCE_PACK_ID,1 ioctl() is active then read() will attempt to
356 fetch the packet whose pack_id (given earlier to write()) matches the
357 sg_header::pack_id given to this read(). If not available it will either
358 wait or yield EAGAIN. As a special case, -1 in sg_header::pack_id given
359 to read() will match the oldest packet.
360
361 Returns number of bytes read if > 0 , otherwise -1 implies an error.
362 Unfortunately the return value in the non-error case is simply the
363 same as the count argument. It is not the actual number of bytes
364 DMA-ed by the SCSI device. This driver is currently unable to provide
365 such an underrun indication.
366
367 If the SCSI device reports an error then a REQUEST SENSE is automatically
368 done and the output is placed in the sense_buffer array which is in the
369 control block. This action is sometimes called "auto-sense".
370
371 Error codes (value in 'errno' after -1 returned):
372 EAGAIN          either no waiting packet or requested packet is not
373                 available while O_NONBLOCK flag was set
374 EFAULT          'buffer' for 'count' bytes is an invalid memory range
375 EINTR           while waiting for a packet, a signal is received, just
376                 try again ...
377 EIO             if the 'count' given to read() is < sizeof(struct sg_header)
378                 and the 'result' element in sg_header is non-zero. Not a
379                 recommended error reporting technique
380 ENXIO           either scsi sub-system is currently processing some error
381                 (eg doing a device reset) or the sg driver/module removed
382                 or corrupted
383
384
385 close(int sg_fd)
386 ----------------
387 Preferably a close() should be done after all issued write()s have had
388 their corresponding read() calls completed. Unfortunately this is not
389 always possible. The semantics of close() in Unix are to return more
390 or less immediately (ie not wait on any event) so the driver needs to
391 arrange for an orderly cleanup of those packets that are still "in
392 flight".
393
394 A process that has an open file descriptor to an sg device may be aborted
395 (eg by a kill signal). In this case, the kernel automatically calls close
396 (which is called 'sg_release()' in the version 2 driver) to facilitate
397 the cleanup mentioned above.
398
399 A problem persists in version 2.1.36 if the sg driver is a module and is
400 removed while packets are still "in flight".
401
402 Returns 0 if successful, otherwise -1 implies an error.
403
404 Error codes (value in 'errno' after -1 returned):
405 ENXIO           sg driver/module removed or corrupted
406
407 ioctl(int sg_fd, int command, ...)  [sg specific]
408 -------------------------------------------------
409 Ken Thompson (or perhaps some other Unix luminary) described ioctl() as
410 the "garbage bin of Unix". This driver compounds the situation by adding
411 more ...
412 If a ioctl command is not recognized by sg (and the various lower levels
413 that it may pass the command on to) then the error EINVAL occurs. If an
414 invalid address is given (in the 3rd argument) then the error EFAULT occurs.
415
416 Those commands with an appended "+" are new in version 2.
417
418 Those commands with an appended "W" are only accessible from file
419 descriptors opened with O_RDWR. They will yield EACCES otherwise.
420
421 SG_GET_TIMEOUT:
422 Ignores its 3rd argument and _returns_ the timeout value (which will be
423 >= 0 ). The unit of this timeout is "jiffies" which are currently 10
424 millisecond intervals on i386 (less on an alpha). Linux supplies
425 a manifest constant HZ which is the number of "jiffies" in 1 second.
426
427 SG_SET_TIMEOUT:
428 Assumes 3rd argument points to an int containing the new timeout value
429 for this file descriptor. The unit is a "jiffy". Packets that are
430 already "in flight" will not be affected. The default value is set
431 on open() and is SG_DEFAULT_TIMEOUT (defined in sg.h). This default is
432 currently 1 minute and may not be long enough for formats. Negative
433 values will yield an EIO error.
434
435 SG_EMULATED_HOST:
436 Assumes 3rd argument points to an int and outputs a flag indicating
437 whether the host (adapter) is connected to a real SCSI bus or is an
438 emulated one (eg ide-scsi device driver). A value of 1 means emulated
439 while 0 is not.
440
441 SG_SET_TRANSFORM  W:
442 Only is meaningful when SG_EMULATED host has yielded 1 (i.e. the low-level
443 is the ide-scsi device driver); otherwise an EINVAL error occurs. The
444 default state is to _not_ transform SCSI commands to the corresponding
445 ATAPI commands but pass them straight through as is. [Only certain classes
446 of SCSI commands need to be transformed to their ATAPI equivalents.]
447 The third argument is interpreted as an integer. When it is non-zero then
448 a flag is set inside the ide-scsi driver that transforms subsequent
449 commands sent to this driver. When zero is passed as the 3rd argument to
450 this ioctl then the flag within the ide-scsi driver is cleared and
451 subsequent commands are not transformed. Beware, this state will affect
452 all devices (and hence all related sg file descriptors) associated with
453 this ide-scsi "bus".
454
455 SG_GET_TRANSFORM:
456 Third argument is ignored. Only is meaningful when SG_EMULATED host has
457 yielded 1 (ie the low-level is the ide-scsi device driver); otherwise
458 an EINVAL error occurs. Returns 0 to indicate _not_ transforming SCSI
459 to ATAPI commands (default). Returns 1 when it is transforming them.
460
461 SG_SET_FORCE_LOW_DMA +:
462 Assumes 3rd argument points to an int containing 0 or 1. 0 (default)
463 means sg decides whether to use memory above 16 Mbyte level (on i386)
464 based on the host adapter being used by this SCSI device. Typically
465 PCI SCSI adapters will indicate they can DMA to the whole 32 bit address
466 space.
467 If 1 is given then the host adapter is overridden and only memory below
468 the 16MB level is used for DMA. A requirement for this should be
469 extremely rare. If the "reserved" buffer allocated on open() is not in
470 use then it will be de-allocated and re-allocated under the 16MB level
471 (and the latter operation could fail yielding ENOMEM).
472 Only the current file descriptor is affected.
473
474 SG_GET_LOW_DMA +:
475 Assumes 3rd argument points to an int and places 0 or 1 in it. 0
476 indicates the whole 32 bit address space is being used for DMA transfers
477 on this file descriptor. 1 indicates the memory below the 16MB level
478 (on i386) is being used (and this may be the case because the host
479 adapters setting has been overridden by SG_SET_FORCE_LOW_DMA,1 .
480
481 SG_GET_SCSI_ID +:
482 Assumes 3rd argument is pointing to an object of type Sg_scsi_id (see
483 sg.h) and populates it. That structure contains ints for host_no,
484 channel, scsi_id, lun, scsi_type, allowable commands per lun and
485 queue_depth. Most of this information is available from other sources
486 (eg SCSI_IOCTL_GET_IDLUN and SCSI_IOCTL_GET_BUS_NUMBER) but tends to be
487 awkward to collect.
488 Allowable commands per lun and queue_depth give an insight to the
489 command queuing capabilities of the adapters and the device. The latter
490 overrides the former (logically) and the former is only of interest
491 if it is equal to queue_depth which probably indicates the device
492 does not support queueing commands (e.g. most scanners).
493
494 SG_SET_FORCE_PACK_ID +:
495 Assumes 3rd argument is pointing to an int. 0 (default) instructs read()
496 to return the oldest (written) packet if multiple packets are
497 waiting to be read (when command queuing is being used).
498 1 instructs read() to view the sg_header::pack_id as input and return the
499 oldest packet matching that pack_id or wait until it arrives (or yield
500 EAGAIN if O_NONBLOCK is in force). As a special case the pack_id of -1
501 given to read() in the mode will match the oldest packet.
502 Only the current file descriptor is affected by this command.
503
504 SG_GET_PACK_ID +:
505 Assumes 3rd argument points to an int and places the pack_id of the
506 oldest (written) packet in it. If no packet is waiting to be read then
507 yields -1.
508
509 SG_GET_NUM_WAITING +:
510 Assumes 3rd argument points to an int and places the number of packets
511 waiting to be read in it.
512
513 SG_GET_SG_TABLESIZE +:
514 Assumes 3rd argument points to an int and places the maximum number of
515 scatter gather elements supported by the host adapter. 0 indicates that
516 the adapter does support scatter gather.
517
518 SG_SET_RESERVED_SIZE +W:
519 Assumes 3rd argument is pointing to an int. That value will be used to
520 request a new reserved buffer of that size. The previous reserved buffer
521 is freed (if it is not in use; if it was in use -EBUSY is returned).
522 A new reserved buffer is then allocated and its actual size can be found by
523 calling the SG_GET_RESERVED_SIZE ioctl(). The reserved buffer is then used
524 for DMA purposes by subsequent write() commands if it is not already in
525 use and if the write() is not calling for a buffer size larger than that
526 reserved. The reserved buffer may well be a series of kernel buffers if the
527 adapter supports scatter-gather. Large buffers can be requested (eg 1 MB).
528
529 SG_GET_RESERVED_SIZE +:
530 Assumes 3rd argument points to an int and places the size in bytes of
531 the reserved buffer from open() or the most recent SG_SET_RESERVED_SIZE
532 ioctl() call on this fd.  The result can be 0 if memory is very tight. In
533 this case it may not be wise to attempt something like burning a CD on
534 this file descriptor.
535
536 SG_SET_MERGE_FD +W:
537 Assumes 3rd argument is pointing to an int. 0 (the default) causes all
538 subsequent sequencing to be per file descriptor. 1 causes all subsequent
539 sequencing to be per device. If this command tries to change the current
540 state and there is one or more _other_ file descriptors using this sg
541 device then an EBUSY error occurs. Per device sequencing was the original
542 semantics and allowed, for example different processes to "share" the
543 device, one perhaps write()ing with the other one read()ing. This command
544 is supplied if anyone needs those semantics. Per file descriptor
545 sequencing, perhaps with the use of the O_EXCL flag, seems more sensible.
546
547 SG_GET_MERGE_FD +:
548 Assumes 3rd argument points to an int and places 0 or 1 in it. 0 implies
549 sequencing is per file descriptor. 1 implies sequencing is per device
550 (original sg driver's semantics).
551
552 SG_SET_COMMAND_Q +:
553 Assumes 3rd argument is pointing to an int. 0 (current default, set by
554 SG_DEF_COMMAND_Q in sg.h) disables command queuing. Attempts to write()
555 a packet while one is already queued will result in a EDOM error.
556 1 turns command queuing on.
557 Changing the queuing state only affects write()s done after the change.
558 Only the current file descriptor is affected by this command.
559
560 SG_GET_COMMAND_Q +:
561 Assumes 3rd argument points to an int and places 0 or 1 in it. 0 implies
562 that command queuing is off on this file descriptor. 1 implies command
563 queuing is on.
564
565 SG_SET_UNDERRUN_FLAG +:
566 Assumes 3rd argument is pointing to an int. 0 (current default, set by
567 SG_DEF_UNDERRUN_FLAG in sg.h) requests underruns be ignored. 1 requests
568 that underruns be flagged. [The only low level driver that acts on this
569 at the moment is the aic7xxx which yields a DID_ERROR error on underrun.]
570 Only the current file descriptor is affected by this command (unless
571 "per device" sequencing has been selected).
572
573 SG_GET_UNDERRUN_FLAG +:
574 Assumes 3rd argument points to an int and places 0 or 1 in it. 0 implies
575 that underruns are not being reported. 1 implies that underruns are being
576 reported (see SG_SET_UNDERRUN_FLAG for more details).
577
578 SG_NEXT_CMD_LEN +:
579 Assumes 3rd argument is pointing to an int. The value of the int (if > 0)
580 will be used as the SCSI command length of the next SCSI command sent to
581 a write() on this fd. After that write() the SCSI command length logic is
582 reset to use automatic length detection (ie depending on SCSI command group
583 and the 'twelve_byte' field). If the current SCSI command length maximum of
584 12 is exceeded then the affected write() will yield an EDOM error.
585 Giving this ioctl() a value of 0 will set automatic length detection for
586 the next write(). N.B. Only the following write() on this fd is affected by
587 this ioctl().
588
589 SG_GET_VERSION_NUM +:
590 Assumes 3rd argument points to an int. The version number is then placed
591 in that int. A sg version such as 2.1.36 will yield "20136" from this ioctl.
592
593 SG_SCSI_RESET +:
594 Assumes 3rd argument points to an int. Unfortunately doesn't currently
595 do much (may in the future after other issues are resolved). Yields an
596 EBUSY error if the SCSI bus or the associated device is being reset
597 when this ioctl() is called, otherwise returns 0.
598
599 SG_SET_DEBUG +:
600 Assumes 3rd argument is pointing to an int. 0 (default) turns debugging
601 off. Values > 0 cause the SCSI sense buffer to be decoded and output
602 to the console/log when a SCSI device error occurs. Values > 8 cause
603 the current sg device driver's state to be output to the console/log
604 (this is a "one off" effect).
605 If you need a _lot_ of the SCSI sub-system debug information (mainly from
606 the mid-level) then try 'echo "scsi dump 0" > /proc/scsi/scsi' and lots of
607 debug will appear in your console/log.
608
609
610 poll(struct pollfd * udfds, unsigned int nfds, int timeout_ms)
611 --------------------------------------------------------------
612 This is a native call in Linux 2.2 but most of its capabilities are available
613 through the older select() call. Given a choice poll() should probably be
614 used. Typically poll() is used when a sg scsi device is open()ed O_NONBLOCK
615 for polling; and optionally with asynchronous notification as well using
616 the fcntl() system call (below) and the SIGPOLL (aka SIGIO) signal.
617 Only if something drastically is wrong (eg file handle gone stale) will
618 POLLERR ever be set. POLLPRI, POLLHUP and POLLNVAL are never set.
619 POLLIN is set when there is one or more packets waiting to be read.
620 When POLLIN is set it implies that a read() will not block (nor yield
621 EAGAIN in non-blocking mode) but return a packet immediately.
622 POLLOUT (aka POLLWRNORM) is set when write() is able to accept a packet
623 (ie will _not_ yield an EDOM error). The setting of POLLOUT is affected
624 by the SG_SET_COMMAND_Q state: if the state is on then POLLOUT will remain
625 set until the number of queued packets reaches SG_MAX_QUEUE, if the
626 state is off then POLLOUT is only set when no packets are queued.
627 Note that a packet can be queued after write()ing but not available to be
628 read(); this typically happens when a SCSI read command is issued while
629 the data is being retrieved.
630 Poll() is per file descriptor unless SG_SET_MERGE_FD is set in which case
631 it is per device.
632
633
634 fcntl(int sg_fd, int cmd) or fcntl(int sg_fd, int cmd, long arg)
635 ----------------------------------------------------------------
636 There are several uses for this system call in association with a sg
637 file descriptor. The following pseudo code shows code that is useful for
638 scanning the sg devices, taking care not to be caught in a wait for
639 an O_EXCL lock by another process, and when the appropriate device is
640 found, switching to normal blocked io. A working example of this logic
641 is in the sg_scan utility program.
642
643 open("/dev/sga", O_RDONLY | O_NONBLOCK)
644 /* check device, EBUSY means some other process has O_EXCL lock on it */
645 /* when the device you want is found then ... */
646 flags = fcntl(sg_fd, F_GETFL)
647 fcntl(sg_fd, F_SETFL, flags & (~ O_NONBLOCK))
648 /* since, for simple apps, it is easier to use normal blocked io */
649
650
651 Some work has to be done in Linux to set up for asynchronous notification.
652 This is a non-blocking mode of operation in which, when the driver receives
653 data back from a device so that a read() can be done, it sends a SIGPOLL
654 (aka SIGIO) signal to the owning process. A working example of this logic
655 is in the sg_poll test program.
656
657 sigemptyset(&sig_set)
658 sigaddset(&sig_set, SIGPOLL)
659 sigaction(SIGPOLL, &s_action, 0)
660 fcntl(sg_fd, F_SETOWN, getpid())
661 flags = fcntl(sg_fd, F_GETFL);
662 fcntl(sg_fd, F_SETFL, flags | O_ASYNC)
663
664
665 Utility and Test Programs
666 =========================
667 See the README file in the sg_utils<date>.tgz tarball. Look on the
668 http://www.torque.net/sg website for the latest version.
669
670 Briefly, that tarball contains the following utilities:
671 sg_dd512        'dd' like program that assumes 512 byte blocks size
672 sg_dd2048       'dd' like program that assumes 2048 byte blocks size
673 sg_dd2352       'dd' like program that assumes 2352 byte blocks size
674 sgq_dd512       like 'sg_dd512' but does command queuing on "if"
675 sgp_dd          probably the most flexible 'dd' variant. It uses POSIX
676                 threads, block size set by "bs=..." plus other options.
677 sg_scan         outputs information (optionally Inquiry) on SCSI devices
678 sg_rbuf         tests SCSI bus transfer speed (without physical IO)
679 sg_whoami       outputs info (optionally capacity) of given SCSI device
680 sginfo          outputs "mode" information about SCSI devices (it is a
681                   re-port of the scsiinfo program onto the sg interface)
682
683 It also contains the following test programs:
684 sg_debug        outputs sg driver state to console/log file
685 sg_poll         tests asynchronous notification
686 sg_runt_ex      example run time selection program for application authors
687 sg_simple1      example program first time users
688 sg_simple2      like sg_simple1 but with more primitive error processing
689 sg_inquiry      does a SCSI Inquiry command (from original HOWTO)
690 sg_tst_med      checks presence of media (from original HOWTO)
691
692 There are also 2 source files (sg_err.[hc]) for outputting and categorizing
693 SCSI 2 errors and warnings. This code is used by most of the above
694 utility and test programs.
695
696 The following programs: sg_dd512, sg_dd2048, sg_dd2352, sg_scan, sg_runt_ex,
697 sg_rbuf, sg_tst_med, sg_inquiry and sginfo, can be compiled either for this
698 new sg driver _or_ the original sg driver (in 2.0 or 2.2 series kernels).
699 sg_runt_ex can be run on 2.0, 2.2 or 2.3 series kernels even if it is
700 compiled on a different series (eg compiled on 2.0, run on 2.2).
701
702
703 Header files
704 ============
705 User applications need to find the correct "sg.h" header file matching
706 their kernel in order to write code using the sg device driver. This is
707 sometimes more difficult than it should be. The correct "sg.h" will usually
708 be found at /usr/src/linux/include/scsi/sg.h . Another important header
709 file is "scsi.h" which will be in the same directory.
710
711 When "#include <scsi/sg.h>" is written in an application then this refers
712 to the file /usr/include/scsi/sg.h . A problem sometimes arises because
713 the files in the /usr/include/scsi directory are controlled by the GNU
714 library people who maintain glibc. Unfortunately these 2 versions of
715 the sg.h header file are not always in sync. [This was the case in Redhat
716 6.0 and 6.1 .] Glibc 2.1.3 and later versions should get this right.
717
718 If this is a problem, the user may need to copy sg.h (and scsi.h) from
719 the kernel source includes to /usr/include scsi. If the user can change
720 the effected source code then another approach is to rely on the fact that
721 /usr/src/linux is a symbolic link to /usr/src/linux/include/linux and
722 change the sg.h include to look like:
723     #include <linux/../scsi/sg.h>
724 This solution is used by the author of cdparanoia (Monty) in his application.
725
726 [Former scsi generic documents suggested adding a symbolic link to
727 bypass this problem but that is not popular with the glibc maintainers.
728 I would like to thank Andreas Jaeger <aj@suse.de> for his contributions
729 on this subject.]
730
731
732 Extra information in scsi-generic_long.txt
733 ==========================================
734 This document is an abridged form of a more comprehensive document called
735 scsi-generic_long.txt (see www.torque.net/sg/p/scsi-generic_long.txt).
736
737 The longer document contains additional sections on:
738    - memory issues
739    - ioctl()s in common with sd, st + sr
740    - distinguishing the original from the new driver
741    - SG_BIG_BUFF and friends
742    - shortcomings
743    - future directions
744    - an appendix with some SCSI 2 information in it
745
746
747 References
748 ==========
749 http://www.t10.org      Very important site for SCSI related information.
750                         Contains SCSI 2 and 3 draft standards.
751 http://www.andante.org/scsi.html
752                         This is Eric Youngdale's site. Eric is primarily
753                         responsible for the Linux SCSI architecture and
754                         its mid-level implementation.
755 http://www.kernel.dk    Jens Axboe's site for Linux cdrom matters including
756                         the SCSI "sr" driver.
757 http://www.torque.net/sg
758                         My site with sg related information.
759 newsgroup:linux-scsi@vger.kernel.org
760                         Newsgroup for Linux related SCSI matters
761 /usr/src/linux/MAINTAINERS
762                         This is a file in the Linux kernel source that
763                         contains up to date information about who maintains
764                         what and where information can be found. Links to
765                         SCSI adapter information are also here.
766
767
768 Conclusion
769 ==========
770 The SCSI generic packet device driver attempts to make as few assumptions
771 as possible about the device it is connected to while giving applications
772 using it as much flexibility as possible on the SCSI command level. Sg
773 needs to hide the "messy" kernel related details while protecting
774 the integrity of the kernel against sg "abuse". Some of these aims are
775 contradictory and some compromises need to be made. For example: should
776 a sg based application be able to reset a SCSI bus when that could cause
777 collateral damage to a disk holding the root file system? There is no
778 easy answer to this and many other related questions.
779
780 If you have any suggestion about sg (or improving (the accuracy of) this
781 document) please contact me.
782
783
784 Douglas Gilbert
785 dgilbert@interlog.com