aboutsummaryrefslogtreecommitdiff
path: root/src/sg_stpg.c
blob: e91b49920d3780a72e9fad7b051aefd027e6a7f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/*
 * Copyright (c) 2004-2007 Hannes Reinecke, Christophe Varoqui and Douglas Gilbert.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>

#include "sg_lib.h"
#include "sg_cmds_basic.h"
#include "sg_cmds_extra.h"

/* A utility program for the Linux OS SCSI subsystem.
 *
 *
 * This program issues the SCSI command SET TARGET PORT GROUPS
 * to the given SCSI device.
 */

static char * version_str = "1.2 20070925";

#define TGT_GRP_BUFF_LEN 1024
#define MX_ALLOC_LEN (0xc000 + 0x80)

#define TPGS_STATE_OPTIMIZED 0x0
#define TPGS_STATE_NONOPTIMIZED 0x1
#define TPGS_STATE_STANDBY 0x2
#define TPGS_STATE_UNAVAILABLE 0x3
#define TPGS_STATE_OFFLINE 0xe          /* SPC-4 rev 9 */
#define TPGS_STATE_TRANSITIONING 0xf

#define VPD_DEVICE_ID  0x83
#define DEF_VPD_DEVICE_ID_LEN  252

#define MAX_PORT_LIST_ARR_LEN 16

struct tgtgrp {
        int id;
        int current;
        int valid;
};

static struct option long_options[] = {
        {"active", 0, 0, 'a'},
        {"help", 0, 0, 'h'},
        {"hex", 0, 0, 'H'},
        {"offline", 0, 0, 'l'},
        {"optimized", 0, 0, 'o'},
        {"raw", 0, 0, 'r'},
        {"standby", 0, 0, 's'},
        {"state", required_argument, 0, 'S'},
        {"tp", required_argument, 0, 't'},
        {"unavailable", 0, 0, 'u'},
        {"verbose", 0, 0, 'v'},
        {"version", 0, 0, 'V'},
        {0, 0, 0, 0},
};

static void
usage()
{
    fprintf(stderr, "Usage: "
          "sg_stpg   [--active] [--help] [--hex] [--offline] [--optimized] "
          "[--raw]\n"
          "                 [--standby] [--state=S,S...] [--tp=P,P...] "
          "[--unavailable]\n"
          "                 [--verbose] [--version] DEVICE\n"
          "  where:\n"
          "    --active|-a        set asymm. access state to "
          "active/non-optimized\n"
          "    --help|-h          print out usage message\n"
          "    --hex|-H           print out report response in hex, then "
          "exit\n"
          "    --offline|-l       set asymm. access state to offline, takes "
	  "relative\n"
	  "                       target port id, rather than target port "
	  "group id\n"
          "    --optimized|-o     set asymm. access state to "
          "active/optimized\n"
          "    --raw|-r           output report response in binary to "
          "stdout, then exit\n"
          "    --standby|-s       set asymm. access state to standby\n"
          "    --state=S,S.. |-S S,S...     list of states (values or "
          "acronyms)\n"
          "    --tp=P,P.. |-t P,P...     list of target port group or "
          "relative\n"
          "                              identifiers\n"
          "    --unavailable|-u   set asymm. access state to unavailable\n"
          "    --verbose|-v       increase verbosity\n"
          "    --version|-V       print version string and exit\n\n"
          "Performs a SCSI SET TARGET PORT GROUPS command\n"
          );

}

static void
dStrRaw(const char* str, int len)
{
    int k;

    for (k = 0 ; k < len; ++k)
        printf("%c", str[k]);
}

