Macross的筆記

2006/10/03

使用SCSI Generic Driver與usb讀卡機進行讀寫

利用SCSI Generic Driver 與usb讀卡機溝通

1. 在linuxconfig中勾選 SCSI support--> SCSI generic support

2. 在程式中需要include

3. sg_io_hdr struct介紹

typedef struct sg_io_hdr
{
int interface_id; /* [i] 'S' for SCSI generic (required) */
int dxfer_direction; /* [i] 資料傳輸方向 (SG_DXFER_FROM_DEV, SG_DXFER_TO_DEV, SG_DXFER_NONE) */
unsigned char cmd_len; /* [i] SCSI 指令長度 ( <= 16 bytes) */
unsigned char mx_sb_len; /* [i] max length to write to sbp */
unsigned short iovec_count; /* [i] 0 implies no scatter gather */
unsigned int dxfer_len; /* [i] 讀取寫入資料長度 */
void * dxferp; /* [i], [*io] points to data transfer memory
or scatter gather list */
unsigned char * cmdp; /* [i], [*i] points to command to perform */
unsigned char * sbp; /* [i], [*o] points to sense_buffer memory */
unsigned int timeout; /* [i] MAX_UINT->no timeout (unit: millisec) */
unsigned int flags; /* [i] 0 -> default, see SG_FLAG... */
int pack_id; /* [i->o] unused internally (normally) */
void * usr_ptr; /* [i->o] unused internally */
unsigned char status; /* [o] scsi status */
unsigned char masked_status;/* [o] shifted, masked scsi status */
unsigned char msg_status; /* [o] messaging level data (optional) */
unsigned char sb_len_wr; /* [o] byte count actually written to sbp */
unsigned short host_status; /* [o] errors from host adapter */
unsigned short driver_status;/* [o] errors from software driver */
int resid; /* [o] dxfer_len - actual_transferred */
unsigned int duration; /* [o] time taken by cmd (unit: millisec) */
unsigned int info; /* [o] auxiliary information */
} sg_io_hdr_t; /* 64 bytes long (on i386) */

PS. http://tldp.org/HOWTO/SCSI-Generic-HOWTO/index.html 有詳細介紹

4. 需要注意裝置被掛載的位置。我的usb讀卡機裝置利用generic driver的話,是被掛載於/dev/scsi/host0/bus0/target0/lun0/generic。
一般則是會在 /dev/sg0 or /dev/sg1。

5. 範例程式 :實做了 inquiry (0x12) and read10 (0x28) command.


#include
#include
#include
#include
#include
#include
#include /* take care: fetches glibc's /usr/include/scsi/sg.h */

/* This is a simple program executing a SCSI INQUIRY command using the
sg_io_hdr interface of the SCSI generic (sg) driver.

* Copyright (C) 2001 D. Gilbert
* This program is free software. Version 1.01 (20020226)
*/

#define INQ_REPLY_LEN 96
#define INQ_CMD_CODE 0x12
#define INQ_CMD_LEN 6

#define RD_CMD_LEN 10
#define RD_CMD_CODE 0x28
#define RD_LEN 512

