Structures.hpp 54.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
/******************************************************************************
 *
 * This file is part of the Castor project.
 * See http://castor.web.cern.ch/castor
 *
 * Copyright (C) 2003  CERN
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details. 
15
16
17
18
19
20
21
22
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * 
 *
 * @author Castor Dev team, castor-dev@cern.ch
 *****************************************************************************/
23
24
25
26

#pragma once

#include <sstream>
27
#include <iomanip>
28
#include <algorithm>
29
#include <arpa/inet.h>
30
#include <endian.h>
Eric Cano's avatar
Eric Cano committed
31
#include <string.h>
32
33
#include <scsi/sg.h>
#include <climits>
Eric Cano's avatar
Eric Cano committed
34
#include <cstdio>
35

36
#include "Constants.hpp"
37
#include "common/exception/Exception.hpp"
38

39
40
namespace castor {
namespace tape {
41
namespace SCSI {
42
  const unsigned int defaultTimeout=900000; //millisecs
43
44
45
46
47
48
49
50
51
52
53
54

  /**
   * Maximum number of tape wraps.
   *
   * This is used to determine the maximum size of the response from the REOWP command,
   * which returns 12 bytes per wrap, plus a 4-byte header.
   *
   * LTO-8 has 208 physical wraps. LTO-9 has 280 wraps. This number should be adjusted
   * upwards when the LTO-10 specification is announced.
   */
  const unsigned int maxLTOTapeWraps = 280;

55
56
57
58
59
60
61
62
  /**
   * Structures as defined in the SCSI specifications, and helper functions for them.
   * SPC-4 (SCSI primary commands) can be found at:
   * http://hackipedia.org/Hardware/SCSI/Primary%20Commands/SCSI%20Primary%20Commands%20-%204.pdf
   * 
   * and SSC-3 (SCSI stream commands, i.e. tape drives) at:
   * http://hackipedia.org/Hardware/SCSI/Stream%20Commands/SCSI%20Stream%20Commands%20-%203.pdf
   */
63
  namespace Structures {
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

    /**
     * Helper template to zero a structure. Small boilerplate reduction.
     * Should not be used with classes with virtual tables! With a zeroed
     * out virtual table pointer, this will be detected soon enough.
     * @param s pointer the struct/class.
     */
    template <typename C>
    void zeroStruct(C * s) {
      memset (s, 0, sizeof(C));
    }
    
    /**
     * Class wrapping around Linux' SG_IO struct, providing
     * zeroing and automatic filling up for the mandatory structures
     * (cdb, databuffer, sense buffer, magic 'S', and default timeout).
     * Make it look like a bare sg_io_hdr_t when using & operator.
     * Another little boilerplate killer.
     */
    class LinuxSGIO_t: public sg_io_hdr_t {
    public:
85
      LinuxSGIO_t() { zeroStruct(this); interface_id = 'S'; timeout = defaultTimeout; }
86
87
88
89
      template <typename T>
      void setCDB(T * cdb) { cmdp = (unsigned char *)cdb; cmd_len = sizeof(T); }
      
      template <typename T>
90
      void setSenseBuffer(T * senseBuff)  
91
92
      { 
        if (sizeof(T) > UCHAR_MAX)
93
          throw cta::exception::Exception("sense structure too big in LinuxSGIO_t::setSense");
94
        mx_sb_len = (unsigned char) sizeof(T);
95
96
97
98
99
        sbp = (unsigned char *)senseBuff;
      }
      
      template <typename T>
      void setDataBuffer(T * dataBuff) { dxferp = dataBuff; dxfer_len = sizeof (T); }
Cristina Moraru's avatar
Cristina Moraru committed
100
101
102
103
104
105
106
107
108
109

      // If dataBuff is a pointer to a variable length array, sizeof will return
      // the size of one element. This function allows to manually set the buffer size
      template <typename T>
      void setDataBuffer(T * dataBuff, unsigned int dataBuffSize)
      {
        dxferp = dataBuff;
        dxfer_len = dataBuffSize;
      }

110
111
      sg_io_hdr_t * operator & () { return (sg_io_hdr_t *) this; }
    };
Eric Cano's avatar
Eric Cano committed
112
    
113
114
115
116
117
118
119
120
121
122
    /**
     * Helper function to deal with endianness.
     * @param t byte array in SCSI order representing a 64 bits number
     * @return 
     */
    inline uint64_t toU64(const unsigned char(& t)[8])
    {
      /* Like network, SCSI is BigEndian */
      return (uint64_t) ntohl ( (*(uint64_t *) t << 32) >> 32)  << 32 | ntohl(*(uint64_t *) t >>32);
    }  
123
124

    /**
125
     * Helper function to deal with endianness: 6-byte version
126
127
128
129
130
131
132
133
     *
     * The REOWP SCSI command assigns 48 bits to store the LOGICAL OBJECT IDENTIFIER (although other
     * commands use 64 bits or sometimes 32 bits). This function converts the 48-bit byte array
     * into a 64-bit unsigned integer.
     *
     * @param t byte array in SCSI order representing a 48-bit number
     * @return 64-bit unsigned integer
     */
134
    inline uint64_t toU64(const unsigned char(& t)[6])
135
136
137
138
139
    {
      /* Like network, SCSI is BigEndian */
      return (uint64_t) ntohl ( (*(uint64_t *) t << 32) >> 16)  << 32 | ntohl(*(uint64_t *) t >>16);
    }

Eric Cano's avatar
Eric Cano committed
140
141
142
143
144
    /**
     * Helper function to deal with endianness.
     * @param t byte array in SCSI order representing a 32 bits number
     * @return 
     */
145
    inline uint32_t toU32(const unsigned char(& t)[4])
Eric Cano's avatar
Eric Cano committed
146
147
148
149
150
    {
      /* Like network, SCSI is BigEndian */
      return ntohl (*((uint32_t *) t));
    }

151
152
153
154
155
156
157
158
     /**
     * Helper function to deal with endianness.
     * for 3 bytes! fields in SCSI replies 
     * @param t byte array in SCSI order representing a 32 bits number
     * @return 
     */
    inline uint32_t toU32(const unsigned char(& t)[3])
    {
159
160
161
162
163
      union {
	unsigned char tmp[4];
	uint32_t val;
      } u;
      u.tmp[0]=0;u.tmp[1]=t[0];u.tmp[2]=t[1];u.tmp[3]=t[2];
164
165
      
      /* Like network, SCSI is BigEndian */
166
      return ntohl (u.val);
167
168
    }
    
169
170
171
172
173
174
175
176
177
178
179
180
     /**
     * Helper function to deal with endianness.
     * for signed values
     * @param t byte array in SCSI order representing a 32 bits number
     * @return 
     */
    inline int32_t toS32(const unsigned char(& t)[4])
    {
      /* Like network, SCSI is BigEndian */
      return (int32_t)(ntohl (*((uint32_t *) t)));
    }
    
181
    /**
182
183
184
     * Helper function to deal with endianness.
     * @param t byte array in SCSI order representing a 16 bits number
     * @return 
185
     */
186
    inline uint16_t toU16(const unsigned char(& t)[2])
187
188
    {
      /* Like network, SCSI is BigEndian */
189
      return ntohs (*((uint16_t *) t));
190
191
    }
    
Eric Cano's avatar
Eric Cano committed
192
    /**
193
     * Helper function setting in place a 32 bits SCSI number from a value
Eric Cano's avatar
Eric Cano committed
194
     * expressed in the local endianness.
195
     * @param t pointer to the char array at the 32 bits value position.
Eric Cano's avatar
Eric Cano committed
196
197
     * @param val the value.
     */
198
199
    inline void setU32(unsigned char(& t)[4], uint32_t val) {
      *((uint32_t *) t) = htonl(val);
Eric Cano's avatar
Eric Cano committed
200
201
    }
    
Eric Cano's avatar
Eric Cano committed
202
    /**
203
204
205
206
     * Helper function setting in place a 16 bits SCSI number from a value
     * expressed in the local endianness.
     * @param t pointer to the char array at the 16 bits value position.
     * @param val the value.
Eric Cano's avatar
Eric Cano committed
207
     */
208
209
    inline void setU16(unsigned char(& t)[2], uint16_t val) {
      *((uint16_t *) t) = htons(val);
Eric Cano's avatar
Eric Cano committed
210
    }
211

212
213
214
215
216
217
218
219
220
221
    /**
     * Helper function setting in place a 64 bits SCSI number from a value
     * expressed in the local endianness.
     * @param t pointer to the char array at the 64 bits value position.
     * @param val the value.
     */
    inline void setU64(unsigned char(& t)[8], uint64_t val) {
        *((uint64_t *) t) = htobe64(val);
    }
    
Eric Cano's avatar
Eric Cano committed
222
    /**
223
224
     * Inquiry CDB as described in SPC-4.
     */
225
226
    class inquiryCDB_t {
    public:
Eric Cano's avatar
Eric Cano committed
227
      inquiryCDB_t() { zeroStruct(this); opCode = SCSI::Commands::INQUIRY; }
228
229
230
231
232
233
234
      unsigned char opCode;
      