static int
decode_target_port(unsigned char * buff, int len, int *d_id, int *d_tpg)
{
    int c_set, piv, assoc, desig_type, i_len;
    int off, u;
    const unsigned char * ucp;
    const unsigned char * ip;

    *d_id = -1;
    *d_tpg = -1;
    off = -1;
    while ((u = sg_vpd_dev_id_iter(buff, len, &off, -1, -1, -1)) == 0) {
        ucp = buff + off;
        i_len = ucp[3];
        if ((off + i_len + 4) > len) {
            fprintf(stderr, "    VPD page error: designator length longer "
                    "than\n     remaining response length=%d\n", (len - off));
            return SG_LIB_CAT_MALFORMED;
        }
        ip = ucp + 4;
        c_set = (ucp[0] & 0xf);
        piv = ((ucp[1] & 0x80) ? 1 : 0);
        assoc = ((ucp[1] >> 4) & 0x3);
        desig_type = (ucp[1] & 0xf);
        switch (desig_type) {
        case 4: /* Relative target port */
            if ((1 != c_set) || (1 != assoc) || (4 != i_len)) {
                fprintf(stderr, "      << expected binary code_set, target "
                        "port association, length 4>>\n");
                dStrHex((const char *)ip, i_len, 0);
                break;
            }
            *d_id = ((ip[2] << 8) | ip[3]);
            break;
        case 5: /* (primary) Target port group */
            if ((1 != c_set) || (1 != assoc) || (4 != i_len)) {
                fprintf(stderr, "      << expected binary code_set, target "
                        "port association, length 4>>\n");
                dStrHex((const char *)ip, i_len, 0);
                break;
            }
            *d_tpg = ((ip[2] << 8) | ip[3]);
            break;
        default:
            break;
        }
    }
    if (-1 == *d_id || -1 == *d_tpg) {
        fprintf(stderr, "VPD page error: no target port group information\n");
        return SG_LIB_CAT_MALFORMED;
    }
    return 0;
}

static void
decode_tpgs_state(const int st)
{
    switch (st) {
    case TPGS_STATE_OPTIMIZED:
        printf(" (active/optimized)");
        break;
    case TPGS_STATE_NONOPTIMIZED:
        printf(" (active/non optimized)");
        break;
    case TPGS_STATE_STANDBY:
        printf(" (standby)");
        break;
    case TPGS_STATE_UNAVAILABLE:
        printf(" (unavailable)");
        break;
    case TPGS_STATE_OFFLINE:
        printf(" (offline)");
        break;
    case TPGS_STATE_TRANSITIONING:
        printf(" (transitioning between states)");
        break;
    default:
        printf(" (unknown: 0x%x)", st);
        break;
    }
}

static int
transition_tpgs_states(struct tgtgrp *tgtState, int numgrp, int portgroup,
                       int newstate)
{
     int i,oldstate;

     for ( i = 0; i < numgrp; i++) {
          if (tgtState[i].id == portgroup)
               break;
     }
     if (i == numgrp) {
          printf("Portgroup 0x%02x does not exist\n", portgroup);
          return 1;
     }

     if (!( (1 << newstate) & tgtState[i].valid )) {
          printf("Portgroup 0x%02x: Invalid state 0x%x\n",
                 portgroup, newstate);
          return 1;
     }
     oldstate = tgtState[i].current;
     tgtState[i].current = newstate;
     if (newstate == TPGS_STATE_OPTIMIZED) {
          /* Switch with current optimized path */
          for ( i = 0; i < numgrp; i++) {
               if (tgtState[i].id == portgroup)
                    continue;
               if (tgtState[i].current == TPGS_STATE_OPTIMIZED)
                    tgtState[i].current = oldstate;
          }
     } else if (oldstate == TPGS_STATE_OPTIMIZED) {
          /* Enable next path group */
          for ( i = 0; i < numgrp; i++) {
               if (tgtState[i].id == portgroup)
                    continue;
               if (tgtState[i].current == TPGS_STATE_NONOPTIMIZED) {
                    tgtState[i].current = TPGS_STATE_OPTIMIZED;
                    break;
               }
          }
     }
     printf("New target port groups:\n");
     for (i = 0; i < numgrp; i++) {
            printf("  target port group id : 0x%x\n",
                   tgtState[i].id);
            printf("    target port group asymmetric access state : ");
            printf("0x%02x\n", tgtState[i].current);
     }
     return 0;
}

static void
encode_tpgs_states(unsigned char *buff, struct tgtgrp *tgtState, int numgrp)
{
     int i;
     unsigned char *desc;

     for (i = 0, desc = buff + 4; i < numgrp; desc += 4, i++) {
          desc[0] = tgtState[i].current & 0x0f;
          desc[2] = (tgtState[i].id >> 8) & 0x0f;
          desc[3] = tgtState[i].id & 0x0f;
     }
} 