int main(int argc, char * argv[])
{
int sg_fd, k;
int readcmd = 0;
int rlen = 512;
unsigned char inqCmdBlk[INQ_CMD_LEN] =
{INQ_CMD_CODE, 0, 0, 0, INQ_REPLY_LEN, 0};
unsigned char rdCmdBlk[RD_CMD_LEN];


/* This is a "standard" SCSI INQUIRY command. It is standard because the
* CMDDT and EVPD bits (in the second byte) are zero. All SCSI targets
* should respond promptly to a standard INQUIRY */
unsigned char inqBuff[INQ_REPLY_LEN];
unsigned char sense_buffer[32];

unsigned char rdBuff[RD_LEN];

sg_io_hdr_t io_hdr;

if (2 > argc) {
printf("Usage: 'sg_simple0 '\n");
return 1;
}

if (argc == 3) {
if (strcmp(argv[2],"r")==0) readcmd = 1;
}

if ((sg_fd = open(argv[1], O_RDONLY)) < 0) {
/* Note that most SCSI commands require the O_RDWR flag to be set */
perror("error opening given file name");
return 1;
}
/* It is prudent to check we have a sg device by trying an ioctl */
if ((ioctl(sg_fd, SG_GET_VERSION_NUM, &k) < 0) || (k < 30000)) {
printf("%s is not an sg device, or old sg driver\n", argv[1]);
return 1;
}

if (readcmd) {
memset(rdCmdBlk,0,sizeof(rdCmdBlk));
rdCmdBlk[0] = RD_CMD_CODE;
rdCmdBlk[8] = 1;

memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
io_hdr.interface_id = 'S';
io_hdr.cmd_len = sizeof(rdCmdBlk);
/* io_hdr.iovec_count = 0; */ /* memset takes care of this */
io_hdr.mx_sb_len = sizeof(sense_buffer);
io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
io_hdr.dxfer_len = RD_LEN;
io_hdr.dxferp = rdBuff;
io_hdr.cmdp = rdCmdBlk;
io_hdr.sbp = sense_buffer;
io_hdr.timeout = 20000; /* 20000 millisecs == 20 seconds */
/* io_hdr.flags = 0; */ /* take defaults: indirect IO, etc */
/* io_hdr.pack_id = 0; */
/* io_hdr.usr_ptr = NULL; */
} else {
/* Prepare INQUIRY command */
memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
io_hdr.interface_id = 'S';
io_hdr.cmd_len = sizeof(inqCmdBlk);
/* io_hdr.iovec_count = 0; */ /* memset takes care of this */
io_hdr.mx_sb_len = sizeof(sense_buffer);
io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
io_hdr.dxfer_len = INQ_REPLY_LEN;
io_hdr.dxferp = inqBuff;
io_hdr.cmdp = inqCmdBlk;
io_hdr.sbp = sense_buffer;
io_hdr.timeout = 20000; /* 20000 millisecs == 20 seconds */
/* io_hdr.flags = 0; */ /* take defaults: indirect IO, etc */
/* io_hdr.pack_id = 0; */
/* io_hdr.usr_ptr = NULL; */
}

if (ioctl(sg_fd, SG_IO, &io_hdr) < 0) {
perror("sg_simple0: Inquiry SG_IO ioctl error");
return 1;
}

/* now for the error processing */
if ((io_hdr.info & SG_INFO_OK_MASK) != SG_INFO_OK) {
if (io_hdr.sb_len_wr > 0) {
printf("INQUIRY sense data: ");
for (k = 0; k < io_hdr.sb_len_wr; ++k) {
if ((k > 0) && (0 == (k % 10)))
printf("\n ");
printf("0x%02x ", sense_buffer[k]);
}
printf("\n");
}
if (io_hdr.masked_status)
printf("INQUIRY SCSI status=0x%x\n", io_hdr.status);
if (io_hdr.host_status)
printf("INQUIRY host_status=0x%x\n", io_hdr.host_status);
if (io_hdr.driver_status)
printf("INQUIRY driver_status=0x%x\n", io_hdr.driver_status);
}
else { /* assume INQUIRY response is present */
if (readcmd) {
char *p = (char *)rdBuff;
printf("read buffer content:\n");
printf("byte 511: %x, byte 512: %x\n",*(p+510),*(p+511));
}else {
char * p = (char *)inqBuff;
printf("Some of the INQUIRY command's response:\n");
printf(" %.8s %.16s %.4s\n", p + 8, p + 16, p + 32);
printf("INQUIRY duration=%u millisecs, resid=%d\n",
io_hdr.duration, io_hdr.resid);
}
}
close(sg_fd);
return 0;
}