      unsigned char EVPD : 1;
      unsigned char : 7;
      
      unsigned char pageCode;
      
235
      unsigned char allocationLength[2];
236
237
      
      unsigned char control;
238
    };
239
    
Eric Cano's avatar
Eric Cano committed
240
    /**
241
242
     * Inquiry data as described in SPC-4.
     */
Eric Cano's avatar
Eric Cano committed
243
244
245
    class inquiryData_t {
    public:
      inquiryData_t () { zeroStruct(this); }
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
      unsigned char perifDevType : 5;
      unsigned char perifQualifyer : 3;

      unsigned char : 7;
      unsigned char RMB : 1;

      unsigned char version : 8;

      unsigned char respDataFmt : 4;
      unsigned char HiSup : 1;
      unsigned char normACA : 1;
      unsigned char : 2;

      unsigned char addLength : 8;

      unsigned char protect : 1;
      unsigned char : 2;
      unsigned char threePC : 1;
      unsigned char TPGS : 2;
      unsigned char ACC : 1;
      unsigned char SCCS : 1;

      unsigned char addr16 : 1;
      unsigned char : 3;
      unsigned char multiP : 1;
      unsigned char VS1 : 1;
      unsigned char encServ : 1;
      unsigned char : 1;

      unsigned char VS2 : 1;
      unsigned char cmdQue : 1;
      unsigned char : 2;
      unsigned char sync : 1;
      unsigned char wbus16 : 1;
      unsigned char : 2;

      char T10Vendor[8];
      char prodId[16];
      char prodRevLvl[4];
      char vendorSpecific1[20];

      unsigned char IUS : 1;
      unsigned char QAS : 1;
      unsigned char clocking : 2;
      unsigned char : 4;

      unsigned char reserved1;

294
      unsigned char versionDescriptor[8][2];
295
296
297

      unsigned char reserved2[22];
      unsigned char vendorSpecific2[1];
Eric Cano's avatar
Eric Cano committed
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
   
   /**
    * Oracle T10K Inquiry data
    */
    class inquiryDataT10k_t {
    public:
      inquiryDataT10k_t () { zeroStruct(this); }
      unsigned char perifDevType : 5;
      unsigned char perifQualifyer : 3;

      unsigned char : 7;
      unsigned char RMB : 1;

      unsigned char version;

      unsigned char respDataFmt : 4;
      unsigned char HiSup : 1;
      unsigned char normACA : 1;
      unsigned char RSVD1: 1;
      unsigned char AERC: 1;

      unsigned char addLength;

      unsigned char protect : 1;
      unsigned char : 2;
      unsigned char threePC : 1;
      unsigned char TPGS : 2;
      unsigned char ACC : 1;
      unsigned char SCCS : 1;

      unsigned char : 3;
      unsigned char mChngr: 1;
      unsigned char multiP : 1;
      unsigned char VS1 : 1;
      unsigned char encServ : 1;
      unsigned char bQue : 1;

      unsigned char VS2 : 1;
      unsigned char cmdQue : 1;
      unsigned char RSVD2: 1;
      unsigned char linked: 1;
      unsigned char : 3;
      unsigned char relAdr : 1;

      char vendorId[8];
      char prodId[16];
      char prodRevLvl[8];
      char vendorSpecific1[14];

      unsigned char keyMgmt;

      unsigned char CSL : 1;
      unsigned char DCMP : 1;
      unsigned char volSafe : 1;
      unsigned char libAtt : 1;
      unsigned char encr : 1;
      unsigned char : 3;

      unsigned char reserved1[2];

      unsigned char versionDescriptor[8][2];
    };
 
   /**
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
     * Inquiry unit serial number vital product data as described in SPC-4.
     */
    class inquiryUnitSerialNumberData_t {
    public:
      inquiryUnitSerialNumberData_t() { zeroStruct(this); }
      // byte 0
      unsigned char peripheralDeviceType: 5; // (000b) connected to this LUN
      unsigned char peripheralQualifier : 3; // (01h) tape drive  
      
      // byte 1
      unsigned char pageCode;                // (80h) Vital Product Data page for serial
      
      // byte 2
      unsigned char :8;                      // Reserved
      
      // byte 3
      unsigned char pageLength;              // n-3
      
      // bytes 4-n
      char productSerialNumber[12];          // 12 bytes for T10000&IBM, 10 for LTO
    };
    
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
     * LOCATE(10) CDB as described in SSC-3.
     */
    class locate10CDB_t {
    public:
      locate10CDB_t() {
        zeroStruct(this);
        opCode = SCSI::Commands::LOCATE_10; 
      }
      // byte 0
      unsigned char opCode;                // OPERATION CODE (2Bh)
      
      // byte 1
      unsigned char IMMED : 1;             // Immediate 
      unsigned char CP    : 1;             // Change Partition
      unsigned char BT    : 1;             // Block address Type
      unsigned char       : 5;             // Reserved
      
      // byte 2
      unsigned char       : 8;             // Reserved
      
      // bytes 3-6
      unsigned char logicalObjectID[4] ;   // Logical object identifier or block address
            
      // byte 7
      unsigned char        :8;             // Reserved
      
      // byte 8
      unsigned char partition;             // Partition
            
      // byte 9
      unsigned char control;               // Control byte
    };
    
419
    /**
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
     * READ POSITION CDB as described in SSC-3.
     */
    class readPositionCDB_t {
    public:
      readPositionCDB_t() {
        zeroStruct(this);
        opCode = SCSI::Commands::READ_POSITION; 
      }
      // byte 0
      unsigned char opCode;                // OPERATION CODE (34h)
      
