summaryrefslogtreecommitdiff
path: root/lib/driver/gnu_linux.c
blob: d63cf5598a2f516d63f116b89ec6dd9486b798ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
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
682
683
684
685
686
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
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
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
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
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
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
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
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
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
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
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
1318
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
1391
1392
1393
1394
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
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
1512
1513
1514
1515
1516
1517
1518
1519
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
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
/*
  Copyright (C) 2001 Herbert Valerio Riedel <hvr@gnu.org>
  Copyright (C) 2002, 2003, 2004, 2005, 2006, 2008, 2009, 2010, 2011
  2012 Rocky Bernstein <rocky@gnu.org>

  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 3 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
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/* This file contains Linux-specific code and implements low-level 
   control of the CD drive.
*/

#ifdef HAVE_CONFIG_H
# include "config.h"
# define __CDIO_CONFIG_H__ 1
#endif

#ifdef HAVE_STRING_H
#include <string.h>
#endif

#include <cdio/sector.h>
#include <cdio/util.h>
#include <cdio/types.h>
#include <cdio/mmc_cmds.h>
#include <cdio/audio.h>
#include <cdio/cdtext.h>
#include "cdio_assert.h"
#include "cdio_private.h"

#ifdef HAVE_LINUX_CDROM

#include <sys/types.h>
#include <sys/wait.h>
#include <limits.h>

#if defined(HAVE_LINUX_VERSION_H)
# include <linux/version.h>
# if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,16)
#   define __CDIO_LINUXCD_BUILD
# else
#  error "You need a kernel greater than 2.2.16 to have CDROM support"
# endif
#else 
#  error "You need <linux/version.h> to have CDROM support"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <mntent.h>

#include <linux/cdrom.h>
#include <scsi/scsi.h>
#include <scsi/sg.h>
#include <scsi/scsi_ioctl.h>
#include <sys/mount.h>

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

#ifndef PATH_MAX
#define PATH_MAX 4096
#endif

typedef enum {
  _AM_NONE,
  _AM_IOCTL,
  _AM_READ_CD,
  _AM_READ_10,
  _AM_MMC_RDWR,
  _AM_MMC_RDWR_EXCL,
} access_mode_t;

typedef struct {
  /* Things common to all drivers like this. 
     This must be first. */
  generic_img_private_t gen; 

  access_mode_t access_mode;

  /* Some of the more OS specific things. */
  /* Entry info for each track, add 1 for leadout. */
  struct cdrom_tocentry  tocent[CDIO_CD_MAX_TRACKS+1]; 

  struct cdrom_tochdr    tochdr;

} _img_private_t;

/* Some ioctl() errno values which occur when the tray is empty */
#define ERRNO_TRAYEMPTY(errno)  \
        ((errno == EIO) || (errno == ENOENT) || (errno == EINVAL))

/**** prototypes for static functions ****/
static bool is_cdrom_linux(const char *drive, char *mnttype);
static bool read_toc_linux (void *p_user_data);
static driver_return_code_t 
run_mmc_cmd_linux( void *p_user_data, 
                   unsigned int i_timeout,
                   unsigned int i_cdb, 
                   const mmc_cdb_t *p_cdb, 
                   cdio_mmc_direction_t e_direction, 
                   unsigned int i_buf, 
                   /*in/out*/ void *p_buf );
static access_mode_t 

str_to_access_mode_linux(const char *psz_access_mode) 
{
  const access_mode_t default_access_mode = _AM_IOCTL;

  if (NULL==psz_access_mode) return default_access_mode;
  
  if (!strcmp(psz_access_mode, "IOCTL"))
    return _AM_IOCTL;
  else if (!strcmp(psz_access_mode, "READ_CD"))
    return _AM_READ_CD;
  else if (!strcmp(psz_access_mode, "READ_10"))
    return _AM_READ_10;
  else if (!strcmp(psz_access_mode, "MMC_RDWR"))
    return _AM_MMC_RDWR;
  else if (!strcmp(psz_access_mode, "MMC_RDWR_EXCL"))
    return _AM_MMC_RDWR_EXCL;
  else {
    cdio_warn ("unknown access type: %s. Default IOCTL used.", 
               psz_access_mode);
    return default_access_mode;
  }
}

static char *
check_mounts_linux(const char *mtab)
{
  FILE *mntfp;
  struct mntent *mntent;
  
  mntfp = setmntent(mtab, "r");
  if ( mntfp != NULL ) {
    char *tmp;
    char *mnt_type;
    char *mnt_dev;
    unsigned int i_mnt_type;
    unsigned int i_mnt_dev;
    
    while ( (mntent=getmntent(mntfp)) != NULL ) {
      i_mnt_type = strlen(mntent->mnt_type) + 1;
      mnt_type = calloc(1, i_mnt_type);
      if (mnt_type == NULL)
        continue;  /* maybe you'll get lucky next time. */
      
      i_mnt_dev = strlen(mntent->mnt_fsname) + 1;
      mnt_dev = calloc(1, i_mnt_dev);
      if (mnt_dev == NULL) {
        free(mnt_type);
        continue;
      }
      
      strncpy(mnt_type, mntent->mnt_type, i_mnt_type);
      strncpy(mnt_dev, mntent->mnt_fsname, i_mnt_dev);
      
      /* Handle "supermount" filesystem mounts */
      if ( strcmp(mnt_type, "supermount") == 0 ) {
        tmp = strstr(mntent->mnt_opts, "fs=");
        if ( tmp ) {
          free(mnt_type);
          mnt_type = strdup(tmp + strlen("fs="));
          if ( mnt_type ) {
            tmp = strchr(mnt_type, ',');
            if ( tmp ) {
              *tmp = '\0';
            }
          }
        }
        tmp = strstr(mntent->mnt_opts, "dev=");
        if ( tmp ) {
          free(mnt_dev);
          mnt_dev = strdup(tmp + strlen("dev="));
          if ( mnt_dev ) {
            tmp = strchr(mnt_dev, ',');
            if ( tmp ) {
              *tmp = '\0';
            }
          }
        }
      }
      if ( mnt_type && mnt_dev ) {
	if ( strcmp(mnt_type, "iso9660") == 0 ) {
	  if (is_cdrom_linux(mnt_dev, mnt_type) > 0) {
	    free(mnt_type);
	    endmntent(mntfp);
	    return mnt_dev;
	  }
        }
      }
      free(mnt_dev);
      free(mnt_type);
    }
    endmntent(mntfp);
  }
  return NULL;
}

/*!
  Get the volume of an audio CD.

  @param p_cdio the CD object to be acted upon.
*/
static driver_return_code_t
audio_get_volume_linux (void *p_user_data,
                        /*out*/ cdio_audio_volume_t *p_volume)
{

  const _img_private_t *p_env = p_user_data;
  return ioctl(p_env->gen.fd, CDROMVOLREAD, p_volume);
}

/*!
  Pause playing CD through analog output
  
  @param p_cdio the CD object to be acted upon.
*/
static driver_return_code_t
audio_pause_linux (void *p_user_data)
{

  const _img_private_t *p_env = p_user_data;
  return ioctl(p_env->gen.fd, CDROMPAUSE);
}

/*!
  Playing starting at given MSF through analog output
  
  @param p_cdio the CD object to be acted upon.
*/
static driver_return_code_t
audio_play_msf_linux (void *p_user_data, msf_t *p_start_msf, msf_t *p_end_msf)
{

  const _img_private_t *p_env = p_user_data;
  struct cdrom_msf cdrom_msf;
  
  cdrom_msf.cdmsf_min0   = cdio_from_bcd8(p_start_msf->m);
  cdrom_msf.cdmsf_sec0   = cdio_from_bcd8(p_start_msf->s);
  cdrom_msf.cdmsf_frame0 = cdio_from_bcd8(p_start_msf->f);
  
  cdrom_msf.cdmsf_min1   = cdio_from_bcd8(p_end_msf->m);
  cdrom_msf.cdmsf_sec1   = cdio_from_bcd8(p_end_msf->s);
  cdrom_msf.cdmsf_frame1 = cdio_from_bcd8(p_end_msf->f);
  
  return ioctl(p_env->gen.fd, CDROMPLAYMSF, &cdrom_msf);
}

