IOCTL_CDROM_READ_TOC: Fixed 'LastTrack' field
[captive.git] / src / libcaptive / storage / cdrom.c
1 /* $Id$
2  * "\Device\CdRom%d" storage emulation driver for reactos of libcaptive
3  * Copyright (C) 2002 Jan Kratochvil <project-captive@jankratochvil.net>
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; exactly version 2 of June 1991 is required
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19
20 #include "config.h"
21
22 #include "captive/storage.h"    /* self */
23 #include "reactos/ddk/iotypes.h"        /* for DRIVER_OBJECT */
24 #include <glib/gmessages.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include "reactos/ddk/ntddscsi.h"       /* for IO_SCSI_CAPABILITIES */
29 #include "reactos/ddk/class2.h" /* for PDEVICE_EXTENSION */
30 #include "reactos/ddk/status.h" /* for STATUS_INVALID_PARAMETER */
31 #include "reactos/ddk/iofuncs.h"        /* for IoCreateDevice() */
32 #include "captive/unicode.h"
33 #include "captive/macros.h"
34
35
36 static DRIVER_OBJECT cdrom_DriverObject;
37 static DISK_GEOMETRY cdrom_DiskGeometry;
38 static DISK_GEOMETRY cdrom_DiskGeometry_check;  /* for g_assert() checking against foreign modifications */
39 static int Image_fd=-1;
40 static off_t Image_size;        /* FIXME: lseek64() */
41
42
43 /* FIXME: We should comply with PDRIVER_DISPATCH prototype but unfortunately
44  * CAPTIVE_STDCALL prevents us to do so at least in RedHat gcc-3.2-4 (gcc bug?).
45  */
46 #define MajorFunction_DEVICE_CONTROL ((PDRIVER_DISPATCH)MajorFunction_DEVICE_CONTROL_func)
47 static NTSTATUS CAPTIVE_STDCALL MajorFunction_DEVICE_CONTROL_func(IN DEVICE_OBJECT *DeviceObject,IN IRP *Irp)
48 {
49 IO_STACK_LOCATION *IrpStack;
50 DEVICE_EXTENSION *DeviceExtension;
51 DISK_GEOMETRY *DiskGeometry;
52
53         g_return_val_if_fail(DeviceObject!=NULL,STATUS_INVALID_PARAMETER);
54         g_return_val_if_fail(Irp!=NULL,STATUS_INVALID_PARAMETER);
55         g_return_val_if_fail(DeviceObject->DriverObject==&cdrom_DriverObject,STATUS_INVALID_PARAMETER);
56
57         IrpStack=IoGetCurrentIrpStackLocation(Irp);
58         g_assert(IrpStack->MajorFunction==IRP_MJ_DEVICE_CONTROL);
59         Irp->IoStatus.Information=0;    /* request-specific, may get overriden later */
60         DeviceExtension=DeviceObject->DeviceExtension;
61
62         DiskGeometry=DeviceExtension->DiskGeometry;
63         g_assert(DiskGeometry==&cdrom_DiskGeometry);
64         g_assert(DiskGeometry->MediaType==cdrom_DiskGeometry_check.MediaType);
65         g_assert(DiskGeometry->TracksPerCylinder==cdrom_DiskGeometry_check.TracksPerCylinder);
66         g_assert(DiskGeometry->SectorsPerTrack==cdrom_DiskGeometry_check.SectorsPerTrack);
67         g_assert(DiskGeometry->BytesPerSector==cdrom_DiskGeometry_check.BytesPerSector);
68         g_assert(DiskGeometry->Cylinders.QuadPart==cdrom_DiskGeometry_check.Cylinders.QuadPart);
69         g_assert(DeviceExtension->PartitionLength.QuadPart==Image_size);
70
71         switch (IrpStack->Parameters.DeviceIoControl.IoControlCode) {
72
73                 case IOCTL_CDROM_READ_TOC: {
74 CDROM_TOC *CdromToc;
75
76                         if (IrpStack->Parameters.DeviceIoControl.OutputBufferLength<sizeof(CDROM_TOC)) {
77                                 Irp->IoStatus.Status=STATUS_BUFFER_TOO_SMALL;
78                                 Irp->IoStatus.Information=sizeof(CDROM_TOC);
79                                 g_assert_not_reached();
80                                 goto done;
81                                 }
82                         CdromToc=(CDROM_TOC *)Irp->AssociatedIrp.SystemBuffer;
83                         CAPTIVE_MEMZERO(CdromToc);
84                         CdromToc->Length[0]=((sizeof(*CdromToc)-2)>>0U)&0xFFU;  /* little-endian */
85                         CdromToc->Length[1]=((sizeof(*CdromToc)-2)>>8U)&0xFFU;
86                         CdromToc->FirstTrack=0; /* one track; TOC_LAST_TRACK does not count */
87                         CdromToc->LastTrack =0; /* one track; TOC_LAST_TRACK does not count */
88                         CdromToc->TrackData[0].Control=TOC_DATA_TRACK;
89                         CdromToc->TrackData[0].Adr=0;   /* Q-subchannel subinfo */
90                         CdromToc->TrackData[0].TrackNumber=0;
91                         CdromToc->TrackData[0].Address[0]=0>>24U;       /* LBA offset; big-endian */
92                         CdromToc->TrackData[0].Address[1]=0>>16U;
93                         CdromToc->TrackData[0].Address[2]=0>> 8U;
94                         CdromToc->TrackData[0].Address[3]=0>> 0U;
95                         CdromToc->TrackData[1].Control=0;
96                         CdromToc->TrackData[1].Adr=0;   /* Q-subchannel subinfo */
97                         CdromToc->TrackData[1].TrackNumber=TOC_LAST_TRACK;
98                         /* FIXME: should we put the Image_size to TOC_LAST_TRACK? */
99                         CdromToc->TrackData[1].Address[0]=(Image_size/512)>>24U;        /* LBA offset; big-endian */
100                         CdromToc->TrackData[1].Address[1]=(Image_size/512)>>16U;
101                         CdromToc->TrackData[1].Address[2]=(Image_size/512)>> 8U;
102                         CdromToc->TrackData[1].Address[3]=(Image_size/512)>> 0U;
103
104                         Irp->IoStatus.Information=sizeof(DISK_GEOMETRY);
105                         Irp->IoStatus.Status=STATUS_SUCCESS;
106                         } break;
107
108                 case IOCTL_CDROM_GET_DRIVE_GEOMETRY:
109                         if (IrpStack->Parameters.DeviceIoControl.OutputBufferLength<sizeof(DISK_GEOMETRY)) {
110                                 Irp->IoStatus.Status=STATUS_BUFFER_TOO_SMALL;
111                                 Irp->IoStatus.Information=sizeof(DISK_GEOMETRY);
112                                 g_assert_not_reached();
113                                 goto done;
114                                 }
115                         *(DISK_GEOMETRY *)Irp->AssociatedIrp.SystemBuffer=cdrom_DiskGeometry;
116                         Irp->IoStatus.Information=sizeof(DISK_GEOMETRY);
117                         Irp->IoStatus.Status=STATUS_SUCCESS;
118                         break;
119
120                 case IOCTL_CDROM_CHECK_VERIFY: {
121                         if (IrpStack->Parameters.DeviceIoControl.OutputBufferLength) {
122                                 if (IrpStack->Parameters.DeviceIoControl.OutputBufferLength<sizeof(ULONG)) {
123                                         Irp->IoStatus.Status=STATUS_BUFFER_TOO_SMALL;
124                                         Irp->IoStatus.Information=sizeof(ULONG);
125                                         g_assert_not_reached();
126                                         goto done;
127                                         }
128                                 *(ULONG *)Irp->AssociatedIrp.SystemBuffer=0;    /* MediaChangeCount */
129                                 Irp->IoStatus.Information=sizeof(ULONG);
130                                 }
131                         else {
132                                 Irp->IoStatus.Information=0;
133                                 }
134                         Irp->IoStatus.Status=STATUS_SUCCESS;
135                         } break;
136
137                 default:
138                         Irp->IoStatus.Status=STATUS_INVALID_DEVICE_REQUEST;
139                         g_assert_not_reached();
140                         goto done;
141                 }
142         /* PASSTHRU */
143
144 done:   /* 'err:' but we flow here even during success */
145         /* required for removable media only */
146         if (!NT_SUCCESS(Irp->IoStatus.Status) && IoIsErrorUserInduced(Irp->IoStatus.Status)) {
147                 g_assert(Irp->Tail.Overlay.Thread!=NULL);       /* FIXME: Error should be postponed to first !=NULL Irp later */
148                 IoSetHardErrorOrVerifyDevice(Irp,DeviceObject);
149                 Irp->IoStatus.Information=0;    /* may got set during some processing before error occured */
150                 }
151
152         IoCompleteRequest(Irp,IO_NO_INCREMENT); /* I hope it won't corrupt our Irp->IoStatus.Status */
153         return Irp->IoStatus.Status;
154 }
155
156
157 /* similiar to drivers/storage/cdrom/cdrom.c/DriverEntry()->...
158  * ...->CdromClassCreateDeviceObject()->
159  * ->reactos/drivers/storage/class2/class2.c/ScsiClassCreateDeviceObject()
160  * We should be driving a lower layer PortDevice but currently we
161  * do not provide it, I hope W32 filesystems don't touch it.
162  */
163 static NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject,IN PUNICODE_STRING RegistryPath)
164 {
165 static IO_SCSI_CAPABILITIES PortCapabilities;   /* it is const filled in DriverEntry() */
166 PDEVICE_OBJECT DeviceObject;
167 PDEVICE_EXTENSION DeviceExtension;
168 NTSTATUS err;
169
170         g_return_val_if_fail(DriverObject!=NULL,STATUS_INVALID_PARAMETER);
171         g_return_val_if_fail(RegistryPath!=NULL,STATUS_INVALID_PARAMETER);
172
173         err=IoCreateDevice(
174                         DriverObject,   /* DriverObject */
175                         sizeof(DEVICE_EXTENSION),       /* DeviceExtensionSize; additional storage not used */
176                         captive_utf8_to_UnicodeString_alloca("\\Device\\CdRom0"),       /* DeviceName */
177                         FILE_DEVICE_CD_ROM,     /* DeviceType */
178                         FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE,     /* DeviceCharacteristics */
179                         FALSE,  /* Exclusive */
180                         &DeviceObject); /* DeviceObject */
181         g_return_val_if_fail(NT_SUCCESS(err),FALSE);
182
183         /* CdromClassCreateDeviceObject() sets:
184          *      DeviceObject->Flags|=DO_DIRECT_IO;
185          * but do we need it?
186          */
187         /* should be left from IoCreateDevice(DeviceCharacteristics) above: */
188         g_assert(DeviceObject->Characteristics & FILE_REMOVABLE_MEDIA);
189         /* ignored: DeviceObject->StackSize */
190         /* ignored: DeviceObject->AlignmentRequirement */
191
192         /* from reactos/drivers/storage/scsiport/scsiport.c/ScsiPortCreatePortDevice() */
193         PortCapabilities.Length=sizeof(PortCapabilities);
194         PortCapabilities.MaximumTransferLength=0x10000; /* 64KB */
195         g_assert((PortCapabilities.MaximumTransferLength%PAGE_SIZE)==0);
196         PortCapabilities.MaximumPhysicalPages=PortCapabilities.MaximumTransferLength/PAGE_SIZE;
197         PortCapabilities.SupportedAsynchronousEvents=0;
198         PortCapabilities.AlignmentMask=1;       /* no alignment required by us; speced as "integer multiple" */
199         PortCapabilities.TaggedQueuing=FALSE;
200         PortCapabilities.AdapterScansDown=FALSE;
201         PortCapabilities.AdapterUsesPio=TRUE;
202
203         DeviceExtension=DeviceObject->DeviceExtension;
204         DeviceExtension->MediaChangeCount=0;
205         DeviceExtension->PhysicalDevice=DeviceObject;   /* no real PhysicalDeviceObject */
206         DeviceExtension->LockCount=0;
207         DeviceExtension->DeviceNumber=0;        /* corresponds to the # in "\\Device\\CdRom0" */
208         /* ignored DeviceExtension->PortDeviceObject
209          * as we are the final driver and we don't have any PortDeviceObject
210          */
211         DeviceExtension->PortCapabilities=&PortCapabilities;
212         DeviceExtension->StartingOffset.QuadPart=0;
213         DeviceExtension->PartitionLength.QuadPart=Image_size;
214         DeviceExtension->PortNumber=0;
215         DeviceExtension->PathId=0;
216         DeviceExtension->TargetId=0;
217         DeviceExtension->Lun=0;
218
219         cdrom_DiskGeometry.MediaType=RemovableMedia;
220         cdrom_DiskGeometry.TracksPerCylinder=64;
221         cdrom_DiskGeometry.SectorsPerTrack=32;
222         cdrom_DiskGeometry.BytesPerSector=2048;
223         cdrom_DiskGeometry.Cylinders.QuadPart=Image_size
224                         /cdrom_DiskGeometry.BytesPerSector
225                         /cdrom_DiskGeometry.SectorsPerTrack
226                         /cdrom_DiskGeometry.TracksPerCylinder;
227         /* 'DeviceExtension->DiskGeometry' is NULL! */
228         cdrom_DiskGeometry_check=cdrom_DiskGeometry;    /* for g_assert() checking against foreign modifications */
229         DeviceExtension->DiskGeometry=&cdrom_DiskGeometry;
230
231         DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL]=MajorFunction_DEVICE_CONTROL;
232
233         return STATUS_SUCCESS;
234 }
235
236 /**
237  * captive_cdrom_init:
238  * @image_pathname: Host OS file #utf8 pathname of the disk image to provide.
239  * %NULL value is forbidden.
240  *
241  * Creates system device "\Device\CdRom%d" providing readonly access
242  * to the given @image_pathname as emulation of CD-ROM driver.
243  *
244  * captive currently supports just one drive and thus "\Device\CdRom0"
245  * is always created. It is forbidden to call this function twice.
246  *
247  * Returns: %TRUE if the initialization was successful.
248  */
249 gboolean captive_cdrom_init(const gchar *image_pathname)
250 {
251 NTSTATUS err;
252
253         g_return_val_if_fail(image_pathname!=NULL,FALSE);
254
255         Image_fd=open(image_pathname,O_RDONLY
256 #ifdef O_BINARY
257                         |O_BINARY
258 #endif
259                         );      /* FIXME: lseek64() */
260         g_return_val_if_fail(Image_fd!=-1,FALSE);
261
262         Image_size=lseek(Image_fd,0,SEEK_END);  /* FIXME: lseek64() */
263         if (Image_size==(off_t)-1) {
264                 g_assert_not_reached();
265                 goto err_close;
266                 }
267
268         err=DriverEntry(
269                         &cdrom_DriverObject,    /* DriverEntry_DriverObject */
270                         captive_utf8_to_UnicodeString_alloca("\\captive\\storage\\cdrom"));     /* DriverEntry_RegistryPath; ignored */
271         g_return_val_if_fail(NT_SUCCESS(err),FALSE);
272
273         return TRUE;
274
275 err_close:
276         close(Image_fd);
277         Image_fd=-1;
278 /* err: */
279         g_return_val_if_reached(FALSE);
280 }