      // byte 1 
      // *note* for T10000 we have BT:1, LONG:1, TCLP:1, Reserved:5
      unsigned char serviceAction: 5;      // Service action to choice FORM
      unsigned char              : 3;      // Reserved
      
      // bytes 2-6
      unsigned char reserved[5];           // Reserved
      
      // bytes 7-8 
Eric Cano's avatar
Eric Cano committed
440
      unsigned char allocationLength[2] ;  // used for EXTENDENT FORM
441
442
443
444
445
            
      // byte 9
      unsigned char control;               // Control byte
    };
    
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
     * READ POSITION  data format, short form as described in SSC-3.
     */
    class readPositionDataShortForm_t {
    public:
      readPositionDataShortForm_t() { zeroStruct(this); }
      // byte 0
      unsigned char BPEW :1;                // Beyond Programmable Early Warning
      unsigned char PERR :1;                // Position ERroR
      unsigned char LOLU :1;                // Logical Object Location Unknown or Block Position Unknown(BPU) for T10000 
      unsigned char      :1;                // Reserved
      unsigned char BYCU :1;                // BYte Count Unknown 
      unsigned char LOCU :1;                // Logical Object Count Unknown or Block Count Unknown(BCU) for T10000 
      unsigned char EOP  :1;                // End Of Partition
      unsigned char BOP  :1;                // Beginning of Partition
      
      // byte 1 
      unsigned char partitionNumber;        // Service action to choice FORM
      
      // bytes 2-3
      unsigned char reserved[2];            // Reserved
      
      // bytes 4-7 
      unsigned char firstBlockLocation[4];  // First Logical object location in SSC3,IBM,LTO
      
      // bytes 8-11
      unsigned char lastBlockLocation[4];   // Last Logical object location in SSC3,IBM,LTO 
      
      // byte 12
      unsigned char    :8;                  // Reserved
      
      // bytes 13-15
      unsigned char blocksInBuffer[3];      // Number of logical objects in object buffer 
      
      // bytes 16-19
      unsigned char bytesInBuffer[4];       // Number if bytes in object buffer
    };
    
484
    /**
485
486
487
488
     * LOG SELECT CDB as described in SPC-4.
     */
    class logSelectCDB_t {
    public:
Eric Cano's avatar
Eric Cano committed
489
490
491
492
      logSelectCDB_t() {
        zeroStruct(this);
        opCode = SCSI::Commands::LOG_SELECT; 
      }
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
      // byte 0
      unsigned char opCode;                // OPERATION CODE (4Ch)
      
      // byte 1
      unsigned char SP : 1;                // the Save Parameters
      unsigned char PCR: 1;                // the Parameter Code Reset
      unsigned char    : 6;                // Reserved 
      
      // byte 2
      unsigned char pageCode: 6;           // PAGE CODE
      unsigned char PC: 2;                 // the Page Control
      
      // byte 3
      unsigned char subPageCode;           // SUBPAGE CODE (Reserved for T10000)
      
      // bytes 4-6
      unsigned char reserved[3];           // Reserved
      
      // bytes 7-8
      unsigned char parameterListLength[2];// PARAMETER LIST LENGTH
      
      // byte 9
Eric Cano's avatar
Eric Cano committed
515
      unsigned char control;               // CONTROL
516
    };
517

Eric Cano's avatar
Eric Cano committed
518
    /**
519
     * Log sense CDB as described in SPC-4, 
Eric Cano's avatar
Eric Cano committed
520
521
522
     */
    class logSenseCDB_t {
    public:
Eric Cano's avatar
Eric Cano committed
523
      logSenseCDB_t() { zeroStruct(this); opCode = SCSI::Commands::LOG_SENSE; }
Eric Cano's avatar
Eric Cano committed
524
525
526
      unsigned char opCode;
      
      unsigned char SP : 1;
527
528
      unsigned char PPC: 1;
      unsigned char :6;
Eric Cano's avatar
Eric Cano committed
529
530
531
532
      
      unsigned char pageCode : 6;
      unsigned char PC : 2;
      
533
      unsigned char subPageCode;
Eric Cano's avatar
Eric Cano committed
534
      
535
536
      unsigned char reserved;
      
Eric Cano's avatar
Eric Cano committed
537
538
539
540
541
542
      unsigned char parameterPointer[2];
      
      unsigned char allocationLength[2];
      
      unsigned char control;
    };
Eric Cano's avatar
Eric Cano committed
543

544
    /**
545
546
     * Log sense Log Page Parameter Format as described in SPC-4, 
     */
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
    class logSenseParameterHeader_t  {
    public:
      // bytes 0-1
      unsigned char parameterCode [2];
      
      // byte 2
      unsigned char formatAndLinking : 2; // reserved and List Parameter bits
      unsigned char TMC : 2;              // Threshold Met Criteria
      unsigned char ETC : 1;              // Enable Threshold Comparison
      unsigned char TSD : 1;              // Target Save Disable
      unsigned char : 1;                  // DS Disable Save for T10000
      unsigned char DU : 1;               // Disable Update 
      
      // byte 3
      unsigned char parameterLength;      // n-3          
    };
    
    class logSenseParameter_t {
    public:
      // bytes 0-3
      logSenseParameterHeader_t header;
           
      // bytes 4-n
      unsigned char parameterValue[1];     // parameters have variable length 
571

572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
      /**
       * Gets the parameter value
       * 
       * @return The value  of the log sense parameter as uint64_t.
       *         If we have a parameter length more than 8 bytes the returning
       *         value is not determined. 
       */
      inline uint64_t getU64Value()  {
        union {
          unsigned char tmp[8];
          uint64_t val64;
        } u;
        
        u.tmp[0]=(header.parameterLength>0)?parameterValue[0]:0;
        u.tmp[1]=(header.parameterLength>1)?parameterValue[1]:0;
        u.tmp[2]=(header.parameterLength>2)?parameterValue[2]:0;
        u.tmp[3]=(header.parameterLength>3)?parameterValue[3]:0;
        u.tmp[4]=(header.parameterLength>4)?parameterValue[4]:0;
        u.tmp[5]=(header.parameterLength>5)?parameterValue[5]:0;
        u.tmp[6]=(header.parameterLength>6)?parameterValue[6]:0;
        u.tmp[7]=(header.parameterLength>7)?parameterValue[7]:0;

        u.val64 = be64toh(u.val64);
     
        return u.val64>>(64-(header.parameterLength<<3));     
      }
      
      /**
       * Gets the parameter value.
       * 
       * @return The value  of the log sense parameter as int64_t.
       *         If we have a parameter length more than 8 bytes the returning
       *         value is not determined. 
       */
      inline int64_t getS64Value()  {
        union {
          unsigned char tmp[8];
          uint64_t val64U;
          int64_t  val64S;
        } u;
        
        u.tmp[0]=(header.parameterLength>0)?parameterValue[0]:0;
        u.tmp[1]=(header.parameterLength>1)?parameterValue[1]:0;
        u.tmp[2]=(header.parameterLength>2)?parameterValue[2]:0;
        u.tmp[3]=(header.parameterLength>3)?parameterValue[3]:0;
        u.tmp[4]=(header.parameterLength>4)?parameterValue[4]:0;
        u.tmp[5]=(header.parameterLength>5)?parameterValue[5]:0;
        u.tmp[6]=(header.parameterLength>6)?parameterValue[6]:0;
        u.tmp[7]=(header.parameterLength>7)?parameterValue[7]:0;
      
        u.val64U = be64toh(u.val64U);
        
        return  (u.val64S < 0?-(-u.val64S>> (64-(header.parameterLength<<3))):
          (u.val64S>>(64-(header.parameterLength<<3))));     
      }  
627
    };
628

629
    /**
630
631
     * Log sense Log Page Format as described in SPC-4, 
     */
632
633
634
635
636
637
638
639
640
641
642
643
644
645
    class logSenseLogPageHeader_t {
    public:
      // byte 0
      unsigned char pageCode : 6;
      unsigned char SPF: 1;          // the Subpage format
      unsigned char DS: 1;           // the Disable Slave bit
      