/*!
  Playing CD through analog output at the desired track and index
  
  @param p_cdio the CD object to be acted upon.
  @param p_track_index location to start/end.
*/
static driver_return_code_t
audio_play_track_index_linux (void *p_user_data, 
                              cdio_track_index_t *p_track_index)
{

  const _img_private_t *p_env = p_user_data;
  return ioctl(p_env->gen.fd, CDROMPLAYTRKIND, p_track_index);
}

/*!
  Read Audio Subchannel information
  
  @param p_user_data the CD object to be acted upon.
  @param p_subchannel returned information
*/
static driver_return_code_t
audio_read_subchannel_linux (void *p_user_data, 
                             /*out*/ cdio_subchannel_t *p_subchannel)
{

  const _img_private_t *p_env = p_user_data;
  struct cdrom_subchnl subchannel;
  int   i_rc;

  subchannel.cdsc_format = CDIO_CDROM_MSF;
  i_rc = ioctl(p_env->gen.fd, CDROMSUBCHNL, &subchannel);
  if (0 == i_rc) {
    p_subchannel->control      = subchannel.cdsc_ctrl;
    p_subchannel->track        = subchannel.cdsc_trk;
    p_subchannel->index        = subchannel.cdsc_ind;

    p_subchannel->abs_addr.m   = 
      cdio_to_bcd8(subchannel.cdsc_absaddr.msf.minute);
    p_subchannel->abs_addr.s   = 
      cdio_to_bcd8(subchannel.cdsc_absaddr.msf.second);
    p_subchannel->abs_addr.f   = 
      cdio_to_bcd8(subchannel.cdsc_absaddr.msf.frame);
    p_subchannel->rel_addr.m   = 
      cdio_to_bcd8(subchannel.cdsc_reladdr.msf.minute);
    p_subchannel->rel_addr.s   = 
      cdio_to_bcd8(subchannel.cdsc_reladdr.msf.second);
    p_subchannel->rel_addr.f   = 
      cdio_to_bcd8(subchannel.cdsc_reladdr.msf.frame);
    p_subchannel->audio_status = subchannel.cdsc_audiostatus;

    return DRIVER_OP_SUCCESS;
  } else {
    cdio_info ("ioctl CDROMSUBCHNL failed: %s\n", strerror(errno));  
    return DRIVER_OP_ERROR;
  }
}

/*!
  Resume playing an audio CD.
  
  @param p_cdio the CD object to be acted upon.
  
*/
static driver_return_code_t
audio_resume_linux (void *p_user_data)
{
  const _img_private_t *p_env = p_user_data;
  return ioctl(p_env->gen.fd, CDROMRESUME, 0);
}

/*!
  Set the volume of an audio CD.
  
  @param p_user_data the CD object to be acted upon.
  
*/
static driver_return_code_t
audio_set_volume_linux (void *p_user_data, cdio_audio_volume_t *p_volume)
{
  const _img_private_t *p_env = p_user_data;
  return ioctl(p_env->gen.fd, CDROMVOLCTRL, p_volume);
}

/*!
  Stop playing an audio CD.
  
  @param p_user_data the CD object to be acted upon.
  
*/
static driver_return_code_t 
audio_stop_linux (void *p_user_data)
{
  const _img_private_t *p_env = p_user_data;
  return ioctl(p_env->gen.fd, CDROMSTOP);
}

static bool
is_mmc_supported(void *user_data)
{
    _img_private_t *env = user_data;
    return (_AM_NONE == env->access_mode) ? false : true;
}

/*!
  Return the value associated with the key "arg".
*/
static const char *
get_arg_linux (void *env, const char key[])
{
  _img_private_t *_obj = env;

  if (!strcmp (key, "source")) {
    return _obj->gen.source_name;
  } else if (!strcmp (key, "access-mode")) {
    switch (_obj->access_mode) {
    case _AM_IOCTL:
      return "IOCTL";
    case _AM_READ_CD:
      return "READ_CD";
    case _AM_READ_10:
      return "READ_10";
    case _AM_MMC_RDWR:
      return "MMC_RDWR";
    case _AM_MMC_RDWR_EXCL:
      return "MMC_RDWR_EXCL";
    case _AM_NONE:
      return "no access method";
    }
  } else if (!strcmp (key, "scsi-tuple")) {
    return _obj->gen.scsi_tuple;
  } else if (!strcmp (key, "mmc-supported?")) {
      return is_mmc_supported(env) ? "true" : "false";
  } 
  return NULL;
}

#undef USE_LINUX_CAP
#ifdef USE_LINUX_CAP
/*!
  Return the the kind of drive capabilities of device.

  Note: string is malloc'd so caller should free() then returned
  string when done with it.

 */
static void
get_drive_cap_linux (const void *p_user_data,
                     /*out*/ cdio_drive_read_cap_t  *p_read_cap,
                     /*out*/ cdio_drive_write_cap_t *p_write_cap,
                     /*out*/ cdio_drive_misc_cap_t  *p_misc_cap)
{
  const _img_private_t *p_env = p_user_data;
  int32_t i_drivetype;

  i_drivetype = ioctl (p_env->gen.fd, CDROM_GET_CAPABILITY, CDSL_CURRENT);

  if (i_drivetype < 0) {
    *p_read_cap  = CDIO_DRIVE_CAP_ERROR;
    *p_write_cap = CDIO_DRIVE_CAP_ERROR;
    *p_misc_cap  = CDIO_DRIVE_CAP_ERROR;
    return;
  }
  
  *p_read_cap  = 0;
  *p_write_cap = 0;
  *p_misc_cap  = 0;

  /* Reader */
  if (i_drivetype & CDC_PLAY_AUDIO) 
    *p_read_cap  |= CDIO_DRIVE_CAP_READ_AUDIO;
  if (i_drivetype & CDC_CD_R) 
    *p_read_cap  |= CDIO_DRIVE_CAP_READ_CD_R;
  if (i_drivetype & CDC_CD_RW) 
    *p_read_cap  |= CDIO_DRIVE_CAP_READ_CD_RW;
  if (i_drivetype & CDC_DVD) 
    *p_read_cap  |= CDIO_DRIVE_CAP_READ_DVD_ROM;

  /* Writer */
  if (i_drivetype & CDC_CD_RW) 
    *p_read_cap  |= CDIO_DRIVE_CAP_WRITE_CD_RW;
  if (i_drivetype & CDC_DVD_R) 
    *p_read_cap  |= CDIO_DRIVE_CAP_WRITE_DVD_R;
  if (i_drivetype & CDC_DVD_RAM) 
    *p_read_cap  |= CDIO_DRIVE_CAP_WRITE_DVD_RAM;

  /* Misc */
  if (i_drivetype & CDC_CLOSE_TRAY) 
    *p_misc_cap  |= CDIO_DRIVE_CAP_MISC_CLOSE_TRAY;
  if (i_drivetype & CDC_OPEN_TRAY) 
    *p_misc_cap  |= CDIO_DRIVE_CAP_MISC_EJECT;
  if (i_drivetype & CDC_LOCK) 
    *p_misc_cap  |= CDIO_DRIVE_CAP_MISC_LOCK;
  if (i_drivetype & CDC_SELECT_SPEED) 
    *p_misc_cap  |= CDIO_DRIVE_CAP_MISC_SELECT_SPEED;
  if (i_drivetype & CDC_SELECT_DISC) 
    *p_misc_cap  |= CDIO_DRIVE_CAP_MISC_SELECT_DISC;
  if (i_drivetype & CDC_MULTI_SESSION) 
    *p_misc_cap  |= CDIO_DRIVE_CAP_MISC_MULTI_SESSION;
  if (i_drivetype & CDC_MEDIA_CHANGED) 
    *p_misc_cap  |= CDIO_DRIVE_CAP_MISC_MEDIA_CHANGED;
  if (i_drivetype & CDC_RESET) 
    *p_misc_cap  |= CDIO_DRIVE_CAP_MISC_RESET;
}
#endif

