summaryrefslogtreecommitdiff
path: root/usb/device/massstorage/MSDLun.c
blob: 42999d7932fddf2a03c17ac1d43bcb8d06084982 (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
/* ----------------------------------------------------------------------------
 *         ATMEL Microcontroller Software Support 
 * ----------------------------------------------------------------------------
 * Copyright (c) 2008, Atmel Corporation
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer below.
 *
 * Atmel's name may not be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
 * ----------------------------------------------------------------------------
 */

//------------------------------------------------------------------------------
//         Headers
//------------------------------------------------------------------------------


#include "MSDLun.h"
#include <utility/trace.h>
#include <usb/device/core/USBD.h>

//------------------------------------------------------------------------------
//         Constants
//------------------------------------------------------------------------------

/// Default LUN block size in bytes
#define     DEFAULT_LUN_BLOCK_SIZE      512

//------------------------------------------------------------------------------
//         Internal variables
//------------------------------------------------------------------------------

/// Inquiry data to return to the host for the Lun.
static SBCInquiryData inquiryData = {

    SBC_DIRECT_ACCESS_BLOCK_DEVICE, // Direct-access block device
    SBC_PERIPHERAL_DEVICE_CONNECTED,// Peripheral device is connected
    0x00,                           // Reserved bits
    0x01,                           // Media is removable
    SBC_SPC_VERSION_4,              // SPC-4 supported
    0x2,                            // Response data format, must be 0x2
    0,                              // Hierarchical addressing not supported
    0,                              // ACA not supported
    0x0,                            // Obsolete bits
    sizeof(SBCInquiryData) - 5,     // Additional length
    0,                              // No embedded SCC
    0,                              // No access control coordinator
    SBC_TPGS_NONE,                  // No target port support group
    0,                              // Third-party copy not supported
    0x0,                            // Reserved bits
    0,                              // Protection information not supported
    0x0,                            // Obsolete bit
    0,                              // No embedded enclosure service component
    0x0,                            // ???
    0,                              // Device is not multi-port
    0x0,                            // Obsolete bits
    0x0,                            // Unused feature
    0x0,                            // Unused features
    0,                              // Task management model not supported
    0x0,                            // ???
    {'A','T','M','E','L',' ',' ',' '},
    {'M','a','s','s',' ',
     'S','t','o','r','a','g','e',' ',
     'M','S','D'},
    {'0','.','0','1'},
    {'M','a','s','s',' ',
     'S','t','o','r','a','g','e',' ',
     'E','x','a','m','p','l','e'},
    0x00,                           // Unused features
    0x00,                           // Reserved bits
    {SBC_VERSION_DESCRIPTOR_SBC_3}, // SBC-3 compliant device
    {0, 0, 0, 0, 0,
     0, 0, 0, 0, 0,
     0, 0, 0, 0, 0,
     0, 0, 0, 0, 0,
     0, 0} // Reserved
};

//------------------------------------------------------------------------------
//         Exported functions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
//! \brief  Initializes a LUN instance. Must be invoked at least once even no
//!         Media is linked.
//! \param  lun          Pointer to the MSDLun instance to initialize
//! \param  media        Media on which the LUN is constructed, set to 0 to
//!                      disconnect the Media or initialize an ejected LUN.
//! \param  ioBuffer     Pointer to a buffer used for read/write operation and
//!                      which must be blockSize bytes long.
//! \param  ioBufferSize Size of the allocated IO buffer.
//! \param  baseAddress  Base address of the LUN in number of media blocks
//! \param  size         Total size of the LUN in number of media blocks
//! \param  blockSize    One block of the LUN in number of media blocks
//! \param  protected    The LUN area is forced to readonly even the media
//!                      is writable
//! \param  dataMonitor  Pointer to a Monitor Function to analyze the flow of
//!                      this LUN.
//------------------------------------------------------------------------------
void LUN_Init(MSDLun        *lun,
              Media         *media,
              unsigned char *ioBuffer,
              unsigned int   ioBufferSize,
              unsigned int   baseAddress,
              unsigned int   size,
              unsigned short blockSize,
              unsigned char  protected,
              void (*dataMonitor)(unsigned char flowDirection,
                                  unsigned int  dataLength,
                                  unsigned int  fifoNullCount,
                                  unsigned int  fifoFullCount))
{
    unsigned int logicalBlockAddress;
    TRACE_INFO("LUN init\n\r");

    // Initialize inquiry data
    lun->inquiryData = &inquiryData;

    // Initialize request sense data
    lun->requestSenseData.bResponseCode = SBC_SENSE_DATA_FIXED_CURRENT;
    lun->requestSenseData.isValid = 1;
    lun->requestSenseData.bObsolete1 = 0;
    lun->requestSenseData.bSenseKey = SBC_SENSE_KEY_NO_SENSE;
    lun->requestSenseData.bReserved1 = 0;
    lun->requestSenseData.isILI = 0;
    lun->requestSenseData.isEOM = 0;
    lun->requestSenseData.isFilemark = 0;
    lun->requestSenseData.pInformation[0] = 0;
    lun->requestSenseData.pInformation[1] = 0;
    lun->requestSenseData.pInformation[2] = 0;
    lun->requestSenseData.pInformation[3] = 0;
    lun->requestSenseData.bAdditionalSenseLength
        = sizeof(SBCRequestSenseData) - 8;
    lun->requestSenseData.bAdditionalSenseCode = 0;
    lun->requestSenseData.bAdditionalSenseCodeQualifier = 0;
    lun->requestSenseData.bFieldReplaceableUnitCode = 0;
    lun->requestSenseData.bSenseKeySpecific = 0;
    lun->requestSenseData.pSenseKeySpecific[0] = 0;
    lun->requestSenseData.pSenseKeySpecific[0] = 0;
    lun->requestSenseData.isSKSV = 0;

    STORE_DWORDB(0, lun->readCapacityData.pLogicalBlockAddress);
    STORE_DWORDB(0, lun->readCapacityData.pLogicalBlockLength);

    // Initialize LUN
    lun->media = media;
    if (media == 0) {
        lun->status = LUN_NOT_PRESENT;
        return;
    }

    lun->baseAddress = baseAddress;

    // Customized block size
    if (blockSize) {
        lun->blockSize = blockSize;
    }
    else {
        if (media->blockSize < DEFAULT_LUN_BLOCK_SIZE)
            lun->blockSize = DEFAULT_LUN_BLOCK_SIZE / media->blockSize;
        else
            lun->blockSize = 1;
    }

    if (size) {
        lun->size = size;
    }
    else {
        lun->size = media->size;
        //if (blockSize)
        //    lun->size = media->size / blockSize;
        //else {
        //    if (media->blockSize < DEFAULT_LUN_BLOCK_SIZE)
        //        lun->size = media->size / lun->blockSize;
        //    else
        //        lun->size = media->size;
        //}
    }
    
    TRACE_INFO("LUN: blkSize %d, size %d\n\r", (int)lun->blockSize, (int)lun->size);
    if (protected) lun->protected = 1;
    else           lun->protected = media->protected;

    lun->ioFifo.pBuffer = ioBuffer;
    lun->ioFifo.bufferSize = ioBufferSize;

    lun->dataMonitor = dataMonitor;

    // Initialize read capacity data
    logicalBlockAddress = lun->size / lun->blockSize - 1;
    STORE_DWORDB(logicalBlockAddress,
                 lun->readCapacityData.pLogicalBlockAddress);
    STORE_DWORDB(lun->blockSize * media->blockSize,
                 lun->readCapacityData.pLogicalBlockLength);

    // Indicate media change
    lun->status = LUN_CHANGED;
}

//------------------------------------------------------------------------------
//! \brief  Eject the media from a LUN
//! \param  lun          Pointer to the MSDLun instance to initialize
//! \return Operation result code
//------------------------------------------------------------------------------
unsigned char LUN_Eject(MSDLun *lun)
{
    if (lun->media) {

        // Avoid any LUN R/W in progress
        if (lun->media->state == MED_STATE_BUSY) {

            return USBD_STATUS_LOCKED;
        }

        // Remove the link of the media
        lun->media = 0;
    }
    // LUN is removed
    lun->status = LUN_NOT_PRESENT;

    return USBD_STATUS_SUCCESS;
}

//------------------------------------------------------------------------------
//! \brief  Writes data on the a LUN starting at the specified block address.
//! \param  lun          Pointer to a MSDLun instance
//! \param  blockAddress First block address to write
//! \param  data         Pointer to the data to write
//! \param  length       Number of blocks to write
//! \param  callback     Optional callback to invoke when the write finishes
//! \return Operation result code
//------------------------------------------------------------------------------
unsigned char LUN_Write(MSDLun        *lun,
                        unsigned int blockAddress,
                        void         *data,
                        unsigned int length,
                        TransferCallback   callback,
                        void         *argument)
{
    unsigned int  medBlk, medLen;
    unsigned char status;

    TRACE_INFO_WP("LUNWrite(%u) ", blockAddress);

    // Check that the data is not too big
    if ((length + blockAddress) * lun->blockSize > lun->size) {

        TRACE_WARNING("LUN_Write: Data too big\n\r");
        status = USBD_STATUS_ABORTED;
    }
    else if (lun->media == 0 || lun->status != LUN_READY) {

        TRACE_WARNING("LUN_Write: Media not ready\n\r");
        status = USBD_STATUS_ABORTED;
    }
    else if (lun->protected) {
        TRACE_WARNING("LUN_Write: LUN is readonly\n\r");
        status = USBD_STATUS_ABORTED;
    }
    else {

        // Compute write start address
        medBlk = lun->baseAddress + blockAddress * lun->blockSize;
        medLen = length * lun->blockSize;

        // Start write operation
        status = MED_Write(lun->media,
                           medBlk,
                           data,
                           medLen,
                           (MediaCallback) callback,
                           argument);

        // Check operation result code
        if (status == MED_STATUS_SUCCESS) {

            status = USBD_STATUS_SUCCESS;
        }
        else {

            TRACE_WARNING("LUN_Write: Cannot write media\n\r");
            status = USBD_STATUS_ABORTED;
        }
    }

    return status;
}

//------------------------------------------------------------------------------
//! \brief  Reads data from a LUN, starting at the specified block address.
//! \param  lun          Pointer to a MSDLun instance
//! \param  blockAddress First block address to read
//! \param  data         Pointer to a data buffer in which to store the data
//! \param  length       Number of blocks to read
//! \param  callback     Optional callback to invoke when the read finishes
//! \return Operation result code
//------------------------------------------------------------------------------
unsigned char LUN_Read(MSDLun        *lun,
                       unsigned int blockAddress,
                       void         *data,
                       unsigned int length,
                       TransferCallback   callback,
                       void         *argument)
{
    unsigned int medBlk, medLen;
    unsigned char status;

    // Check that the data is not too big
    if ((length + blockAddress) * lun->blockSize > lun->size) {

        TRACE_WARNING("LUN_Read: Area: (%d + %d)*%d > %d\n\r",
                      (int)length, (int)blockAddress, (int)lun->blockSize, (int)lun->size);
        status = USBD_STATUS_ABORTED;
    }
    else if (lun->media == 0 || lun->status != LUN_READY) {

        TRACE_WARNING("LUN_Read: Media not present\n\r");
        status = USBD_STATUS_ABORTED;
    }
    else {

        TRACE_INFO_WP("LUNRead(%u) ", blockAddress);

        // Compute read start address
        medBlk = lun->baseAddress + (blockAddress * lun->blockSize);
        medLen = length * lun->blockSize;

        // Start write operation
        status = MED_Read(lun->media,
                          medBlk,
                          data,
                          medLen,
                          (MediaCallback) callback,
                          argument);

        // Check result code
        if (status == MED_STATUS_SUCCESS) {

            status = USBD_STATUS_SUCCESS;
        }
        else {

            TRACE_WARNING("LUN_Read: Cannot read media\n\r");
            status = USBD_STATUS_ABORTED;
        }
    }

    return status;
}
personal git repositories of Harald Welte. Your mileage may vary