      // byte 1
      unsigned char subPageCode;
      
      // bytes 2-3
      unsigned char pageLength[2];   // n-3 number of bytes without header   
    };
    /**
646
647
     * Log sense Log Page Format as described in SPC-4, 
     */
648
649
650
651
652
653
654
655
656
    class logSenseLogPage_t {
    public:
      // bytes 0-3
      logSenseLogPageHeader_t header;
      
      // bytes 4-n      
      logSenseParameter_t parameters [1]; // parameters have variable length
    };
    
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
    /**
     * MODE SENSE(6) CDB as described in SPC-4.
     */
    class modeSense6CDB_t {
    public:
      modeSense6CDB_t() {
        zeroStruct(this);
        opCode = SCSI::Commands::MODE_SENSE_6; 
      }
      // byte 0
      unsigned char opCode;           // OPERATION CODE (1Ah)
      
      // byte 1 
      unsigned char     : 3;          // Reserved
      unsigned char DBD : 1;          // Disable Block Descriptors
      unsigned char     : 4;          // Reserved  
      
      // byte 2
      unsigned char pageCode : 6;     // Page code
      unsigned char PC       : 2;     // Page Control
            
      // byte3  
      unsigned char subPageCode ;     // Subpage code
      
      // byte4  
682
      unsigned char allocationLength; // The maximum number of bytes to be transferred
683
684
685
686
            
      // byte 5
      unsigned char control;          // Control byte
    };
687

688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
    /**
     * MODE SENSE(6) MODE SELECT(6) parameter header as described in SPC-4.
     */
    class modeParameterHeader6_t {
    public:
      // byte 0
      unsigned char modeDataLength;   // The mode data length does not include itself 
      
      // byte 1 
      unsigned char mediumType;       // The medium type in the drive
      
      // byte 2
      /* in SPC-4 we have device-specific parameter byte here
       * but from all drive specifications the fields are the same
       * so we use them here.
       */
      unsigned char speed        : 4; // Read/write speed
      unsigned char bufferedMode : 3; // Returns after data is in the buffer or on the medium
      unsigned char WP           : 1; // Write Protect
            
      // byte3  
      unsigned char blockDescriptorLength ; //  (08h) or (00h)
    };
    
    /**
     * MODE SENSE(6,10) and MODE SELECT(6,10) block descriptor as described in SPC-4.
     */
    class modeParameterBlockDecriptor_t {
    public:
      // byte 0
      unsigned char densityCode;       // Density code
      
      // bytes 1-3 
      unsigned char numberOfBlocks[3]; // Number of block or block count
      
      // byte 4
      unsigned char : 8;               // Reserved
                 
      // bytes 5-7 
      unsigned char blockLength[3] ;   //  Block length
    };
    
    /**
     * MODE SENSE(6) or MODE SENSE(10) mode page 10h: Device Configuration.
     * There is no description in SPC-4 or SSC-3.
     * We use descriptions from: 
     * IBM System Storage Tape Drive 3592 SCSI Reference,
     * Sun StorageTekTM T10000 Tape Drive Fibre Channel Interface Reference Manual,
     * IBM TotalStorage LTO Ultrium Tape Drive SCSI Reference.
    */
    class modePageDeviceConfiguration_t {
    public:
      // byte 0
      unsigned char pageCode :6;          // Page code (10h)
      unsigned char SPF      :1;          // SubPage Format (0b)
      unsigned char PS       :1;          // Parameters Savable
      
      // byte 1 
      unsigned char pageLength;           // (0Eh)
      
      // byte 2
      unsigned char activeFormat : 5;     // Active Format
      unsigned char CAF          : 1;     // Change Active Format 
      unsigned char CAP          : 1;     // Change Active Partition 
      unsigned char              : 1;     // Reserved
                 
      // byte 3
      unsigned char activePartition ;     //  Active Partition
      
      // byte 4
      unsigned char writeBufferFullRatio; // Write object buffer full ratio
      
      // byte 5
      unsigned char readBufferEmptyRatio; // Read object buffer empty ratio
      
      // bytes 6-7
      unsigned char writeDelayTime[2];    // Write delay time in 100ms for IBM, LTO and in sec for T1000
      
      // byte 8
      unsigned char REW : 1;  // Report Early Warning
      unsigned char RBO : 1;  // Recover Buffer Order
      unsigned char SOCF: 2;  // Stop On Consecutive Filemarks
      unsigned char AVC : 1;  // Automatic Velocity Control
      unsigned char RSMK : 1; // Report SetMarKs (obsolete for IBM,LTO)
      unsigned char LOIS : 1; // Logical Object ID Supported or Block IDs Supported for T10000
      unsigned char OBR  : 1; // Object Buffer Recovery or Data Buffer Recovery for T10000
      
      // byte 9
      unsigned char gapSize;  // Obsolete for IBM, LTO
      
      // byte 10
      unsigned char BAM : 1;  // Block Address Mode or reserved for T10000
      unsigned char BAML: 1;  // Block Address Mode Lock or reserved for T10000
      unsigned char SWP : 1;  // Soft Write Protect
      unsigned char SEW : 1;  // Synchronize at Early Warning 
      unsigned char EEG : 1;  // EOD Enabled Generation
      unsigned char eodDefined :3; // End Of Data
      
      // bytes 11-13
      unsigned char bufSizeAtEarlyWarning[3]; // Object buffer size at early warning
      
      // byte 14
      unsigned char selectDataComprAlgorithm; // Select data compression algorithm
      
      // byte 15
      unsigned char PRMWP  : 1;        // PeRManent Write Protect
      unsigned char PERSWP : 1;        // PERSistent Write Protect
      unsigned char ASOCWP : 1;        // ASsOCiated Write Protect
      unsigned char rewindOnReset : 2; // Reserved for T10000
      unsigned char OIR  : 1;          // Only If Reserved  or reserved for T10000
      unsigned char WTRE : 2;          // WORM Tamper Read Enable
    };
    
    class modeSenseDeviceConfiguration_t {
    public:
      modeSenseDeviceConfiguration_t() { zeroStruct(this); }
      modeParameterHeader6_t header;
      modeParameterBlockDecriptor_t blockDescriptor;
      modePageDeviceConfiguration_t modePage;
    };
    
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
    /**
     * MODE SENSE(6) or MODE SENSE(10) mode page 0Ah: Control Data Protection.
     * as described in SSC-5.
     */
    class modePageControlDataProtection_t {
    public:
      // byte 0
      unsigned char pageCode :6;       // Page code (0Ah)
      unsigned char SPF      :1;       // SubPage Format (1b)
      unsigned char PS       :1;       // Parameters Savable 
                                       // 0b required for MODE SELECT IBM,LTO
                                       // 1b returned in MODE SENSE IBM, LTO
                                       // 0b Not supported for T10000
      