/*! Get the LSN of the first track of the last session of
  on the CD.
  
  @param p_cdio the CD object to be acted upon.
  @param i_last_session pointer to the session number to be returned.
*/
static driver_return_code_t 
get_last_session_linux (void *p_user_data, 
                        /*out*/ lsn_t *i_last_session)
{
  const _img_private_t *p_env = p_user_data;
  struct cdrom_multisession ms;
  int i_rc;
  
  ms.addr_format = CDROM_LBA;
  i_rc = ioctl(p_env->gen.fd, CDROMMULTISESSION, &ms);
  if (0 == i_rc) {
    *i_last_session = ms.addr.lba;
    return DRIVER_OP_SUCCESS;
  } else {
    cdio_warn ("ioctl CDROMMULTISESSION failed: %s\n", strerror(errno));  
    return DRIVER_OP_ERROR;
  }
}



/*! 
  Find out if media has changed since the last call.
  @param p_user_data the environment object to be acted upon.
  @return 1 if media has changed since last call, 0 if not. Error
  return codes are the same as driver_return_code_t
*/
static int
get_media_changed_linux (const void *p_user_data) {
  const _img_private_t *p_env = p_user_data;
  return ioctl(p_env->gen.fd, CDROM_MEDIA_CHANGED, 0);
}

/*!
  Return the media catalog number MCN.

  Note: string is malloc'd so caller should free() then returned
  string when done with it.

 */
static char *
get_mcn_linux (const void *p_user_data) {

  struct cdrom_mcn mcn;
  const _img_private_t *p_env = p_user_data;
  memset(&mcn, 0, sizeof(mcn));
  if (ioctl(p_env->gen.fd, CDROM_GET_MCN, &mcn) != 0)
    return NULL;
  return strdup((char *)mcn.medium_catalog_number);
}

/*!  
  Get format of track. 
*/
static track_format_t
get_track_format_linux(void *p_user_data, track_t i_track) 
{
  _img_private_t *p_env = p_user_data;
  
  if ( !p_env ) return TRACK_FORMAT_ERROR;

  if (!p_env->gen.toc_init) read_toc_linux (p_user_data) ;

  if (i_track > (p_env->gen.i_tracks+p_env->gen.i_first_track) 
      || i_track < p_env->gen.i_first_track)
    return TRACK_FORMAT_ERROR;

  i_track -= p_env->gen.i_first_track;

  /* This is pretty much copied from the "badly broken" cdrom_count_tracks
     in linux/cdrom.c.
   */
  if (p_env->tocent[i_track].cdte_ctrl & CDIO_CDROM_DATA_TRACK) {
    if (p_env->tocent[i_track].cdte_format == CDIO_CDROM_CDI_TRACK)
      return TRACK_FORMAT_CDI;
    else if (p_env->tocent[i_track].cdte_format == CDIO_CDROM_XA_TRACK)
      return TRACK_FORMAT_XA;
    else
      return TRACK_FORMAT_DATA;
  } else
    return TRACK_FORMAT_AUDIO;
  
}

/*!
  Return true if we have XA data (green, mode2 form1) or
  XA data (green, mode2 form2). That is track begins:
  sync - header - subheader
  12     4      -  8

  FIXME: there's gotta be a better design for this and get_track_format?
*/
static bool
get_track_green_linux(void *p_user_data, track_t i_track) 
{
  _img_private_t *p_env = p_user_data;
  
  if (!p_env->gen.toc_init) read_toc_linux (p_user_data) ;

  if (i_track >= (p_env->gen.i_tracks+p_env->gen.i_first_track) 
      || i_track < p_env->gen.i_first_track)
    return false;

  i_track -= p_env->gen.i_first_track;

  /* FIXME: Dunno if this is the right way, but it's what 
     I was using in cd-info for a while.
   */
  return ((p_env->tocent[i_track].cdte_ctrl & 2) != 0);
}

/*!  
  Return the starting MSF (minutes/secs/frames) for track number
  track_num in obj.  Track numbers usually start at something 
  greater than 0, usually 1.

  The "leadout" track is specified either by
  using i_track LEADOUT_TRACK or the total tracks+1.
  False is returned if there is no track entry.
*/
static bool
get_track_msf_linux(void *p_user_data, track_t i_track, msf_t *msf)
{
  _img_private_t *p_env = p_user_data;

  if (NULL == msf || 
      (i_track > CDIO_CD_MAX_TRACKS && i_track != CDIO_CDROM_LEADOUT_TRACK))
    return false;

  if (!p_env->gen.toc_init) read_toc_linux (p_user_data) ;

  if (i_track == CDIO_CDROM_LEADOUT_TRACK) 
    i_track = p_env->gen.i_tracks + p_env->gen.i_first_track;

  if (i_track > (p_env->gen.i_tracks+p_env->gen.i_first_track) 
      || i_track < p_env->gen.i_first_track) {
    return false;
  } else {
    struct cdrom_msf0  *msf0= 
      &p_env->tocent[i_track-p_env->gen.i_first_track].cdte_addr.msf;
    msf->m = cdio_to_bcd8(msf0->minute);
    msf->s = cdio_to_bcd8(msf0->second);
    msf->f = cdio_to_bcd8(msf0->frame);
    return true;
  }
}


/*!
  Check, if a device is mounted and return the target (=mountpoint)
  needed for umounting (idea taken from libunieject).
 */

static int is_mounted (const char * device, char * target) {
  FILE * fp;
  char real_device_1[PATH_MAX];
  char real_device_2[PATH_MAX];

  char file_device[PATH_MAX];
  char file_target[PATH_MAX];
  
  fp = fopen ( "/proc/mounts", "r");
  /* Older systems just have /etc/mtab */
  if(!fp)
    fp = fopen ( "/etc/mtab", "r");

  /* Neither /proc/mounts nor /etc/mtab could be opened, give up here */
  if(!fp) return 0;

  /* Get real device */
  if (NULL == cdio_realpath(device, real_device_1)) {
    cdio_warn("Problems resolving device %s: %s\n", device, strerror(errno));
  }
    
    
  /* Read entries */

  while ( fscanf(fp, "%s %s %*s %*s %*d %*d\n", file_device, file_target) != EOF ) {
      if (NULL == cdio_realpath(file_device, real_device_2)) {
          cdio_debug("Problems resolving device %s: %s\n", 
                     file_device, strerror(errno));
      }
    if(!strcmp(real_device_1, real_device_2)) {
      strcpy(target, file_target);
      fclose(fp);
      return 1;
    }
      
  }
  fclose(fp);
  return 0;
}

/*!
  Umount a filesystem specified by it's mountpoint. We must do this
  by forking and calling the umount command, because the raw umount
  (or umount2) system calls will *always* trigger an EPERM even if 
  we are allowed to umount the filesystem. The umount command is 
  suid root.

  Code here is inspired by the standard linux eject command by
  Jeff Tranter and Frank Lichtenheld.
 */

static int do_umount(char * target) {
  int status;

  switch (fork()) {
  case 0: /* child */
    execlp("pumount", "pumount", target, NULL);
    execlp("umount", "umount", target, NULL);
    return -1;
  case -1:
    return -1;
  default: /* parent */
    wait(&status);
    if (WIFEXITED(status) == 0) {
      return -1;
    }
    if (WEXITSTATUS(status) != 0) {
      return -1;
    }
    break;
  }
  return 0;
}
     

/*!
  Eject media in CD-ROM drive. Return DRIVER_OP_SUCCESS if successful, 
  DRIVER_OP_ERROR on error.
 */

