summaryrefslogtreecommitdiff
path: root/nuttx/drivers/loop.c
blob: 9d51dd74656c0d2930767cabf7c741d66df40961 (plain) (blame)
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/****************************************************************************
 * drivers/loop.c
 *
 *   Copyright (C) 2008-2009, 2011, 2014 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * 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. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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
 * COPYRIGHT OWNER 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.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/mount.h>

#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <semaphore.h>
#include <debug.h>
#include <errno.h>

#include <nuttx/kmalloc.h>
#include <nuttx/fs/fs.h>

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

#define loop_semgive(d) sem_post(&(d)->sem)  /* To match loop_semtake */
#define MAX_OPENCNT     (255)                /* Limit of uint8_t */

/****************************************************************************
 * Private Types
 ****************************************************************************/

struct loop_struct_s
{
  sem_t        sem;          /* For safe read-modify-write operations */
  uint32_t     nsectors;     /* Number of sectors on device */
  off_t        offset;       /* Offset (in bytes) to the first sector */
  uint16_t     sectsize;     /* The size of one sector */
  uint8_t      opencnt;      /* Count of open references to the loop device */
#ifdef CONFIG_FS_WRITABLE
  bool         writeenabled; /* true: can write to device */
#endif
  int          fd;           /* Descriptor of char device/file */
};

/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

static int     loop_semtake(FAR struct loop_struct_s *dev);
static int     loop_open(FAR struct inode *inode);
static int     loop_close(FAR struct inode *inode);
static ssize_t loop_read(FAR struct inode *inode, FAR unsigned char *buffer,
                       size_t start_sector, unsigned int nsectors);
#ifdef CONFIG_FS_WRITABLE
static ssize_t loop_write(FAR struct inode *inode,
                          FAR const unsigned char *buffer,
                          size_t start_sector, unsigned int nsectors);
#endif
static int     loop_geometry(FAR struct inode *inode,
                             FAR struct geometry *geometry);

/****************************************************************************
 * Private Data
 ****************************************************************************/

static const struct block_operations g_bops =
{
  loop_open,     /* open     */
  loop_close,    /* close    */
  loop_read,     /* read     */
#ifdef CONFIG_FS_WRITABLE
  loop_write,    /* write    */
#else
  NULL,          /* write    */
#endif
  loop_geometry, /* geometry */
  NULL           /* ioctl    */
};

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Name: loop_semtake
 ****************************************************************************/

static int loop_semtake(FAR struct loop_struct_s *dev)
{
  int ret;

  /* Take the semaphore (perhaps waiting) */

  ret = sem_wait(&dev->sem);
  if (ret < 0)
    {
      int errcode = get_errno();

      /* The only case that an error should occur here is if
       * the wait was awakened by a signal.
       */

      ASSERT(errcode == EINTR);
      return -ret;
    }

  return OK;
}

/****************************************************************************
 * Name: loop_open
 *
 * Description: Open the block device
 *
 ****************************************************************************/

static int loop_open(FAR struct inode *inode)
{
  FAR struct loop_struct_s *dev;
  int ret;

  DEBUGASSERT(inode && inode->i_private);
  dev = (FAR struct loop_struct_s *)inode->i_private;

  /* Make sure we have exclusive access to the state structure */

  ret = loop_semtake(dev);
  if (ret == OK)
    {
      if (dev->opencnt == MAX_OPENCNT)
        {
          ret = -EMFILE;
        }
      else
        {
          /* Increment the open count */

          dev->opencnt++;
        }

      loop_semgive(dev);
    }

  return ret;
}

/****************************************************************************
 * Name: loop_close
 *
 * Description: close the block device
 *
 ****************************************************************************/

static int loop_close(FAR struct inode *inode)
{
  FAR struct loop_struct_s *dev;
  int ret;

  DEBUGASSERT(inode && inode->i_private);
  dev = (FAR struct loop_struct_s *)inode->i_private;

  /* Make sure we have exclusive access to the state structure */

  ret = loop_semtake(dev);
  if (ret == OK)
    {
      if (dev->opencnt == 0)
        {
          ret = -EIO;
        }
      else
        {
          /* Decrement the open count */

          dev->opencnt--;
        }

      loop_semgive(dev);
    }

  return ret;
}

/****************************************************************************
 * Name: loop_read
 *
 * Description:  Read the specified number of sectors
 *
 ****************************************************************************/

static ssize_t loop_read(FAR struct inode *inode, FAR unsigned char *buffer,
                         size_t start_sector, unsigned int nsectors)
{
  FAR struct loop_struct_s *dev;
  ssize_t nbytesread;
  off_t offset;
  int ret;

  DEBUGASSERT(inode && inode->i_private);
  dev = (FAR struct loop_struct_s *)inode->i_private;

  if (start_sector + nsectors > dev->nsectors)
    {
      dbg("Read past end of file\n");
      return -EIO;
    }

  /* Calculate the offset to read the sectors and seek to the position */

  offset = start_sector * dev->sectsize + dev->offset;
  ret = lseek(dev->fd, offset, SEEK_SET);
  if (ret == (off_t)-1)
    {
      dbg("Seek failed for offset=%d: %d\n", (int)offset, get_errno());
      return -EIO;
    }

  /* Then read the requested number of sectors from that position */

  do
    {
      nbytesread = read(dev->fd, buffer, nsectors * dev->sectsize);
      if (nbytesread < 0 && get_errno() != EINTR)
        {
          dbg("Read failed: %d\n", get_errno());
          return -get_errno();
        }
    }
  while (nbytesread < 0);

  /* Return the number of sectors read */

  return nbytesread / dev->sectsize;
}

/****************************************************************************
 * Name: loop_write
 *
 * Description: Write the specified number of sectors
 *
 ****************************************************************************/