      // byte 1 
      unsigned char subpageCode;       // SubPage code (F0h)  
      
      // bytes 2-3
      unsigned char pageLength[2];     // Page length (n - 3) 1Ch for IBM,LTO
      
      // byte 4
      unsigned char LBPMethod;         // LBP method
      
      // byte 5
      unsigned char LBPInformationLength : 6; // LBP information length 
      unsigned char                      : 2; // Reserved
      
      // byte 6
      unsigned char : 5;               // Reserved
      unsigned char RBDP : 1;          // Recover Buffered Data Protected
      unsigned char LBP_R : 1;         // Logical blocks protected during read
      unsigned char LBP_W : 1;         // Logical blocks protected during write
      
      // byte 7
      unsigned char : 4;               // Reserved
      unsigned char T10PIexponent : 4; // T1000 only for T10 PI mode
      
      // bytes 8-31
      unsigned char reserved[24];      // Reserved. Added for IBM, LTO and do  
                                       // not used by T10000
    };
  
    /**
     * MODE SENSE(6) structure for mode page 0Ah: Control Data Protection.
     * as described in SSC-5.
     */
    class modeSenseControlDataProtection_t {
    public:
      modeSenseControlDataProtection_t() { zeroStruct(this); }
      modeParameterHeader6_t header;
      modeParameterBlockDecriptor_t blockDescriptor;
      modePageControlDataProtection_t modePage;
    };    
    
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
     /**
     * MODE SELECT(6) CDB as described in SPC-4.
     */
    class modeSelect6CDB_t {
    public:
      modeSelect6CDB_t() {
        zeroStruct(this);
        opCode = SCSI::Commands::MODE_SELECT_6; 
      }
      // byte 0
      unsigned char opCode;          // OPERATION CODE (15h)
      
      // byte 1 
      unsigned char SP : 1;          // Save Parameters
      unsigned char    : 3;          // Reserved
      unsigned char PF : 1;          // Page Format
      unsigned char    : 3;          // Reserved
      
      // bytes 2-3
      unsigned char reserved[2];     // Reserved
                  
      // byte 4
      unsigned char paramListLength; // Parameter list length
            
      // byte 5
      unsigned char control;         // Control byte
    };
    
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
    /**
     * TEST UNIT READY as described in SPC-4.
     */
    class testUnitReadyCDB_t {
    public:
      testUnitReadyCDB_t() {
        zeroStruct(this);
        opCode = SCSI::Commands::TEST_UNIT_READY; 
      }
      // byte 0
      unsigned char opCode;       // OPERATION CODE (00h)
      
      // byte 1 
      unsigned char      : 8;     // Reserved
            
      // byte 2
      unsigned char EDCC : 1;     // Enable Deferred CHECK CONDITION (IBM only)
      unsigned char      : 7;     // Reserved
            
      // byte 3-4  
      unsigned char reserverd[2]; // Reserved
            
      // byte 5
      unsigned char control;      // Control byte
    };
    
Eric Cano's avatar
Eric Cano committed
917
918
919
920
921
    /**
     * Part of a tape alert log page.
     * This structure does not need to be initialized, as the containing structure
     * (tapeAlertLogPage_t) will do it while initializing itself.
     */
Eric Cano's avatar
Eric Cano committed
922
923
    class tapeAlertLogParameter_t {
    public:
924
      unsigned char parameterCode [2];
Eric Cano's avatar
Eric Cano committed
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
      
      unsigned char formatAndLinking : 2;
      unsigned char TMC : 2;
      unsigned char ETC : 1;
      unsigned char TSD : 1;
      unsigned char : 1;
      unsigned char DU : 1;
      
      unsigned char parameterLength;
      
      unsigned char flag : 1;
      unsigned char : 7;
    };
    
    /**
940
     * Tape alert log page, returned by LOG SENSE. Defined in SSC-3, section 8.2.3 TapeAler log page.
Eric Cano's avatar
Eric Cano committed
941
     */
942
    template <int n>
Eric Cano's avatar
Eric Cano committed
943
944
    class tapeAlertLogPage_t {
    public:
Eric Cano's avatar
Eric Cano committed
945
      tapeAlertLogPage_t() { zeroStruct(this); }
Eric Cano's avatar
Eric Cano committed
946
947
948
949
950
      unsigned char pageCode : 6;
      unsigned char : 2;
      
      unsigned char subPageCode;
      
951
      unsigned char pageLength[2];
Eric Cano's avatar
Eric Cano committed
952
      
953
      tapeAlertLogParameter_t parameters [n];
Eric Cano's avatar
Eric Cano committed
954
955
      
      /**
956
957
       * Utility function computing the number of parameters. This converts a
       * length in bytes (as found in the struct) in a parameter count.
Eric Cano's avatar
Eric Cano committed
958
959
       * @return number of parameters.
       */
960
      unsigned int parameterNumber()  {
961
        unsigned int numFromLength = SCSI::Structures::toU16(pageLength) / sizeof (tapeAlertLogParameter_t);
962
963
        return numFromLength;
      }
Eric Cano's avatar
Eric Cano committed
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
    };
    
    /**
     * Sense buffer as defined in SPC-4, 
     * section 4.5.2 Descriptor format sense data and 
     * section 4.5.3 Fixed format sense data
     * The sense buffer size is stored in the form of
     * a single byte. Therefore, the constructor forbids
     * creation of a senseData_t structure bigger than
     * 255 bytes.
     * As the structure will be different depending on the response code,
     * everything after the first byte is represented by a union, which
     * can be any of the 2 forms (fixedFormat/descriptorFormat).
     * getXXXXX helper member function allow the getting of on of the other
     * version of the common fields.
     */
    template <int n>
    class senseData_t {
    public:
      senseData_t() {
        if (sizeof(*this) > 255)
985
          throw cta::exception::Exception("In SCSI::Structures::senseData_t::senseData_t(): size too big (> 255>");      
Eric Cano's avatar
Eric Cano committed
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
        zeroStruct(this);
      }
      // byte 0
      unsigned char responseCode: 7;
      unsigned char : 1;
      // Following bytes can take 2 versions:
      union {
       struct {
          // byte 1
          unsigned char senseKey : 4;
          unsigned char : 4;
          // Additional sense code (byte 2))
          unsigned char ASC;
          // Additional sense code qualifier (byte 3)
          unsigned char ASCQ;
          // byte 4
          unsigned char : 7;
          unsigned char SDAT_OVFL : 1;
          // byte 5-6
          unsigned char reserved[2];
          // byte 7
          unsigned char additionalSenseLength;
          // byte 8 onwards
          unsigned char additionalSenseBuffer[n - 8];
       } descriptorFormat;
       struct {
         // byte 1
         unsigned char obsolete;
         // byte 2
         unsigned char senseKey : 4;
         unsigned char SDAT_OVFL : 1;
         unsigned char ILI : 1;
         unsigned char EOM : 1;
         unsigned char filemark : 1;
         // bytes 3-6
         unsigned char information[4];
         // byte 7
         unsigned char additionalSenseLength;
         // bytes 8 - 11
         unsigned char commandSpecificInformation[4];
         // Additional sense code (byte 12))
         unsigned char ASC;
         // Additional sense code qualifier (byte 13)
         unsigned char ASCQ;
         // bytes 14
         unsigned char fieldReplaceableUnitCode;
         // bytes 15-17
          unsigned char senseSpecificInformation[3];
          // bytes 18 onwards
          unsigned char aditionalSenseBuffer[n - 18];
        } fixedFormat;
        // Helper functions for common fields
        // First make the difference between the fixed/descriptor
        // and current/deffered
      };
      bool isFixedFormat() {
        return responseCode == 0x70 || responseCode == 0x71;
      }
      
