There are various ways to debug what is happening with the sg driver. The information provided in the /proc/scsi/sg directory can be useful, especially the debug pseudo file. It outputs the state of the sg driver when it is called. Invoking it at the right time can be a challenge. One approach (used in SANE) is to invoke the system() system call like this:
Another debugging technique is to trace all system calls a program makes with the strace command (see its "man" page). This command can also be used to obtain timing information (with the "-r" and "t" options).
To debug the sg driver itself then the kernel needs to be built with CONFIG_SCSI_LOGGING selected. Then copious output will be sent by the sg driver whenever it is invoked to the log (normally /var/log/messages) and/or the console. This debug output is turned on by:
$ echo "scsi log timeout 7" > /proc/scsi/scsi
$ echo "scsi log timeout 0" > /proc/scsi/scsi
If you want the system to log SCSI (CHECK_CONDITION related) errors that sg detects rather than process them within the application using sg then set ioctl(SG_SET_DEBUG) to a value greater than zero. Processing SCSI errors within the application using sg is my preference.