int
main(int argc, char * argv[])
{
    int sg_fd, k, off, res, c, report_len, tgt_port_count, trunc;
    unsigned char reportTgtGrpBuff[TGT_GRP_BUFF_LEN];
    unsigned char setTgtGrpBuff[TGT_GRP_BUFF_LEN];
    unsigned char rsp_buff[MX_ALLOC_LEN + 2];
    unsigned char * ucp;
    struct tgtgrp tgtGrpState[256], *tgtStatePtr;
    int state = -1;
    const char * state_arg = NULL;
    const char * tp_arg = NULL;
    int hex = 0;
    int raw = 0;
    int verbose = 0;
    int port_arr[MAX_PORT_LIST_ARR_LEN];
    int port_arr_len = 0;
    int state_arr[MAX_PORT_LIST_ARR_LEN];
    int state_arr_len = 0;
    int portgroup = -1;
    int relport = -1;
    int numgrp = 0;
    const char * device_name = NULL;
    int ret = 0;

    while (1) {
        int option_index = 0;

        c = getopt_long(argc, argv, "ahHloOrsS:t:uvV", long_options,
                        &option_index);
        if (c == -1)
            break;

        switch (c) {
        case 'a':
            state = TPGS_STATE_NONOPTIMIZED;
            break;
        case 'h':
        case '?':
            usage();
            return 0;
        case 'H':
            hex = 1;
            break;
        case 'l':
        case 'O':
            state = TPGS_STATE_OFFLINE;
            break;
        case 'o':
            state = TPGS_STATE_OPTIMIZED;
            break;
        case 'r':
            raw = 1;
            break;
        case 's':
            state = TPGS_STATE_STANDBY;
            break;
        case 'S':
            state_arg = optarg;
            break;
        case 't':
            tp_arg = optarg;
            break;
        case 'u':
            state = TPGS_STATE_UNAVAILABLE;
            break;
        case 'v':
            ++verbose;
            break;
        case 'V':
            fprintf(stderr, "Version: %s\n", version_str);
            return 0;
        default:
            fprintf(stderr, "unrecognised option code 0x%x ??\n", c);
            usage();
            return SG_LIB_SYNTAX_ERROR;
        }
    }
    if (optind < argc) {
        if (NULL == device_name) {
            device_name = argv[optind];
            ++optind;
        }
        if (optind < argc) {
            for (; optind < argc; ++optind)
                fprintf(stderr, "Unexpected extra argument: %s\n",
                        argv[optind]);
            usage();
            return SG_LIB_SYNTAX_ERROR;
        }
    }

    if (NULL == device_name) {
        fprintf(stderr, "missing device name!\n");
        usage();
        return SG_LIB_SYNTAX_ERROR;
    }
    sg_fd = sg_cmds_open_device(device_name, 0 /* rw */, verbose);
    if (sg_fd < 0) {
        fprintf(stderr, "open error: %s: %s\n", device_name,
                safe_strerror(-sg_fd));
        return SG_LIB_FILE_ERROR;
    }

    res = sg_ll_inquiry(sg_fd, 0, 1, VPD_DEVICE_ID, rsp_buff,
                        DEF_VPD_DEVICE_ID_LEN, 1, verbose);
    if (0 == res) {
        report_len = ((rsp_buff[2] << 8) + rsp_buff[3]) + 4;
        if (VPD_DEVICE_ID != rsp_buff[1]) {
            fprintf(stderr, "invalid VPD response; probably a STANDARD "
                    "INQUIRY response\n");
            if (verbose) {
                fprintf(stderr, "First 32 bytes of bad response\n");
                dStrHex((const char *)rsp_buff, 32, 0);
            }
            return SG_LIB_CAT_MALFORMED;
        }
        if (report_len > MX_ALLOC_LEN) {
            fprintf(stderr, "response length too long: %d > %d\n", report_len,
                    MX_ALLOC_LEN);
            return SG_LIB_CAT_MALFORMED;
        } else if (report_len > DEF_VPD_DEVICE_ID_LEN) {
            if (sg_ll_inquiry(sg_fd, 0, 1, VPD_DEVICE_ID, rsp_buff,
                              report_len, 1, verbose))
                return SG_LIB_CAT_OTHER;
        }
        decode_target_port(rsp_buff + 4, report_len - 4, &relport, &portgroup);
        printf("Device is at port Group 0x%02x, relative port 0x%02x\n",
               portgroup, relport);
    }

    memset(reportTgtGrpBuff, 0x0, sizeof(reportTgtGrpBuff));
    trunc = 0;

    res = sg_ll_report_tgt_prt_grp(sg_fd, reportTgtGrpBuff,
                            sizeof(reportTgtGrpBuff), 1, verbose);
    ret = res;
    if (0 == res) {
        report_len = (reportTgtGrpBuff[0] << 24) +
                     (reportTgtGrpBuff[1] << 16) + 
                     (reportTgtGrpBuff[2] << 8) +
                     reportTgtGrpBuff[3] + 4;
        if (report_len > (int)sizeof(reportTgtGrpBuff)) {
            trunc = 1;
            fprintf(stderr, "  <<report too long for internal buffer,"
                    " output truncated\n");
            report_len = (int)sizeof(reportTgtGrpBuff);
        }
        if (raw) {
            dStrRaw((const char *)reportTgtGrpBuff, report_len);
            goto err_out;
        }
        if (verbose)
            printf("Report list length = %d\n", report_len);
        if (hex) {
            if (verbose)
                fprintf(stderr, "\nOutput response in hex:\n");
            dStrHex((const char *)reportTgtGrpBuff, report_len, 1);
            goto err_out;
        }
        memset(tgtGrpState, 0, sizeof(struct tgtgrp) * 256);
        tgtStatePtr = tgtGrpState;
        printf("Current target port groups:\n");
        for (k = 4, ucp = reportTgtGrpBuff + 4, numgrp = 0; k < report_len;
             k += off, ucp += off, numgrp ++) {

            printf("  target port group id : 0x%x , Pref=%d\n",
                   (ucp[2] << 8) + ucp[3], !!(ucp[0] & 0x80));
            printf("    target port group asymmetric access state : ");
            printf("0x%02x", ucp[0] & 0x0f);
            printf("\n");
            tgtStatePtr->id = (ucp[2] << 8) + ucp[3];
            tgtStatePtr->current = ucp[0] & 0x0f;
            tgtStatePtr->valid = ucp[1];
            
            tgt_port_count = ucp[7];

            tgtStatePtr++;
            off = 8 + tgt_port_count * 4;
        }
    } else if (SG_LIB_CAT_INVALID_OP == res)
        fprintf(stderr, "Report Target Port Groups command not supported\n");
    else if (SG_LIB_CAT_ILLEGAL_REQ == res)
        fprintf(stderr, "bad field in Report Target Port Groups cdb "
                "including unsupported service action\n");
    else if (SG_LIB_CAT_UNIT_ATTENTION == res)
        fprintf(stderr, "Report Target Port Groups, unit attention\n");
    else if (SG_LIB_CAT_ABORTED_COMMAND == res)
        fprintf(stderr, "Report Target Port Groups, aborted command\n");
    else {
        fprintf(stderr, "Report Target Port Groups command failed\n");
        if (0 == verbose)
            fprintf(stderr, "    try '-v' for more information\n");
    }
    if (0 != res)
         goto err_out;

    printf("Port group 0x%02x: Set asymmetric access state to", portgroup);
    decode_tpgs_state(state);
    printf("\n");

    transition_tpgs_states(tgtGrpState, numgrp, portgroup, state);

    memset(setTgtGrpBuff, 0x0, sizeof(setTgtGrpBuff));
    trunc = 0;

    encode_tpgs_states(setTgtGrpBuff, tgtGrpState, numgrp);
    report_len = numgrp * 4 + 4;

    res = sg_ll_set_tgt_prt_grp(sg_fd, setTgtGrpBuff, report_len, 1, verbose);

    if (0 == res)
        goto err_out;
    else if (SG_LIB_CAT_INVALID_OP == res)
        fprintf(stderr, "Set Target Port Groups command not supported\n");
    else if (SG_LIB_CAT_ILLEGAL_REQ == res)
        fprintf(stderr, "bad field in Report Target Port Groups cdb "
                "including unsupported service action\n");
    else if (SG_LIB_CAT_UNIT_ATTENTION == res)
        fprintf(stderr, "Set Target Port Groups, unit attention\n");
    else if (SG_LIB_CAT_ABORTED_COMMAND == res)
        fprintf(stderr, "Set Target Port Groups, aborted command\n");
    else {
        fprintf(stderr, "Set Target Port Groups command failed\n");
        if (0 == verbose)
            fprintf(stderr, "    try '-v' for more information\n");
    }

err_out:
    res = sg_cmds_close_device(sg_fd);
    if (res < 0) {
        fprintf(stderr, "close error: %s\n", safe_strerror(-res));
        if (0 == ret)
            return SG_LIB_FILE_ERROR;
    }
    return (ret >= 0) ? ret : SG_LIB_CAT_OTHER;
}