static driver_return_code_t
eject_media_linux (void *p_user_data) {

  _img_private_t *p_env = p_user_data;
  driver_return_code_t ret=DRIVER_OP_SUCCESS;
  int status;
  bool was_open = false;
  char mount_target[PATH_MAX];
  
  if ( p_env->gen.fd <= -1 ) {
    p_env->gen.fd = open (p_env->gen.source_name, O_RDONLY|O_NONBLOCK);
  }
  else {
    was_open = true;
  }
  
  if ( p_env->gen.fd <= -1 ) return DRIVER_OP_ERROR;

  if ((status = ioctl(p_env->gen.fd, CDROM_DRIVE_STATUS, CDSL_CURRENT)) > 0) {
    switch(status) {
    case CDS_TRAY_OPEN:
      cdio_info ("Drive status reports that tray is open\n");
      break;
    default:
      cdio_info ("Unknown state of CD-ROM (%d)\n", status);
      /* Fall through */
    case CDS_DISC_OK:
      /* Some systems automount the drive, so we must umount it.
         We check if the drive is actually mounted */
      if(is_mounted (p_env->gen.source_name, mount_target)) {
        /* Try to umount the drive */
        if(do_umount(mount_target)) {
          cdio_log(CDIO_LOG_WARN, "Could not umount %s\n",
                   p_env->gen.source_name);
          ret=DRIVER_OP_ERROR;
          break;
        }
        /* For some reason, we must close and reopen the device after
           it got umounted (at least the commandline eject program
           opens the device just after umounting it) */
        close(p_env->gen.fd);
        p_env->gen.fd = open (p_env->gen.source_name, O_RDONLY|O_NONBLOCK);
      }
      
      if((ret = ioctl(p_env->gen.fd, CDROMEJECT)) != 0) {
        int eject_error = errno;
        /* Try ejecting the MMC way... */
        ret = mmc_eject_media(p_env->gen.cdio);
        if (0 != ret) {
          cdio_info("ioctl CDROMEJECT and MMC eject failed: %s", 
                    strerror(eject_error));
          ret = DRIVER_OP_ERROR;
        }
      }
      /* force kernel to reread partition table when new disc inserted */
      if (0 != ioctl(p_env->gen.fd, BLKRRPART)) {
        cdio_info ("BLKRRPART request failed: %s\n", strerror(errno));
      }
      break;
    }
  } else {
    cdio_warn ("CDROM_DRIVE_STATUS failed: %s\n", strerror(errno));
    ret=DRIVER_OP_ERROR;
  }
  if(!was_open) {
    close(p_env->gen.fd);
    p_env->gen.fd = -1;
  }
  return ret;
}

/*! 
  Get disc type associated with cd object.
*/
static discmode_t
dvd_discmode_linux (_img_private_t *p_env)
{
  discmode_t discmode=CDIO_DISC_MODE_NO_INFO;

  /* See if this is a DVD. */
  cdio_dvd_struct_t dvd;  /* DVD READ STRUCT for layer 0. */

  dvd.physical.type = CDIO_DVD_STRUCT_PHYSICAL;
  dvd.physical.layer_num = 0;
  if (0 == ioctl (p_env->gen.fd, DVD_READ_STRUCT, &dvd)) {
    switch(dvd.physical.layer[0].book_type) {
    case CDIO_DVD_BOOK_DVD_ROM:  return CDIO_DISC_MODE_DVD_ROM;
    case CDIO_DVD_BOOK_DVD_RAM:  return CDIO_DISC_MODE_DVD_RAM;
    case CDIO_DVD_BOOK_DVD_R:    return CDIO_DISC_MODE_DVD_R;
    case CDIO_DVD_BOOK_DVD_RW:   return CDIO_DISC_MODE_DVD_RW;
    case CDIO_DVD_BOOK_DVD_PR:   return CDIO_DISC_MODE_DVD_PR;
    case CDIO_DVD_BOOK_DVD_PRW:  return CDIO_DISC_MODE_DVD_PRW;
    default:                     return CDIO_DISC_MODE_DVD_OTHER;
    }
  }
  return discmode;
}

/*! 
  Get disc type associated with the cd object.
*/
static discmode_t
get_discmode_linux (void *p_user_data)
{
  _img_private_t *p_env = p_user_data;

  discmode_t discmode;

  if (!p_env) return CDIO_DISC_MODE_ERROR;

  /* Try DVD types first. See note below. */
  discmode = dvd_discmode_linux(p_env);

  if (CDIO_DISC_MODE_NO_INFO != discmode) return discmode;
  /* 
     Justin B Ruggles <jruggle@earthlink.net> reports that the
     GNU/Linux ioctl(.., CDROM_DISC_STATUS) does not return "CD DATA
     Form 2" for SVCD's even though they are are form 2.  In
     mmc_get_discmode we issue a SCSI MMC-2 TOC command first to
     try get more accurate information. But we took care above *not*
     to issue a FULL TOC on DVD media.
  */
  discmode = mmc_get_discmode(p_env->gen.cdio);
  if (CDIO_DISC_MODE_NO_INFO != discmode) 
    return discmode;
  else {
    int32_t i_discmode = ioctl (p_env->gen.fd, CDROM_DISC_STATUS);

    if (i_discmode < 0) return CDIO_DISC_MODE_ERROR;
    
    switch(i_discmode) {
    case CDS_AUDIO:
      return CDIO_DISC_MODE_CD_DA;
    case CDS_DATA_1:
    case CDS_DATA_2: /* Actually, recent GNU/Linux kernels don't return 
                        CDS_DATA_2, but just in case. */
      return CDIO_DISC_MODE_CD_DATA;
    case CDS_MIXED:
      return CDIO_DISC_MODE_CD_MIXED;
    case CDS_XA_2_1:
    case CDS_XA_2_2: 
      return CDIO_DISC_MODE_CD_XA;
    case CDS_NO_INFO:
      return CDIO_DISC_MODE_NO_INFO;
    default:
      return CDIO_DISC_MODE_ERROR;
    }
  }
}

/* Check a drive to see if it is a CD-ROM 
   Return 1 if a CD-ROM. 0 if it exists but isn't a CD-ROM drive
   and -1 if no device exists .
*/
static bool
is_cdrom_linux(const char *drive, char *mnttype)
{
  bool is_cd=false;
  int cdfd;
  
  /* If it doesn't exist, return -1 */
  if ( !cdio_is_device_quiet_generic(drive) ) {
    return(false);
  }
  
  /* If it does exist, verify that it's an available CD-ROM */
  cdfd = open(drive, (O_RDONLY|O_NONBLOCK), 0);
  if ( cdfd >= 0 ) {
    if ( ioctl(cdfd, CDROM_GET_CAPABILITY, 0) != -1 ) {
      is_cd = true;
    }
    close(cdfd);
    }
  /* Even if we can't read it, it might be mounted */
  else if ( mnttype && (strcmp(mnttype, "iso9660") == 0) ) {
    is_cd = true;
  }
  return(is_cd);
}

/* MMC driver to read audio sectors. 
   Can read only up to 25 blocks.
*/
static driver_return_code_t
read_audio_sectors_linux (void *p_user_data, void *p_buf, lsn_t i_lsn, 
                           uint32_t i_blocks)
{
  _img_private_t *p_env = p_user_data;
  return mmc_read_sectors( p_env->gen.cdio, p_buf, i_lsn, 
                           CDIO_MMC_READ_TYPE_CDDA, i_blocks);
}