      bool isDescriptorFormat() {
        return responseCode == 0x72 || responseCode == 0x73;
      }
      
      bool isCurrent() {
        return responseCode == 0x70 || responseCode == 0x72;
      }

1053
      bool isDeferred() {
Eric Cano's avatar
Eric Cano committed
1054
1055
1056
1057
1058
1059
1060
1061
1062
        return responseCode == 0x71 || responseCode == 0x73;
      }

      uint8_t getASC() {
        if (isFixedFormat()) {
          return fixedFormat.ASC;
        } else if (isDescriptorFormat()) {
          return descriptorFormat.ASC;
        } else {
1063
1064
1065
          std::stringstream err;
          err << "In senseData_t::getASC: no ACS with this response code or response code not supported ("
                  << std::hex << std::showbase << (int)responseCode << ")";
1066
          throw cta::exception::Exception(err.str());
Eric Cano's avatar
Eric Cano committed
1067
1068
1069
1070
1071
1072
1073
1074
1075
        }
      }

      uint8_t getASCQ() {
        if (isFixedFormat()) {
          return fixedFormat.ASCQ;
        } else if (isDescriptorFormat()) {
          return descriptorFormat.ASCQ;
        } else {
1076
1077
1078
          std::stringstream err;
          err << "In senseData_t::getASCQ: no ACSQ with this response code or response code not supported ("
                  << std::hex << std::showbase << (int)responseCode << ")";
1079
          throw cta::exception::Exception(err.str());
Eric Cano's avatar
Eric Cano committed
1080
        }
1081
      }
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
      /**
       * Returns the Sense Key value.
       */
      unsigned char getSenseKey() {
        if (isFixedFormat()) {
          return fixedFormat.senseKey;
        } else if (isDescriptorFormat()) {
          return descriptorFormat.senseKey;
        } else {
          std::stringstream err;
          err << "In senseData_t::getSenseKey: no Sense Key with this response "
            "code or response code not supported ("
            << std::hex << std::showbase << (int)responseCode << ")";
1095
          throw cta::exception::Exception(err.str());
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
        }
      }
      /**
       * Returns the Sense Key value as string.
       */
      std::string getSenseKeyString() {
        if ( castor::tape::SCSI::senseKeys::lastWithText >= getSenseKey()) {
          return castor::tape::SCSI::senseKeys::senseKeysText[getSenseKey()];
        } else {
          std::stringstream err;
          err << "In senseData_t::getSenseKeyString: no Sense Key with this "
            "value ("<< std::hex << std::showbase 
            << (int)getSenseKey() << ")";
1109
          throw cta::exception::Exception(err.str());
1110
1111
        }
      }      
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
      /**
       * Function turning the ACS/ACSQ contents into a string.
       * This function is taken from the Linux kernel sources.
       * see scsi_extd_sense_format.
       * @return the error string as defined by SCSI specifications.
       */
      std::string getACSString() {
        SCSI::senseConstants sc;
        uint8_t asc = getASC();
        uint8_t ascq = getASCQ();
        uint16_t code = (asc << 8) | ascq;
        for (int i = 0; sc.ascStrings[i].text; i++)
          if (sc.ascStrings[i].code12 == code)
            return std::string(sc.ascStrings[i].text);
        for (int i = 0; sc.ascRangesStrings[i].text; i++)
          if (sc.ascRangesStrings[i].asc == asc &&
                  sc.ascRangesStrings[i].ascq_min <= ascq &&
                  sc.ascRangesStrings[i].ascq_max >= ascq) {
            char buff[100];
            snprintf(buff, sizeof (buff), sc.ascRangesStrings[i].text, ascq);
            return std::string(buff);
          }
        char buff[100];
        snprintf(buff, sizeof (buff), "Unknown ASC/ASCQ:%02x/%02x", asc, ascq);
        return std::string(buff);
      }
1138
      /* TODO: add support for other bits. See section 4.5.6
1139
       * of SPC-4 for sense key = NO SENSE. */
Eric Cano's avatar
Eric Cano committed
1140
    };
1141

1142
1143
1144
1145
1146
1147
1148
    /**
     * READ END OF WRAP POSITION CDB as described in LTO-8 SCSI Reference, p.119
     */
    class readEndOfWrapPositionCDB_t {
    public:
      readEndOfWrapPositionCDB_t() {
        zeroStruct(this);
1149
1150
        // REOWP is a service action of the MAINTENANCE_IN command: A3 1F 45
        opCode = SCSI::Commands::MAINTENANCE_IN;
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
        SERVICE_ACTION = 0x1F;
        serviceActionQualifier = 0x45;
      }
      // byte 0
      unsigned char opCode;                    // OPERATION CODE (A3h)

      // byte 1
      unsigned char SERVICE_ACTION :5;         // 1Fh
      unsigned char                :3;

      // byte 2
      unsigned char serviceActionQualifier;    // 45h

      // byte 3
      unsigned char WNV            :1;         // Wrap Number Valid: 0 = request data for first wrap on the tape
                                               //                    1 = return data for wrap in wrapNumber field
      unsigned char RA             :1;         // Report All: 0 = short form reply (return data for a single wrap)
                                               //             1 = long form reply  (return data for all wraps)
      unsigned char                :6;

      // byte 4
      unsigned char reserved1;                 // Reserved

      // byte 5
      unsigned char wrapNumber;                // Wrap for which the end of wrap position is requested.
                                               // If set, WNV must be 1 and RA must be 0.
      // bytes 6-9
1178
1179
      unsigned char allocationLength[4];       // Maximum number of bytes to be transferred
                                               // In the case of Report All, each wrap descriptor is 12
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
                                               // bytes. LTO-9 tapes have 280 wraps, so reply can be up
                                               // to 3084 bytes. And longer in case of LTO-10 (details
                                               // not available at time of writing).
      // byte 10
      unsigned char reserved2;                 // Reserved

      // byte 11
      unsigned char control;                   // Control byte
    };

1190
1191
1192
    /**
     * REOWP Short form parameter data, as described in LTO-8 SCSI Reference, p.120
     */
Michael Davis's avatar
Michael Davis committed
1193
    class readEndOfWrapPositionDataShortForm_t {
1194
    public:
Michael Davis's avatar
Michael Davis committed
1195
      readEndOfWrapPositionDataShortForm_t() { zeroStruct(this); }
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
      // bytes 0-1
      unsigned char responseDataLength[2];           // 08h, the number of bytes to follow

      // bytes 2-3
      unsigned char reserved[2];                     // Reserved

      // bytes 4-9
      unsigned char logicalObjectIdentifier[6];      // The logical object identifier of the object at the
                                                     // end of the wrap requested by the WNV bit and the
                                                     // WRAP_NUMBER field
    };

    /**
     * REOWP Long form parameter data, as described in LTO-8 SCSI Reference, p.120-121
     */
Michael Davis's avatar
Michael Davis committed
1211
    class readEndOfWrapPositionDataLongForm_t {
1212
    public:
Michael Davis's avatar
Michael Davis committed
1213
      readEndOfWrapPositionDataLongForm_t() { zeroStruct(this); }
1214
1215
1216
1217
1218
1219
1220
      // bytes 0-1
      unsigned char responseDataLength[2];           // n-1, the number of bytes to follow