69 Comments:

  • 请问SG和SD设备在使用上有什么不同呢

    By Anonymous 匿名, at 8:01 上午  

  • [B]NZBsRus.com[/B]
    Skip Sluggish Downloads With NZB Files You Can Rapidly Find Movies, Console Games, MP3s, Software and Download Them @ Alarming Rates

    [URL=http://www.nzbsrus.com][B]NZB Search[/B][/URL]

    By Anonymous 匿名, at 9:30 下午  

  • It isn't hard at all to start making money online in the undercover world of [URL=http://www.www.blackhatmoneymaker.com]blackhat money[/URL], Don’t feel silly if you haven’t heard of it before. Blackhat marketing uses alternative or misunderstood methods to generate an income online.

    By Anonymous 匿名, at 1:02 上午  

  • Hi,

    I am regular visitor of this website[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url]You have really contiributed very good info here macrossvin.blogspot.com. Do you pay attention towards your health?. In plain english I must warn you that, you are not serious about your health. Research indicates that almost 80% of all United States adults are either fat or overweight[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url] Therefore if you're one of these citizens, you're not alone. In fact, most of us need to lose a few pounds once in a while to get sexy and perfect six pack abs. Now the question is how you are planning to have quick weight loss? [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss[/url] is really not as tough as you think. Some improvement in of daily activity can help us in losing weight quickly.

    About me: I am writer of [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss tips[/url]. I am also health expert who can help you lose weight quickly. If you do not want to go under hard training program than you may also try [url=http://www.weightrapidloss.com/acai-berry-for-quick-weight-loss]Acai Berry[/url] or [url=http://www.weightrapidloss.com/colon-cleanse-for-weight-loss]Colon Cleansing[/url] for effective weight loss.

    By Anonymous 匿名, at 9:29 下午  

  • buy viagra now viagra xkcd - buy viagra turkey

    By Anonymous 匿名, at 5:52 下午  

  • http://ariaskinandbody.com/node/43529

    By Anonymous 匿名, at 4:01 上午  

  • buy viagra generic viagra walmart - generic viagra online us no prescription

    By Anonymous 匿名, at 12:41 上午  

  • generic viagra purchase viagra melbourne - buy viagra online get prescription

    By Anonymous 匿名, at 12:52 下午  

  • order viagra generic viagra patent - buy viagra online in nz

    By Anonymous 匿名, at 4:41 下午  

  • viagra pills generic viagra shipped to us - order viagra no prescription

    By Anonymous 匿名, at 11:59 上午  

  • buy soma online buy soma hair care - soma 12 panel drug screen

    By Anonymous 匿名, at 4:36 上午  

  • [url=http://loveepicentre.com/][img]http://loveepicentre.com/uploades/photos/4.jpg[/img][/url]
    professional dating service [url=http://loveepicentre.com/advice.php]pictures of teenagers dating[/url] dating chat website free
    dating atchison kansas [url=http://loveepicentre.com/articles.php]dating a younger woman[/url] big and beautiful dating service
    younger men older woman dating [url=http://loveepicentre.com/]dating a divorced dads[/url] whos dating who matt bomer

    By Anonymous 匿名, at 3:27 下午  

  • top [url=http://www.xgambling.org/]free casino games[/url] coincide the latest [url=http://www.realcazinoz.com/]casino bonus[/url] unshackled no consign hand-out at the leading [url=http://www.baywatchcasino.com/]baywatchcasino.com
    [/url].

    By Anonymous 匿名, at 8:54 下午  

  • buy soma online soma bras usa - soma drug classification

    By Anonymous 匿名, at 3:00 上午  

  • buy cialis online cheap cialis lilly - cialis 36 hour price

    By Anonymous 匿名, at 12:28 下午  

  • xanax online are yellow 2mg xanax time released - generic xanax ingredients

    By Anonymous 匿名, at 9:40 下午  

  • buy tramadol online tramadol for dogs post surgery - can overdose tramadol kill you

    By Anonymous 匿名, at 8:55 上午  

  • xanax online xanax withdrawal 1 mg daily - xanax bars vs xanax

    By Anonymous 匿名, at 9:06 上午  

  • buy tramadol online buy tramadol online no prescription cod - tramadol hcl user reviews

    By Anonymous 匿名, at 3:14 下午  

  • generic xanax xanax online eu - xanax yellow side effects

    By Anonymous 匿名, at 9:30 上午  

  • buy tramadol online how to order tramadol online no prescription - buy tramadol for dogs

    By Anonymous 匿名, at 2:47 上午  

  • buy tramadol online overdose of tramadol hydrochloride - overdose amount for tramadol

    By Anonymous 匿名, at 6:37 下午  

  • xanax antidepressant xanax 2 mg street price - xanax for anxiety side effects

    By Anonymous 匿名, at 9:56 上午  

  • buy tramadol online tramadol withdrawal management - do people buy tramadol

    By Anonymous 匿名, at 10:07 上午  

  • buy carisoprodol generic name of carisoprodol - how to buy carisoprodol

    By Anonymous 匿名, at 10:38 下午  

  • [url=http://www.realcazinoz.com]casino[/url], also known as accepted casinos or Internet casinos, are online versions of great ("buddy and mortar") casinos. Online casinos plump excepting gamblers to filch up and wager on casino games from the poop about with the Internet.
    Online casinos superficially consign on the supermarket odds and payback percentages that are comparable to land-based casinos. Some online casinos entitle higher payback percentages payment glumness automobile games, and some report payout congruity audits on their websites. Assuming that the online casino is using an fittingly programmed indefinitely additionally a recap up generator, lift games like blackjack solicitation next to understanding of an established heritage edge. The payout sculpt up inclusive of without contemplating these games are established prior the rules of the game.
    Multitudinous online casinos sublease or prejudice their software from companies like Microgaming, Realtime Gaming, Playtech, Cosmopolitan Standing Technology and CryptoLogic Inc.

    By Anonymous 匿名, at 7:25 下午  

  • carisoprodol 350 mg carisoprodol soma sun - carisoprodol 350 mg oral tablet

    By Anonymous 匿名, at 9:26 下午  

  • buy tramadol online tramadol hcl addiction - tramadol 50mg strong

    By Anonymous 匿名, at 10:51 下午  

  • buy tramadol online tramadol order online overnight - taking tramadol high blood pressure

    By Anonymous 匿名, at 6:49 上午  

  • xanax online xanax dot drug screen' - does generic xanax look like

    By Anonymous 匿名, at 6:22 下午  

  • order cialis online canada buy cialis in vancouver bc - cialis what does it do

    By Anonymous 匿名, at 3:37 下午  

  • cialis online canada cialis daily buy online - cialis libido

    By Anonymous 匿名, at 8:57 下午  

  • xanax online xanax and alcohol yahoo answers - xanax 1 mg mylan

    By Anonymous 匿名, at 9:25 下午  

  • cialis online buy cialis daily online - cialis daily erfahrungen

    By Anonymous 匿名, at 7:35 下午  

  • buy tramadol no rx buy tramadol online missouri - tramadol 50mg kapslar

    By Anonymous 匿名, at 1:49 上午  

  • http://landvoicelearning.com/#97734 what is tramadol ultram 50 mg - tramadol 50 mg buy online

    By Anonymous 匿名, at 2:58 下午  

  • buy tramadol can dog overdose tramadol - buy tramadol overnight no prescription

    By Anonymous 匿名, at 8:12 下午  

  • buy tramadol online tramadol 50mg n024 - tramadol dosage

    By Anonymous 匿名, at 4:08 上午  

  • http://landvoicelearning.com/#21906 pet meds tramadol 50mg - can you legally buy tramadol

    By Anonymous 匿名, at 8:41 上午  

  • http://buytramadolonlinecool.com/#59473 tramadol ultram hcl - tramadol for sale no prescription usa

    By Anonymous 匿名, at 8:44 下午  

  • http://landvoicelearning.com/#38471 tramadol high booze - tramadol dosage kids

    By Anonymous 匿名, at 11:41 下午  

  • klonopin drug buy klonopin online cheap - klonopin much get high

    By Anonymous 匿名, at 10:45 上午  

  • buy tramadol online tramadol ingredients - tramadol hcl solubility

    By Anonymous 匿名, at 3:26 下午  

  • http://blog.dawn.com/dblog/buy/#85714 tramadol 325 mg high - buy tramadol 200mg online

    By Anonymous 匿名, at 10:18 下午  

  • http://buytramadolonlinecool.com/#28875 tramadol for dogs contraindications - tramadol 50 mg take

    By Anonymous 匿名, at 7:02 上午  

  • tramadol overnight shipping tramadol for depression - what dosage of tramadol should i take

    By Anonymous 匿名, at 9:46 上午  

  • buy tramadol online buy tramadol online without prescriptions - tramadol withdrawal hydrocodone

    By Anonymous 匿名, at 8:51 下午  

  • http://buytramadolonlinecool.com/#30694 buy tramadol cod shipping - tramadol online

    By Anonymous 匿名, at 4:18 上午  

  • learn how to buy tramdadol buy tramadol overnight with mastercard - tramadol 50mg vs tylenol 3

    By Anonymous 匿名, at 2:44 下午  

  • buy klonopin online side effects for klonopin medication - klonopin roche

    By Anonymous 匿名, at 5:41 下午  

  • buy tramadol does tramadol hcl 50 mg contain acetaminophen - 200 mg tramadol high

    By Anonymous 匿名, at 1:06 上午  

  • carisoprodol drug buy cheap carisoprodol online - carisoprodol 350 mg oral tablet

    By Anonymous 匿名, at 9:08 上午  

  • buy tramadol online tramadol hcl urine drug test - tramadol 50mg for dogs safe for humans

    By Anonymous 匿名, at 6:35 下午  

  • carisoprodol 350 mg buy carisoprodol 350mg - carisoprodol 350 mg withdrawal

    By Anonymous 匿名, at 2:10 上午  

  • http://southcarolinaaccidentattorney.com/#51643 muscle relaxant soma carisoprodol - carisoprodol 350 mg review

    By Anonymous 匿名, at 5:17 下午  

  • irrammems xaikalitag SeimiLeva [url=http://uillumaror.com]iziananatt[/url] jeveneraniled http://gusannghor.com SleeneLen

    By Anonymous 匿名, at 2:47 上午  

  • Your own ρost fеatures ρгoven
    hеlpful to me. It’s reallу educаtional and you're naturally extremely educated in this region. You possess opened up my sight for you to varying opinion of this particular subject matter using intriquing, notable and sound content material.
    Here is my web page ... buy viagra online

    By Anonymous 匿名, at 5:42 上午  

  • Yоur own reρoгt featurеs verіfied helpful to us.
    It’ѕ quitе informаtive and уou're simply naturally very experienced in this region. You get popped my personal eyes in order to different views on this kind of matter with intriguing and solid articles.
    Check out my web-site - Xanax

    By Anonymous 匿名, at 10:55 上午  

  • Your article hаs prοven necessarу to me personally.
    It’s eхtremely helpful and you aгe obviouslу extremely knowledgeable of this type.
    Yоu havе got exposed my peгsonal sight in ordеr to different opinion οf this ѕubject mattег
    tοgether ωith intгiquіng, notаble anԁ strong content materiаl.


    Ηеre is mу blog poѕt bellhs.net
    Also see my website - viagra

    By Anonymous 匿名, at 2:47 上午  

  • Your write-up provіdes confirmed useful to us.
    ӏt’s quite educational and уou
    really аre natuгally quіte educateԁ
    in thiѕ field. Үou posseѕs openeԁ
    our eyes to be able tо numerouѕ opinion of thіs specifіc toріc with interеsting and reliable cоntent.


    Feel free to visit my weblog meridia online
    Here is my web page :: meridia online

    By Anonymous 匿名, at 3:39 下午  

  • Your current post offerѕ confirmeԁ helpful
    tο me personally. It’s quite helpful and you гeally are cеrtainly quite experienceԁ in this area.
    You get еxposed my oωn eye to bе able to
    vаrious opіnion of this spеcific toρіc using intrіguing and sound wгittеn content.
    Here is my site buy Xenical

    By Anonymous 匿名, at 11:36 上午  

  • Your ωritе-uρ has νerified necеѕѕaгy to
    me personally. Іt’ѕ quite eduсаtіοnal аnd you're simply certainly really well-informed in this region. You get popped our eyes for you to varying views on this kind of subject matter together with interesting and sound articles.

    Also visit my web blog buy viagra

    By Anonymous 匿名, at 9:43 上午  

  • Υour post pгovides eѕtablished nеceѕsary to mуself.
    Ιt’s quite useful аnd yοu're simply naturally really well-informed in this region. You possess opened up our sight to be able to varying opinion of this particular subject with intriguing and strong articles.

    My homepage; www.dlresearch.cn

    By Anonymous 匿名, at 11:53 下午  

  • Your own article offers established beneficіal to
    mе. It’s гeally useful and you're simply naturally very well-informed in this field. You possess popped my sight to various thoughts about this kind of topic with intriquing, notable and solid content.

    Also visit my webpage :: phentermine

    By Anonymous 匿名, at 5:34 下午  

  • Thе post has prοven benеfіciаl
    tо me. It’s eхtremely informative аnd you геally aгe cleаrly reаlly eduсаteԁ in thіs area.
    You possess poρped mу personаl eyеs in ordeг to variouѕ thoughts about this pаrtiсulaг ѕubjеct
    matter аlong with intrіquing, notable and strong content mateгial.


    Feel fгee to suгf to my webpage buy Klonopin

    By Anonymous 匿名, at 5:13 下午  

  • Your post provides ѵerifіed useful to me. It’s really educatіonal and you
    really are obviously really knowledgeable of this type.
    Yοu possеss opened up my personal
    eуeѕ to dіffeгent views on this paгticular subјect togethеr with intriguing,
    notаble and sоlid written contеnt.

    My websіtе ambien

    By Anonymous 匿名, at 2:39 下午  

  • Nice post. I learn something new and challenging on blogs I stumbleupon on a daily basis.
    It will always be exciting to read articles from other writers and practice something from their sites.


    my site abdominal fat loss

    By Anonymous 匿名, at 5:53 下午  

  • My brother suggested I may like this web site. He was once entirely right.

    This put up truly made my day. You cann't imagine just how so much time I had spent for this info! Thanks!

    Also visit my site http://www.sbwire.com/press-releases/somanabolic-muscle-maximizer-review-important-information-factors-in-nutrition-to-build-lean-muscles-247681.htm ()

    By Anonymous 匿名, at 10:26 下午  

  • покер стратеги еще игровые автоматы бесплатно играть бесплатно обезьяна [url=http://xxx.kazino-del-rio.ru/infa585.html]Клубничка Казино[/url] игровые аппараты mega jack.

    By Anonymous 匿名, at 12:04 下午  

張貼留言

<< Home