/* Packet driver to read mode2 sectors. 
   Can read only up to 25 blocks.
*/
static driver_return_code_t
_read_mode2_sectors_mmc (_img_private_t *p_env, void *p_buf, lba_t lba, 
                         uint32_t i_blocks, bool b_read_10)
{
  mmc_cdb_t cdb = {{0, }};

  CDIO_MMC_SET_READ_LBA(cdb.field, lba);

  if (b_read_10) {
    int retval;
    
    CDIO_MMC_SET_COMMAND(cdb.field, CDIO_MMC_GPCMD_READ_10);
    CDIO_MMC_SET_READ_LENGTH16(cdb.field, i_blocks);

    if ((retval = mmc_set_blocksize (p_env->gen.cdio, M2RAW_SECTOR_SIZE)))
      return retval;
    
    if ((retval = run_mmc_cmd_linux (p_env, 0, 
                                     mmc_get_cmd_len(cdb.field[0]),
                                     &cdb, 
                                     SCSI_MMC_DATA_READ,
                                     M2RAW_SECTOR_SIZE * i_blocks, 
                                     p_buf)))
      {
        mmc_set_blocksize (p_env->gen.cdio, CDIO_CD_FRAMESIZE);
        return retval;
      }
    
    /* Restore blocksize. */
    retval = mmc_set_blocksize (p_env->gen.cdio, CDIO_CD_FRAMESIZE);
    return retval;
  } else {

    cdb.field[1] = 0; /* sector size mode2 */
    cdb.field[9] = 0x58; /* 2336 mode2 */

    CDIO_MMC_SET_COMMAND(cdb.field, CDIO_MMC_GPCMD_READ_CD);
    CDIO_MMC_SET_READ_LENGTH24(cdb.field, i_blocks);

    return run_mmc_cmd_linux (p_env, 0, 
                              mmc_get_cmd_len(cdb.field[0]), &cdb, 
                              SCSI_MMC_DATA_READ,
                              M2RAW_SECTOR_SIZE * i_blocks, p_buf);
  }
}

static driver_return_code_t
_read_mode2_sectors (_img_private_t *p_env, void *p_buf, lba_t lba, 
                     uint32_t i_blocks, bool b_read_10)
{
  unsigned int l = 0;
  int retval = 0;

  while (i_blocks > 0)
    {
      const unsigned i_blocks2 = (i_blocks > 25) ? 25 : i_blocks;
      void *p_buf2 = ((char *)p_buf ) + (l * M2RAW_SECTOR_SIZE);
      
      retval |= _read_mode2_sectors_mmc (p_env, p_buf2, lba + l, 
                                         i_blocks2, b_read_10);

      if (retval)
        break;

      i_blocks -= i_blocks2;
      l += i_blocks2;
    }

  return retval;
}

/*!
   Reads a single mode1 sector from cd device into data starting
   from lsn. Returns 0 if no error. 
 */
static driver_return_code_t
_read_mode1_sector_linux (void *p_user_data, void *p_data, lsn_t lsn, 
                          bool b_form2)
{

#if 0
  char buf[M2RAW_SECTOR_SIZE] = { 0, };
  struct cdrom_msf *p_msf = (struct cdrom_msf *) &buf;
  msf_t _msf;

  _img_private_t *p_env = p_user_data;

  cdio_lsn_to_msf (lsn, &_msf);
  p_msf->cdmsf_min0 = cdio_from_bcd8(_msf.m);
  p_msf->cdmsf_sec0 = cdio_from_bcd8(_msf.s);
  p_msf->cdmsf_frame0 = cdio_from_bcd8(_msf.f);

 retry:
  switch (p_env->access_mode)
    {
    case _AM_NONE:
      cdio_warn ("no way to read mode1");
      return 1;
      break;
      
    case _AM_IOCTL:
      if (ioctl (p_env->gen.fd, CDROMREADMODE1, &buf) == -1)
        {
          perror ("ioctl()");
          return 1;
          /* exit (EXIT_FAILURE); */
        }
      break;
      
    case _AM_READ_CD:
    case _AM_READ_10:
      if (_read_mode2_sectors (p_env, buf, lsn, 1, 
                               (p_env->access_mode == _AM_READ_10)))
        {
          perror ("ioctl()");
          if (p_env->access_mode == _AM_READ_CD)
            {
              cdio_info ("READ_CD failed; switching to READ_10 mode...");
              p_env->access_mode = _AM_READ_10;
              goto retry;
            }
          else
            {
              cdio_info ("READ_10 failed; switching to ioctl(CDROMREADMODE2) mode...");
              p_env->access_mode = _AM_IOCTL;
              goto retry;
            }
          return 1;
        }
      break;
    }

  memcpy (p_data, buf + CDIO_CD_SYNC_SIZE + CDIO_CD_HEADER_SIZE, 
          b_form2 ? M2RAW_SECTOR_SIZE: CDIO_CD_FRAMESIZE);
  
#else
  return cdio_generic_read_form1_sector(p_user_data, p_data, lsn);
#endif
  return 0;
}

/*!
   Reads i_blocks of mode2 sectors from cd device into data starting
   from lsn.
   Returns 0 if no error. 
 */
static driver_return_code_t
_read_mode1_sectors_linux (void *p_user_data, void *p_data, lsn_t lsn, 
                           bool b_form2, uint32_t i_blocks)
{
  _img_private_t *p_env = p_user_data;
  unsigned int i;
  int retval;
  unsigned int blocksize = b_form2 ? M2RAW_SECTOR_SIZE : CDIO_CD_FRAMESIZE;

  for (i = 0; i < i_blocks; i++) {
    if ( (retval = _read_mode1_sector_linux (p_env,
                                            ((char *)p_data) + (blocksize*i),
                                            lsn + i, b_form2)) )
      return retval;
  }
  return DRIVER_OP_SUCCESS;
}

/*!
   Reads a single mode2 sector from cd device into data starting
   from lsn. Returns 0 if no error. 
 */
static driver_return_code_t
_read_mode2_sector_linux (void *p_user_data, void *p_data, lsn_t lsn, 
                          bool b_form2)
{
  char buf[M2RAW_SECTOR_SIZE] = { 0, };
  struct cdrom_msf *msf = (struct cdrom_msf *) &buf;
  msf_t _msf;

  _img_private_t *p_env = p_user_data;

  cdio_lba_to_msf (cdio_lsn_to_lba(lsn), &_msf);
  msf->cdmsf_min0 = cdio_from_bcd8(_msf.m);
  msf->cdmsf_sec0 = cdio_from_bcd8(_msf.s);
  msf->cdmsf_frame0 = cdio_from_bcd8(_msf.f);

 retry:
  switch (p_env->access_mode)
    {
    case _AM_NONE:
      cdio_warn ("no way to read mode2");
      return 1;
      break;
      
    case _AM_IOCTL:
    case _AM_MMC_RDWR:
    case _AM_MMC_RDWR_EXCL:
      if (ioctl (p_env->gen.fd, CDROMREADMODE2, &buf) == -1)
        {
          perror ("ioctl()");
          return 1;
          /* exit (EXIT_FAILURE); */
        }
      break;
      
    case _AM_READ_CD:
    case _AM_READ_10:
      if (_read_mode2_sectors (p_env, buf, lsn, 1, 
                               (p_env->access_mode == _AM_READ_10)))
        {
          perror ("ioctl()");
          if (p_env->access_mode == _AM_READ_CD)
            {
              cdio_info ("READ_CD failed; switching to READ_10 mode...");
              p_env->access_mode = _AM_READ_10;
              goto retry;
            }
          else
            {
              cdio_info ("READ_10 failed; switching to ioctl(CDROMREADMODE2) mode...");
              p_env->access_mode = _AM_IOCTL;
              goto retry;
            }
          return 1;
        }
      break;
    }

  if (b_form2)
    memcpy (p_data, buf, M2RAW_SECTOR_SIZE);
  else
    memcpy (((char *)p_data), buf + CDIO_CD_SUBHEADER_SIZE, CDIO_CD_FRAMESIZE);
  
  return DRIVER_OP_SUCCESS;
}

/*!
   Reads i_blocks of mode2 sectors from cd device into data starting
   from lsn.
   Returns 0 if no error. 
 */