#ifdef CONFIG_FS_WRITABLE
static ssize_t loop_write(FAR struct inode *inode,
                          FAR const unsigned char *buffer,
                          size_t start_sector, unsigned int nsectors)
{
  FAR struct loop_struct_s *dev;
  ssize_t nbyteswritten;
  off_t offset;
  int ret;

  DEBUGASSERT(inode && inode->i_private);
  dev = (FAR struct loop_struct_s *)inode->i_private;

  /* Calculate the offset to write the sectors and seek to the position */

  offset = start_sector * dev->sectsize + dev->offset;
  ret = lseek(dev->fd, offset, SEEK_SET);
  if (ret == (off_t)-1)
    {
      dbg("Seek failed for offset=%d: %d\n", (int)offset, get_errno());
    }

  /* Then write the requested number of sectors to that position */

  do
    {
      nbyteswritten = write(dev->fd, buffer, nsectors * dev->sectsize);
      if (nbyteswritten < 0 && get_errno() != EINTR)
        {
          dbg("Write failed: %d\n", get_errno());
          return -get_errno();
        }
    }
  while (nbyteswritten < 0);

  /* Return the number of sectors written */

  return nbyteswritten / dev->sectsize;
}
#endif

/****************************************************************************
 * Name: loop_geometry
 *
 * Description: Return device geometry
 *
 ****************************************************************************/

static int loop_geometry(FAR struct inode *inode,
                         FAR struct geometry *geometry)
{
  FAR struct loop_struct_s *dev;

  DEBUGASSERT(inode);
  if (geometry)
    {
      dev = (FAR struct loop_struct_s *)inode->i_private;
      geometry->geo_available     = true;
      geometry->geo_mediachanged  = false;
#ifdef CONFIG_FS_WRITABLE
      geometry->geo_writeenabled  = dev->writeenabled;
#else
      geometry->geo_writeenabled  = false;
#endif
      geometry->geo_nsectors      = dev->nsectors;
      geometry->geo_sectorsize    = dev->sectsize;
      return OK;
    }

  return -EINVAL;
}

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: losetup
 *
 * Description:
 *   Setup the loop device so that it exports the file referenced by 'filename'
 *   as a block device.
 *
 ****************************************************************************/

int losetup(FAR const char *devname, FAR const char *filename,
            uint16_t sectsize, off_t offset, bool readonly)
{
  FAR struct loop_struct_s *dev;
  struct stat sb;
  int ret;

  /* Sanity check */

#ifdef CONFIG_DEBUG
  if (!devname || !filename || !sectsize)
    {
      return -EINVAL;
    }
#endif

  /* Get the size of the file */

  ret = stat(filename, &sb);
  if (ret < 0)
    {
      dbg("Failed to stat %s: %d\n", filename, get_errno());
      return -get_errno();
    }

  /* Check if the file system is big enough for one block */

  if (sb.st_size - offset < sectsize)
    {
      dbg("File is too small for blocksize\n");
      return -ERANGE;
    }

  /* Allocate a loop device structure */

  dev = (FAR struct loop_struct_s *)kmm_zalloc(sizeof(struct loop_struct_s));
  if (!dev)
    {
      return -ENOMEM;
    }

  /* Initialize the loop device structure. */

  sem_init(&dev->sem, 0, 1);
  dev->nsectors  = (sb.st_size - offset) / sectsize;
  dev->sectsize  = sectsize;
  dev->offset    = offset;

  /* Open the file. */

#ifdef CONFIG_FS_WRITABLE
  dev->writeenabled = false; /* Assume failure */
  dev->fd           = -1;

  /* First try to open the device R/W access (unless we are asked
   * to open it readonly).
   */

  if (!readonly)
    {
      dev->fd = open(filename, O_RDWR);
    }

  if (dev->fd >= 0)
    {
      dev->writeenabled = true; /* Success */
    }
  else
#endif
    {
      /* If that fails, then try to open the device read-only */

      dev->fd = open(filename, O_RDWR);
      if (dev->fd < 0)
        {
          dbg("Failed to open %s: %d\n", filename, get_errno());
          ret = -get_errno();
          goto errout_with_dev;
        }
    }

  /* Inode private data will be reference to the loop device structure */

  ret = register_blockdriver(devname, &g_bops, 0, dev);
  if (ret < 0)
    {
      fdbg("register_blockdriver failed: %d\n", -ret);
      goto errout_with_fd;
    }

  return OK;

errout_with_fd:
  close(dev->fd);
errout_with_dev:
  kmm_free(dev);
  return ret;
}

/****************************************************************************
 * Name: loteardown
 *
 * Description:
 *   Undo the setup performed by losetup
 *
 ****************************************************************************/

int loteardown(FAR const char *devname)
{
  FAR struct loop_struct_s *dev;
  FAR struct inode *inode;
  int ret;

  /* Sanity check */

#ifdef CONFIG_DEBUG
  if (!devname)
    {
      return -EINVAL;
    }
#endif

  /* Open the block driver associated with devname so that we can get the inode
   * reference.
   */

  ret = open_blockdriver(devname, MS_RDONLY, &inode);
  if (ret < 0)
    {
      dbg("Failed to open %s: %d\n", devname, -ret);
      return ret;
    }

  /* Inode private data is a reference to the loop device structure */

  dev = (FAR struct loop_struct_s *)inode->i_private;
  close_blockdriver(inode);

  DEBUGASSERT(dev);

  /* Are there still open references to the device */

  if (dev->opencnt > 0)
    {
      return -EBUSY;
    }

  /* Otherwise, unregister the block device */

  ret = unregister_blockdriver(devname);

  /* Release the device structure */

  if (dev->fd >= 0)
    {
      (void)close(dev->fd);
    }

  kmm_free(dev);
  return ret;
}