      // bytes 2-3
      unsigned char reserved[2];                     // Reserved

      // bytes 4-n
1221
      struct WrapDescriptor {
1222
1223
1224
1225
1226
        unsigned char wrapNumber[2];                 // Wrap number
        unsigned char partition[2];                  // The partition number of the above wrap
        unsigned char reserved[2];                   // Reserved
        unsigned char logicalObjectIdentifier[6];    // The logical object identifier of the object at the end of the above wrap
      } wrapDescriptor[maxLTOTapeWraps];             // Array of wrap descriptiors
1227
1228
      
      uint16_t getNbWrapsReturned(){
1229
        return ((SCSI::Structures::toU16(responseDataLength) - sizeof(reserved)) / sizeof(WrapDescriptor));
1230
      }
1231
    };
1232

1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
    /**
     * REQUEST SENSE CDB as described in LTO-8 SCSI Reference, p.157
     */
    class requestSenseCDB_t {
    public:
      requestSenseCDB_t() {
        zeroStruct(this);
        opCode = SCSI::Commands::REQUEST_SENSE;
      }
      // byte 0
      unsigned char opCode;              // OPERATION CODE (03h)

      // bytes 1-3
Michael Davis's avatar
Michael Davis committed
1246
      unsigned char reserved[3];         // Reserved
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317

      // byte 4
      unsigned char allocationLength;    // Maximum number of bytes to be transferred (up to 96), see 5.2.29

      // byte 5
      unsigned char control;             // Control byte
    };

    /**
     * REQUEST SENSE data format, as described in LTO-8 SCSI Reference, p.158
     */
    class requestSenseData_t {
    public:
      requestSenseData_t() { zeroStruct(this); }
      // byte 0
      unsigned char RESPONSE_CODE :7;              // 70h current, 71h deferred
      unsigned char VALID         :1;              // Information bytes 3-6 are valid

      // byte 1
      unsigned char               :8;              // Obsolete

      // byte 2
      unsigned char SENSE_KEY     :4;              // See Annex B
      unsigned char               :1;              // Reserved
      unsigned char ILI           :1;              // Incorrect Length Indicator
      unsigned char EOM           :1;              // Device is at end of medium
      unsigned char FILEMARK      :1;              // The current command has encountered a filemark

      // bytes 3-6
      unsigned char information[4];                // Valid if VALID bit is set. Generally only used for non-deferred errors.

      // byte 7
      unsigned char additionalSenseLength;         // 0Ah only 18 bytes of sense data returned, 58h full 96 bytes of sense data returned

      // bytes 8-11
      unsigned char commandSpecificInformation[4]; // Not supported by LTO-8 drives

      // byte 12
      unsigned char additionalSenseCode;           // See Annex B

      // byte 13
      unsigned char additionalSenseCodeQualifier;  // See Annex B

      // byte 14
      unsigned char fieldReplacableUnitCode;       // Used for extended fault isolation information

      // byte 15
      unsigned char BIT_POINTER   :3;              // Points to bit in error of the field specified by the FIELD_POINTER
      unsigned char BPV           :1;              // Bit Pointer Valid, indicates whether BIT_POINTER contains information
      unsigned char               :2;              // Reserved
      unsigned char C_D           :1;              // Control/Data, indicates if error is in a data field or CDB field
      unsigned char SKSV_BIT      :1;              // Sense Key Specific Valid

      // bytes 16-17
      unsigned char SKSV[2];                       // Field Pointer, points to the CDB byte or parameter byte in error

      // bytes 18-19
      unsigned char reportingErrorFlagData[2];     // Reporting Error Flag Data

      // byte 20
      unsigned char               :8;              // Reserved

      // byte 21
      unsigned char VOLVALID      :1;              // Indicates if Volume Label and Volume Label Cartridge Type contain valid information
      unsigned char DUMP          :1;              // Indicates if a debug dump is present in the drive
      unsigned char               :1;              // Reserved
      unsigned char CLN           :1;              // Is the device requesting a clean?
      unsigned char DRVSRVC       :1;              // Does the drive have a hardware fault causing it to be inoperative?
      unsigned char               :3;              // Reserved

      // bytes 22-28
1318
      char volumeLabel[7];                         // Seven characters from left of Volume Label
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390

      // byte 29
      unsigned char physicalWrap;                  // Physical wrap of the current location. LSB reflects current physical direction:
                                                   //    0b - current direction is away from the physical beginning of tape
                                                   //    1b - current direction is towards the physical beginning of tape
                                                   //   FFh - logical wrap number exceeds 254, physical direction is not reflected
      // bytes 30-33
      unsigned char relativeLPOSValue[4];          // The current physical position on tape

      // byte 34
      unsigned char SCSIAddress;                   // Obsolete, use portIdentifier instead

      // byte 35
      unsigned char RS422Information;              // May contain a value passed across the RS-422 serial interface by a tape library

      // byte 36
      unsigned char activePartition :3;            // Partition number of the current logical position of the volume
      unsigned char                 :5;            // Reserved

      // bytes 37-39
      unsigned char portIdentifier[3];             // Address of the port through which the sense is reported, fibre channel or SAS

      // byte 40
      unsigned char relativeTgtPort     :3;        // Relative target port through which sense data is reported
      unsigned char                     :3;        // Reserved
      unsigned char tapePartitionsExist :1;        // Does the mounted volume contain more than one partition?
      unsigned char tapeDirectoryValid  :1;        // Is the tape directory valid?

      // byte 41
      unsigned char hostCommand;                   // SCSI Opcode of the command to which sense data is being returned

      // byte 42
      unsigned char mediaType           :4;        // Vendor reserved
      unsigned char cartridgeGenType    :4;        // Cartridge generation type, 000b = Gen1, 111b = Gen 8

      // bytes 43-44
      unsigned char volumeLabelCartridgeType[2];   // Valid if VOLVALID bit is set to 1b. Can be 'L7', 'M8', 'L8', etc.

      // bytes 45-48
      unsigned char logicalBlockNumber[4];         // Current LBA that would be reported in Read Position command

      // bytes 49-52
      unsigned char datasetNumber[4];

      // bytes 53-54
      unsigned char firstErrorFSC[2];

      // bytes 55-56
      unsigned char firstErrorFlagData[2];

      // bytes 57-58
      unsigned char secondErrorFSC[2];

      // bytes 59-60
      unsigned char secondErrorFlagData[2];

      // bytes 61-62
      unsigned char nextToLastErrorFSC[2];

      // bytes 63-64
      unsigned char nextToLastErrorFlagData[2];

      // bytes 65-66
      unsigned char lastErrorFSC[2];

      // bytes 67-68
      unsigned char lastErrorFlagData[2];

      // byte 69
      unsigned char LPOSRegion;

      // bytes 70-85
1391
      char ERPSummaryInformation[16];
1392
1393

      // bytes 86-95
1394
      char cartridgeSerialNumber[10];    // This is the value from the CRM right-justified, not the Barcode
1395
    };
1396

1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
    namespace encryption {

      class spinCDB_t {
      public:
        spinCDB_t() {
          zeroStruct(this);
          opCode = SCSI::Commands::SECURITY_PROTOCOL_IN;
        }