static driver_return_code_t
_read_mode2_sectors_linux (void *p_user_data, void *data, lsn_t lsn, 
                           bool b_form2, uint32_t i_blocks)
{
  _img_private_t *p_env = p_user_data;
  unsigned int i;
  uint16_t i_blocksize = b_form2 ? M2RAW_SECTOR_SIZE : CDIO_CD_FRAMESIZE;

  /* For each frame, pick out the data part we need */
  for (i = 0; i < i_blocks; i++) {
    int retval;
    if ( (retval = _read_mode2_sector_linux (p_env, 
                                            ((char *)data) + (i_blocksize*i),
                                            lsn + i, b_form2)) )
      return retval;
  }
  return DRIVER_OP_SUCCESS;
}

/*! 
  Read and cache the CD's Track Table of Contents and track info.
  Return false if successful or true if an error.
*/
static bool
read_toc_linux (void *p_user_data) 
{
  _img_private_t *p_env = p_user_data;
  int i;

  /* read TOC header */
  if ( ioctl(p_env->gen.fd, CDROMREADTOCHDR, &p_env->tochdr) == -1 ) {
    cdio_warn("%s: %s\n", 
            "error in ioctl CDROMREADTOCHDR", strerror(errno));
    return false;
  }

  p_env->gen.i_first_track = p_env->tochdr.cdth_trk0;
  p_env->gen.i_tracks      = p_env->tochdr.cdth_trk1;

  if (p_env->gen.i_tracks > CDIO_CD_MAX_TRACKS) {
     cdio_log(CDIO_LOG_WARN, "Number of tracks exceeds maximum (%d vs. %d)\n",
              p_env->gen.i_tracks, CDIO_CD_MAX_TRACKS);
     p_env->gen.i_tracks = CDIO_CD_MAX_TRACKS;
  }


  /* read individual tracks */
  for (i= p_env->gen.i_first_track; i<=p_env->gen.i_tracks; i++) {
    struct cdrom_tocentry *p_toc = 
      &(p_env->tocent[i-p_env->gen.i_first_track]);
    
    p_toc->cdte_track = i;
    p_toc->cdte_format = CDROM_MSF;
    if ( ioctl(p_env->gen.fd, CDROMREADTOCENTRY, p_toc) == -1 ) {
      cdio_warn("%s %d: %s\n",
              "error in ioctl CDROMREADTOCENTRY for track", 
              i, strerror(errno));
      return false;
    }

    set_track_flags(&(p_env->gen.track_flags[i]), p_toc->cdte_ctrl);
    
    /****
    struct cdrom_msf0 *msf= &env->tocent[i-1].cdte_addr.msf;
    
    fprintf (stdout, "--- track# %d (msf %2.2x:%2.2x:%2.2x)\n",
             i, msf->minute, msf->second, msf->frame);
    ****/

  }

  /* read the lead-out track */
  p_env->tocent[p_env->gen.i_tracks].cdte_track = CDIO_CDROM_LEADOUT_TRACK;
  p_env->tocent[p_env->gen.i_tracks].cdte_format = CDROM_MSF;

  if (ioctl(p_env->gen.fd, CDROMREADTOCENTRY, 
            &p_env->tocent[p_env->gen.i_tracks]) == -1 ) {
    cdio_warn("%s: %s\n", 
             "error in ioctl CDROMREADTOCENTRY for lead-out",
            strerror(errno));
    return false;
  }

  /*
  struct cdrom_msf0 *msf= &env->tocent[p_env->gen.i_tracks].cdte_addr.msf;

  fprintf (stdout, "--- track# %d (msf %2.2x:%2.2x:%2.2x)\n",
           i, msf->minute, msf->second, msf->frame);
  */

  p_env->gen.toc_init = true;
  return true;
}

/*!
  Run a SCSI MMC command. 
 
  cdio          CD structure set by cdio_open().
  i_timeout     time in milliseconds we will wait for the command
                to complete. If this value is -1, use the default 
                time-out value.
  p_buf         Buffer for data, both sending and receiving
  i_buf         Size of buffer
  e_direction   direction the transfer is to go.
  cdb           CDB bytes. All values that are needed should be set on 
                input. We'll figure out what the right CDB length should be.

  We return true if command completed successfully and false if not.
 */
static driver_return_code_t
run_mmc_cmd_linux(void *p_user_data, 
                  unsigned int i_timeout_ms,
                  unsigned int i_cdb, const mmc_cdb_t *p_cdb, 
                  cdio_mmc_direction_t e_direction, 
                  unsigned int i_buf, /*in/out*/ void *p_buf)
{
  _img_private_t *p_env = p_user_data;
  struct cdrom_generic_command cgc;
  cdio_mmc_request_sense_t sense;
  unsigned char *u_sense = (unsigned char *) &sense;

  p_env->gen.scsi_mmc_sense_valid = 0;
  memset (&cgc, 0, sizeof (struct cdrom_generic_command));
  memcpy(&cgc.cmd, p_cdb, i_cdb);
  cgc.buflen = i_buf;
  cgc.buffer = p_buf;
  cgc.sense  = (struct request_sense *) &sense;

  cgc.data_direction = (SCSI_MMC_DATA_READ  == e_direction) ? CGC_DATA_READ  :
                       (SCSI_MMC_DATA_WRITE == e_direction) ? CGC_DATA_WRITE :
                       CGC_DATA_NONE;

#ifdef HAVE_LINUX_CDROM_TIMEOUT
  cgc.timeout = i_timeout_ms;
#endif

  memset(u_sense, 0, sizeof(sense));
  { 
    int i_rc = ioctl (p_env->gen.fd, CDROM_SEND_PACKET, &cgc);

    /* Record SCSI sense reply for API call mmc_last_cmd_sense(). 
    */
    if (sense.additional_sense_len) {
        /* SCSI Primary Command standard 
           SPC 4.5.3, Table 26: 252 bytes legal, 263 bytes possible */
        int sense_size = sense.additional_sense_len + 8; 
    
        if (sense_size > sizeof(sense))
            sense_size = sizeof(sense);
        memcpy((void *) p_env->gen.scsi_mmc_sense, &sense, sense_size);
        p_env->gen.scsi_mmc_sense_valid = sense_size;
    }

    if (0 == i_rc) return DRIVER_OP_SUCCESS;
    if (-1 == i_rc) {
      cdio_info("ioctl CDROM_SEND_PACKET for command %s (0x%0x) failed:\n\t%s", 
                mmc_cmd2str((uint8_t) p_cdb->field[0]),
                p_cdb->field[0], 
                strerror(errno));  
      switch (errno) {
      case EPERM:
        return DRIVER_OP_NOT_PERMITTED;
        break;
      case EINVAL:
        return DRIVER_OP_BAD_PARAMETER;
        break;
      case EFAULT:
        return DRIVER_OP_BAD_POINTER;
        break;
      case EIO: 
      default:
        return DRIVER_OP_ERROR;
        break;
      }
    } else if (i_rc < -1)
      return DRIVER_OP_ERROR;
    else
      /*Not sure if this the best thing, but we'll use anyway. */
      return DRIVER_OP_SUCCESS;
  }
}

/*!
   Return the size of the CD in logical block address (LBA) units.
   @return the lsn. On error return CDIO_INVALID_LSN.

   As of GNU/Linux 2.6, CDROMTOCENTRY gives
   ioctl CDROMREADTOCENTRY failed: Invalid argument


   In some cases CDROMREADTOCHDR seems to fix this, but I haven't been
   able to find anything that documents this requirement or behavior. It's 
   not the way CDROMREADTOCHDR works on other 'nixs.

   Also note that in one at least one test the corresponding MMC gives
   a different answer, so there may be some disagreement about what is in
   fact the last lsn.
 */
static lsn_t
get_disc_last_lsn_linux (void *p_user_data)
{
  _img_private_t *p_env = p_user_data;

  struct cdrom_tocentry tocent;
  uint32_t i_size;

  if (!p_env->gen.toc_init) read_toc_linux (p_user_data) ;

  tocent.cdte_track = CDIO_CDROM_LEADOUT_TRACK;
  tocent.cdte_format = CDROM_LBA;
  if (ioctl (p_env->gen.fd, CDROMREADTOCENTRY, &tocent) == -1)
    {
      cdio_warn ("ioctl CDROMREADTOCENTRY failed: %s\n", strerror(errno));  
      return CDIO_INVALID_LSN;
    }

  i_size = tocent.cdte_addr.lba;

  return i_size;
}