        unsigned char opCode;
        unsigned char securityProtocol;
        unsigned char securityProtocolSpecific[2];
        unsigned char reserved[2];
        unsigned char allocationLength[4];
        unsigned char reserved2;
        unsigned char controlByte;
      };

      class spoutCDB_t {
      public:
        spoutCDB_t() {
          zeroStruct(this);
          opCode = SCSI::Commands::SECURITY_PROTOCOL_OUT;
        }

        unsigned char opCode;
        unsigned char securityProtocol;
        unsigned char securityProtocolSpecific[2];
        unsigned char reserved[2];
        unsigned char allocationLength[4];
        unsigned char reserved2;
        unsigned char controlByte;
      };

      template <int n>
      class spinPageList_t {
      public:
        spinPageList_t() { zeroStruct(this); }
        unsigned char reserved[6];
        unsigned char supportedProtocolListLength[2];
        unsigned char list[n];
      };

      /**
       * Security Protocol OUT-Set Data Encryption Page as described in SSC-4.
       */
      class spoutSDEParam_t {
      public:
        spoutSDEParam_t() {
          zeroStruct(this);
          setU16(pageCode, SCSI::encryption::spoutSecurityProtocolSpecificPages::setDataEncryptionPage);
          setU16(keyLength, SCSI::encryption::ENC_KEY_LENGTH);
        }

        unsigned char pageCode[2];
        unsigned char length[2];

        unsigned char lock        : 1;
        unsigned char             : 4;
        unsigned char nexusScope  : 3; // Specifies the scope of the data encryption parameters

        unsigned char CKORL       : 1; // Clear key on reservation loss
        unsigned char CKORP       : 1; // Clear key on reservation preempt
        unsigned char CKOD        : 1; // Clear key on reservation demount
        unsigned char SDK         : 1; // Supplemental decryption key
        unsigned char RDMC        : 2; // Raw decryption mode control
        unsigned char CEEM        : 2; // Check external encryption mode

        unsigned char encryptionMode;
        unsigned char decryptionMode;
        unsigned char algorithmIndex;
        unsigned char keyFormat;
        unsigned char kadFormat;
        unsigned char reserved[7];
        unsigned char keyLength[2];
        unsigned char keyData[SCSI::encryption::ENC_KEY_LENGTH];
      };
    }

1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
    namespace RAO {
        
       /**
        * Receive RAO Command Descriptor Block (CDB)
        */
       class recieveRAO_t {
       public:
         recieveRAO_t() {
           zeroStruct(this);
           opcode = SCSI::Commands::MAINTENANCE_IN;
         }
         unsigned char opcode;

         unsigned char serviceAction   :5;
         unsigned char                 :2;
         unsigned char udsLimits       :1;

         unsigned char raoListOffset[4];

         unsigned char allocationLength[4];

         unsigned char udsType         :3;
         unsigned char                 :5;

         unsigned char control;

       };

       /**
        * UDS (User Data Segments) limits page
        */
       class udsLimitsPage_t {
       public:
         udsLimitsPage_t() {
           zeroStruct(this);
         }
Cristina Moraru's avatar
Cristina Moraru committed
1512
1513
1514
1515
1516
1517
1518
1519
         unsigned char maxSupported[2];
         unsigned char maxSize[2];
       };

       class udsLimits {
       public:
         uint16_t maxSupported;
         uint16_t maxSize;
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
       };

       /**
        * Generate RAO CDB
        */
       class generateRAO_t {
       public:
         generateRAO_t() {
           zeroStruct(this);
           opcode = SCSI::Commands::MAINTENANCE_OUT;
           raoProcess = 2;
         }
         unsigned char opcode;

         unsigned char serviceAction   :5;
         unsigned char                 :3;

         unsigned char raoProcess      :3;
         unsigned char                 :5;

         unsigned char udsType         :3;
         unsigned char                 :5;

         unsigned char reserved[2];

         unsigned char paramsListLength[4];

         unsigned char reserved2;

         unsigned char control;

       };

1553
       class udsDescriptor_t {
1554
       public:
1555
         udsDescriptor_t() {
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
           zeroStruct(this);
           setU16(descriptorLength, 0x1e);
         }
         unsigned char descriptorLength[2];
         unsigned char reserved[3];
         unsigned char udsName[10];
         unsigned char partitionNumber;
         unsigned char beginLogicalObjID[8];
         unsigned char endLogicalObjID[8];
       };

       /**
        * RAO list struct
        */
1570
       class raoList_t {
1571
       public:
1572
         raoList_t() {
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
           zeroStruct(this);
         }
         unsigned char raoProcess      :3;
         unsigned char                 :5;

         unsigned char status          :3;
         unsigned char                 :5;

         unsigned char res[2];

         unsigned char raoDescriptorListLength[4];

1585
         udsDescriptor_t udsDescriptors[1];
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597

       };

       /**
        * Generate RAO parameters
        */
       class generateRAOParams_t {
       public:
         generateRAOParams_t() {
           zeroStruct(this);
         }
         unsigned char res[4];
1598
1599
         unsigned char udsListLength[4];
         udsDescriptor_t udsDescriptors[1];
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
       };
       
       /**
        * Block Limits
        */
       class blockLims {
       public:
         blockLims() {
           zeroStruct(this);
         }
Cristina Moraru's avatar
Cristina Moraru committed
1610
         unsigned char fseq[10];
1611
1612
         uint64_t begin;
         uint64_t end;
1613
1614
       };
    }
1615
 
1616
    template <size_t n>
Eric Cano's avatar
Eric Cano committed
1617
1618
1619
1620
1621
1622
1623
1624
1625
    /**
     * Extract a string from a fixed size array. This function
     * gets rid of zeros in array and stops the extracted string
     * there. In SCSI, the arrays are space padded, so the string
     * should have a size equal to n usually. This function is templated
     * to manage the fixed-size array in the SCSI structures conveniently.
     * @param t array pointer to the char array.
     * @return the extracted string.
     */
1626
1627
1628
1629
1630
    std::string toString(const char(& t)[n]) {
      std::stringstream r;
      r.write(t, std::find(t, t + n, '\0') - t);
      return r.str();
    }
1631
1632
1633
1634
1635
1636
1637
    
    std::string toString(const inquiryData_t &);
    
    template <size_t n>
    std::string hexDump(const unsigned char(& d)[n]) {
      std::stringstream hex;
      hex << std::hex << std::setfill('0');
1638
      size_t pos = 0;
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
      while (pos < (8* (n / 8))) {
        hex << std::setw(4) << pos << " | ";
        for (int i=0; i<8; i++)
          hex << std::setw(2) << ((int) d[pos + i]) << " ";
        hex << "| ";
        for (int i=0; i<8; i++)
          hex << std::setw(0) << d[pos + i];
        hex << std::endl;
        pos += 8;
      }
      if (n % 8) {
        hex << std::setw(4) << pos << " | ";
1651
        for (size_t i=0; i<(n % 8); i++)
1652
          hex << std::setw(2) << ((int) d[pos + i]) << " ";
1653
        for (size_t i=(n % 8); i<8; i++)
1654
1655
          hex << "   ";
        hex << "| ";
1656
        for (size_t i=0; i<(n % 8); i++)
1657
1658
1659
1660
1661
          hex << std::setw(0) << d[pos + i];
        hex << std::endl;
      }
      return hex.str();
    }
1662
} // namespace Structures
1663
1664
1665
} // namespace SCSI
} // namespace tape
} // namespace castor