/*!
  Set the arg "key" with "value" in the source device.
  Currently "source" and "access-mode" are valid keys.
  "source" sets the source device in I/O operations 
  "access-mode" sets the the method of CD access 

  DRIVER_OP_SUCCESS is returned if no error was found, 
  and nonzero if there as an error.
*/
static driver_return_code_t
set_arg_linux (void *p_user_data, const char key[], const char value[])
{
  _img_private_t *p_env = p_user_data;

  if (!strcmp (key, "source"))
    {
      if (!value) return DRIVER_OP_ERROR;
      free (p_env->gen.source_name);
      p_env->gen.source_name = strdup (value);
    }
  else if (!strcmp (key, "access-mode"))
    {
      return str_to_access_mode_linux(value);
    }
  else return DRIVER_OP_ERROR;

  return DRIVER_OP_SUCCESS;
}

/* checklist: /dev/cdrom, /dev/dvd /dev/hd?, /dev/scd? /dev/sr? */
static const char checklist1[][40] = {
  {"cdrom"}, {"dvd"}
};
static const int checklist1_size = sizeof(checklist1) / sizeof(checklist1[0]);

static const struct
  {
    char format[22];
    int num_min;
    int num_max;
  }
checklist2[] =
  {
    { "/dev/hd%c",  'a', 'z' },
    { "/dev/scd%d", 0,   27 },
    { "/dev/sr%d",  0,   27 },
  };
static const int checklist2_size = sizeof(checklist2) / sizeof(checklist2[0]);


/* Set CD-ROM drive speed */
static driver_return_code_t
set_speed_linux (void *p_user_data, int i_drive_speed)
{
  const _img_private_t *p_env = p_user_data;

  if (!p_env) return DRIVER_OP_UNINIT;
  return ioctl(p_env->gen.fd, CDROM_SELECT_SPEED, i_drive_speed);
}

#endif /* HAVE_LINUX_CDROM */

/*!
  Return an array of strings giving possible CD devices.
 */
char **
cdio_get_devices_linux (void)
{
#ifndef HAVE_LINUX_CDROM
  return NULL;
#else
  unsigned int i;
  char drive[40];
  char *ret_drive;
  char **drives = NULL;
  unsigned int num_drives=0;

  /* Scan the system for CD-ROM drives.
  */
  for ( i=0; i < checklist1_size; ++i ) {
    if (snprintf(drive, sizeof(drive), "/dev/%s", checklist1[i]) < 0)
      continue;
    if ( is_cdrom_linux(drive, NULL) > 0 ) {
      cdio_add_device_list(&drives, drive, &num_drives);
    }
  }

  /* Now check the currently mounted CD drives */
  if (NULL != (ret_drive = check_mounts_linux("/etc/mtab"))) {
    cdio_add_device_list(&drives, ret_drive, &num_drives);
    free(ret_drive);
  }
  
  /* Finally check possible mountable drives in /etc/fstab */
  if (NULL != (ret_drive = check_mounts_linux("/etc/fstab"))) {
    cdio_add_device_list(&drives, ret_drive, &num_drives);
    free(ret_drive);
  }

  /* Scan the system for CD-ROM drives.
     Not always 100% reliable, so use the USE_MNTENT code above first.
  */
  for ( i=0; i < checklist2_size; ++i ) {
    unsigned int j;
    for ( j=checklist2[i].num_min; j<=checklist2[i].num_max; ++j ) {
      if (snprintf(drive, sizeof(drive), checklist2[i].format, j) < 0)
        continue;
      if ( (is_cdrom_linux(drive, NULL)) > 0 ) {
        cdio_add_device_list(&drives, drive, &num_drives);
      }
    }
  }
  cdio_add_device_list(&drives, NULL, &num_drives);
  return drives;
#endif /*HAVE_LINUX_CDROM*/
}

/*!
  Return a string containing the default CD device.
 */
char *
cdio_get_default_device_linux(void)
{
#ifndef HAVE_LINUX_CDROM
  return NULL;
  
#else
  unsigned int i;
  char drive[40];
  char *ret_drive;

  /* Scan the system for CD-ROM drives.
  */
  for ( i=0; i < checklist1_size; ++i ) {
    if (snprintf(drive, sizeof(drive), "/dev/%s", checklist1[i]) < 0)
      continue;
    if ( is_cdrom_linux(drive, NULL) > 0 ) {
      return strdup(drive);
    }
  }

  /* Now check the currently mounted CD drives */
  if (NULL != (ret_drive = check_mounts_linux("/etc/mtab")))
    return ret_drive;
  
  /* Finally check possible mountable drives in /etc/fstab */
  if (NULL != (ret_drive = check_mounts_linux("/etc/fstab")))
    return ret_drive;

  /* Scan the system for CD-ROM drives.
     Not always 100% reliable, so use the USE_MNTENT code above first.
  */
  for ( i=0; i < checklist2_size; ++i ) {
    unsigned int j;
    for ( j=checklist2[i].num_min; j<=checklist2[i].num_max; ++j ) {
      if (snprintf(drive, sizeof(drive), checklist2[i].format, j) < 0)
        continue;
      if ( is_cdrom_linux(drive, NULL) > 0 ) {
        return(strdup(drive));
      }
    }
  }
  return NULL;
#endif /*HAVE_LINUX_CDROM*/
}

/*!
  Close tray on CD-ROM.
  
  @param psz_device the CD-ROM drive to be closed.
  
*/
driver_return_code_t 
close_tray_linux (const char *psz_device)
{
#ifdef HAVE_LINUX_CDROM
  int i_rc;
  int fd = open (psz_device, O_RDONLY|O_NONBLOCK);
  int status;

  if ( fd > -1 ) {
    if((status = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT)) > 0) {
      switch(status) {
      case CDS_TRAY_OPEN:
        goto try_anyway;
        break;
      case CDS_DISC_OK:
        cdio_info ("Tray already closed.");
        i_rc = DRIVER_OP_SUCCESS;
        break;
      default:
        cdio_info ("Unknown CD-ROM status (%d), trying anyway", status);
        goto try_anyway;
      }
    } else {
      cdio_info ("CDROM_DRIVE_STATUS failed: %s, trying anyway", 
                 strerror(errno));
    try_anyway:
      i_rc = DRIVER_OP_SUCCESS;
      if((i_rc = ioctl(fd, CDROMCLOSETRAY)) != 0) {
        cdio_warn ("ioctl CDROMCLOSETRAY failed: %s\n", strerror(errno));  
        i_rc = DRIVER_OP_ERROR;
      }
    }
    close(fd);
  } else 
    i_rc = DRIVER_OP_ERROR;
  return i_rc;
#else 
  return DRIVER_OP_NO_DRIVER;
#endif /*HAVE_LINUX_CDROM*/
}

#ifdef HAVE_LINUX_CDROM
/*!
  Produce a text composed from the system SCSI address tuple according to
  habits of Linux 2.4 and 2.6 :  "Bus,Host,Channel,Target,Lun" and store
  it in generic_img_private_t.scsi_tuple.
  To be accessed via cdio_get_arg("scsi-tuple-linux") or ("scsi-tuple").
  Drivers which implement this code have to return 5 valid decimal numbers
  separated by comma, or empty text if no such numbers are available.
  @return   1=success , 0=failure
*/
static int
set_scsi_tuple_linux(_img_private_t *env)
{
  int bus_no = -1, host_no = -1, channel_no = -1, target_no = -1, lun_no = -1; 
  int ret, i;
  char tuple[160], hdx[10];
#ifdef SCSI_IOCTL_GET_IDLUN
  struct my_scsi_idlun {
    int x;
    int host_unique_id;
  };
  struct my_scsi_idlun idlun;
#endif
  struct stat stbuf, env_stbuf;

  /* Check whether this is a hdX and declare tuple unavailable.
     /dev/hdX is traditionally for IDE drives and the ioctls here traditionally
     return ok and all 0s for all IDE drives. So the tuples are no unique ids.
  */
  if (fstat(env->gen.fd, &env_stbuf) == -1)
    goto no_tuple;
  strcpy(hdx, "/dev/hdX");
  for (i = 'a'; i <= 'z'; i++) {
    hdx[7] = i;
    if (stat(hdx, &stbuf) == -1)
  continue;
    if (env_stbuf.st_dev == stbuf.st_dev && env_stbuf.st_ino == stbuf.st_ino)
      goto no_tuple;
  }

#ifdef SCSI_IOCTL_GET_BUS_NUMBER
  if (ioctl(env->gen.fd, SCSI_IOCTL_GET_BUS_NUMBER, &bus_no) == -1)
    bus_no = -1;
#endif

#ifdef SCSI_IOCTL_GET_IDLUN
  /* http://www.tldp.org/HOWTO/SCSI-Generic-HOWTO/scsi_g_idlun.html */

  ret = ioctl(env->gen.fd, SCSI_IOCTL_GET_IDLUN, &idlun);
  if (ret != -1) {
    host_no= (idlun.x >> 24) & 255;
    channel_no= (idlun.x >> 16) & 255;
    target_no= (idlun.x) & 255;
    lun_no= (idlun.x >> 8) & 255;
  }
#endif

  if (env->gen.scsi_tuple != NULL)
    free (env->gen.scsi_tuple);
  env->gen.scsi_tuple = NULL;
  if (bus_no < 0 || host_no < 0 || channel_no < 0 || target_no < 0 ||
      lun_no < 0) {
no_tuple:;
    env->gen.scsi_tuple = strdup("");
    return 0;
  }
  snprintf(tuple, sizeof(tuple)-1, "%d,%d,%d,%d,%d",
          bus_no, host_no, channel_no, target_no, lun_no);
  env->gen.scsi_tuple = strdup(tuple);
  return 1; 
}
#endif

/*!
  Initialization routine. This is the only thing that doesn't
  get called via a function pointer. In fact *we* are the
  ones to set that up.
 */
CdIo_t *
cdio_open_linux (const char *psz_source_name)
{
#ifdef HAVE_LINUX_CDROM
  return cdio_open_am_linux(psz_source_name, NULL);
#else 
  return NULL;
#endif /*HAVE_LINUX_CDROM*/
}

/*!
  Initialization routine. This is the only thing that doesn't
  get called via a function pointer. In fact *we* are the
  ones to set that up.
 */
CdIo_t *
cdio_open_am_linux (const char *psz_orig_source, const char *access_mode)
{

#ifdef HAVE_LINUX_CDROM
  CdIo_t *ret;
  _img_private_t *_data;
  char *psz_source;
  int open_access_mode;  /* Access mode passed to cdio_generic_init. */

  cdio_funcs_t _funcs = {
    .audio_get_volume      = audio_get_volume_linux,
    .audio_pause           = audio_pause_linux,
    .audio_play_msf        = audio_play_msf_linux,
    .audio_play_track_index= audio_play_track_index_linux,
#if USE_MMC_SUBCHANNEL
    .audio_read_subchannel = audio_read_subchannel_mmc,
#else
    .audio_read_subchannel = audio_read_subchannel_linux,
#endif
    .audio_resume          = audio_resume_linux,
    .audio_set_volume      = audio_set_volume_linux,
    .audio_stop            = audio_stop_linux,
    .eject_media           = eject_media_linux,
    .free                  = cdio_generic_free,
    .get_arg               = get_arg_linux,
    .get_blocksize         = get_blocksize_mmc,
    .get_cdtext            = get_cdtext_generic,
    .get_cdtext_raw        = read_cdtext_generic,
    .get_default_device    = cdio_get_default_device_linux,
    .get_devices           = cdio_get_devices_linux,
    .get_disc_last_lsn     = get_disc_last_lsn_linux,
    .get_discmode          = get_discmode_linux,
#if USE_LINUX_CAP
    .get_drive_cap         = get_drive_cap_linux,
#else
    .get_drive_cap         = get_drive_cap_mmc,
#endif
    .get_first_track_num   = get_first_track_num_generic,
    .get_hwinfo            = NULL,
    .get_last_session      = get_last_session_linux,
    .get_media_changed     = get_media_changed_linux,
    .get_mcn               = get_mcn_linux,
    .get_num_tracks        = get_num_tracks_generic,
    .get_track_channels    = get_track_channels_generic,
    .get_track_copy_permit = get_track_copy_permit_generic,
    .get_track_format      = get_track_format_linux,
    .get_track_green       = get_track_green_linux,
    .get_track_lba         = NULL, /* This could be implemented if need be. */
    .get_track_preemphasis = get_track_preemphasis_generic,
    .get_track_msf         = get_track_msf_linux,
    .lseek                 = cdio_generic_lseek,
    .read                  = cdio_generic_read,
    .read_audio_sectors    = read_audio_sectors_linux,
#if 1
    .read_data_sectors     = read_data_sectors_generic,
#else 
    .read_data_sectors     = read_data_sectors_mmc,
#endif
    .read_mode1_sector     = _read_mode1_sector_linux,
    .read_mode1_sectors    = _read_mode1_sectors_linux,
    .read_mode2_sector     = _read_mode2_sector_linux,
    .read_mode2_sectors    = _read_mode2_sectors_linux,
    .read_toc              = read_toc_linux,
    .run_mmc_cmd           = run_mmc_cmd_linux,
    .set_arg               = set_arg_linux,
    .set_blocksize         = set_blocksize_mmc,
#if 1
    .set_speed             = set_speed_linux,
#else
    .set_speed             = set_speed_mmc,
#endif
  };

  _data                 = calloc (1, sizeof (_img_private_t));

  _data->access_mode    = str_to_access_mode_linux(access_mode);
  _data->gen.init       = false;
  _data->gen.toc_init   = false;
  _data->gen.fd         = -1;
  _data->gen.b_cdtext_error = false;

  if (NULL == psz_orig_source) {
    psz_source=cdio_get_default_device_linux();
    if (NULL == psz_source) {
      free(_data);
      return NULL;
    }
    
    set_arg_linux(_data, "source", psz_source);
    free(psz_source);
  } else {
    if (cdio_is_device_generic(psz_orig_source))
      set_arg_linux(_data, "source", psz_orig_source);
    else {
      /* The below would be okay if all device drivers worked this way. */
#if 0
      cdio_info ("source %s is not a device", psz_orig_source);
#endif
      free(_data);
      return NULL;
    }
  }

  ret = cdio_new ((void *)_data, &_funcs);
  if (ret == NULL) return NULL;

  ret->driver_id = DRIVER_LINUX;

  open_access_mode = O_NONBLOCK;
  if (_AM_MMC_RDWR == _data->access_mode)
    open_access_mode |= O_RDWR;
  else if (_AM_MMC_RDWR_EXCL == _data->access_mode)
    open_access_mode |= O_RDWR | O_EXCL;
  else
    open_access_mode |= O_RDONLY;
  if (cdio_generic_init(_data, open_access_mode)) {
    set_scsi_tuple_linux(_data);
    return ret;
  } else {
    cdio_generic_free (_data);
    free(ret);
    return NULL;
  }
  
#else 
  return NULL;
#endif /* HAVE_LINUX_CDROM */

}

bool
cdio_have_linux (void)
{
#ifdef HAVE_LINUX_CDROM
  return true;
#else 
  return false;
#endif /* HAVE_LINUX_CDROM */
}


/* 
 * Local variables:
 *  c-file-style: "gnu"
 *  tab-width: 8
 *  indent-tabs-mode: nil
 * End:
 */