#ifdef ALLOC_PRAGMA
-// Make the initialization routines discardable, so that they
+// Make the initialization routines discardable, so that they
// don't waste space
#pragma alloc_text(init, DriverEntry)
NTSTATUS
STDCALL
ACPIDispatchDeviceControl(
- IN PDEVICE_OBJECT DeviceObject,
- IN PIRP Irp)
+ IN PDEVICE_OBJECT DeviceObject,
+ IN PIRP Irp)
{
PIO_STACK_LOCATION IrpSp;
NTSTATUS Status;
* -------------
* Either fixed-feature or generic (namespace) types.
*/
- if (strncmp(device->id.hid, BN_HID_POWER_BUTTON,
+ if (strncmp(device->id.hid, BN_HID_POWER_BUTTON,
sizeof(BM_DEVICE_HID)) == 0) {
if (device->id.type == BM_TYPE_FIXED_BUTTON) {
/* Register for fixed-feature events. */
status = acpi_install_fixed_event_handler(
- ACPI_EVENT_POWER_BUTTON, bn_notify_fixed,
+ ACPI_EVENT_POWER_BUTTON, bn_notify_fixed,
(void*)button);
}
else {
* -------------
* Either fixed-feature or generic (namespace) types.
*/
- else if (strncmp( device->id.hid, BN_HID_SLEEP_BUTTON,
+ else if (strncmp( device->id.hid, BN_HID_SLEEP_BUTTON,
sizeof(BM_DEVICE_HID)) == 0) {
if (device->id.type == BM_TYPE_FIXED_BUTTON) {
/* Register for fixed-feature events. */
status = acpi_install_fixed_event_handler(
- ACPI_EVENT_SLEEP_BUTTON, bn_notify_fixed,
+ ACPI_EVENT_SLEEP_BUTTON, bn_notify_fixed,
(void*)button);
}
else {
* LID Switch?
* -----------
*/
- else if (strncmp( device->id.hid, BN_HID_LID_SWITCH,
+ else if (strncmp( device->id.hid, BN_HID_LID_SWITCH,
sizeof(BM_DEVICE_HID)) == 0) {
button->type = BN_TYPE_LID_SWITCH;
*/
MEMCPY(criteria.hid, BN_HID_LID_SWITCH, sizeof(BN_HID_LID_SWITCH));
status = bm_register_driver(&criteria, &driver);
-
+
if (status == AE_NOT_FOUND)
status = AE_OK;
case BN_TYPE_POWER_BUTTON_FIXED:
DEBUG_PRINT(ACPI_INFO, ("Fixed-feature button status change event detected.\n"));
- /*bm_generate_event(button->device_handle, BN_PROC_ROOT,
+ /*bm_generate_event(button->device_handle, BN_PROC_ROOT,
BN_PROC_POWER_BUTTON, BN_NOTIFY_STATUS_CHANGE, 0);*/
break;
case BN_TYPE_SLEEP_BUTTON_FIXED:
DEBUG_PRINT(ACPI_INFO, ("Fixed-feature button status change event detected.\n"));
- /*bm_generate_event(button->device_handle, BN_PROC_ROOT,
+ /*bm_generate_event(button->device_handle, BN_PROC_ROOT,
BN_PROC_SLEEP_BUTTON, BN_NOTIFY_STATUS_CHANGE, 0);*/
break;
case BM_NOTIFY_DEVICE_ADDED:
status = bn_add_device(device_handle, context);
break;
-
+
case BM_NOTIFY_DEVICE_REMOVED:
status = bn_remove_device(context);
break;
-
+
case BN_NOTIFY_STATUS_CHANGE:
DEBUG_PRINT(ACPI_INFO, ("Button status change event detected.\n"));
case BN_TYPE_POWER_BUTTON:
case BN_TYPE_POWER_BUTTON_FIXED:
- /*bm_generate_event(device_handle, BN_PROC_ROOT,
+ /*bm_generate_event(device_handle, BN_PROC_ROOT,
BN_PROC_POWER_BUTTON, notify_type, 0);*/
break;
* Evaluate _STA:
* --------------
*/
- status = bm_evaluate_simple_integer(device->acpi_handle, "_STA",
+ status = bm_evaluate_simple_integer(device->acpi_handle, "_STA",
&(device->status));
return status;
}
if (info.valid & ACPI_VALID_UID) {
- MEMCPY((void*)device->id.uid, (void*)info.unique_id,
+ MEMCPY((void*)device->id.uid, (void*)info.unique_id,
sizeof(BM_DEVICE_UID));
}
if (info.valid & ACPI_VALID_HID) {
- MEMCPY((void*)device->id.hid, (void*)info.hardware_id,
+ MEMCPY((void*)device->id.hid, (void*)info.hardware_id,
sizeof(BM_DEVICE_HID));
}
/*
* Presence of _DCK indicates a docking station.
*/
- if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
+ if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
"_DCK", &acpi_handle))) {
device->flags |= BM_FLAGS_DOCKING_STATION;
}
* Presence of _EJD and/or _EJx indicates 'ejectable'.
* TODO: _EJx...
*/
- if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
+ if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
"_EJD", &acpi_handle))) {
device->flags |= BM_FLAGS_EJECTABLE;
}
/*
* Presence of _PR0 or _PS0 indicates 'power manageable'.
*/
- if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
+ if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
"_PR0", &acpi_handle)) ||
- ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
+ ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
"_PS0", &acpi_handle))) {
device->flags |= BM_FLAGS_POWER_CONTROL;
}
/*
* Presence of _CRS indicates 'configurable'.
*/
- if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
+ if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
"_CRS", &acpi_handle))) {
device->flags |= BM_FLAGS_CONFIGURABLE;
}
/*
* Presence of _HID or _ADR indicates 'identifiable'.
*/
- if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
+ if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
"_HID", &acpi_handle)) ||
- ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
+ ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
"_ADR", &acpi_handle))) {
device->flags |= BM_FLAGS_IDENTIFIABLE;
}
/*
* Presence of _STA indicates 'dynamic status'.
*/
- if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
+ if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle,
"_STA", &acpi_handle))) {
device->flags |= BM_FLAGS_DYNAMIC_STATUS;
}
/*
* Device Type:
* ------------
- */
+ */
switch (acpi_type) {
case INTERNAL_TYPE_SCOPE:
device->id.type = BM_TYPE_SCOPE;
/*
* Power Management:
* -----------------
- * If this node doesn't provide direct power control
+ * If this node doesn't provide direct power control
* then we inherit PM capabilities from its parent.
*
* TODO: Inherit!
if (ACPI_SUCCESS(status)) {
/*
- * TODO: This is a hack to get around the problem
- * identifying scope objects. Scopes
+ * TODO: This is a hack to get around the problem
+ * identifying scope objects. Scopes
* somehow need to be uniquely identified.
*/
status = acpi_get_type(child_handle, &acpi_type);
else {
level--;
child_handle = parent_handle;
- acpi_get_parent(parent_handle,
+ acpi_get_parent(parent_handle,
&parent_handle);
if (parent) {
node->device.acpi_handle = ACPI_ROOT_OBJECT;
node->device.id.type = BM_TYPE_FIXED_BUTTON;
if (device_hid) {
- MEMCPY((void*)node->device.id.hid, device_hid,
+ MEMCPY((void*)node->device.id.hid, device_hid,
sizeof(node->device.id.hid));
}
node->device.flags = BM_FLAGS_FIXED_FEATURE;
*/
DEBUG_PRINT(ACPI_INFO, ("Registering for all device notifications.\n"));
- status = acpi_install_notify_handler(ACPI_ROOT_OBJECT,
+ status = acpi_install_notify_handler(ACPI_ROOT_OBJECT,
ACPI_SYSTEM_NOTIFY, &bm_notify, NULL);
if (ACPI_FAILURE(status)) {
DEBUG_PRINT(ACPI_ERROR, ("Unable to register for standard notifications.\n"));
return_ACPI_STATUS(status);
}
- status = acpi_install_notify_handler(ACPI_ROOT_OBJECT,
+ status = acpi_install_notify_handler(ACPI_ROOT_OBJECT,
ACPI_DEVICE_NOTIFY, &bm_notify, NULL);
if (ACPI_FAILURE(status)) {
DEBUG_PRINT(ACPI_ERROR, ("Unable to register for device-specific notifications.\n"));
DEBUG_PRINT(ACPI_INFO, ("Unregistering for device notifications.\n"));
- status = acpi_remove_notify_handler(ACPI_ROOT_OBJECT,
+ status = acpi_remove_notify_handler(ACPI_ROOT_OBJECT,
ACPI_SYSTEM_NOTIFY, &bm_notify);
if (ACPI_FAILURE(status)) {
DEBUG_PRINT(ACPI_ERROR, ("Unable to un-register for standard notifications.\n"));
}
- status = acpi_remove_notify_handler(ACPI_ROOT_OBJECT,
+ status = acpi_remove_notify_handler(ACPI_ROOT_OBJECT,
ACPI_DEVICE_NOTIFY, &bm_notify);
if (ACPI_FAILURE(status)) {
DEBUG_PRINT(ACPI_ERROR, ("Unable to un-register for device-specific notifications.\n"));
DEBUG_PRINT(ACPI_INFO, ("Sending notify [0x%02x] to device [0x%02x].\n", notify_type, node->device.handle));
- if (!(node->device.flags & BM_FLAGS_DRIVER_CONTROL) ||
+ if (!(node->device.flags & BM_FLAGS_DRIVER_CONTROL) ||
!(node->driver.notify)) {
DEBUG_PRINT(ACPI_WARN, ("No driver installed for device [0x%02x].\n", node->device.handle));
return_ACPI_STATUS(AE_NOT_EXIST);
}
- status = node->driver.notify(notify_type, node->device.handle,
+ status = node->driver.notify(notify_type, node->device.handle,
&(node->driver.context));
return_ACPI_STATUS(status);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
-
+
if (old_status == node->device.status) {
return_ACPI_STATUS(AE_OK);
}
if (status_change) {
*status_change = TRUE;
}
-
+
/*
* Device Insertion?
* -----------------
*/
- if ((device->status & BM_STATUS_PRESENT) &&
+ if ((device->status & BM_STATUS_PRESENT) &&
!(old_status & BM_STATUS_PRESENT)) {
/* TODO: Make sure driver is loaded, and if not, load. */
status = bm_generate_notify(node, BM_NOTIFY_DEVICE_ADDED);
* Device Removal?
* ---------------
*/
- else if (!(device->status & BM_STATUS_PRESENT) &&
+ else if (!(device->status & BM_STATUS_PRESENT) &&
(old_status & BM_STATUS_PRESENT)) {
/* TODO: Unload driver if last device instance. */
status = bm_generate_notify(node, BM_NOTIFY_DEVICE_REMOVED);
/*
* Device-Specific or Standard?
* ----------------------------
- * Device-specific notifies are forwarded to the control module's
+ * Device-specific notifies are forwarded to the control module's
* notify() function for processing. Standard notifies are handled
* internally.
*/
/*
* Calculate Power State:
* ----------------------
- * Try to infer the devices's power state by checking the state of
- * the devices's power resources. We start by evaluating _PR0
- * (resource requirements at D0) and work through _PR1 and _PR2.
- * We know the current devices power state when all resources (for
- * a give Dx state) are ON. If no power resources are on then the
+ * Try to infer the devices's power state by checking the state of
+ * the devices's power resources. We start by evaluating _PR0
+ * (resource requirements at D0) and work through _PR1 and _PR2.
+ * We know the current devices power state when all resources (for
+ * a give Dx state) are ON. If no power resources are on then the
* device is assumed to be off (D3).
*/
for (i=ACPI_STATE_D0; i<ACPI_STATE_D3; i++) {
- status = bm_evaluate_reference_list(device->acpi_handle,
+ status = bm_evaluate_reference_list(device->acpi_handle,
object_name, &pr_list);
if (ACPI_SUCCESS(status)) {
- status = bm_pr_list_get_state(&pr_list,
+ status = bm_pr_list_get_state(&pr_list,
&list_state);
if (ACPI_SUCCESS(status)) {
device->power.state = ACPI_STATE_UNKNOWN;
if (device->flags & BM_FLAGS_POWER_STATE) {
- status = bm_evaluate_simple_integer(device->acpi_handle,
+ status = bm_evaluate_simple_integer(device->acpi_handle,
"_PSC", &(device->power.state));
}
else {
/*
* Get Resources:
* --------------
- * Get the power resources associated with the device's current
+ * Get the power resources associated with the device's current
* and target power states.
*/
if (device->power.state != ACPI_STATE_UNKNOWN) {
object_name[3] = '0' + device->power.state;
- bm_evaluate_reference_list(device->acpi_handle,
+ bm_evaluate_reference_list(device->acpi_handle,
object_name, ¤t_list);
}
object_name[3] = '0' + state;
- bm_evaluate_reference_list(device->acpi_handle, object_name,
+ bm_evaluate_reference_list(device->acpi_handle, object_name,
&target_list);
/*
* Transition Resources:
* ---------------------
- * Transition all power resources referenced by this device to
- * the correct power state (taking into consideration sequencing
+ * Transition all power resources referenced by this device to
+ * the correct power state (taking into consideration sequencing
* and dependencies to other devices).
*/
if (current_list.count || target_list.count) {
/*
* Execute _PSx:
* -------------
- * Execute the _PSx method corresponding to the target Dx state,
+ * Execute the _PSx method corresponding to the target Dx state,
* if it exists.
*/
object_name[2] = 'S';
* Power Management Flags:
* -----------------------
*/
- if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PSC",
+ if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PSC",
&acpi_handle))) {
device->power.flags |= BM_FLAGS_POWER_STATE;
}
- if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_IRC",
+ if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_IRC",
&acpi_handle))) {
device->power.flags |= BM_FLAGS_INRUSH_CURRENT;
}
- if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PRW",
+ if (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PRW",
&acpi_handle))) {
device->power.flags |= BM_FLAGS_WAKE_CAPABLE;
}
* Figure out which Dx states are supported by this device for the
* S0 (working) state. Note that D0 and D3 are required (assumed).
*/
- device->power.dx_supported[ACPI_STATE_S0] = BM_FLAGS_D0_SUPPORT |
+ device->power.dx_supported[ACPI_STATE_S0] = BM_FLAGS_D0_SUPPORT |
BM_FLAGS_D3_SUPPORT;
- if ((ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PR1",
- &acpi_handle))) ||
- (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PS1",
+ if ((ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PR1",
+ &acpi_handle))) ||
+ (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PS1",
&acpi_handle)))) {
- device->power.dx_supported[ACPI_STATE_S0] |=
+ device->power.dx_supported[ACPI_STATE_S0] |=
BM_FLAGS_D1_SUPPORT;
}
- if ((ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PR2",
- &acpi_handle))) ||
- (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PS2",
+ if ((ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PR2",
+ &acpi_handle))) ||
+ (ACPI_SUCCESS(acpi_get_handle(device->acpi_handle, "_PS2",
&acpi_handle)))) {
- device->power.dx_supported[ACPI_STATE_S0] |=
+ device->power.dx_supported[ACPI_STATE_S0] |=
BM_FLAGS_D2_SUPPORT;
}
/*
* Evalute _SxD:
* -------------
- * Which returns the highest (power) Dx state supported in
- * this system (Sx) state. We convert this value to a bit
+ * Which returns the highest (power) Dx state supported in
+ * this system (Sx) state. We convert this value to a bit
* mask of supported states (conceptually simpler).
*/
- status = bm_evaluate_simple_integer(device->acpi_handle,
+ status = bm_evaluate_simple_integer(device->acpi_handle,
object_name, &dx_supported);
if (ACPI_SUCCESS(status)) {
switch (dx_supported) {
case 0:
- device->power.dx_supported[i] |=
+ device->power.dx_supported[i] |=
BM_FLAGS_D0_SUPPORT;
/* fall through */
case 1:
- device->power.dx_supported[i] |=
+ device->power.dx_supported[i] |=
BM_FLAGS_D1_SUPPORT;
/* fall through */
case 2:
- device->power.dx_supported[i] |=
+ device->power.dx_supported[i] |=
BM_FLAGS_D2_SUPPORT;
/* fall through */
case 3:
- device->power.dx_supported[i] |=
+ device->power.dx_supported[i] |=
BM_FLAGS_D3_SUPPORT;
break;
}
/*
* Validate:
* ---------
- * Mask of any states that _Sx_d falsely advertises
- * (e.g.claims D1 support but neither _PR2 or _PS2
- * exist). In other words, S1-S5 can't offer a Dx
+ * Mask of any states that _Sx_d falsely advertises
+ * (e.g.claims D1 support but neither _PR2 or _PS2
+ * exist). In other words, S1-S5 can't offer a Dx
* state that isn't supported by S0.
*/
- device->power.dx_supported[i] &=
+ device->power.dx_supported[i] &=
device->power.dx_supported[ACPI_STATE_S0];
}
* TODO:
* -----
* 1. Sequencing of power resource list transitions.
- * 2. Global serialization of power resource transtions (see ACPI
+ * 2. Global serialization of power resource transtions (see ACPI
* spec section 7.1.2/7.1.3).
* 3. Better error handling.
*/
BM_NOTIFY notify_type,
BM_HANDLE device_handle,
void **context);
-
+
ACPI_STATUS
bm_pr_request (
BM_REQUEST *request,
void *context);
-
+
/****************************************************************************
* Internal Functions
****************************************************************************/
pr->state = ACPI_STATE_UNKNOWN;
- /*
+ /*
* Evaluate _STA:
* --------------
* Evalute _STA to determine whether the power resource is ON or OFF.
}
/*
- * Mask off all bits but the first as some systems return non-standard
+ * Mask off all bits but the first as some systems return non-standard
* values (e.g. 0x51).
*/
switch (device_status & 0x01) {
* -----------------------------
* The current state of a list of power resources is ON if all
* power resources are currently in the ON state. In other words,
- * if any power resource in the list is OFF then the collection
+ * if any power resource in the list is OFF then the collection
* isn't fully ON.
*/
for (i = 0; i < pr_list->count; i++) {
/*
* Reference Target:
* -----------------
- * Reference all resources for the target power state first (so
- * the device doesn't get turned off while transitioning). Power
+ * Reference all resources for the target power state first (so
+ * the device doesn't get turned off while transitioning). Power
* resources that aren't on (new reference count of 1) are turned on.
*/
for (i = 0; i < target_list->count; i++) {
- status = bm_get_device_context(target_list->handles[i],
+ status = bm_get_device_context(target_list->handles[i],
(BM_DRIVER_CONTEXT*)(&pr));
if (ACPI_FAILURE(status)) {
DEBUG_PRINT(ACPI_WARN, ("Invalid reference to power resource [0x%02X].\n", target_list->handles[i]));
* Dereference Current:
* --------------------
* Dereference all resources for the current power state. Power
- * resources no longer referenced (new reference count of 0) are
+ * resources no longer referenced (new reference count of 0) are
* turned off.
*/
for (i = 0; i < current_list->count; i++) {
- status = bm_get_device_context(current_list->handles[i],
+ status = bm_get_device_context(current_list->handles[i],
(BM_DRIVER_CONTEXT*)(&pr));
if (ACPI_FAILURE(status)) {
DEBUG_PRINT(ACPI_WARN, ("Invalid reference to power resource [0x%02X].\n", target_list->handles[i]));
pr->device_handle = device->handle;
pr->acpi_handle = device->acpi_handle;
- /*
+ /*
* Get information on this power resource.
*/
status = acpi_evaluate_object(pr->acpi_handle, NULL, NULL, &buffer);
DEBUG_PRINT(ACPI_INFO, ("Sending request [0x%02x] to device [0x%02x].\n", request->command, node->device.handle));
- if (!(node->device.flags & BM_FLAGS_DRIVER_CONTROL) ||
+ if (!(node->device.flags & BM_FLAGS_DRIVER_CONTROL) ||
!(node->driver.request)) {
DEBUG_PRINT(ACPI_WARN, ("No driver installed for device [0x%02x].\n", node->device.handle));
return_ACPI_STATUS(AE_NOT_EXIST);
if (ACPI_FAILURE(status)) {
break;
}
- status = bm_copy_to_buffer(&(request->buffer),
+ status = bm_copy_to_buffer(&(request->buffer),
&(device->power.state), sizeof(BM_POWER_STATE));
break;
{
BM_POWER_STATE *power_state = NULL;
- status = bm_cast_buffer(&(request->buffer),
+ status = bm_cast_buffer(&(request->buffer),
(void**)&power_state, sizeof(BM_POWER_STATE));
if (ACPI_FAILURE(status)) {
break;
return AE_BAD_PARAMETER;
}
- /*
+ /*
* Present?
* --------
* We're only going to match on devices that are present.
return AE_NOT_FOUND;
}
- /*
+ /*
* type?
*/
if (criteria->type && !(criteria->type & device->id.type)) {
return AE_NOT_FOUND;
}
- /*
+ /*
* hid?
*/
- if ((criteria->hid[0]) && (0 != STRNCMP(criteria->hid,
+ if ((criteria->hid[0]) && (0 != STRNCMP(criteria->hid,
device->id.hid, sizeof(BM_DEVICE_HID)))) {
return AE_NOT_FOUND;
}
- /*
+ /*
* adr?
*/
if ((criteria->adr) && (criteria->adr != device->id.adr)) {
if (node->scope.head) {
status = bm_compare(&(node->device), criteria);
if (ACPI_SUCCESS(status)) {
- results->handles[results->count++] =
+ results->handles[results->count++] =
node->device.handle;
}
node = node->scope.head;
else {
status = bm_compare(&(node->device), criteria);
if (ACPI_SUCCESS(status)) {
- results->handles[results->count++] =
+ results->handles[results->count++] =
node->device.handle;
}
/*
* Locate Next Device:
* -------------------
- * The next node is either a peer at this level
- * (node->next is valid), or we work are way back
- * up the tree until we either find a non-parsed
+ * The next node is either a peer at this level
+ * (node->next is valid), or we work are way back
+ * up the tree until we either find a non-parsed
* peer or hit the top (node->parent is NULL).
*/
while (!node->next && node->parent) {
if (!package || (package->type != ACPI_TYPE_PACKAGE) ||
(package->package.count == 0) || !package_format ||
- (package_format->length < 1) ||
+ (package_format->length < 1) ||
(!package_format->pointer) || !buffer) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
tail_offset += sizeof(ACPI_INTEGER);
break;
case 'S':
- size_required += sizeof(u8*) +
+ size_required += sizeof(u8*) +
sizeof(ACPI_INTEGER) + 1;
tail_offset += sizeof(ACPI_INTEGER);
break;
case ACPI_TYPE_BUFFER:
switch (format[i]) {
case 'S':
- size_required += sizeof(u8*) +
+ size_required += sizeof(u8*) +
element->string.length + 1;
tail_offset += sizeof(u8*);
break;
case 'B':
- size_required += sizeof(u8*) +
+ size_required += sizeof(u8*) +
element->buffer.length;
tail_offset += sizeof(u8*);
break;
case ACPI_TYPE_INTEGER:
switch (format[i]) {
case 'N':
- *((ACPI_INTEGER*)head) =
+ *((ACPI_INTEGER*)head) =
element->integer.value;
head += sizeof(ACPI_INTEGER);
break;
case 'S':
pointer = (u8**)head;
*pointer = tail;
- *((ACPI_INTEGER*)tail) =
+ *((ACPI_INTEGER*)tail) =
element->integer.value;
head += sizeof(ACPI_INTEGER*);
tail += sizeof(ACPI_INTEGER);
case 'S':
pointer = (u8**)head;
*pointer = tail;
- memcpy(tail, element->string.pointer,
+ memcpy(tail, element->string.pointer,
element->string.length);
head += sizeof(u8*);
tail += element->string.length;
case 'B':
pointer = (u8**)head;
*pointer = tail;
- memcpy(tail, element->buffer.pointer,
+ memcpy(tail, element->buffer.pointer,
element->buffer.length);
head += sizeof(u8*);
tail += element->buffer.length;
* PARAMETERS: <TBD>
*
* RETURN: AE_OK
- * AE_BUFFER_OVERFLOW Evaluated object returned data, but
+ * AE_BUFFER_OVERFLOW Evaluated object returned data, but
* caller did not provide buffer.
*
* DESCRIPTION: Helper for acpi_evaluate_object that handles buffer
- * allocation. Note that the caller is responsible for
+ * allocation. Note that the caller is responsible for
* freeing buffer->pointer!
*
****************************************************************************/
/*
* Evalute Object:
* ---------------
- * The first attempt is just to get the size of the object data
- * (that is unless there's no return data, e.g. _INI); the second
+ * The first attempt is just to get the size of the object data
+ * (that is unless there's no return data, e.g. _INI); the second
* gets the data.
*/
status = acpi_evaluate_object(acpi_handle, pathname, arguments, buffer);
}
/* Re-evaluate -- this time it should work */
- status = acpi_evaluate_object(acpi_handle, pathname,
+ status = acpi_evaluate_object(acpi_handle, pathname,
arguments, buffer);
}
if (ACPI_FAILURE(status)) {
DEBUG_EVAL_ERROR(ACPI_WARN, acpi_handle, pathname, status);
if (buffer && buffer->pointer) {
- acpi_os_free(buffer->pointer);
+ acpi_os_free(buffer->pointer);
buffer->pointer = NULL;
buffer->length = 0;
}
* Validate Data:
* --------------
*/
- status = bm_cast_buffer(&buffer, (void**)&element,
+ status = bm_cast_buffer(&buffer, (void**)&element,
sizeof(ACPI_OBJECT));
if (ACPI_FAILURE(status)) {
DEBUG_EVAL_ERROR(ACPI_WARN, acpi_handle, pathname, status);
* Validate Package:
* -----------------
*/
- status = bm_cast_buffer(&buffer, (void**)&package,
+ status = bm_cast_buffer(&buffer, (void**)&package,
sizeof(ACPI_OBJECT));
if (ACPI_FAILURE(status)) {
DEBUG_EVAL_ERROR(ACPI_WARN, acpi_handle, pathname, status);
* Resolve reference string (e.g. "\_PR_.CPU_") to an
* ACPI_HANDLE.
*/
- status = acpi_get_handle(acpi_handle,
+ status = acpi_get_handle(acpi_handle,
element->string.pointer, &reference_handle);
if (ACPI_FAILURE(status)) {
status = AE_BAD_DATA;
/*
* Resolve ACPI_HANDLE to BM_HANDLE.
*/
- status = bm_get_handle(reference_handle,
+ status = bm_get_handle(reference_handle,
&(reference_list->handles[i]));
if (ACPI_FAILURE(status)) {
status = AE_BAD_DATA;
if (!BM_NODE_PRESENT(node->parent)) {
return_ACPI_STATUS(AE_OK);
}
-
+
/*
* Dynamic Status?
* ---------------
* Evaluate _STA:
* --------------
*/
- status = bm_evaluate_simple_integer(node->device.acpi_handle, "_STA",
+ status = bm_evaluate_simple_integer(node->device.acpi_handle, "_STA",
&(node->device.status));
if (ACPI_SUCCESS(status)) {
*device_status = node->device.status;
/*
* Install driver:
* ----------------
- * For each match, record the driver information and execute the
+ * For each match, record the driver information and execute the
* driver's Notify() funciton (if present) to notify the driver
* of the device's presence.
*/
DEBUG_PRINT(ACPI_INFO, ("Registering driver for device [0x%02x].\n", node->device.handle));
/* Notify driver of new device. */
- status = driver->notify(BM_NOTIFY_DEVICE_ADDED,
+ status = driver->notify(BM_NOTIFY_DEVICE_ADDED,
node->device.handle, &(node->driver.context));
if (ACPI_SUCCESS(status)) {
node->driver.notify = driver->notify;
DEBUG_PRINT(ACPI_INFO, ("Unregistering driver for device [0x%02x].\n", node->device.handle));
/* Notify driver of device removal. */
- status = node->driver.notify(BM_NOTIFY_DEVICE_REMOVED,
+ status = node->driver.notify(BM_NOTIFY_DEVICE_REMOVED,
node->device.handle, &(node->driver.context));
node->device.flags &= ~BM_FLAGS_DRIVER_CONTROL;
RESOURCE* resource;
ULONG i;
KIRQL Dirql;
-
+
/* Count number of resources */
Done = FALSE;
resource = resources;
}
resource = (RESOURCE *) ((NATIVE_UINT) resource + (NATIVE_UINT) resource->length);
}
-
+
/* Allocate memory */
*ResourceListSize = sizeof(CM_RESOURCE_LIST) + sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR) * (NumberOfResources - 1);
ResourceList = (PCM_RESOURCE_LIST)ExAllocatePool(PagedPool, *ResourceListSize);
ResourceList->List[0].PartialResourceList.Revision = 1;
ResourceList->List[0].PartialResourceList.Count = NumberOfResources;
ResourceDescriptor = ResourceList->List[0].PartialResourceList.PartialDescriptors;
-
+
/* Fill resources list structure */
Done = FALSE;
resource = resources;
for (i = 0; i < irq_data->number_of_interrupts; i++)
{
ResourceDescriptor->Type = CmResourceTypeInterrupt;
-
+
ResourceDescriptor->ShareDisposition =
(irq_data->shared_exclusive == SHARED ? CmResourceShareShared : CmResourceShareDeviceExclusive);
ResourceDescriptor->Flags =
}
resource = (RESOURCE *) ((NATIVE_UINT) resource + (NATIVE_UINT) resource->length);
}
-
+
acpi_rs_dump_resource_list(resource);
return TRUE;
}
#define BM_HID_SLEEP_BUTTON "PNP0C0E"
/*
- * BM_DEVICE_CID:
+ * BM_DEVICE_CID:
* The compatibility ID can be a string with 44 characters
* The extra pad is in case there is a change. It also
* provides 8 byte alignment for the BM_DEVICE_ID structure.
ACPI_STATUS
bm_pr_terminate (void);
-
+
/* bmutils.c */
ACPI_STATUS
* Hardware IDs:
* -------------
* TODO: Power and Sleep button HIDs also exist in <bm.h>. Should all
- * HIDs (ACPI well-known devices) exist in one place (e.g.
+ * HIDs (ACPI well-known devices) exist in one place (e.g.
* acpi_hid.h)?
*/
#define BN_HID_POWER_BUTTON "PNP0C0C"
*virt = MmMapIoSpace(Address, size, MmNonCached);
if (!*virt)
return AE_ERROR;
-
+
return AE_OK;
}
DPRINT("acpi_os_delete_semaphore(handle 0x%X)\n", handle);
- if (!Mutex)
+ if (!Mutex)
return AE_BAD_PARAMETER;
ExFreePool(Mutex);
ACPI_STATUS
acpi_os_signal_semaphore(
- ACPI_HANDLE handle,
+ ACPI_HANDLE handle,
u32 units)
{
PFAST_MUTEX Mutex = (PFAST_MUTEX)handle;
{
PPDO_DEVICE_EXTENSION DeviceExtension;
PCM_RESOURCE_LIST ResourceList;
-
+
DeviceExtension = (PPDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
-
+
if (DeviceExtension->ResourceListSize == 0)
{
return Irp->IoStatus.Status;
}
-
+
ResourceList = ExAllocatePool(PagedPool, DeviceExtension->ResourceListSize);
if (!ResourceList)
{
Irp->IoStatus.Information = 0;
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
RtlCopyMemory(ResourceList, DeviceExtension->ResourceList, DeviceExtension->ResourceListSize);
Irp->IoStatus.Information = (ULONG_PTR)ResourceList;
return STATUS_SUCCESS;
#ifdef ALLOC_PRAGMA
-// Make the initialization routines discardable, so that they
+// Make the initialization routines discardable, so that they
// don't waste space
#pragma alloc_text(init, DriverEntry)
*Size -= size1;
/* Clean whitespace from end of string */
- while ((size1 > 0) && (Buffer[--size1] == ' '))
+ while ((size1 > 0) && (Buffer[--size1] == ' '))
Buffer[size1] = '\0';
DPRINT("ANSI name: %s\n", Buffer);
case ISAPNP_SRIN_CDEVICE_ID:
if ((Size == 4) && (compat < MAX_COMPATIBLE_ID)) {
Peek(tmp, 4);
- LogicalDevice->CVendorId[compat] = UCHAR2USHORT(tmp[0], tmp[1]);
+ LogicalDevice->CVendorId[compat] = UCHAR2USHORT(tmp[0], tmp[1]);
LogicalDevice->CDeviceId[compat] = UCHAR2USHORT(tmp[2], tmp[3]);
compat++;
Size = 0;
size = 0;
}
break;
-
+
case ISAPNP_SRIN_CDEVICE_ID:
/* FIXME: Parse compatible IDs */
break;
DeviceExtension = (PISAPNP_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
if (Irp->IoStatus.Information) {
- /* FIXME: Another bus driver has already created a DEVICE_RELATIONS
+ /* FIXME: Another bus driver has already created a DEVICE_RELATIONS
structure so we must merge this structure with our own */
}
NTSTATUS
STDCALL
DriverEntry(
- IN PDRIVER_OBJECT DriverObject,
+ IN PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING RegistryPath)
{
DbgPrint("ISA Plug and Play Bus Driver\n");
DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
if (Irp->IoStatus.Information) {
- /* FIXME: Another bus driver has already created a DEVICE_RELATIONS
+ /* FIXME: Another bus driver has already created a DEVICE_RELATIONS
structure so we must merge this structure with our own */
}
#ifdef ALLOC_PRAGMA
-// Make the initialization routines discardable, so that they
+// Make the initialization routines discardable, so that they
// don't waste space
#pragma alloc_text(init, DriverEntry)
NTSTATUS
STDCALL
PciDispatchDeviceControl(
- IN PDEVICE_OBJECT DeviceObject,
- IN PIRP Irp)
+ IN PDEVICE_OBJECT DeviceObject,
+ IN PIRP Irp)
{
PIO_STACK_LOCATION IrpSp;
NTSTATUS Status;
#define PCI_STATUS_FAST_BACK 0x80 /* Accept fast-back to back */
#define PCI_STATUS_PARITY 0x100 /* Detected parity error */
#define PCI_STATUS_DEVSEL_MASK 0x600 /* DEVSEL timing */
-#define PCI_STATUS_DEVSEL_FAST 0x000
+#define PCI_STATUS_DEVSEL_FAST 0x000
#define PCI_STATUS_DEVSEL_MEDIUM 0x200
#define PCI_STATUS_DEVSEL_SLOW 0x400
#define PCI_STATUS_SIG_TARGET_ABORT 0x800 /* Set on target abort */
/*
* Base addresses specify locations in memory or I/O space.
- * Decoded size can be determined by writing a value of
- * 0xffffffff to the register, and reading it back. Only
+ * Decoded size can be determined by writing a value of
+ * 0xffffffff to the register, and reading it back. Only
* 1 bits are decoded.
*/
#define PCI_BASE_ADDRESS_0 0x10 /* 32 bits */
/* Header type 0 (normal devices) */
#define PCI_CARDBUS_CIS 0x28
#define PCI_SUBSYSTEM_VENDOR_ID 0x2c
-#define PCI_SUBSYSTEM_ID 0x2e
+#define PCI_SUBSYSTEM_ID 0x2e
#define PCI_ROM_ADDRESS 0x30 /* Bits 31..11 are address, 10..1 reserved */
#define PCI_ROM_ADDRESS_ENABLE 0x01
#define PCI_ROM_ADDRESS_MASK (~0x7ffUL)
if (DeviceCapabilities->Version != 1)
return STATUS_UNSUCCESSFUL;
-
+
DeviceCapabilities->UniqueID = FALSE;
DeviceCapabilities->Address = DeviceExtension->SlotNumber.u.AsULONG;
DeviceCapabilities->UINumber = (ULONG)-1; /* FIXME */
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS Serial enumerator driver
* FILE: drivers/bus/serenum/detect.c
* PURPOSE: Detection of serial devices
- *
+ *
* PROGRAMMERS: Jason Filby (jasonfilby@yahoo.com)
* Filip Navara (xnavara@volny.cz)
* Hervé Poussineau (hpoussin@reactos.com)
PIRP Irp;
IO_STATUS_BLOCK IoStatus;
NTSTATUS Status;
-
+
KeInitializeEvent (&Event, NotificationEvent, FALSE);
-
+
Irp = IoBuildDeviceIoControlRequest(CtlCode,
DeviceObject,
InputBuffer,
DPRINT("Serenum: IoBuildDeviceIoControlRequest() failed\n");
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
Status = IoCallDriver(DeviceObject, Irp);
-
+
if (Status == STATUS_PENDING)
{
DPRINT("Serenum: Operation pending\n");
KeWaitForSingleObject(&Event, Suspended, KernelMode, FALSE, NULL);
Status = IoStatus.Status;
}
-
+
if (OutputBufferSize)
{
*OutputBufferSize = IoStatus.Information;
}
-
+
return Status;
}
KEVENT event;
LARGE_INTEGER zero;
NTSTATUS Status;
-
+
KeInitializeEvent(&event, NotificationEvent, FALSE);
zero.QuadPart = 0;
Irp = IoBuildSynchronousFsdRequest(
&ioStatus);
if (!Irp)
return FALSE;
-
+
Status = IoCallDriver(LowerDevice, Irp);
if (Status == STATUS_PENDING)
{
PPDO_DEVICE_EXTENSION PdoDeviceExtension = NULL;
PFDO_DEVICE_EXTENSION FdoDeviceExtension;
NTSTATUS Status;
-
+
DPRINT("Serenum: SerenumReportDetectedDevice() called with %wZ (%wZ) detected\n", DeviceId, DeviceDescription);
-
+
Status = IoCreateDevice(
DeviceObject->DriverObject,
sizeof(PDO_DEVICE_EXTENSION),
FALSE,
&Pdo);
if (!NT_SUCCESS(Status)) goto ByeBye;
-
+
Pdo->Flags |= DO_BUS_ENUMERATED_DEVICE;
Pdo->Flags |= DO_POWER_PAGABLE;
PdoDeviceExtension = (PPDO_DEVICE_EXTENSION)Pdo->DeviceExtension;
if (!NT_SUCCESS(Status)) goto ByeBye;
Status = SerenumDuplicateUnicodeString(&PdoDeviceExtension->CompatibleIds, CompatibleIds, PagedPool);
if (!NT_SUCCESS(Status)) goto ByeBye;
-
+
/* Device attached to serial port (Pdo) may delegate work to
* serial port stack (Fdo = DeviceObject variable) */
Pdo->StackSize = DeviceObject->StackSize + 1;
-
+
FdoDeviceExtension->AttachedPdo = Pdo;
PdoDeviceExtension->AttachedFdo = DeviceObject;
-
+
Pdo->Flags |= DO_BUFFERED_IO;
Pdo->Flags &= ~DO_DEVICE_INITIALIZING;
-
+
return STATUS_SUCCESS;
ByeBye:
{
KTIMER Timer;
LARGE_INTEGER DueTime;
-
+
DueTime.QuadPart = milliseconds * -10;
KeInitializeTimer(&Timer);
KeSetTimer(&Timer, DueTime, NULL);
SERIAL_TIMEOUTS Timeouts;
SERIALPERF_STATS PerfStats;
NTSTATUS Status;
-
+
/* 1. COM port initialization, check for device enumerate */
CHECKPOINT;
Status = SerenumDeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_DTR,
NULL, 0, &Msr, &Size);
if (!NT_SUCCESS(Status)) return Status;
if ((Msr & SR_MSR_DSR) == 0) goto SerenumDisconnectIdle;
-
+
/* 2. COM port setup, 1st phase */
CHECKPOINT;
BaudRate = SERIAL_BAUD_1200;
NULL, 0, NULL, NULL);
if (!NT_SUCCESS(Status)) return Status;
SerenumWait(200);
-
+
/* 3. Wait for response, 1st phase */
CHECKPOINT;
Status = SerenumDeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_RTS,
Status = ReadBytes(LowerDevice, Buffer, sizeof(Buffer), &Size);
if (!NT_SUCCESS(Status)) return Status;
if (Size != 0) goto SerenumCollectPnpComDeviceId;
-
+
/* 4. COM port setup, 2nd phase */
CHECKPOINT;
Status = SerenumDeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_DTR,
&Purge, 0, NULL, NULL);
if (!NT_SUCCESS(Status)) return Status;
SerenumWait(200);
-
+
/* 5. Wait for response, 2nd phase */
CHECKPOINT;
Status = SerenumDeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_DTR,
NULL, 0, &Msr, &Size);
if (!NT_SUCCESS(Status)) return Status;
if ((Msr & SR_MSR_DSR) == 0) goto SerenumVerifyDisconnect; else goto SerenumConnectIdle;
-
+
/* 6. Collect PnP COM device ID */
SerenumCollectPnpComDeviceId:
CHECKPOINT;
NULL, 0, &Msr, &Size);
if (!NT_SUCCESS(Status)) return Status;
if ((Msr & SR_MSR_DSR) == 0) goto SerenumVerifyDisconnect;
-
+
/* 7. Verify disconnect */
SerenumVerifyDisconnect:
CHECKPOINT;
if (!NT_SUCCESS(Status)) return Status;
SerenumWait(5000);
goto SerenumDisconnectIdle;
-
+
/* 8. Connect idle */
SerenumConnectIdle:
CHECKPOINT;
return STATUS_DEVICE_NOT_CONNECTED;
else
return STATUS_SUCCESS;
-
+
/* 9. Disconnect idle */
SerenumDisconnectIdle:
CHECKPOINT;
UNICODE_STRING HardwareIds;
UNICODE_STRING CompatibleIds;
NTSTATUS Status;
-
+
DPRINT("Serenum: SerenumDetectLegacyDevice(DeviceObject %p, LowerDevice %p)\n",
DeviceObject,
LowerDevice);
-
+
RtlZeroMemory(Buffer, sizeof(Buffer));
-
+
/* Reset UART */
CHECKPOINT;
Mcr = 0; /* MCR: DTR/RTS/OUT2 off */
Status = SerenumDeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_MODEM_CONTROL,
- &Mcr, sizeof(Mcr), NULL, NULL);
+ &Mcr, sizeof(Mcr), NULL, NULL);
if (!NT_SUCCESS(Status)) return Status;
-
+
/* Set communications parameters */
CHECKPOINT;
/* DLAB off */
Status = SerenumDeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_LINE_CONTROL,
&LCR, sizeof(LCR), NULL, NULL);
if (!NT_SUCCESS(Status)) return Status;
-
+
/* Flush receive buffer */
CHECKPOINT;
Command = SERIAL_PURGE_RXCLEAR;
if (!NT_SUCCESS(Status)) return Status;
/* Wait 100 ms */
SerenumWait(100);
-
+
/* Enable DTR/RTS */
CHECKPOINT;
Status = SerenumDeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_DTR,
Status = SerenumDeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_RTS,
NULL, 0, NULL, NULL);
if (!NT_SUCCESS(Status)) return Status;
-
+
/* Set timeout to 500 microseconds */
CHECKPOINT;
Timeouts.ReadIntervalTimeout = 100;
Status = SerenumDeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_TIMEOUTS,
&Timeouts, sizeof(Timeouts), NULL, NULL);
if (!NT_SUCCESS(Status)) return Status;
-
+
/* Fill the read buffer */
CHECKPOINT;
Status = ReadBytes(LowerDevice, Buffer, sizeof(Buffer)/sizeof(Buffer[0]), &Count);
if (!NT_SUCCESS(Status)) return Status;
-
+
for (i = 0; i < Count; i++)
{
if (Buffer[i] == 'B')
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS Serial enumerator driver
* FILE: drivers/bus/serenum/fdo.c
* PURPOSE: IRP_MJ_PNP operations for FDOs
- *
+ *
* PROGRAMMERS: Hervé Poussineau (hpoussin@reactos.com)
*/
PDEVICE_OBJECT Fdo;
PFDO_DEVICE_EXTENSION DeviceExtension;
NTSTATUS Status;
-
+
DPRINT("Serenum: SerenumAddDevice called. Pdo = %p\n", Pdo);
-
+
/* Create new device object */
Status = IoCreateDevice(DriverObject,
sizeof(FDO_DEVICE_EXTENSION),
}
DeviceExtension = (PFDO_DEVICE_EXTENSION)Fdo->DeviceExtension;
RtlZeroMemory(DeviceExtension, sizeof(FDO_DEVICE_EXTENSION));
-
+
/* Register device interface */
Status = IoRegisterDeviceInterface(
Pdo,
IoDeleteDevice(Fdo);
return Status;
}
-
+
DeviceExtension->Common.IsFDO = TRUE;
DeviceExtension->Common.PnpState = dsStopped;
DeviceExtension->Pdo = Pdo;
}
Fdo->Flags |= DO_BUFFERED_IO;
Fdo->Flags &= ~DO_DEVICE_INITIALIZING;
-
+
return STATUS_SUCCESS;
}
{
PFDO_DEVICE_EXTENSION DeviceExtension;
NTSTATUS Status;
-
+
DPRINT("Serenum: SerenumFdoStartDevice() called\n");
DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
-
+
ASSERT(DeviceExtension->Common.PnpState == dsStopped);
-
+
Status = IoSetDeviceInterfaceState(&DeviceExtension->SerenumInterfaceName, TRUE);
if (!NT_SUCCESS(Status))
{
DPRINT("Serenum: IoSetDeviceInterfaceState() failed with status 0x%08lx\n", Status);
return Status;
}
-
+
DeviceExtension->Common.PnpState = dsStarted;
-
+
return STATUS_SUCCESS;
}
ULONG NumPDO;
ULONG i;
NTSTATUS Status = STATUS_SUCCESS;
-
+
DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
ASSERT(DeviceExtension->Common.IsFDO);
-
+
/* Do enumeration if needed */
if (!(DeviceExtension->Flags & FLAG_ENUMERATION_DONE))
{
DeviceExtension->Flags |= FLAG_ENUMERATION_DONE;
}
NumPDO = (DeviceExtension->AttachedPdo != NULL ? 1 : 0);
-
+
DeviceRelations = (PDEVICE_RELATIONS)ExAllocatePoolWithTag(
PagedPool,
sizeof(DEVICE_RELATIONS) + sizeof(PDEVICE_OBJECT) * (NumPDO - 1),
SERENUM_TAG);
if (!DeviceRelations)
return STATUS_INSUFFICIENT_RESOURCES;
-
+
/* Fill returned structure */
DeviceRelations->Count = NumPDO;
for (i = 0; i < NumPDO; i++)
ObReferenceObject(DeviceExtension->AttachedPdo);
DeviceRelations->Objects[i] = DeviceExtension->AttachedPdo;
}
-
+
*pDeviceRelations = DeviceRelations;
return Status;
}
PIO_STACK_LOCATION Stack;
ULONG_PTR Information = 0;
NTSTATUS Status;
-
+
Stack = IoGetCurrentIrpStackLocation(Irp);
MinorFunction = Stack->MinorFunction;
-
+
switch (MinorFunction)
{
/* FIXME: do all these minor functions
break;
}
default:
- DPRINT1("Serenum: IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / Unknown type 0x%lx\n",
+ DPRINT1("Serenum: IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / Unknown type 0x%lx\n",
Stack->Parameters.QueryDeviceRelations.Type);
return ForwardIrpAndForget(DeviceObject, Irp);
}
return ForwardIrpAndForget(DeviceObject, Irp);
}
}
-
+
Irp->IoStatus.Information = Information;
Irp->IoStatus.Status = Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS Serial enumerator driver
* FILE: drivers/dd/serenum/misc.c
* PURPOSE: Misceallenous operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (hpoussin@reactos.com)
*/
IN POOL_TYPE PoolType)
{
ASSERT(Destination);
-
+
if (Source == NULL)
{
RtlInitUnicodeString(Destination, NULL);
return STATUS_SUCCESS;
}
-
+
Destination->Buffer = ExAllocatePool(PoolType, Source->MaximumLength);
if (Destination->Buffer == NULL)
{
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
Destination->MaximumLength = Source->MaximumLength;
Destination->Length = Source->Length;
RtlCopyMemory(Destination->Buffer, Source->Buffer, Source->MaximumLength);
-
+
return STATUS_SUCCESS;
}
UNICODE_STRING UnicodeString;
ULONG DestinationSize = 0;
NTSTATUS Status = STATUS_SUCCESS;
-
+
ASSERT(Destination);
-
+
/* Calculate length needed for destination unicode string */
va_start(args, Destination);
Source = va_arg(args, PCSZ);
RtlInitUnicodeString(Destination, NULL);
return STATUS_SUCCESS;
}
-
+
/* Initialize destination string */
DestinationSize += sizeof(WCHAR); // final NULL
Destination->Buffer = (PWSTR)ExAllocatePoolWithTag(PagedPool, DestinationSize, SERENUM_TAG);
return STATUS_INSUFFICIENT_RESOURCES;
Destination->Length = 0;
Destination->MaximumLength = (USHORT)DestinationSize;
-
+
/* Copy arguments to destination string */
/* Use a temporary unicode string, which buffer is shared with
* destination string, to copy arguments */
PDEVICE_OBJECT LowerDevice;
KEVENT Event;
NTSTATUS Status;
-
+
ASSERT(((PCOMMON_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->IsFDO);
LowerDevice = ((PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->LowerDevice;
-
+
ASSERT(LowerDevice);
-
+
KeInitializeEvent(&Event, NotificationEvent, FALSE);
IoCopyCurrentIrpStackLocationToNext(Irp);
-
+
DPRINT("Serenum: Calling lower device %p [%wZ]\n", LowerDevice, &LowerDevice->DriverObject->DriverName);
IoSetCompletionRoutine(Irp, ForwardIrpAndWaitCompletion, &Event, TRUE, TRUE, TRUE);
-
+
Status = IoCallDriver(LowerDevice, Irp);
if (Status == STATUS_PENDING)
{
if (NT_SUCCESS(Status))
Status = Irp->IoStatus.Status;
}
-
+
return Status;
}
{
PFDO_DEVICE_EXTENSION DeviceExtension;
PDEVICE_OBJECT LowerDevice;
-
+
DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
ASSERT(DeviceExtension->Common.IsFDO);
-
+
LowerDevice = DeviceExtension->LowerDevice;
ASSERT(LowerDevice);
DPRINT("Serenum: calling lower device 0x%p [%wZ]\n",
{
PPDO_DEVICE_EXTENSION DeviceExtension;
PDEVICE_OBJECT Fdo;
-
+
DeviceExtension = (PPDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
ASSERT(!DeviceExtension->Common.IsFDO);
-
+
Fdo = DeviceExtension->AttachedFdo;
ASSERT(Fdo);
DPRINT("Serenum: calling attached Fdo 0x%p [%wZ]\n",
IN PIRP Irp)
{
PDEVICE_OBJECT LowerDevice;
-
+
ASSERT(((PCOMMON_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->IsFDO);
LowerDevice = ((PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->LowerDevice;
ASSERT(LowerDevice);
-
+
IoSkipCurrentIrpStackLocation(Irp);
return IoCallDriver(LowerDevice, Irp);
}
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS Serial enumerator driver
* FILE: drivers/bus/serenum/pdo.c
* PURPOSE: IRP_MJ_PNP operations for PDOs
- *
+ *
* PROGRAMMERS: Hervé Poussineau (hpoussin@reactos.com)
*/
IN PDEVICE_OBJECT DeviceObject)
{
PPDO_DEVICE_EXTENSION DeviceExtension;
-
+
DeviceExtension = (PPDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
-
+
ASSERT(DeviceExtension->Common.PnpState == dsStopped);
-
+
DeviceExtension->Common.PnpState = dsStarted;
return STATUS_SUCCESS;
}
PUNICODE_STRING SourceString;
UNICODE_STRING String;
NTSTATUS Status;
-
+
IdType = IoGetCurrentIrpStackLocation(Irp)->Parameters.QueryId.IdType;
DeviceExtension = (PPDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
RtlInitUnicodeString(&String, NULL);
-
+
switch (IdType)
{
case BusQueryDeviceID:
DPRINT1("Serenum: IRP_MJ_PNP / IRP_MN_QUERY_ID / unknown query id type 0x%lx\n", IdType);
return STATUS_NOT_SUPPORTED;
}
-
+
Status = SerenumDuplicateUnicodeString(
&String,
SourceString,
{
PFDO_DEVICE_EXTENSION DeviceExtension;
PDEVICE_RELATIONS DeviceRelations;
-
+
DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
ASSERT(DeviceExtension->Common.IsFDO);
-
+
DeviceRelations = (PDEVICE_RELATIONS)ExAllocatePoolWithTag(
PagedPool,
sizeof(DEVICE_RELATIONS),
SERENUM_TAG);
if (!DeviceRelations)
return STATUS_INSUFFICIENT_RESOURCES;
-
+
ObReferenceObject(DeviceObject);
DeviceRelations->Count = 1;
DeviceRelations->Objects[0] = DeviceObject;
-
+
*pDeviceRelations = DeviceRelations;
return STATUS_SUCCESS;
}
PIO_STACK_LOCATION Stack;
ULONG_PTR Information = 0;
NTSTATUS Status;
-
+
Stack = IoGetCurrentIrpStackLocation(Irp);
MinorFunction = Stack->MinorFunction;
-
+
switch (MinorFunction)
{
/* FIXME: do all these minor functions
}
default:
{
- DPRINT1("Serenum: IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / Unknown type 0x%lx\n",
+ DPRINT1("Serenum: IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / Unknown type 0x%lx\n",
Stack->Parameters.QueryDeviceRelations.Type);
Status = STATUS_NOT_IMPLEMENTED;
break;
PDEVICE_CAPABILITIES DeviceCapabilities;
ULONG i;
DPRINT("Serenum: IRP_MJ_PNP / IRP_MN_QUERY_CAPABILITIES\n");
-
+
DeviceCapabilities = (PDEVICE_CAPABILITIES)Stack->Parameters.DeviceCapabilities.Capabilities;
/* FIXME: capabilities can change with connected device */
DeviceCapabilities->LockSupported = FALSE;
PUNICODE_STRING Source;
PWSTR Description;
DPRINT("Serenum: IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_TEXT / DeviceTextDescription\n");
-
+
Source = &((PPDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->DeviceDescription;
Description = ExAllocatePool(PagedPool, Source->Length + sizeof(WCHAR));
if (!Description)
{
PPNP_BUS_INFORMATION BusInfo;
DPRINT("Serenum: IRP_MJ_PNP / IRP_MN_QUERY_BUS_INFORMATION\n");
-
+
BusInfo = (PPNP_BUS_INFORMATION)ExAllocatePool(PagedPool, sizeof(PNP_BUS_INFORMATION));
if (!BusInfo)
Status = STATUS_INSUFFICIENT_RESOURCES;
Status = Irp->IoStatus.Status;
}
}
-
+
Irp->IoStatus.Information = Information;
Irp->IoStatus.Status = Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS Serial enumerator driver
* FILE: drivers/bus/serenum/serenum.c
* PURPOSE: Serial enumeration driver entry point
- *
+ *
* PROGRAMMERS: Hervé Poussineau (hpoussin@reactos.com)
*/
IN PIRP Irp)
{
NTSTATUS Status = STATUS_NOT_SUPPORTED;
-
+
if (((PCOMMON_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->IsFDO)
{
/* Forward some IRPs to lower device */
}
}
}
-
+
Irp->IoStatus.Status = Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return Status;
IN PUNICODE_STRING RegPath)
{
ULONG i;
-
+
DriverObject->DriverUnload = DriverUnload;
DriverObject->DriverExtension->AddDevice = SerenumAddDevice;
-
+
for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++)
DriverObject->MajorFunction[i] = IrpStub;
-
+
//DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] = SerialQueryInformation;
DriverObject->MajorFunction[IRP_MJ_PNP] = SerenumPnp;
//DriverObject->MajorFunction[IRP_MJ_POWER] = SerialPower;
-
+
return STATUS_SUCCESS;
}
#include <ddk/ntddser.h>
#include <ddk/wdmguid.h>
#include <stdio.h>
-
+
#include <debug.h>
#define SR_MSR_DSR 0x20
#define ExFreePoolWithTag(p, tag) ExFreePool(p)
-
+
/* FIXME: these prototypes MUST NOT be here! */
NTSTATUS STDCALL
IoAttachDeviceToDeviceStackSafe(
IN PDEVICE_OBJECT SourceDevice,
IN PDEVICE_OBJECT TargetDevice,
OUT PDEVICE_OBJECT *AttachedToDeviceObject);
-
+
#elif defined(_MSC_VER)
#include <ntddk.h>
#include <ntddser.h>
#include <c:/progra~1/winddk/inc/ddk/wdm/wxp/wdmguid.h>
#include <stdio.h>
-
+
#define STDCALL
-
+
#define DPRINT1 DbgPrint("(%s:%d) ", __FILE__, __LINE__), DbgPrint
#define CHECKPOINT1 DbgPrint("(%s:%d)\n")
-
+
#define TAG(A, B, C, D) (ULONG)(((A)<<0) + ((B)<<8) + ((C)<<16) + ((D)<<24))
-
+
NTSTATUS STDCALL
IoAttachDeviceToDeviceStackSafe(
IN PDEVICE_OBJECT SourceDevice,
IN PDEVICE_OBJECT TargetDevice,
OUT PDEVICE_OBJECT *AttachedToDeviceObject);
-
+
#define DPRINT DPRINT1
#define CHECKPOINT CHECKPOINT1
-
+
#define SR_MSR_DSR 0x20
#else
#error Unknown compiler!
typedef struct _FDO_DEVICE_EXTENSION
{
COMMON_DEVICE_EXTENSION Common;
-
+
PDEVICE_OBJECT LowerDevice;
PDEVICE_OBJECT Pdo;
IO_REMOVE_LOCK RemoveLock;
-
+
UNICODE_STRING SerenumInterfaceName;
-
+
PDEVICE_OBJECT AttachedPdo;
ULONG Flags;
} FDO_DEVICE_EXTENSION, *PFDO_DEVICE_EXTENSION;
typedef struct _PDO_DEVICE_EXTENSION
{
COMMON_DEVICE_EXTENSION Common;
-
+
PDEVICE_OBJECT AttachedFdo;
-
+
UNICODE_STRING DeviceDescription; // REG_SZ
UNICODE_STRING DeviceId; // REG_SZ
UNICODE_STRING HardwareIds; // REG_MULTI_SZ
vidmem[(cursorx * 2) + (cursory * columns * 2)] = ' ';
vidmem[(cursorx * 2) + (cursory * columns * 2) + 1] = (char) DeviceExtension->CharAttribute;
break;
-
+
case '\n':
cursory++;
cursorx = 0;
break;
-
+
case '\r':
cursorx = 0;
break;
-
+
case '\t':
offset = TAB_WIDTH - (cursorx % TAB_WIDTH);
for (j = 0; j < offset; j++)
{
vidmem[(cursorx * 2) + (cursory * columns * 2)] = ' ';
cursorx++;
-
+
if (cursorx >= columns)
{
cursory++;
}
}
break;
-
+
default:
vidmem[(cursorx * 2) + (cursory * columns * 2)] = *pch;
vidmem[(cursorx * 2) + (cursory * columns * 2) + 1] = (char) DeviceExtension->CharAttribute;
}
}
}
-
+
/* Set the cursor position */
offset = (cursory * columns) + cursorx;
}
}
Buf->dwTransfered = Buf->nLength;
-
+
Irp->IoStatus.Information = 0;
Status = STATUS_SUCCESS;
}
BOOL STDCALL
VidResetDisplay(VOID)
{
- /*
+ /*
* We are only using standard VGA facilities so we can rely on the
* HAL 'int10mode3' reset to cleanup the hardware state.
*/
while ((j < bminfo->bV5SizeImage) && (k < (ULONG) (bminfo->bV5Width * bminfo->bV5Height)))
{
unsigned char b;
-
+
clen = BootimageBitmap[bfOffBits + j];
j++;
-
+
if (clen > 0)
{
/* Encoded mode */
-
+
b = BootimageBitmap[bfOffBits + j];
j++;
-
+
for (i = 0; i < (clen / 2); i++)
{
ImageData[k] = (b & 0xf0) >> 4;
/* Absolute mode */
b = BootimageBitmap[bfOffBits + j];
j++;
-
+
if (b == 0)
{
/* End of line */
{
DPRINT("Unaligned copy!\n");
}
-
+
clen = b;
for (i = 0; i < (clen / 2); i++)
{
b = BootimageBitmap[bfOffBits + j];
j++;
-
+
ImageData[k] = (b & 0xf0) >> 4;
k++;
ImageData[k] = b & 0xf;
InbvMapVideoMemory();
InbvInitVGAMode();
-
+
Status = PsCreateSystemThread(
&BitmapThreadHandle,
THREAD_ALL_ACCESS,
&BitmapThreadId,
InbvBitmapThreadMain,
NULL);
-
+
if (!NT_SUCCESS(Status))
{
return FALSE;
PIO_STACK_LOCATION IrpSp;
NTSTATUS Status;
NTBOOTVID_FUNCTION_TABLE* FunctionTable;
-
+
IrpSp = IoGetCurrentIrpStackLocation(Irp);
Status = STATUS_SUCCESS;
break;
case IOCTL_BOOTVID_CLEANUP:
- VidCleanUp();
+ VidCleanUp();
break;
default:
typedef struct tagCIEXYZ
{
- FXPT2DOT30 ciexyzX;
- FXPT2DOT30 ciexyzY;
- FXPT2DOT30 ciexyzZ;
+ FXPT2DOT30 ciexyzX;
+ FXPT2DOT30 ciexyzY;
+ FXPT2DOT30 ciexyzZ;
} CIEXYZ, *LPCIEXYZ;
typedef struct tagCIEXYZTRIPLE
{
- CIEXYZ ciexyzRed;
- CIEXYZ ciexyzGreen;
- CIEXYZ ciexyzBlue;
+ CIEXYZ ciexyzRed;
+ CIEXYZ ciexyzGreen;
+ CIEXYZ ciexyzBlue;
} CIEXYZTRIPLE, *LPCIEXYZTRIPLE;
-typedef struct {
- DWORD bV5Size;
- LONG bV5Width;
- LONG bV5Height;
- WORD bV5Planes;
- WORD bV5BitCount;
- DWORD bV5Compression;
- DWORD bV5SizeImage;
- LONG bV5XPelsPerMeter;
- LONG bV5YPelsPerMeter;
- DWORD bV5ClrUsed;
- DWORD bV5ClrImportant;
- DWORD bV5RedMask;
- DWORD bV5GreenMask;
- DWORD bV5BlueMask;
- DWORD bV5AlphaMask;
- DWORD bV5CSType;
- CIEXYZTRIPLE bV5Endpoints;
- DWORD bV5GammaRed;
- DWORD bV5GammaGreen;
- DWORD bV5GammaBlue;
- DWORD bV5Intent;
- DWORD bV5ProfileData;
- DWORD bV5ProfileSize;
- DWORD bV5Reserved;
-} BITMAPV5HEADER, *PBITMAPV5HEADER;
+typedef struct {
+ DWORD bV5Size;
+ LONG bV5Width;
+ LONG bV5Height;
+ WORD bV5Planes;
+ WORD bV5BitCount;
+ DWORD bV5Compression;
+ DWORD bV5SizeImage;
+ LONG bV5XPelsPerMeter;
+ LONG bV5YPelsPerMeter;
+ DWORD bV5ClrUsed;
+ DWORD bV5ClrImportant;
+ DWORD bV5RedMask;
+ DWORD bV5GreenMask;
+ DWORD bV5BlueMask;
+ DWORD bV5AlphaMask;
+ DWORD bV5CSType;
+ CIEXYZTRIPLE bV5Endpoints;
+ DWORD bV5GammaRed;
+ DWORD bV5GammaGreen;
+ DWORD bV5GammaBlue;
+ DWORD bV5Intent;
+ DWORD bV5ProfileData;
+ DWORD bV5ProfileSize;
+ DWORD bV5Reserved;
+} BITMAPV5HEADER, *PBITMAPV5HEADER;
/*
* Private driver structures
* NOTES:
* In your usermode application, do something like this:
*
- * DebugHandle = CreateFile("\\\\.\\DebugOut",
- * GENERIC_WRITE,
- * 0,
+ * DebugHandle = CreateFile("\\\\.\\DebugOut",
+ * GENERIC_WRITE,
+ * 0,
* NULL,
- * OPEN_EXISTING,
- * FILE_ATTRIBUTE_NORMAL,
+ * OPEN_EXISTING,
+ * FILE_ATTRIBUTE_NORMAL,
* NULL);
*
* and write to your hearts content to DebugHandle.
char Buf[513];
unsigned Remaining;
unsigned Length;
-
+
nErrCode = STATUS_SUCCESS;
switch(piosStack->MajorFunction)
{
}
-NTSTATUS STDCALL
+NTSTATUS STDCALL
DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
{
PDEVICE_OBJECT DebugOutDevice;
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS VT100 emulator
* FILE: drivers/dd/green/createclose.c
* PURPOSE: IRP_MJ_CREATE, IRP_MJ_CLOSE and IRP_MJ_CLEANUP operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (hpoussin@reactos.com)
*/
IN PIRP Irp)
{
DPRINT("Green: IRP_MJ_CREATE\n");
-
+
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
IN PIRP Irp)
{
DPRINT("Green: IRP_MJ_CLOSE\n");
-
+
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS VT100 emulator
* FILE: drivers/dd/green/dispatch.c
* PURPOSE: Dispatch routines
- *
+ *
* PROGRAMMERS: Hervé Poussineau (hpoussin@reactos.com)
*/
GREEN_DEVICE_TYPE DeviceType;
ULONG_PTR Information;
NTSTATUS Status;
-
+
MajorFunction = IoGetCurrentIrpStackLocation(Irp)->MajorFunction;
DeviceType = ((PCOMMON_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->Type;
-
+
Information = Irp->IoStatus.Information;
Status = Irp->IoStatus.Status;
-
+
DPRINT("Green: Dispatching major function 0x%lx, DeviceType %d\n",
MajorFunction, DeviceType);
-
+
if (MajorFunction == IRP_MJ_CREATE && DeviceType == Green)
return GreenCreate(DeviceObject, Irp);
else if (MajorFunction == IRP_MJ_CLOSE && DeviceType == Green)
DPRINT1("Green: unknown combination: MajorFunction 0x%lx, DeviceType %d\n",
MajorFunction, DeviceType);
}
-
+
Irp->IoStatus.Information = Information;
Irp->IoStatus.Status = Status;
IoCompleteRequest (Irp, IO_NO_INCREMENT);
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS VT100 emulator
* FILE: drivers/dd/green/green.c
* PURPOSE: Driver entry point
- *
+ *
* PROGRAMMERS: Hervé Poussineau (hpoussin@reactos.com)
*/
IN PUNICODE_STRING RegPath)
{
ULONG i;
-
+
DriverObject->DriverUnload = DriverUnload;
DriverObject->DriverExtension->AddDevice = GreenAddDevice;
-
+
for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++)
DriverObject->MajorFunction[i] = GreenDispatch;
-
+
/* keyboard only */
//DriverObject->DriverStartIo = GreenStartIo;
-
+
/* keyboard and screen */
DriverObject->MajorFunction[IRP_MJ_CREATE] = GreenCreate;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = GreenClose;
-
+
return STATUS_SUCCESS;
}
#include <ntos/halfuncs.h>
#include <ddk/ntddblue.h>
#include <ddk/ntddkbd.h> /* should be in kbdmou.h */
-
+
#include <debug.h>
-
+
/* FIXME: should be in kbdmou.h */
typedef struct _CONNECT_DATA {
PDEVICE_OBJECT ClassDeviceObject;
PVOID ClassService;
} CONNECT_DATA, *PCONNECT_DATA;
-
+
/* FIXME: should be in kbdmou.h */
#define IOCTL_INTERNAL_KEYBOARD_CONNECT \
CTL_CODE(FILE_DEVICE_KEYBOARD, 0x0080, METHOD_NEITHER, FILE_ANY_ACCESS)
-
+
NTSTATUS STDCALL
ObReferenceObjectByName(PUNICODE_STRING ObjectPath,
ULONG Attributes,
KPROCESSOR_MODE AccessMode,
PVOID ParseContext,
PVOID* ObjectPtr);
-
+
/* FIXME: should be in kbdmou.h */
typedef VOID (*PSERVICE_CALLBACK_ROUTINE)(PDEVICE_OBJECT, PKEYBOARD_INPUT_DATA, PKEYBOARD_INPUT_DATA, PULONG);
-
+
typedef struct _CLASS_INFORMATION
{
PDEVICE_OBJECT DeviceObject;
PVOID CallBack;
} CLASS_INFORMATION, *PCLASS_INFORMATION;
-
+
#define KEYBOARD_BUFFER_SIZE 100
-
+
#elif defined(_MSC_VER)
#include <ntddk.h>
#include <ntddser.h>
#include <kbdmou.h>
#define STDCALL
-
+
#define DPRINT1 DbgPrint("(%s:%d) ", __FILE__, __LINE__), DbgPrint
#define CHECKPOINT1 DbgPrint("(%s:%d)\n", __FILE__, __LINE__)
#define DPRINT DPRINT1
{
COMMON_DEVICE_EXTENSION Common;
PDEVICE_OBJECT Green;
-
+
CLASS_INFORMATION ClassInformation;
HANDLE WorkerThreadHandle;
KDPC KeyboardDpc;
-
+
ULONG ActiveQueue;
ULONG InputDataCount[2];
KEYBOARD_INPUT_DATA KeyboardInputData[2][KEYBOARD_BUFFER_SIZE];
{
COMMON_DEVICE_EXTENSION Common;
PDEVICE_OBJECT Green;
-
+
PUCHAR VideoMemory; /* Pointer to video memory */
USHORT CharAttribute; /* Current color attribute */
ULONG Mode;
UCHAR Rows; /* Number of rows */
UCHAR Columns; /* Number of columns */
UCHAR TabWidth;
-
+
ULONG LogicalOffset; /* Position of the cursor */
-
+
UCHAR SendBuffer[1024];
ULONG SendBufferPosition;
} SCREEN_DEVICE_EXTENSION, *PSCREEN_DEVICE_EXTENSION;
{
COMMON_DEVICE_EXTENSION Common;
PDEVICE_OBJECT Serial;
-
+
PDEVICE_OBJECT LowerDevice;
ULONG BaudRate;
SERIAL_LINE_CONTROL LineControl;
SERIAL_TIMEOUTS Timeouts;
-
+
PDEVICE_OBJECT Keyboard;
PDEVICE_OBJECT Screen;
} GREEN_DEVICE_EXTENSION, *PGREEN_DEVICE_EXTENSION;
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS VT100 emulator
* FILE: drivers/dd/green/keyboard.c
* PURPOSE: Keyboard part of green management
- *
+ *
* PROGRAMMERS: Hervé Poussineau (hpoussin@reactos.com)
*/
{
BOOLEAN NormalKey = FALSE;
USHORT MakeCode;
-
+
if (InputBufferSize == 0)
return FALSE;
-
+
switch (*InputBuffer)
{
case 0x1b: MakeCode = 0x01; NormalKey = TRUE; break; /* ESC */
-
+
case '1': MakeCode = 0x02; NormalKey = TRUE; break;
case '2': MakeCode = 0x03; NormalKey = TRUE; break;
case '3': MakeCode = 0x04; NormalKey = TRUE; break;
case '-': MakeCode = 0x0c; NormalKey = TRUE; break;
case '=': MakeCode = 0x0d; NormalKey = TRUE; break;
case '\b': MakeCode = 0x0e; NormalKey = TRUE; break;
-
+
case '\t': MakeCode = 0x0f; NormalKey = TRUE; break;
case 'q': MakeCode = 0x10; NormalKey = TRUE; break;
case 'w': MakeCode = 0x11; NormalKey = TRUE; break;
case 'p': MakeCode = 0x19; NormalKey = TRUE; break;
case '[': MakeCode = 0x1a; NormalKey = TRUE; break;
case ']': MakeCode = 0x1b; NormalKey = TRUE; break;
-
+
case '\r': MakeCode = 0x1c; NormalKey = TRUE; break;
-
+
case 'a': MakeCode = 0x1e; NormalKey = TRUE; break;
case 's': MakeCode = 0x1f; NormalKey = TRUE; break;
case 'd': MakeCode = 0x20; NormalKey = TRUE; break;
case 'l': MakeCode = 0x26; NormalKey = TRUE; break;
case ';': MakeCode = 0x27; NormalKey = TRUE; break;
case '\'': MakeCode = 0x28; NormalKey = TRUE; break;
-
+
case '`': MakeCode = 0x29; NormalKey = TRUE; break;
-
+
case '\\': MakeCode = 0x2b; NormalKey = TRUE; break;
-
+
case 'z': MakeCode = 0x2c; NormalKey = TRUE; break;
case 'x': MakeCode = 0x2d; NormalKey = TRUE; break;
case 'c': MakeCode = 0x2e; NormalKey = TRUE; break;
case ',': MakeCode = 0x33; NormalKey = TRUE; break;
case '.': MakeCode = 0x34; NormalKey = TRUE; break;
case '/': MakeCode = 0x35; NormalKey = TRUE; break;
-
+
case ' ': MakeCode = 0x39; NormalKey = TRUE; break;
}
if (NormalKey && *OutputBufferSize >= 2)
*BytesConsumed = 2;
return TRUE;
}
-
+
/* Consume strange character by ignoring it */
DPRINT1("Green: strange byte received 0x%02x ('%c')\n",
*InputBuffer, *InputBuffer >= 32 ? *InputBuffer : '.');
PKEYBOARD_DEVICE_EXTENSION DeviceExtension;
UNICODE_STRING DeviceName = RTL_CONSTANT_STRING(L"\\Device\\KeyboardClass1");
NTSTATUS Status;
-
+
DPRINT("Green: KeyboardInitialize() called\n");
-
+
Status = IoCreateDevice(DriverObject,
sizeof(KEYBOARD_DEVICE_EXTENSION),
&DeviceName, /* FIXME: don't hardcode string */
&Fdo);
if (!NT_SUCCESS(Status))
return Status;
-
+
DeviceExtension = (PKEYBOARD_DEVICE_EXTENSION)Fdo->DeviceExtension;
RtlZeroMemory(DeviceExtension, sizeof(KEYBOARD_DEVICE_EXTENSION));
DeviceExtension->Common.Type = Keyboard;
Fdo->Flags |= DO_POWER_PAGABLE | DO_BUFFERED_IO;
Fdo->Flags &= ~DO_DEVICE_INITIALIZING;
-
+
*KeyboardFdo = Fdo;
-
+
return STATUS_SUCCESS;
}
PKEYBOARD_DEVICE_EXTENSION DeviceExtension;
ULONG Queue;
ULONG InputDataConsumed;
-
+
DeviceExtension = (PKEYBOARD_DEVICE_EXTENSION)pDeviceExtension;
-
+
Queue = DeviceExtension->ActiveQueue % 2;
InterlockedIncrement((PLONG)&DeviceExtension->ActiveQueue);
(*(PSERVICE_CALLBACK_ROUTINE)DeviceExtension->ClassInformation.CallBack)(
DeviceExtension->KeyboardInputData[Queue],
&DeviceExtension->KeyboardInputData[Queue][DeviceExtension->InputDataCount[Queue]],
&InputDataConsumed);
-
+
DeviceExtension->InputDataCount[Queue] = 0;
}
static VOID STDCALL
ULONG BytesConsumed;
PKEYBOARD_INPUT_DATA Input;
NTSTATUS Status;
-
+
DPRINT("Green: KeyboardDeviceWorker() called\n");
-
+
DeviceObject = (PDEVICE_OBJECT)Context;
DeviceExtension = (PKEYBOARD_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
GreenDeviceExtension = (PGREEN_DEVICE_EXTENSION)DeviceExtension->Green->DeviceExtension;
LowerDevice = GreenDeviceExtension->Serial;
BufferSize = sizeof(Buffer);
-
+
/* Initialize device extension */
DeviceExtension->ActiveQueue = 0;
DeviceExtension->InputDataCount[0] = 0;
DeviceExtension->InputDataCount[1] = 0;
KeInitializeDpc(&DeviceExtension->KeyboardDpc, KeyboardDpcSendData, DeviceExtension);
RtlZeroMemory(&DeviceExtension->KeyboardInputData, sizeof(DeviceExtension->KeyboardInputData));
-
+
/* main read loop */
while (TRUE)
{
KeStallExecutionProcessor(10);
continue;
}
-
+
Status = IoCallDriver(LowerDevice, Irp);
if (Status == STATUS_PENDING)
{
}
if (!NT_SUCCESS(Status))
continue;
-
+
/* Read all available data and process */
i = 0;
while (i < ioStatus.Information)
{
Queue = DeviceExtension->ActiveQueue % 2;
-
+
Input = &DeviceExtension->KeyboardInputData[Queue][DeviceExtension->InputDataCount[Queue]];
-
+
/* Translate current chars to scan codes */
SpaceInQueue = KEYBOARD_BUFFER_SIZE - DeviceExtension->InputDataCount[Queue];
if (TranslateCharToScanCodes(
{
DPRINT1("Green: got char 0x%02x (%c)\n", Buffer[i], Buffer[i] >= 32 ? Buffer[i] : ' ');
DeviceExtension->InputDataCount[Queue] += BytesConsumed;
-
+
/* Send the data to the keyboard class driver */
KeRaiseIrql(DISPATCH_LEVEL, &OldIrql);
KeInsertQueueDpc(&DeviceExtension->KeyboardDpc, NULL, NULL);
}
}
}
-
+
PsTerminateSystemThread(STATUS_SUCCESS);
}
OBJECT_ATTRIBUTES objectAttributes;
PDEVICE_OBJECT LowerDevice;
NTSTATUS Status;
-
+
Stack = IoGetCurrentIrpStackLocation(Irp);
Irp->IoStatus.Information = 0;
DeviceExtension = (PKEYBOARD_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
GreenDeviceExtension = (PGREEN_DEVICE_EXTENSION)DeviceExtension->Green->DeviceExtension;
LowerDevice = GreenDeviceExtension->Serial;
DPRINT1("Green: LowerDevice %p\n", LowerDevice);
-
+
switch (Stack->Parameters.DeviceIoControl.IoControlCode)
{
case IOCTL_INTERNAL_KEYBOARD_CONNECT:
{
ULONG Fcr;
-
+
DPRINT("Green: IRP_MJ_INTERNAL_DEVICE_CONTROL / IOCTL_INTERNAL_KEYBOARD_CONNECT\n");
if (Stack->Parameters.DeviceIoControl.InputBufferLength < sizeof(CONNECT_DATA))
{
Status = STATUS_INVALID_PARAMETER;
break;
}
-
+
DeviceExtension->ClassInformation =
*((PCLASS_INFORMATION)Stack->Parameters.DeviceIoControl.Type3InputBuffer);
-
+
/* Initialize serial port */
Fcr = 0;
Status = GreenDeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_FIFO_CONTROL,
Status = GreenDeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_LINE_CONTROL,
&GreenDeviceExtension->LineControl, sizeof(GreenDeviceExtension->LineControl), NULL, NULL);
if (!NT_SUCCESS(Status)) break;
-
+
/* Set timeouts */
Status = GreenDeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_TIMEOUTS,
&GreenDeviceExtension->Timeouts, sizeof(GreenDeviceExtension->Timeouts), NULL, NULL);
if (!NT_SUCCESS(Status)) break;
-
+
/* Start read loop */
InitializeObjectAttributes(&objectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
Status = PsCreateSystemThread(
Status = STATUS_INVALID_DEVICE_REQUEST;
}
}
-
+
Irp->IoStatus.Status = Status;
IoCompleteRequest (Irp, IO_NO_INCREMENT);
return Status;
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS VT100 emulator
* FILE: drivers/dd/green/misc.c
* PURPOSE: Misceallenous operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (hpoussin@reactos.com)
*/
PIRP Irp;
IO_STATUS_BLOCK IoStatus;
NTSTATUS Status;
-
+
KeInitializeEvent (&Event, NotificationEvent, FALSE);
-
+
Irp = IoBuildDeviceIoControlRequest(CtlCode,
DeviceObject,
InputBuffer,
DPRINT("Green: IoBuildDeviceIoControlRequest() failed\n");
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
Status = IoCallDriver(DeviceObject, Irp);
-
+
if (Status == STATUS_PENDING)
{
DPRINT("Green: Operation pending\n");
KeWaitForSingleObject(&Event, Suspended, KernelMode, FALSE, NULL);
Status = IoStatus.Status;
}
-
+
if (OutputBufferSize)
{
*OutputBufferSize = IoStatus.Information;
}
-
+
return Status;
}
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS VT100 emulator
* FILE: drivers/dd/green/pnp.c
* PURPOSE: IRP_MJ_PNP operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (hpoussin@reactos.com)
*/
PGREEN_DEVICE_EXTENSION DeviceExtension;
UNICODE_STRING serialPortName;
NTSTATUS Status;
-
+
DPRINT("Green: AddDevice(DriverObject %p, Pdo %p)\n", DriverObject, Pdo);
-
+
/* Create green FDO */
Status = IoCreateDevice(DriverObject,
sizeof(GREEN_DEVICE_EXTENSION),
&Fdo);
if (!NT_SUCCESS(Status))
return Status;
-
+
DeviceExtension = (PGREEN_DEVICE_EXTENSION)Fdo->DeviceExtension;
RtlZeroMemory(DeviceExtension, sizeof(GREEN_DEVICE_EXTENSION));
DeviceExtension->Common.Type = Green;
-
+
Status = KeyboardInitialize(DriverObject, &DeviceExtension->Keyboard);
if (!NT_SUCCESS(Status))
{
return Status;
}
((PKEYBOARD_DEVICE_EXTENSION)DeviceExtension->Keyboard->DeviceExtension)->Green = Fdo;
-
+
Status = ScreenInitialize(DriverObject, &DeviceExtension->Screen);
if (!NT_SUCCESS(Status))
{
return Status;
}
((PSCREEN_DEVICE_EXTENSION)DeviceExtension->Screen->DeviceExtension)->Green = Fdo;
-
+
/* initialize green Fdo */
DeviceExtension->LowerDevice = IoAttachDeviceToDeviceStack(Fdo, Pdo);
DeviceExtension->LineControl.WordLength = 8;
DeviceExtension->Timeouts.ReadTotalTimeoutMultiplier = INFINITE;
DeviceExtension->Timeouts.WriteTotalTimeoutMultiplier = 0; /* FIXME */
DeviceExtension->Timeouts.WriteTotalTimeoutConstant = 0; /* FIXME */
-
+
/* open associated serial port */
RtlInitUnicodeString(&serialPortName, L"\\Device\\Serial1"); /* FIXME: don't hardcode string */
Status = ObReferenceObjectByName(
NULL,
(PVOID*)&DeviceExtension->Serial);
/* FIXME: we never ObDereferenceObject */
-
+
Fdo->Flags |= DO_POWER_PAGABLE | DO_BUFFERED_IO;
Fdo->Flags &= ~DO_DEVICE_INITIALIZING;
-
+
return Status;
}
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS VT100 emulator
* FILE: drivers/dd/green/screen.c
* PURPOSE: Screen part of green management
- *
+ *
* PROGRAMMERS: Eric Kohl (ekohl@abo.rhein-zeitung.de)
* Art Yerkes
* Hervé Poussineau (hpoussin@reactos.com)
int CurrentInt;
UCHAR CurrentChar;
NTSTATUS Status;
-
+
SizeLeft = sizeof(DeviceExtension->SendBuffer) - DeviceExtension->SendBufferPosition;
if (SizeLeft < NumberOfChars * 2 || NumberOfChars == 0)
{
DeviceExtension->SendBufferPosition = 0;
SizeLeft = sizeof(DeviceExtension->SendBuffer);
}
-
+
va_start(args, NumberOfChars);
while (NumberOfChars-- > 0)
{
if (CurrentInt > 0)
{
CurrentChar = (UCHAR)CurrentInt;
-
+
/* Why 0xff chars are printed on a 'dir' ? */
if (CurrentChar == 0xff) CurrentChar = ' ';
-
+
DeviceExtension->SendBuffer[DeviceExtension->SendBufferPosition++] = CurrentChar;
SizeLeft--;
}
PSCREEN_DEVICE_EXTENSION DeviceExtension;
UNICODE_STRING DeviceName = RTL_CONSTANT_STRING(L"\\Device\\BlueScreen");
NTSTATUS Status;
-
+
DPRINT("Green: ScreenInitialize() called\n");
-
+
Status = IoCreateDevice(DriverObject,
sizeof(SCREEN_DEVICE_EXTENSION),
&DeviceName, /* FIXME: don't hardcode string */
&Fdo);
if (!NT_SUCCESS(Status))
return Status;
-
+
DeviceExtension = (PSCREEN_DEVICE_EXTENSION)Fdo->DeviceExtension;
RtlZeroMemory(DeviceExtension, sizeof(SCREEN_DEVICE_EXTENSION));
DeviceExtension->Common.Type = Screen;
return STATUS_INSUFFICIENT_RESOURCES;
}
DeviceExtension->TabWidth = 8;
-
+
/* more initialization */
DeviceExtension->Mode = ENABLE_PROCESSED_OUTPUT |
ENABLE_WRAP_AT_EOL_OUTPUT;
-
+
/* initialize screen at next write */
AddToSendBuffer(DeviceExtension, 2, ESC, 'c'); /* reset device */
AddToSendBuffer(DeviceExtension, 4, ESC, '[', '7', 'l'); /* disable line wrap */
AddToSendBuffer(DeviceExtension, 4, ESC, '[', '3', 'g'); /* clear all tabs */
-
+
Fdo->Flags |= DO_POWER_PAGABLE | DO_BUFFERED_IO;
Fdo->Flags &= ~DO_DEVICE_INITIALIZING;
-
+
*ScreenFdo = Fdo;
-
+
return STATUS_SUCCESS;
}
PSCREEN_DEVICE_EXTENSION DeviceExtension;
PUCHAR VideoMemory; /* FIXME: is it useful? */
ULONG VideoMemorySize; /* FIXME: is it useful? */
-
+
ULONG Columns, Rows;
ULONG CursorX, CursorY;
ULONG i, j;
NTSTATUS Status;
-
+
DPRINT("Green: IRP_MJ_WRITE\n");
-
+
Stack = IoGetCurrentIrpStackLocation (Irp);
Buffer = Irp->UserBuffer;
DeviceExtension = (PSCREEN_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
VideoMemory = DeviceExtension->VideoMemory;
-
+
Columns = DeviceExtension->Columns;
Rows = DeviceExtension->Rows;
CursorX = (DeviceExtension->LogicalOffset / 2) % Columns + 1;
for (i = 0; i < Stack->Parameters.Write.Length; i++)
DbgPrint(" 0x%02x", Buffer[i]);
DbgPrint("\n");
-
+
if (!(DeviceExtension->Mode & ENABLE_PROCESSED_OUTPUT))
{
/* raw output mode */
CHECKPOINT;
Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;
IoCompleteRequest (Irp, IO_NO_INCREMENT);
-
+
return STATUS_NOT_SUPPORTED;
}
else
DPRINT1("Y: %lu -> %lu\n", CursorY, CursorY + 1);
CursorY++;
AddToSendBuffer(DeviceExtension, 6, ESC, '[', -(int)CursorY, ';', '1', 'H');
-
+
}
}
}
}
}
}
-
+
DeviceExtension->LogicalOffset = ((CursorX-1) + (CursorY-1) * Columns) * 2;
-
+
/* flush output buffer */
AddToSendBuffer(DeviceExtension, 0);
-
+
Status = STATUS_SUCCESS;
Irp->IoStatus.Status = Status;
IoCompleteRequest (Irp, IO_NO_INCREMENT);
-
+
return Status;
}
PIO_STACK_LOCATION Stack;
PSCREEN_DEVICE_EXTENSION DeviceExtension;
NTSTATUS Status;
-
+
Stack = IoGetCurrentIrpStackLocation(Irp);
DeviceExtension = (PSCREEN_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
-
+
switch (Stack->Parameters.DeviceIoControl.IoControlCode)
{
case IOCTL_CONSOLE_GET_SCREEN_BUFFER_INFO:
{
PCONSOLE_SCREEN_BUFFER_INFO pcsbi;
DPRINT("Green: IRP_MJ_DEVICE_CONTROL / IOCTL_CONSOLE_GET_SCREEN_BUFFER_INFO\n");
-
+
pcsbi = (PCONSOLE_SCREEN_BUFFER_INFO)Irp->AssociatedIrp.SystemBuffer;
-
+
pcsbi->dwSize.X = DeviceExtension->Columns;
pcsbi->dwSize.Y = DeviceExtension->Rows;
-
+
pcsbi->dwCursorPosition.X = (SHORT)(DeviceExtension->LogicalOffset % DeviceExtension->Columns);
pcsbi->dwCursorPosition.Y = (SHORT)(DeviceExtension->LogicalOffset / DeviceExtension->Columns);
-
+
pcsbi->wAttributes = DeviceExtension->CharAttribute;
-
+
pcsbi->srWindow.Left = 1;
pcsbi->srWindow.Right = DeviceExtension->Columns;
pcsbi->srWindow.Top = 1;
pcsbi->srWindow.Bottom = DeviceExtension->Rows;
-
+
pcsbi->dwMaximumWindowSize.X = DeviceExtension->Columns;
pcsbi->dwMaximumWindowSize.Y = DeviceExtension->Rows;
-
+
Irp->IoStatus.Information = sizeof(CONSOLE_SCREEN_BUFFER_INFO);
Status = STATUS_SUCCESS;
break;
{
PCONSOLE_SCREEN_BUFFER_INFO pcsbi;
DPRINT("Green: IRP_MJ_DEVICE_CONTROL / IOCTL_CONSOLE_SET_SCREEN_BUFFER_INFO\n");
-
+
pcsbi = (PCONSOLE_SCREEN_BUFFER_INFO)Irp->AssociatedIrp.SystemBuffer;
/* FIXME: remove */ { pcsbi->dwCursorPosition.X++; }
/* FIXME: remove */ { pcsbi->dwCursorPosition.Y++; }
ASSERT(pcsbi->dwCursorPosition.Y >= 1);
ASSERT(pcsbi->dwCursorPosition.X <= DeviceExtension->Columns);
ASSERT(pcsbi->dwCursorPosition.Y <= DeviceExtension->Rows);
-
+
DeviceExtension->LogicalOffset = (
(pcsbi->dwCursorPosition.Y-1) * DeviceExtension->Columns +
(pcsbi->dwCursorPosition.X-1)) * 2;
AddToSendBuffer(DeviceExtension, 6, ESC, '[',
-(int)pcsbi->dwCursorPosition.Y, ';',
-(int)pcsbi->dwCursorPosition.X, 'H');
-
+
/* flush buffer */
AddToSendBuffer(DeviceExtension, 0);
-
+
DeviceExtension->CharAttribute = pcsbi->wAttributes;
-
+
Irp->IoStatus.Information = 0;
Status = STATUS_SUCCESS;
break;
{
PCONSOLE_CURSOR_INFO pcci = (PCONSOLE_CURSOR_INFO)Irp->AssociatedIrp.SystemBuffer;
DPRINT("Green: IRP_MJ_DEVICE_CONTROL / IOCTL_CONSOLE_GET_CURSOR_INFO\n");
-
+
pcci->dwSize = 1;
pcci->bVisible = TRUE;
-
+
Irp->IoStatus.Information = sizeof (CONSOLE_CURSOR_INFO);
Status = STATUS_SUCCESS;
break;
{
PCONSOLE_MODE pcm = (PCONSOLE_MODE)Irp->AssociatedIrp.SystemBuffer;
DPRINT("Green: IRP_MJ_DEVICE_CONTROL / IOCTL_CONSOLE_GET_MODE\n");
-
+
pcm->dwMode = DeviceExtension->Mode;
-
+
Irp->IoStatus.Information = sizeof(CONSOLE_MODE);
Status = STATUS_SUCCESS;
break;
{
PCONSOLE_MODE pcm = (PCONSOLE_MODE)Irp->AssociatedIrp.SystemBuffer;
DPRINT("Green: IRP_MJ_DEVICE_CONTROL / IOCTL_CONSOLE_SET_MODE\n");
-
+
DeviceExtension->Mode = pcm->dwMode;
-
+
Irp->IoStatus.Information = 0;
Status = STATUS_SUCCESS;
break;
case IOCTL_CONSOLE_SET_TEXT_ATTRIBUTE:
{
DPRINT("Green: IRP_MJ_DEVICE_CONTROL / IOCTL_CONSOLE_SET_TEXT_ATTRIBUTE\n");
-
+
DeviceExtension->CharAttribute = (WORD)*(PWORD)Irp->AssociatedIrp.SystemBuffer;
Irp->IoStatus.Information = 0;
Status = STATUS_SUCCESS;
ULONG x, y;
BOOLEAN DoOptimization = FALSE;
DPRINT("Green: IRP_MJ_DEVICE_CONTROL / IOCTL_CONSOLE_DRAW\n");
-
+
ConsoleDraw = (PCONSOLE_DRAW)MmGetSystemAddressForMdl(Irp->MdlAddress);
/* FIXME: remove */ { ConsoleDraw->X++; ConsoleDraw->CursorX++; }
/* FIXME: remove */ { ConsoleDraw->Y++; ConsoleDraw->CursorY++; }
ASSERT(ConsoleDraw->CursorY >= 1);
ASSERT(ConsoleDraw->CursorX <= DeviceExtension->Columns);
ASSERT(ConsoleDraw->CursorY <= DeviceExtension->Rows);
-
+
#if 0
if (ConsoleDraw->X == 1
&& ConsoleDraw->Y == 1
}
#endif
/* add here more optimizations if needed */
-
+
if (!DoOptimization)
{
for (y = 0; y < ConsoleDraw->SizeY; y++)
}
}
}
-
+
DeviceExtension->LogicalOffset = (
(ConsoleDraw->CursorY-1) * DeviceExtension->Columns +
(ConsoleDraw->CursorX-1)) * 2;
AddToSendBuffer(DeviceExtension, 6, ESC, '[',
-(int)(ConsoleDraw->CursorY), ';',
-(int)(ConsoleDraw->CursorX), 'H');
-
+
/* flush buffer */
AddToSendBuffer(DeviceExtension, 0);
-
+
Irp->IoStatus.Information = 0;
Status = STATUS_SUCCESS;
break;
Stack->Parameters.DeviceIoControl.IoControlCode);
Status = STATUS_NOT_IMPLEMENTED;
}
-
+
Irp->IoStatus.Status = Status;
IoCompleteRequest (Irp, IO_NO_INCREMENT);
return Status;
// Parameters = Instance->DriverObject->DriverExtension;
DPRINT("DeviceObject at 0x%x, DeviceExtension at 0x%x\n", DeviceObject, Parameters);
-
+
if (! Parameters)
{
DPRINT("NULL POINTER!\n");
Parameters->IRQ = DEFAULT_IRQ;
// Only to be enabled once we can get support for multiple cards working :)
-/*
+/*
DPRINT("Loading settings from: %S\n", RegistryPath);
-
+
s = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE, RegistryPath, Table,
&Parameters, NULL);
*/
*/
{
DPRINT("MPU401Create() called!\n");
-
+
// Initialize the MPU-401?
// ... do stuff ...
NTSTATUS Status;
DPRINT("MPU401Close() called!\n");
-
+
DeviceExtension = DeviceObject->DeviceExtension;
Status = STATUS_SUCCESS;
DeviceExtension = DeviceObject->DeviceExtension;
Stack = IoGetCurrentIrpStackLocation(Irp);
-
+
DPRINT("Control code %d [0x%x]\n", Stack->Parameters.DeviceIoControl.IoControlCode,
Stack->Parameters.DeviceIoControl.IoControlCode);
Data = (PBYTE) Irp->AssociatedIrp.SystemBuffer;
DPRINT("Sending %d bytes of MIDI data to 0x%d:\n", Stack->Parameters.DeviceIoControl.InputBufferLength, DeviceExtension->Port);
-
+
for (ByteCount = 0; ByteCount < Stack->Parameters.DeviceIoControl.InputBufferLength; ByteCount ++)
{
DPRINT("0x%x ", Data[ByteCount]);
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return(STATUS_SUCCESS);
}
}
-
+
return(STATUS_SUCCESS);
/*
BOOLEAN WaitToSend(UINT BasePort)
{
int TimeOut;
-
+
DbgPrint("WaitToSend ");
// Check if it's OK to send
DbgPrint("FAILED\n");
return FALSE;
}
-
+
DbgPrint("SUCCEEDED\n");
return TRUE;
DbgPrint("FAILED\n");
return FALSE;
}
-
+
DbgPrint("SUCCEEDED\n");
return TRUE;
{
PIO_STACK_LOCATION piosStack = IoGetCurrentIrpStackLocation(Irp);
NTSTATUS nErrCode;
-
+
nErrCode = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
}
/* TODO: \Device\Zero should be memory-mappable */
-NTSTATUS STDCALL
+NTSTATUS STDCALL
DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
{
PDEVICE_OBJECT pdoNullDevice;
* FILE: services/parallel/parallel.c
* PURPOSE: Parallel port driver
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
* ??/??/??: Created
* 18/06/98: Made more NT like
*/
* ch = character to write
*/
{
-
+
int count=0;
int status;
int wait=0;
count++;
}
while ( count < 500000 && !(status & LP_PBUSY) );
-
+
if (count==500000)
{
DPRINT("printer_putchar(): timed out\n");
return;
}
-
+
WRITE_PORT_UCHAR((PUCHAR)LP_B,ch);
while (wait != 10000) { wait++; }
WRITE_PORT_UCHAR((PUCHAR)LP_C, (LP_PSELECP | LP_PINITP | LP_PSTROBE ));
PIO_STACK_LOCATION Stack = IoGetCurrentIrpStackLocation(Irp);
NTSTATUS status;
int i;
-
+
switch (Stack->MajorFunction)
{
case IRP_MJ_CREATE:
Parallel_Reset();
status = STATUS_SUCCESS;
break;
-
+
case IRP_MJ_CLOSE:
status = STATUS_SUCCESS;
break;
-
+
case IRP_MJ_WRITE:
DPRINT("(Parallel Port Driver) Writing %d bytes\n",
Stack->Parameters.Write.Length);
}
status = STATUS_SUCCESS;
break;
-
+
default:
status = STATUS_NOT_IMPLEMENTED;
break;
}
-
+
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(status);
}
PDEVICE_OBJECT DeviceObject;
UNICODE_STRING DeviceName = ROS_STRING_INITIALIZER(L"\\Device\\Parallel");
NTSTATUS Status;
-
+
DPRINT("Parallel Port Driver 0.0.1\n");
-
+
Status = IoCreateDevice(DriverObject,
0,
&DeviceName,
DriverObject->MajorFunction[IRP_MJ_CREATE] = Dispatch;
DriverObject->MajorFunction[IRP_MJ_WRITE] = Dispatch;
DriverObject->DriverUnload = NULL;
-
+
return(STATUS_SUCCESS);
}
* gets inverted, but it is also active low.
*/
-/*
+/*
* bit defines for 8255 status port
* base + 1
* accessed with LP_S(minor), which gets the byte...
#define LP_PSELECD 0x10 /* unchanged input, active high */
#define LP_PERRORP 0x08 /* unchanged input, active low */
-/*
+/*
* defines for 8255 control port
- * base + 2
+ * base + 2
* accessed with LP_C(minor)
*/
#define LP_PINTEN 0x10
#define LP_PAUTOLF 0x02 /* inverted output, active low */
#define LP_PSTROBE 0x01 /* inverted output, active low */
-/*
- * the value written to ports to test existence. PC-style ports will
+/*
+ * the value written to ports to test existence. PC-style ports will
* return the value written. AT-style ports will return 0. so why not
- * make them the same ?
+ * make them the same ?
*/
#define LP_DUMMY 0x00
Status = STATUS_INVALID_DEVICE_REQUEST;
}
Irp->IoStatus.Status = Status;
- IoCompleteRequest(Irp, NT_SUCCESS(Status) ? IO_DISK_INCREMENT : IO_NO_INCREMENT);
+ IoCompleteRequest(Irp, NT_SUCCESS(Status) ? IO_DISK_INCREMENT : IO_NO_INCREMENT);
return Status;
}
unsigned int dstlen = 1024 * 1440;
FILE_STANDARD_INFORMATION finfo;
DWORD err;
-
+
DPRINT("Ramdisk driver\n");
-
+
/* Export other driver entry points... */
DriverObject->MajorFunction[IRP_MJ_CREATE] = RamdrvDispatchOpenClose;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = RamdrvDispatchOpenClose;
DriverObject->MajorFunction[IRP_MJ_READ] = RamdrvDispatchReadWrite;
DriverObject->MajorFunction[IRP_MJ_WRITE] = RamdrvDispatchReadWrite;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = RamdrvDispatchDeviceControl;
-
-
+
+
// create device and symbolic link
Status = IoCreateDevice( DriverObject,
sizeof( RAMDRV_DEVICE_EXTENSION ),
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/circularbuffer.c
* PURPOSE: Operations on a circular buffer
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
IN ULONG NewBufferSize)
{
PUCHAR NewBuffer;
-
+
DPRINT("Serial: IncreaseCircularBufferSize(pBuffer %p, NewBufferSize %lu)\n", pBuffer, NewBufferSize);
ASSERT(pBuffer);
ASSERT(pBuffer->Length);
return STATUS_INVALID_PARAMETER;
else if (pBuffer->Length == NewBufferSize)
return STATUS_SUCCESS;
-
+
NewBuffer = (PUCHAR)ExAllocatePoolWithTag(NonPagedPool, NewBufferSize * sizeof(UCHAR), SERIAL_TAG);
if (!NewBuffer)
return STATUS_INSUFFICIENT_RESOURCES;
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/cleanup.c
* PURPOSE: Serial IRP_MJ_CLEANUP operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/close.c
* PURPOSE: Serial IRP_MJ_CLOSE operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
IN PIRP Irp)
{
PSERIAL_DEVICE_EXTENSION pDeviceExtension;
-
+
DPRINT("Serial: IRP_MJ_CLOSE\n");
pDeviceExtension = (PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
pDeviceExtension->IsOpened = FALSE;
-
+
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/create.c
* PURPOSE: Serial IRP_MJ_CREATE operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
PFILE_OBJECT FileObject;
PSERIAL_DEVICE_EXTENSION DeviceExtension;
NTSTATUS Status;
-
+
DPRINT("Serial: IRP_MJ_CREATE\n");
Stack = IoGetCurrentIrpStackLocation(Irp);
FileObject = Stack->FileObject;
DeviceExtension = (PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
-
+
ASSERT(FileObject);
-
+
if (Stack->Parameters.Create.Options & FILE_DIRECTORY_FILE)
{
CHECKPOINT;
Status = STATUS_NOT_A_DIRECTORY;
goto ByeBye;
}
-
- if (FileObject->FileName.Length != 0 ||
+
+ if (FileObject->FileName.Length != 0 ||
FileObject->RelatedFileObject != NULL)
{
CHECKPOINT;
Status = STATUS_ACCESS_DENIED;
goto ByeBye;
}
-
+
if(DeviceExtension->IsOpened)
{
DPRINT("Serial: COM%lu is already opened\n", DeviceExtension->ComPort);
Status = STATUS_ACCESS_DENIED;
goto ByeBye;
}
-
+
DPRINT("Serial: open COM%lu: successfull\n", DeviceExtension->ComPort);
DeviceExtension->IsOpened = TRUE;
Status = STATUS_SUCCESS;
-
+
ByeBye:
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/devctrl.c
* PURPOSE: Serial IRP_MJ_DEVICE_CONTROL operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
ASSERT(Irp);
ASSERT(BufferIn);
ASSERT(BufferOut);
-
+
switch (IO_METHOD_FROM_CTL_CODE(IoControlCode))
{
case METHOD_BUFFERED:
*BufferOut = Irp->UserBuffer;
return;
}
-
+
/* Should never happen */
}
PUCHAR ComPortBase = (PUCHAR)DeviceExtension->BaseAddress;
ULONG BaudRate;
NTSTATUS Status = STATUS_SUCCESS;
-
+
if (NewBaudRate & SERIAL_BAUD_USER)
{
BaudRate = NewBaudRate & ~SERIAL_BAUD_USER;
default: Status = STATUS_INVALID_PARAMETER;
}
}
-
+
if (NT_SUCCESS(Status))
{
Status = IoAcquireRemoveLock(&DeviceExtension->RemoveLock, (PVOID)DeviceExtension->ComPort);
WRITE_PORT_UCHAR(SER_DLM(ComPortBase), divisor >> 8);
/* Switch back to normal registers */
WRITE_PORT_UCHAR(SER_LCR(ComPortBase), Lcr);
-
+
IoReleaseRemoveLock(&DeviceExtension->RemoveLock, (PVOID)DeviceExtension->ComPort);
}
}
-
+
if (NT_SUCCESS(Status))
DeviceExtension->BaudRate = BaudRate;
return Status;
PUCHAR ComPortBase;
UCHAR Lcr = 0;
NTSTATUS Status;
-
+
ASSERT(DeviceExtension);
ASSERT(NewSettings);
-
+
DPRINT("Serial: SerialSetLineControl(COM%lu, Settings { %lu %lu %lu })\n",
DeviceExtension->ComPort, NewSettings->StopBits, NewSettings->Parity, NewSettings->WordLength);
-
+
/* Verify parameters */
switch (NewSettings->WordLength)
{
case 8: Lcr |= SR_LCR_CS8; break;
default: return STATUS_INVALID_PARAMETER;
}
-
+
if (NewSettings->WordLength < 5 || NewSettings->WordLength > 8)
return STATUS_INVALID_PARAMETER;
-
+
switch (NewSettings->Parity)
{
case NO_PARITY: Lcr |= SR_LCR_PNO; break;
case SPACE_PARITY: Lcr |= SR_LCR_PSP; break;
default: return STATUS_INVALID_PARAMETER;
}
-
+
switch (NewSettings->StopBits)
{
case STOP_BIT_1:
default:
return STATUS_INVALID_PARAMETER;
}
-
+
/* Update current parameters */
ComPortBase = (PUCHAR)DeviceExtension->BaseAddress;
Status = IoAcquireRemoveLock(&DeviceExtension->RemoveLock, (PVOID)DeviceExtension->ComPort);
if (!NT_SUCCESS(Status))
return Status;
WRITE_PORT_UCHAR(SER_LCR(ComPortBase), Lcr);
-
+
/* Read junk out of RBR */
READ_PORT_UCHAR(SER_RBR(ComPortBase));
IoReleaseRemoveLock(&DeviceExtension->RemoveLock, (PVOID)DeviceExtension->ComPort);
-
+
if (NT_SUCCESS(Status))
DeviceExtension->SerialLineControl = *NewSettings;
-
+
return Status;
}
IN PSERIAL_DEVICE_EXTENSION DeviceExtension)
{
ASSERT(DeviceExtension);
-
+
RtlZeroMemory(&DeviceExtension->SerialPerfStats, sizeof(SERIALPERF_STATS));
DeviceExtension->BreakInterruptErrorCount = 0;
return TRUE;
IN PSERIAL_DEVICE_EXTENSION DeviceExtension)
{
ASSERT(pCommProp);
-
+
RtlZeroMemory(pCommProp, sizeof(SERIAL_COMMPROP));
-
+
pCommProp->PacketLength = sizeof(SERIAL_COMMPROP);
pCommProp->PacketVersion = 2;
pCommProp->ServiceMask = SERIAL_SP_SERIALCOMM;
| SERIAL_PCF_XONXOFF;
pCommProp->SettableParams = SERIAL_SP_BAUD | SERIAL_SP_DATABITS | SERIAL_SP_HANDSHAKING
| SERIAL_SP_PARITY | SERIAL_SP_PARITY_CHECK | SERIAL_SP_STOPBITS;
-
+
/* SettableBaud is related to Uart type */
pCommProp->SettableBaud = SERIAL_BAUD_075 | SERIAL_BAUD_110 | SERIAL_BAUD_134_5
| SERIAL_BAUD_150 | SERIAL_BAUD_300 | SERIAL_BAUD_600 | SERIAL_BAUD_1200
pCommProp->SettableBaud |= SERIAL_BAUD_56K | SERIAL_BAUD_57600 | SERIAL_BAUD_115200 | SERIAL_BAUD_128K;
pCommProp->MaxBaud = SERIAL_BAUD_115200;
}
-
+
pCommProp->SettableData = SERIAL_DATABITS_5 | SERIAL_DATABITS_6 | SERIAL_DATABITS_7 | SERIAL_DATABITS_8;
pCommProp->SettableStopParity = SERIAL_STOPBITS_10 | SERIAL_STOPBITS_15 | SERIAL_STOPBITS_20
| SERIAL_PARITY_NONE | SERIAL_PARITY_ODD | SERIAL_PARITY_EVEN | SERIAL_PARITY_MARK | SERIAL_PARITY_SPACE;
-
+
return STATUS_SUCCESS;
}
IN PSERIAL_DEVICE_EXTENSION DeviceExtension)
{
KIRQL Irql;
-
+
ASSERT(pSerialStatus);
RtlZeroMemory(pSerialStatus, sizeof(SERIAL_STATUS));
-
+
pSerialStatus->Errors = 0;
if (DeviceExtension->BreakInterruptErrorCount)
pSerialStatus->Errors |= SERIAL_ERROR_BREAK;
pSerialStatus->Errors |= SERIAL_ERROR_QUEUEOVERRUN;
if (DeviceExtension->SerialPerfStats.ParityErrorCount)
pSerialStatus->Errors |= SERIAL_ERROR_PARITY;
-
+
pSerialStatus->HoldReasons = 0; /* FIXME */
-
+
KeAcquireSpinLock(&DeviceExtension->InputBufferLock, &Irql);
pSerialStatus->AmountInInQueue = (DeviceExtension->InputBuffer.WritePosition + DeviceExtension->InputBuffer.Length
- DeviceExtension->InputBuffer.ReadPosition) % DeviceExtension->InputBuffer.Length;
KeReleaseSpinLock(&DeviceExtension->InputBufferLock, Irql);
-
+
KeAcquireSpinLock(&DeviceExtension->OutputBufferLock, &Irql);
pSerialStatus->AmountInOutQueue = (DeviceExtension->OutputBuffer.WritePosition + DeviceExtension->OutputBuffer.Length
- DeviceExtension->OutputBuffer.ReadPosition) % DeviceExtension->OutputBuffer.Length;
KeReleaseSpinLock(&DeviceExtension->OutputBufferLock, Irql);
-
+
pSerialStatus->EofReceived = FALSE; /* always FALSE */
pSerialStatus->WaitForImmediate = FALSE; /* always FALSE */
-
+
return STATUS_SUCCESS;
}
PVOID BufferIn, BufferOut;
PUCHAR ComPortBase;
NTSTATUS Status;
-
+
DPRINT("Serial: IRP_MJ_DEVICE_CONTROL dispatch\n");
-
+
Stack = IoGetCurrentIrpStackLocation(Irp);
LengthIn = Stack->Parameters.DeviceIoControl.InputBufferLength;
LengthOut = Stack->Parameters.DeviceIoControl.OutputBufferLength;
ComPortBase = (PUCHAR)DeviceExtension->BaseAddress;
IoControlCode = Stack->Parameters.DeviceIoControl.IoControlCode;
SerialGetUserBuffers(Irp, IoControlCode, &BufferIn, &BufferOut);
-
+
/* FIXME: need to probe buffers */
/* FIXME: see http://www.osronline.com/ddkx/serial/serref_61bm.htm */
switch (IoControlCode)
case IOCTL_SERIAL_CLR_DTR:
{
DPRINT("Serial: IOCTL_SERIAL_CLR_DTR\n");
- /* FIXME: If the handshake flow control of the device is configured to
+ /* FIXME: If the handshake flow control of the device is configured to
* automatically use DTR, return STATUS_INVALID_PARAMETER */
Status = IoAcquireRemoveLock(&DeviceExtension->RemoveLock, (PVOID)DeviceExtension->ComPort);
if (NT_SUCCESS(Status))
case IOCTL_SERIAL_CLR_RTS:
{
DPRINT("Serial: IOCTL_SERIAL_CLR_RTS\n");
- /* FIXME: If the handshake flow control of the device is configured to
+ /* FIXME: If the handshake flow control of the device is configured to
* automatically use RTS, return STATUS_INVALID_PARAMETER */
Status = IoAcquireRemoveLock(&DeviceExtension->RemoveLock, (PVOID)DeviceExtension->ComPort);
if (NT_SUCCESS(Status))
else
{
ULONG PurgeMask = *(PULONG)BufferIn;
-
+
Status = STATUS_SUCCESS;
/* FIXME: use SERIAL_PURGE_RXABORT and SERIAL_PURGE_TXABORT flags */
if (PurgeMask & SERIAL_PURGE_RXCLEAR)
}
KeReleaseSpinLock(&DeviceExtension->InputBufferLock, Irql);
}
-
+
if (PurgeMask & SERIAL_PURGE_TXCLEAR)
{
KeAcquireSpinLock(&DeviceExtension->OutputBufferLock, &Irql);
}
case IOCTL_SERIAL_SET_DTR:
{
- /* FIXME: If the handshake flow control of the device is configured to
+ /* FIXME: If the handshake flow control of the device is configured to
* automatically use DTR, return STATUS_INVALID_PARAMETER */
DPRINT("Serial: IOCTL_SERIAL_SET_DTR\n");
if (!(DeviceExtension->MCR & SR_MCR_DTR))
}
case IOCTL_SERIAL_SET_RTS:
{
- /* FIXME: If the handshake flow control of the device is configured to
+ /* FIXME: If the handshake flow control of the device is configured to
* automatically use DTR, return STATUS_INVALID_PARAMETER */
DPRINT("Serial: IOCTL_SERIAL_SET_RTS\n");
if (!(DeviceExtension->MCR & SR_MCR_RTS))
return IoCallDriver(DeviceExtension->LowerDevice, Irp);
}
}
-
+
Irp->IoStatus.Information = Information;
Irp->IoStatus.Status = Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/info.c
* PURPOSE: Serial IRP_MJ_QUERY_INFORMATION operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
ULONG BufferLength;
ULONG_PTR Information = 0;
NTSTATUS Status;
-
+
DeviceExtension = (PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
Stack = IoGetCurrentIrpStackLocation(Irp);
SystemBuffer = Irp->AssociatedIrp.SystemBuffer;
BufferLength = Stack->Parameters.QueryFile.Length;
-
+
switch (Stack->Parameters.QueryFile.FileInformationClass)
{
case FileStandardInformation:
{
PFILE_STANDARD_INFORMATION StandardInfo = (PFILE_STANDARD_INFORMATION)SystemBuffer;
-
+
DPRINT("Serial: IRP_MJ_QUERY_INFORMATION / FileStandardInformation\n");
if (BufferLength < sizeof(FILE_STANDARD_INFORMATION))
Status = STATUS_BUFFER_OVERFLOW;
case FilePositionInformation:
{
PFILE_POSITION_INFORMATION PositionInfo = (PFILE_POSITION_INFORMATION)SystemBuffer;
-
+
ASSERT(PositionInfo);
-
+
DPRINT("Serial: IRP_MJ_QUERY_INFORMATION / FilePositionInformation\n");
if (BufferLength < sizeof(PFILE_POSITION_INFORMATION))
Status = STATUS_BUFFER_OVERFLOW;
return ForwardIrpAndForget(DeviceObject, Irp);
}
}
-
+
Irp->IoStatus.Information = Information;
Irp->IoStatus.Status = Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/bus/serial/legacy.c
* PURPOSE: Legacy serial port enumeration
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
* Mark Junker (mjscod@gmx.de)
*/
UCHAR OldScr, Scr5A, ScrA5;
BOOLEAN FifoEnabled;
UCHAR NewFifoStatus;
-
+
Lcr = READ_PORT_UCHAR(SER_LCR(BaseAddress));
WRITE_PORT_UCHAR(SER_LCR(BaseAddress), Lcr ^ 0xFF);
TestLcr = READ_PORT_UCHAR(SER_LCR(BaseAddress)) ^ 0xFF;
WRITE_PORT_UCHAR(SER_LCR(BaseAddress), Lcr);
-
+
/* Accessing the LCR must work for a usable serial port */
if (TestLcr != Lcr)
return UartUnknown;
-
+
/* Ensure that all following accesses are done as required */
READ_PORT_UCHAR(SER_RBR(BaseAddress));
READ_PORT_UCHAR(SER_IER(BaseAddress));
READ_PORT_UCHAR(SER_LSR(BaseAddress));
READ_PORT_UCHAR(SER_MSR(BaseAddress));
READ_PORT_UCHAR(SER_SCR(BaseAddress));
-
+
/* Test scratch pad */
OldScr = READ_PORT_UCHAR(SER_SCR(BaseAddress));
WRITE_PORT_UCHAR(SER_SCR(BaseAddress), 0x5A);
WRITE_PORT_UCHAR(SER_SCR(BaseAddress), 0xA5);
ScrA5 = READ_PORT_UCHAR(SER_SCR(BaseAddress));
WRITE_PORT_UCHAR(SER_SCR(BaseAddress), OldScr);
-
+
/* When non-functional, we have a 8250 */
if (Scr5A != 0x5A || ScrA5 != 0xA5)
return Uart8250;
-
+
/* Test FIFO type */
FifoEnabled = (READ_PORT_UCHAR(SER_IIR(BaseAddress)) & 0x80) != 0;
WRITE_PORT_UCHAR(SER_FCR(BaseAddress), SR_FCR_ENABLE_FIFO);
* with 0x80 */
return Uart16550;
}
-
+
/* FIFO is only functional for 16550A+ */
return Uart16550A;
}
PDEVICE_OBJECT Fdo;
KIRQL Dirql;
NTSTATUS Status;
-
+
/* Create resource list */
ResourceListSize = sizeof(CM_RESOURCE_LIST) + sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR);
ResourceList = (PCM_RESOURCE_LIST)ExAllocatePoolWithTag(PagedPool, ResourceListSize, SERIAL_TAG);
ResourceDescriptor->u.Port.Start.u.HighPart = 0;
ResourceDescriptor->u.Port.Start.u.LowPart = ComPortBase;
ResourceDescriptor->u.Port.Length = 8;
-
+
ResourceDescriptor = &ResourceList->List[0].PartialResourceList.PartialDescriptors[1];
ResourceDescriptor->Type = CmResourceTypeInterrupt;
ResourceDescriptor->ShareDisposition = CmResourceShareShared;
&Dirql,
&ResourceDescriptor->u.Interrupt.Affinity);
ResourceDescriptor->u.Interrupt.Level = (ULONG)Dirql;
-
+
/* Report resource list */
Status = IoReportResourceForDetection(
DriverObject, ResourceList, ResourceListSize,
ExFreePoolWithTag(ResourceList, SERIAL_TAG);
return Status;
}
-
+
/* Test if port exists */
UartType = SerialDetectUartType((PUCHAR)ComPortBase);
-
+
/* Report device if detected... */
if (UartType != UartUnknown)
{
ULONG i;
NTSTATUS Status;
NTSTATUS ReturnedStatus = STATUS_SUCCESS;
-
+
for (i = 0; i < sizeof(ComPortBase)/sizeof(ComPortBase[0]); i++)
{
Status = DetectLegacyDevice(DriverObject, ComPortBase[i], Irq[i], &ComPortNumber[i]);
ReturnedStatus = Status;
DPRINT("Serial: Legacy device at 0x%x (IRQ %lu): status = 0x%08lx\n", ComPortBase[i], Irq[i], Status);
}
-
+
return ReturnedStatus;
}
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/misc.c
* PURPOSE: Misceallenous operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
/* FIXME: call IoAcquireRemoveLock/IoReleaseRemoveLock around each I/O operation */
PDEVICE_OBJECT LowerDevice = ((PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->LowerDevice;
KEVENT Event;
NTSTATUS Status;
-
+
ASSERT(LowerDevice);
-
+
KeInitializeEvent(&Event, NotificationEvent, FALSE);
IoCopyCurrentIrpStackLocationToNext(Irp);
-
+
DPRINT("Serial: Calling lower device %p [%wZ]\n", LowerDevice, &LowerDevice->DriverObject->DriverName);
IoSetCompletionRoutine(Irp, ForwardIrpAndWaitCompletion, &Event, TRUE, TRUE, TRUE);
-
+
Status = IoCallDriver(LowerDevice, Irp);
if (Status == STATUS_PENDING)
{
if (NT_SUCCESS(Status))
Status = Irp->IoStatus.Status;
}
-
+
return Status;
}
IN PIRP Irp)
{
PDEVICE_OBJECT LowerDevice = ((PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->LowerDevice;
-
+
ASSERT(LowerDevice);
-
+
IoSkipCurrentIrpStackLocation(Irp);
return IoCallDriver(LowerDevice, Irp);
}
KIRQL Irql;
UCHAR IER;
NTSTATUS Status;
-
+
DeviceExtension = (PSERIAL_DEVICE_EXTENSION)pDeviceExtension;
ComPortBase = (PUCHAR)DeviceExtension->BaseAddress;
-
+
KeAcquireSpinLock(&DeviceExtension->InputBufferLock, &Irql);
while (READ_PORT_UCHAR(SER_LSR(ComPortBase)) & SR_LSR_DATA_RECEIVED)
{
}
KeSetEvent(&DeviceExtension->InputBufferNotEmpty, 0, FALSE);
KeReleaseSpinLock(&DeviceExtension->InputBufferLock, Irql);
-
+
/* allow new interrupts */
IER = READ_PORT_UCHAR(SER_IER(ComPortBase));
WRITE_PORT_UCHAR(SER_IER(ComPortBase), IER | SR_IER_DATA_RECEIVED);
KIRQL Irql;
UCHAR IER;
NTSTATUS Status;
-
+
DeviceExtension = (PSERIAL_DEVICE_EXTENSION)pDeviceExtension;
ComPortBase = (PUCHAR)DeviceExtension->BaseAddress;
-
+
KeAcquireSpinLock(&DeviceExtension->OutputBufferLock, &Irql);
while (!IsCircularBufferEmpty(&DeviceExtension->OutputBuffer)
&& READ_PORT_UCHAR(SER_LSR(ComPortBase)) & SR_LSR_THR_EMPTY)
PSERIAL_DEVICE_EXTENSION DeviceExtension;
PUCHAR ComPortBase;
UCHAR Iir;
-
+
DeviceObject = (PDEVICE_OBJECT)ServiceContext;
DeviceExtension = (PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
ComPortBase = (PUCHAR)DeviceExtension->BaseAddress;
-
+
Iir = READ_PORT_UCHAR(SER_IIR(ComPortBase));
if (Iir == 0xff)
return TRUE;
Iir &= SR_IIR_ID_MASK;
if ((Iir & SR_IIR_SELF) != 0) { return FALSE; }
-
+
switch (Iir)
{
case SR_IIR_MSR_CHANGE:
{
UCHAR MSR, IER;
DPRINT("Serial: SR_IIR_MSR_CHANGE\n");
-
+
MSR = READ_PORT_UCHAR(SER_MSR(ComPortBase));
if (MSR & SR_MSR_CTS_CHANGED)
{
case SR_IIR_THR_EMPTY:
{
DPRINT("Serial: SR_IIR_THR_EMPTY\n");
-
+
KeInsertQueueDpc(&DeviceExtension->SendByteDpc, NULL, NULL);
return TRUE;
}
case SR_IIR_DATA_RECEIVED:
{
DPRINT("Serial: SR_IIR_DATA_RECEIVED\n");
-
+
KeInsertQueueDpc(&DeviceExtension->ReceivedByteDpc, NULL, NULL);
return TRUE;
}
{
UCHAR LSR;
DPRINT("Serial: SR_IIR_ERROR\n");
-
+
LSR = READ_PORT_UCHAR(SER_LSR(ComPortBase));
if (LSR & SR_LSR_OVERRUN_ERROR)
InterlockedIncrement(&DeviceExtension->SerialPerfStats.SerialOverrunErrorCount);
InterlockedIncrement(&DeviceExtension->SerialPerfStats.FrameErrorCount);
if (LSR & SR_LSR_BREAK_INT)
InterlockedIncrement(&DeviceExtension->BreakInterruptErrorCount);
-
+
return TRUE;
}
}
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/pnp.c
* PURPOSE: Serial IRP_MJ_PNP operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
/* FIXME: call IoAcquireRemoveLock/IoReleaseRemoveLock around each I/O operation */
UNICODE_STRING DeviceName;
static ULONG DeviceNumber = 0;
static ULONG ComPortNumber = 1;
-
+
DPRINT("Serial: SerialAddDeviceInternal called\n");
-
+
ASSERT(DeviceObject);
ASSERT(Pdo);
-
+
/* Create new device object */
swprintf(DeviceNameBuffer, L"\\Device\\Serial%lu", DeviceNumber);
RtlInitUnicodeString(&DeviceName, DeviceNameBuffer);
}
DeviceExtension = (PSERIAL_DEVICE_EXTENSION)Fdo->DeviceExtension;
RtlZeroMemory(DeviceExtension, sizeof(SERIAL_DEVICE_EXTENSION));
-
+
/* Register device interface */
Status = IoRegisterDeviceInterface(Pdo, &GUID_DEVINTERFACE_COMPORT, NULL, &DeviceExtension->SerialInterfaceName);
if (!NT_SUCCESS(Status))
DPRINT("Serial: IoRegisterDeviceInterface() failed with status 0x%08x\n", Status);
goto ByeBye;
}
-
+
DeviceExtension->SerialPortNumber = DeviceNumber++;
if (pComPortNumber == NULL)
DeviceExtension->ComPort = ComPortNumber++;
{
*pFdo = Fdo;
}
-
+
return STATUS_SUCCESS;
ByeBye:
*/
if (Pdo == NULL)
return STATUS_SUCCESS;
-
+
/* We have here a PDO not null. It represents a real serial
* port. So call the internal AddDevice function.
*/
UNICODE_STRING KeyName;
HANDLE hKey;
NTSTATUS Status;
-
+
DeviceExtension = (PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
-
+
ASSERT(ResourceList);
ASSERT(DeviceExtension);
ASSERT(DeviceExtension->PnpState == dsStopped);
-
+
DeviceExtension->BaudRate = 19200 | SERIAL_BAUD_USER;
DeviceExtension->BaseAddress = 0;
Dirql = 0;
if (!Dirql)
return STATUS_INSUFFICIENT_RESOURCES;
ComPortBase = (PUCHAR)DeviceExtension->BaseAddress;
-
+
if (DeviceExtension->UartType == UartUnknown)
DeviceExtension->UartType = SerialDetectUartType(ComPortBase);
-
+
/* Get current settings */
DeviceExtension->MCR = READ_PORT_UCHAR(SER_MCR(ComPortBase));
DeviceExtension->MSR = READ_PORT_UCHAR(SER_MSR(ComPortBase));
DeviceExtension->WaitMask = 0;
-
+
/* Set baud rate */
Status = SerialSetBaudRate(DeviceExtension, DeviceExtension->BaudRate);
if (!NT_SUCCESS(Status))
DPRINT("Serial: SerialSetBaudRate() failed with status 0x%08x\n", Status);
return Status;
}
-
+
/* Set line control */
DeviceExtension->SerialLineControl.StopBits = STOP_BIT_1;
DeviceExtension->SerialLineControl.Parity = NO_PARITY;
DPRINT("Serial: SerialSetLineControl() failed with status 0x%08x\n", Status);
return Status;
}
-
+
/* Clear receive/transmit buffers */
if (DeviceExtension->UartType >= Uart16550A)
{
WRITE_PORT_UCHAR(SER_FCR(ComPortBase),
SR_FCR_CLEAR_RCVR | SR_FCR_CLEAR_XMIT);
}
-
+
/* Create link \DosDevices\COMX -> \Device\SerialX */
swprintf(DeviceNameBuffer, L"\\Device\\Serial%lu", DeviceExtension->SerialPortNumber);
swprintf(LinkNameBuffer, L"\\DosDevices\\COM%lu", DeviceExtension->ComPort);
DPRINT("Serial: IoCreateSymbolicLink() failed with status 0x%08x\n", Status);
return Status;
}
-
+
/* Activate serial interface */
Status = IoSetDeviceInterfaceState(&DeviceExtension->SerialInterfaceName, TRUE);
if (!NT_SUCCESS(Status))
IoDeleteSymbolicLink(&LinkName);
return Status;
}
-
+
/* Connect interrupt and enable them */
Status = IoConnectInterrupt(
&DeviceExtension->Interrupt, SerialInterruptService,
IoDeleteSymbolicLink(&LinkName);
return Status;
}
-
+
/* Write an entry value under HKLM\HARDWARE\DeviceMap\SERIALCOMM */
/* This step is not mandatory, so don't exit in case of error */
RtlInitUnicodeString(&KeyName, L"\\Registry\\Machine\\HARDWARE\\DeviceMap\\SERIALCOMM");
ZwSetValueKey(hKey, &DeviceName, 0, REG_SZ, &ComPortBuffer, ComPort.Length + sizeof(WCHAR));
ZwClose(hKey);
}
-
+
DeviceExtension->PnpState = dsStarted;
-
+
/* Activate interrupt modes */
IER = READ_PORT_UCHAR(SER_IER(ComPortBase));
IER |= SR_IER_DATA_RECEIVED | SR_IER_THR_EMPTY | SR_IER_LSR_CHANGE | SR_IER_MSR_CHANGE;
WRITE_PORT_UCHAR(SER_IER(ComPortBase), IER);
-
+
/* Activate DTR, RTS */
DeviceExtension->MCR |= SR_MCR_DTR | SR_MCR_RTS;
WRITE_PORT_UCHAR(SER_MCR(ComPortBase), DeviceExtension->MCR);
-
+
return STATUS_SUCCESS;
}
PIO_STACK_LOCATION Stack;
ULONG_PTR Information = 0;
NTSTATUS Status;
-
+
Stack = IoGetCurrentIrpStackLocation(Irp);
MinorFunction = Stack->MinorFunction;
-
+
switch (MinorFunction)
{
case IRP_MN_START_DEVICE:
{
BOOLEAN ConflictDetected;
DPRINT("Serial: IRP_MJ_PNP / IRP_MN_START_DEVICE\n");
-
+
/* FIXME: first HACK: PnP manager can send multiple
* IRP_MN_START_DEVICE for one device
*/
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return Status;
}
-
+
/* Call lower driver */
Status = ForwardIrpAndWait(DeviceObject, Irp);
if (NT_SUCCESS(Status))
return ForwardIrpAndForget(DeviceObject, Irp);
}
}
-
+
Irp->IoStatus.Information = Information;
Irp->IoStatus.Status = Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/power.c
* PURPOSE: Serial IRP_MJ_POWER operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/create.c
* PURPOSE: Serial IRP_MJ_READ/IRP_MJ_WRITE operations
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
SerialGetUserBuffer(IN PIRP Irp)
{
ASSERT(Irp);
-
+
return Irp->AssociatedIrp.SystemBuffer;
}
PVOID ObjectsArray[2];
ULONG_PTR Information = 0;
NTSTATUS Status;
-
+
ASSERT(DeviceObject);
ASSERT(WorkItemData);
-
+
DeviceExtension = (PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
ComPortBase = (PUCHAR)DeviceExtension->BaseAddress;
Length = IoGetCurrentIrpStackLocation(Irp)->Parameters.Read.Length;
Buffer = SerialGetUserBuffer(Irp);
-
+
DPRINT("Serial: UseIntervalTimeout = %s, IntervalTimeout = %lu\n",
WorkItemData->UseIntervalTimeout ? "YES" : "NO",
WorkItemData->UseIntervalTimeout ? WorkItemData->IntervalTimeout.QuadPart : 0);
DPRINT("Serial: UseTotalTimeout = %s\n",
WorkItemData->UseTotalTimeout ? "YES" : "NO");
-
+
ObjectCount = 1;
ObjectsArray[0] = &DeviceExtension->InputBufferNotEmpty;
if (WorkItemData->UseTotalTimeout)
ObjectsArray[ObjectCount] = &TotalTimeoutTimer;
ObjectCount++;
}
-
+
/* while buffer is not fully filled */
while (Length > 0)
{
{
PopCircularBufferEntry(&DeviceExtension->InputBuffer, &ReceivedByte);
DPRINT("Serial: reading byte from buffer: 0x%02x\n", ReceivedByte);
-
+
Buffer[Information++] = ReceivedByte;
Length--;
}
KeClearEvent(&DeviceExtension->InputBufferNotEmpty);
KeReleaseSpinLock(&DeviceExtension->InputBufferLock, Irql);
-
+
if (WorkItemData->DontWait
&& !(WorkItemData->ReadAtLeastOneByte && Information == 0))
{
DPRINT("Serial: buffer empty. Don't wait more bytes\n");
break;
}
-
+
Status = KeWaitForMultipleObjects(
ObjectCount,
ObjectsArray,
FALSE,
(WorkItemData->UseIntervalTimeout && Information > 0) ? &WorkItemData->IntervalTimeout : NULL,
NULL);
-
+
if (Status == STATUS_TIMEOUT /* interval timeout */
|| Status == STATUS_WAIT_1) /* total timeout */
{
break;
}
}
-
+
/* stop total timeout timer */
if (WorkItemData->UseTotalTimeout)
KeCancelTimer(&TotalTimeoutTimer);
-
+
Irp->IoStatus.Information = Information;
if (Information == 0)
Irp->IoStatus.Status = STATUS_TIMEOUT;
{
PWORKITEM_DATA WorkItemData;
PIRP Irp;
-
+
DPRINT("Serial: SerialReadWorkItem() called\n");
-
+
WorkItemData = (PWORKITEM_DATA)pWorkItemData;
Irp = WorkItemData->Irp;
-
+
ReadBytes(DeviceObject, Irp, WorkItemData);
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
IoFreeWorkItem(WorkItemData->IoWorkItem);
ExFreePoolWithTag(pWorkItemData, SERIAL_TAG);
}
PWORKITEM_DATA WorkItemData;
PIO_WORKITEM WorkItem;
NTSTATUS Status;
-
+
DPRINT("Serial: IRP_MJ_READ\n");
-
+
Stack = IoGetCurrentIrpStackLocation(Irp);
Length = Stack->Parameters.Read.Length;
Buffer = SerialGetUserBuffer(Irp);
DeviceExtension = (PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
-
+
if (Stack->Parameters.Read.ByteOffset.QuadPart != 0 || Buffer == NULL)
{
Status = STATUS_INVALID_PARAMETER;
goto ByeBye;
}
-
+
if (Length == 0)
{
Status = STATUS_SUCCESS;
goto ByeBye;
}
-
+
/* Allocate memory for parameters */
WorkItemData = ExAllocatePoolWithTag(PagedPool, sizeof(WORKITEM_DATA), SERIAL_TAG);
if (!WorkItemData)
}
RtlZeroMemory(WorkItemData, sizeof(WORKITEM_DATA));
WorkItemData->Irp = Irp;
-
+
/* Calculate time outs */
if (DeviceExtension->SerialTimeOuts.ReadIntervalTimeout == INFINITE &&
DeviceExtension->SerialTimeOuts.ReadTotalTimeoutMultiplier == INFINITE &&
{
ULONG TotalTimeout;
LARGE_INTEGER SystemTime;
-
+
WorkItemData->UseTotalTimeout = TRUE;
TotalTimeout = DeviceExtension->SerialTimeOuts.ReadTotalTimeoutConstant +
DeviceExtension->SerialTimeOuts.ReadTotalTimeoutMultiplier * Length;
TotalTimeout * 10000;
}
}
-
+
/* Pend IRP */
WorkItem = IoAllocateWorkItem(DeviceObject);
if (WorkItem)
IoMarkIrpPending(Irp);
return STATUS_PENDING;
}
-
+
/* insufficient resources, we can't pend the Irp */
CHECKPOINT;
Status = IoAcquireRemoveLock(&DeviceExtension->RemoveLock, (PVOID)DeviceExtension->ComPort);
}
ReadBytes(DeviceObject, Irp, WorkItemData);
Status = Irp->IoStatus.Status;
-
+
IoReleaseRemoveLock(&DeviceExtension->RemoveLock, (PVOID)DeviceExtension->ComPort);
ByeBye:
PUCHAR ComPortBase;
KIRQL Irql;
NTSTATUS Status = STATUS_SUCCESS;
-
+
DPRINT("Serial: IRP_MJ_WRITE\n");
-
+
/* FIXME: pend operation if possible */
/* FIXME: use write timeouts */
-
+
Stack = IoGetCurrentIrpStackLocation(Irp);
Length = Stack->Parameters.Write.Length;
Buffer = SerialGetUserBuffer(Irp);
DeviceExtension = (PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
ComPortBase = (PUCHAR)DeviceExtension->BaseAddress;
-
+
if (Stack->Parameters.Write.ByteOffset.QuadPart != 0 || Buffer == NULL)
{
Status = STATUS_INVALID_PARAMETER;
goto ByeBye;
}
-
+
Status = IoAcquireRemoveLock(&DeviceExtension->RemoveLock, (PVOID)DeviceExtension->ComPort);
if (!NT_SUCCESS(Status))
goto ByeBye;
-
+
/* push bytes into output buffer */
KeAcquireSpinLock(&DeviceExtension->OutputBufferLock, &Irql);
while (Information < Length)
}
KeReleaseSpinLock(&DeviceExtension->OutputBufferLock, Irql);
IoReleaseRemoveLock(&DeviceExtension->RemoveLock, (PVOID)DeviceExtension->ComPort);
-
+
/* send bytes */
SerialSendByte(NULL, DeviceExtension, NULL, NULL);
/* $Id:
- *
+ *
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS kernel
* FILE: drivers/dd/serial/serial.c
* PURPOSE: Serial driver loading/unloading
- *
+ *
* PROGRAMMERS: Hervé Poussineau (poussine@freesurf.fr)
*/
IN PUNICODE_STRING RegPath)
{
ULONG i;
-
+
DriverObject->DriverUnload = DriverUnload;
DriverObject->DriverExtension->AddDevice = SerialAddDevice;
-
+
for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++)
DriverObject->MajorFunction[i] = ForwardIrpAndForget;
DriverObject->MajorFunction[IRP_MJ_CREATE] = SerialCreate;
DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] = SerialQueryInformation;
DriverObject->MajorFunction[IRP_MJ_PNP] = SerialPnp;
DriverObject->MajorFunction[IRP_MJ_POWER] = SerialPower;
-
+
return DetectLegacyDevices(DriverObject);
}
#include <ddk/ntddk.h>
#include <ddk/ntddser.h>
#include <stdio.h>
-
+
#include <debug.h>
-
+
/* FIXME: these prototypes MUST NOT be here! */
NTSTATUS STDCALL
IoAttachDeviceToDeviceStackSafe(
IN PDEVICE_OBJECT SourceDevice,
IN PDEVICE_OBJECT TargetDevice,
OUT PDEVICE_OBJECT *AttachedToDeviceObject);
-
+
#elif defined(_MSC_VER)
#include <ntddk.h>
#include <ntddser.h>
#include <stdio.h>
-
+
#define STDCALL
-
+
#define DPRINT1 DbgPrint("(%s:%d) ", __FILE__, __LINE__), DbgPrint
#define CHECKPOINT1 DbgPrint("(%s:%d)\n", __FILE__, __LINE__)
-
+
#define TAG(A, B, C, D) (ULONG)(((A)<<0) + ((B)<<8) + ((C)<<16) + ((D)<<24))
-
+
NTSTATUS STDCALL
IoAttachDeviceToDeviceStackSafe(
IN PDEVICE_OBJECT SourceDevice,
IN PDEVICE_OBJECT TargetDevice,
OUT PDEVICE_OBJECT *AttachedToDeviceObject);
-
+
#ifdef NDEBUG2
#define DPRINT
#define CHECKPOINT
PDEVICE_OBJECT LowerDevice;
SERIAL_DEVICE_STATE PnpState;
IO_REMOVE_LOCK RemoveLock;
-
+
ULONG SerialPortNumber;
-
+
ULONG ComPort;
ULONG BaudRate;
ULONG BaseAddress;
PKINTERRUPT Interrupt;
KDPC ReceivedByteDpc;
KDPC SendByteDpc;
-
+
SERIAL_LINE_CONTROL SerialLineControl;
UART_TYPE UartType;
ULONG WaitMask;
-
+
ULONG BreakInterruptErrorCount;
SERIALPERF_STATS SerialPerfStats;
SERIAL_TIMEOUTS SerialTimeOuts;
KSPIN_LOCK InputBufferLock;
CIRCULAR_BUFFER OutputBuffer;
KSPIN_LOCK OutputBufferLock;
-
+
UNICODE_STRING SerialInterfaceName;
-
+
/* Current values */
UCHAR MCR; /* Base+4, Modem Control Register */
UCHAR MSR; /* Base+6, Modem Status Register */
{
PIRP Irp;
PIO_WORKITEM IoWorkItem;
-
+
BOOLEAN UseIntervalTimeout;
BOOLEAN UseTotalTimeout;
LARGE_INTEGER IntervalTimeout;
BOOLEAN WaitToSend(UINT BasePort)
{
int TimeOut;
-
+
DPRINT("WaitToSend ");
// Check if it's OK to send
DPRINT("FAILED\n");
return FALSE;
}
-
+
DPRINT("SUCCEEDED\n");
return TRUE;
DPRINT("FAILED\n");
return FALSE;
}
-
+
DPRINT("SUCCEEDED\n");
return TRUE;
return FALSE;
DPRINT("Sound card initialized!\n");
-
+
return (DSP_Major * 256) + DSP_Minor;
}
DPRINT("Sorry - only 1 device supported by Sound Blaster driver at present :(\n");
return STATUS_NOT_IMPLEMENTED;
}
-
+
DPRINT("Creating IO device\n");
s = IoCreateDevice(Context, // driverobject
// Parameters = Instance->DriverObject->DriverExtension;
DPRINT("DeviceObject at 0x%x, DeviceExtension at 0x%x\n", DeviceObject, Parameters);
-
+
if (! Parameters)
{
DPRINT("NULL POINTER!\n");
Parameters->BufferSize = DEFAULT_BUFSIZE;
// Only to be enabled once we can get support for multiple cards working :)
-/*
+/*
DPRINT("Loading settings from: %S\n", RegistryPath);
-
+
s = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE, RegistryPath, Table,
&Parameters, NULL);
*/
{
DPRINT("BlasterCreate() called!\n");
-
+
// Initialize the MPU-401
// ... do stuff ...
IO_NO_INCREMENT);
DPRINT("BlasterCreate() completed\n");
-
+
return(STATUS_SUCCESS);
}
NTSTATUS Status;
DPRINT("BlasterClose() called!\n");
-
+
DeviceExtension = DeviceObject->DeviceExtension;
Status = STATUS_SUCCESS;
Data = (PBYTE) Irp->AssociatedIrp.SystemBuffer;
DPRINT("Sending %d bytes of MIDI data to 0x%d:\n", Stack->Parameters.DeviceIoControl.InputBufferLength, DeviceExtension->Port);
-
+
for (ByteCount = 0; ByteCount < Stack->Parameters.DeviceIoControl.InputBufferLength; ByteCount ++)
{
DPRINT("0x%x ", Data[ByteCount]);
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return(STATUS_SUCCESS);
}
*/
}
-
+
return(STATUS_SUCCESS);
/*
* FILE: drivers/dd/sound/dsp.c
* PURPOSE: Digital Signal Processing ?
* PROGRAMMER: Snatched from ?
- *
- * UPDATE HISTORY:
+ *
+ * UPDATE HISTORY:
* ??/??/??: Created
* 10/23/02: Steven Edwards (Steven_Ed4153@yahoo.com)
- * Minor build fix
+ * Minor build fix
*/
#include "dsp.h"
return SB_TRUE;
}
-
+
void write_dsp(unsigned short base,unsigned char data)
{
// while ((inb(base+DSP_WRITE_PORT) & 0x80) != 0);
// outb(base+DSP_WRITE_PORT, data);
}
-
+
* FILE: drivers/dd/sound/mixer.c
* PURPOSE: Wave Mixer?
* PROGRAMMER: ?
- *
- * UPDATE HISTORY:
+ *
+ * UPDATE HISTORY:
* ??/??/??: Created
* 10/23/02: Steven Edwards (Steven_Ed4153@yahoo.com)
- * Minor build fixes
+ * Minor build fixes
*/
#include "dsp.h"
if(hi==0x80) sb16->dma16=7;
if(hi==0x40) sb16->dma16=6;
if(hi==0x20) sb16->dma16=5;
-
+
if(lo==0x08) sb16->dma8=3;
if(lo==0x02) sb16->dma8=1;
if(lo==0x01) sb16->dma8=0;
* PROGRAMMER: Steven Edwards
* UPDATE HISTORY:
* 19/01/04 Created
- *
+ *
*/
/* INCLUDES ****************************************************************/
unsigned char dma16;
unsigned char* buffer;
}SB16;
-
+
* PURPOSE: SoundBlaster 16 Driver
* PROGRAMMER: Snatched from David Welch (welch@mcmail.com)
* Modified for Soundblaster by Robert Bergkvist (fragdance@hotmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
* ??/??/??: Created
- *
+ *
*/
/* FUNCTIONS **************************************************************/
{
PIO_STACK_LOCATION Stack = IoGetCurrentIrpStackLocation(Irp);
NTSTATUS status;
-
+
switch (Stack->MajorFunction)
{
case IRP_MJ_CREATE:
reset_dsp(sb16.base);
status = STATUS_SUCCESS;
break;
-
+
case IRP_MJ_CLOSE:
status = STATUS_SUCCESS;
break;
-
+
case IRP_MJ_WRITE:
DPRINT1("(SoundBlaster 16 Driver) Writing %d bytes\n",Stack->Parameters.Write.Length);
sb16_play((WAVE_HDR*)Irp->UserBuffer);
status = STATUS_SUCCESS;
break;
-
+
default:
status = STATUS_NOT_IMPLEMENTED;
break;
}
-
+
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(status);
}
{
PDEVICE_OBJECT DeviceObject;
NTSTATUS ret;
-
+
DPRINT1("SoundBlaster 16 Driver 0.0.1\n");
if(sb16_getenvironment()!=SB_TRUE)
{
ret = IoCreateDevice(DriverObject,0,"\\Device\\WaveOut",FILE_DEVICE_WAVE_OUT,0,FALSE,&DeviceObject);
if (ret!=STATUS_SUCCESS)
return(ret);
-
+
DeviceObject->Flags=0;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = Dispatch;
DriverObject->MajorFunction[IRP_MJ_CREATE] =Dispatch;
DriverObject->MajorFunction[IRP_MJ_WRITE] = Dispatch;
DriverObject->MajorFunction[IRP_MJ_WRITE] = Dispatch;
DriverObject->DriverUnload = NULL;
-
+
return(STATUS_SUCCESS);
}
* PURPOSE: SoundBlaster 16 Driver
* PROGRAMMER: Snatched from David Welch (welch@mcmail.com)
* Modified for Soundblaster by Robert Bergkvist (fragdance@hotmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
* ??/??/??: Created
- *
+ *
*/
/* FUNCTIONS **************************************************************/
KAFFINITY Affinity;
PKINTERRUPT IrqObject;
unsigned int mask,newmask;
-
+
unsigned int i;
unsigned int tmp[255];
i=0;
__asm__("pushf\n\tpop %0\n\tcli\n\t"
: "=m" (eflags)
: );
-
+
memcpy(sb16.buffer,(&wave->data),wave->dLen);
- IoConnectInterrupt(&IrqObject,DMAOutputISR,0,NULL,MappedIrq,Dirql,Dirql,0,FALSE,Affinity,FALSE);
+ IoConnectInterrupt(&IrqObject,DMAOutputISR,0,NULL,MappedIrq,Dirql,Dirql,0,FALSE,Affinity,FALSE);
// mask=inb(0x21);
newmask=((int)1<<sb16.irq);
// Restore the interrupt flag
__asm__("push %0\n\tpopf\n\t"
:
- : "m" (eflags));
+ : "m" (eflags));
+
+
-
-
// disable_dma(sb16.dma8);
//outb(0x0a,5);
// clear_dma_ff(1);
//outb(0x2,(((unsigned int)(sb16.buffer-IDMAP_BASE)>>8))&0xff);
//enable_dma(sb16.dma8);
//outb(0xa,1);
-
+
write_dsp(sb16.base,0x00D1);
-
+
write_dsp(sb16.base,0x40);
write_dsp(sb16.base,((unsigned char)256-(1000000/wave->nSamplesPerSec)));
// outb(sb16.base + 4, (int) 4);
// outb(sb16.base + 5, (int) 0xFF);
-
+
// outb(sb16.base + 4, (int) 0x22);
// outb(sb16.base + 5, (int) 0xFF);
write_dsp(sb16.base,0x14);
- write_dsp(sb16.base,(wave->dLen&0x00ff));
+ write_dsp(sb16.base,(wave->dLen&0x00ff));
write_dsp(sb16.base,((wave->dLen)&0xff00)>>8);
// write_dsp(sb16.base,0xc0);
// write_dsp(sb16.base,0x0);
// OldIRQ=HalGetInterruptVector(Internal,0,0,irq+8,&irql,&affinity);
// DPRINT1("OldIRQ: 0x%x\n",OldIRQ);
-
+
// status=IoConnectInterrupt(&IrqObject,playRoutine,0,NULL,OldIRQ,irql,irql,0,FALSE,affinity,FALSE);
// if(status!=STATUS_SUCCESS) DPRINT1("Couldn't set irq\n");
// else DPRINT1("IRQ set\n");
-
+
}
void dump_wav(WAVE_HDR* wave)
KAFFINITY affinity;
typedef struct
-{
+{
unsigned char rID[4] __attribute__((packed)); //4 0
unsigned int rLen __attribute__((packed)); //4 4
unsigned char wID[4] __attribute__((packed)); //4 8
* FILE: services/test/test.c
* PURPOSE: Testing driver
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
* ??/??/??: Created
* 18/06/98: Made more NT like
*/
NTSTATUS STDCALL TestWrite(PIRP Irp, PIO_STACK_LOCATION Stk)
{
PVOID Address;
-
+
Address = MmGetSystemAddressForMdl(Irp->MdlAddress);
DbgPrint("Asked to write '%s'\n",(PCH)Address);
return(STATUS_SUCCESS);
PIO_STACK_LOCATION Stack = IoGetCurrentIrpStackLocation(Irp);
NTSTATUS status;
int i;
-
+
switch (Stack->MajorFunction)
{
case IRP_MJ_CREATE:
DbgPrint("(Test Driver) Creating\n");
status = STATUS_SUCCESS;
break;
-
+
case IRP_MJ_CLOSE:
status = STATUS_SUCCESS;
break;
-
+
case IRP_MJ_WRITE:
DbgPrint("(Test Driver) Writing\n");
status = TestWrite(Irp,Stack);
break;
-
+
default:
status = STATUS_NOT_IMPLEMENTED;
break;
}
-
+
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(status);
}
NTSTATUS ret;
ANSI_STRING astr;
UNICODE_STRING ustr;
-
+
DbgPrint("Test Driver 0.0.1\n");
-
+
#if 0
RtlInitAnsiString(&astr,"\\Device\\Test");
RtlAnsiStringToUnicodeString(&ustr,&astr,TRUE);
CdfsDirectoryControl;
DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] =
CdfsQueryInformation;
- DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION] =
+ DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION] =
CdfsSetInformation;
DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] =
CdfsQueryVolumeInformation;
* FILE: services/fs/cdfs/cleanup.c
* PURPOSE: CDROM (ISO 9660) filesystem driver
* PROGRAMMER: Hartmut Birr
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
CcUninitializeCacheMap (FileObject, NULL, NULL);
#endif
}
-
+
return STATUS_SUCCESS;
}
* FILE: services/fs/cdfs/close.c
* PURPOSE: CDROM (ISO 9660) filesystem driver
* PROGRAMMER: Art Yerkes
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
*/
{
PCCB Ccb;
-
+
DPRINT("CdfsCloseFile(DeviceExt %x, FileObject %x)\n",
DeviceExt,
FileObject);
NTSTATUS Status;
DPRINT("CdfsDeviceIoControl(DeviceObject %x, CtlCode %x, "
- "InputBuffer %x, InputBufferSize %x, OutputBuffer %x, "
- "POutputBufferSize %x (%x)\n", DeviceObject, CtlCode,
- InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize,
+ "InputBuffer %x, InputBufferSize %x, OutputBuffer %x, "
+ "POutputBufferSize %x (%x)\n", DeviceObject, CtlCode,
+ InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize,
OutputBufferSize ? *OutputBufferSize : 0);
KeInitializeEvent (&Event, NotificationEvent, FALSE);
RequestedDisposition = ((Stack->Parameters.Create.Options >> 24) & 0xff);
RequestedOptions = Stack->Parameters.Create.Options & FILE_VALID_OPTION_FLAGS;
- DPRINT("RequestedDisposition %x, RequestedOptions %x\n",
+ DPRINT("RequestedDisposition %x, RequestedOptions %x\n",
RequestedDisposition, RequestedOptions);
FileObject = Stack->FileObject;
* PURPOSE: CDROM (ISO 9660) filesystem driver
* PROGRAMMER: Art Yerkes
* Eric Kohl
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
{
PDIR_RECORD Record = *Ptr;
ULONG Index;
-
+
if (*CurrentOffset >= DirLength)
return(STATUS_NO_MORE_ENTRIES);
* FILE: services/fs/cdfs/fcb.c
* PURPOSE: CDROM (ISO 9660) filesystem driver
* PROGRAMMER: Art Yerkes
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
FileObject->FsContext2 = newCCB;
newCCB->PtrFileObject = FileObject;
Fcb->DevExt = Vcb;
-
+
if (CdfsFCBIsDirectory(Fcb))
{
#ifdef USE_ROS_CC_AND_FS
DPRINT("RecordLength == 0 Stopped!\n");
break;
}
-
+
DPRINT("RecordLength %u ExtAttrRecordLength %u NameLength %u\n",
Record->RecordLength, Record->ExtAttrRecordLength, Record->FileIdLength);
* PURPOSE: CDROM (ISO 9660) filesystem driver
* PROGRAMMER: Art Yerkes
* Eric Kohl
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
if (CdfsFCBIsDirectory(Fcb))
{
- StandardInfo->AllocationSize.QuadPart = 0LL;;
+ StandardInfo->AllocationSize.QuadPart = 0LL;
StandardInfo->EndOfFile.QuadPart = 0LL;
StandardInfo->Directory = TRUE;
}
&NetworkInfo->ChangeTime);
if (CdfsFCBIsDirectory(Fcb))
{
- NetworkInfo->AllocationSize.QuadPart = 0LL;;
+ NetworkInfo->AllocationSize.QuadPart = 0LL;
NetworkInfo->EndOfFile.QuadPart = 0LL;
}
else
return Status;
}
- DPRINT("FirstSession %d, LastSession %d, FirstTrack %d\n",
+ DPRINT("FirstSession %d, LastSession %d, FirstTrack %d\n",
Toc.FirstSession, Toc.LastSession, Toc.TrackData.TrackNumber);
Offset = 0;
* FILE: services/fs/cdfs/misc.c
* PURPOSE: CDROM (ISO 9660) filesystem driver
* PROGRAMMER: Eric Kohl
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
{
if (FileObject->Flags & FO_SYNCHRONOUS_IO)
{
- FileObject->CurrentByteOffset.QuadPart =
+ FileObject->CurrentByteOffset.QuadPart =
ReadOffset.QuadPart + ReturnedReadLength;
}
Irp->IoStatus.Information = ReturnedReadLength;
* FILE: services/fs/ext2/attr.c
* PURPOSE: Set/Get file attributes support
* PROGRAMMER: David Welch (welch@cwcom.net)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
Ext2SetInformation(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
DPRINT("Ext2SetInformation(DeviceObject %x Irp %x)\n",DeviceObject,Irp);
-
+
Irp->IoStatus.Status = STATUS_NOT_IMPLEMENTED;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp,
IO_NO_INCREMENT);
-
+
return(STATUS_UNSUCCESSFUL);
}
PFILE_NAME_INFORMATION PFileNameInformation;
PFILE_POSITION_INFORMATION PFilePositionInformation;
PVOID Buffer;
-
+
DPRINT("Ext2QueryInformation(DeviceObject %x Irp %x)\n", DeviceObject, Irp);
-
+
Param = IoGetCurrentIrpStackLocation(Irp);
FileObject = Param->FileObject;
DeviceExt = DeviceObject->DeviceExtension;
Length = Param->Parameters.QueryFile.Length;
Buffer = Irp->AssociatedIrp.SystemBuffer;
-
+
switch (Param->Parameters.QueryFile.FileInformationClass)
{
case FileDirectoryInformation:
case FileBothDirectoryInformation:
Status = STATUS_NOT_IMPLEMENTED;
break;
-
+
case FileBasicInformation:
PFileBasicInformation = (PFILE_BASIC_INFORMATION)Buffer;
memset(PFileBasicInformation, 0, sizeof(FILE_BASIC_INFORMATION));
Status = STATUS_SUCCESS;
break;
-
+
case FileStandardInformation:
PFileStandardInformation = (PFILE_STANDARD_INFORMATION)Buffer;
memset(PFileStandardInformation, 0, sizeof(FILE_STANDARD_INFORMATION));
Status = STATUS_SUCCESS;
break;
-
+
case FileInternalInformation:
PFileInternalInformation = (PFILE_INTERNAL_INFORMATION)Buffer;
memset(PFileInternalInformation, 0, sizeof(FILE_INTERNAL_INFORMATION));
Status = STATUS_SUCCESS;
break;
-
+
case FileEaInformation:
PFileEaInformation = (PFILE_EA_INFORMATION)Buffer;
memset(PFileEaInformation, 0, sizeof(FILE_EA_INFORMATION));
PFileEaInformation->EaSize = 0;
Status = STATUS_SUCCESS;
break;
-
+
case FileAccessInformation:
PFileAccessInformation = (PFILE_ACCESS_INFORMATION)Buffer;
memset(PFileAccessInformation, 0, sizeof(FILE_ACCESS_INFORMATION));
PFileAccessInformation->AccessFlags = 0;
Status = STATUS_SUCCESS;
break;
-
+
case FileNameInformation:
PFileNameInformation = (PFILE_NAME_INFORMATION)Buffer;
memset(PFileNameInformation, 0, sizeof(FILE_NAME_INFORMATION));
Status = STATUS_SUCCESS;
break;
-
+
case FilePositionInformation:
PFilePositionInformation = (PFILE_POSITION_INFORMATION)Buffer;
- memcpy(PFilePositionInformation,
+ memcpy(PFilePositionInformation,
&FileObject->CurrentByteOffset,
sizeof(FileObject->CurrentByteOffset));
Status = STATUS_SUCCESS;
break;
-
+
case FileRenameInformation:
Status = STATUS_NOT_IMPLEMENTED;
break;
-
+
default:
Status = STATUS_NOT_SUPPORTED;
}
-
-
-
-
+
+
+
+
Irp->IoStatus.Status = Status;
if (NT_SUCCESS(Status))
Irp->IoStatus.Information =
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp,
IO_NO_INCREMENT);
-
+
return(Status);
}
* FILE: services/fs/ext2/blockdev.c
* PURPOSE: Temporary sector reading support
* PROGRAMMER: David Welch (welch@cwcom.net)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
NTSTATUS status;
ULONG sectorSize;
int j;
-
+
DPRINT("VFATReadSector(pDeviceObject %x, DiskSector %d, Buffer %x)\n",
pDeviceObject,DiskSector,Buffer);
sectorNumber.u.HighPart = 0;
sectorNumber.u.LowPart = DiskSector * BLOCKSIZE;
- DPRINT("DiskSector:%ld BLKSZ:%ld sectorNumber:%ld:%ld\n",
+ DPRINT("DiskSector:%ld BLKSZ:%ld sectorNumber:%ld:%ld\n",
(unsigned long) DiskSector,
(unsigned long) BLOCKSIZE,
(unsigned long) sectorNumber.u.HighPart,
&event,
&ioStatus );
- if (!irp)
+ if (!irp)
{
DbgPrint("READ failed!!!\n");
return FALSE;
}
-
+
DPRINT("Calling IO Driver...\n");
status = IoCallDriver(pDeviceObject, irp);
DPRINT("Waiting for IO Operation...\n");
- if (status == STATUS_PENDING)
+ if (status == STATUS_PENDING)
{
KeWaitForSingleObject(&event,
Suspended,
status = ioStatus.Status;
}
- if (!NT_SUCCESS(status))
+ if (!NT_SUCCESS(status))
{
DbgPrint("IO failed!!! Error code: %d(%x)\n", status, status);
return FALSE;
}
-
+
return TRUE;
}
ULONG sectorSize;
PULONG mbr;
int j;
-
+
DPRINT("VFATWriteSector(pDeviceObject %x, DiskSector %d, Buffer %x)\n",
pDeviceObject,DiskSector,Buffer);
* FILE: services/fs/ext2/dir.c
* PURPOSE: ext2 filesystem
* PROGRAMMER: David Welch (welch@cwcom.net)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
static VOID Ext2ConvertName(PWSTR Out, PCH In, ULONG Len)
{
ULONG i;
-
+
for (i=0; i<Len; i++)
{
*Out = *In;
PFILE_NAMES_INFORMATION FNI;
PFILE_BOTH_DIRECTORY_INFORMATION FBI;
struct ext2_inode inode;
-
+
DPRINT("FileIndex %d\n",FileIndex);
DPRINT("Buffer %x\n",Buffer);
-
+
Ext2ReadInode(DeviceExt,
dir_entry->inode,
&inode);
-
+
switch (IoStack->Parameters.QueryDirectory.FileInformationClass)
{
case FileNamesInformation:
FNI = (PFILE_NAMES_INFORMATION)Buffer;
FNI->NextEntryOffset = sizeof(FileDirectoryInformation) +
dir_entry->name_len + 1;
- FNI->FileNameLength = dir_entry->name_len;
+ FNI->FileNameLength = dir_entry->name_len;
Ext2ConvertName(FNI->FileName, dir_entry->name, dir_entry->name_len);
Buffer = Buffer + FNI->NextEntryOffset;
break;
-
+
case FileDirectoryInformation:
FDI = (PFILE_DIRECTORY_INFORMATION)Buffer;
- FDI->NextEntryOffset = sizeof(FileDirectoryInformation) +
+ FDI->NextEntryOffset = sizeof(FileDirectoryInformation) +
dir_entry->name_len + 1;
FDI->FileIndex = FileIndex;
// FDI->CreationTime = 0;
Ext2ConvertName(FDI->FileName, dir_entry->name, dir_entry->name_len);
Buffer = Buffer + FDI->NextEntryOffset;
break;
-
+
case FileBothDirectoryInformation:
FBI = (PFILE_BOTH_DIRECTORY_INFORMATION)Buffer;
FBI->NextEntryOffset = sizeof(FileBothDirectoryInformation) +
memset(FBI->ShortName, 0, sizeof(FBI->ShortName));
Buffer = Buffer + FBI->NextEntryOffset;
break;
-
+
default:
UNIMPLEMENTED;
}
ULONG StartIndex;
PVOID Buffer = NULL;
struct ext2_dir_entry dir_entry;
-
+
Buffer = Irp->UserBuffer;
DPRINT("Buffer %x\n",Buffer);
DPRINT("IoStack->Flags %x\n",IoStack->Flags);
-
+
if (IoStack->Flags & SL_RETURN_SINGLE_ENTRY)
{
Max = 1;
{
UNIMPLEMENTED;
}
-
+
DPRINT("Buffer->FileIndex %d\n",
((PFILE_DIRECTORY_INFORMATION)Buffer)->FileIndex);
if (IoStack->Flags & SL_INDEX_SPECIFIED)
{
StartIndex = 0;
}
-
+
if (IoStack->Flags & SL_RESTART_SCAN)
{
StartIndex = 0;
}
-
+
DPRINT("StartIndex %d\n",StartIndex);
-
+
for (i=0; i<Max ;i++)
{
if (!Ext2ScanDir(DeviceExt,&Fcb->inode,"*",&dir_entry,&StartIndex))
return(STATUS_NO_MORE_FILES);
}
Buffer = Ext2ProcessDirEntry(DeviceExt,
- &dir_entry,
- IoStack,
- Buffer,
+ &dir_entry,
+ IoStack,
+ Buffer,
StartIndex);
}
return(STATUS_SUCCESS);
PEXT2_FCB Fcb = (PVOID)FileObject->FsContext;
NTSTATUS Status;
PDEVICE_EXTENSION DeviceExt;
-
+
DPRINT("Ext2DirectoryControl(DeviceObject %x, Irp %x)\n",DeviceObject,Irp);
-
+
DeviceExt = DeviceObject->DeviceExtension;
-
+
switch (Stack->MinorFunction)
{
case IRP_MN_QUERY_DIRECTORY:
Status = Ext2QueryDirectory(DeviceExt, Fcb, Irp, Stack);
break;
-
+
default:
Status = STATUS_UNSUCCESSFUL;
}
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
- return(Status);
+ return(Status);
}
BOOL Ext2ScanDir(PDEVICE_EXTENSION DeviceExt,
- struct ext2_inode* dir,
+ struct ext2_inode* dir,
PCH filename,
struct ext2_dir_entry* ret,
PULONG StartIndex)
struct ext2_dir_entry* current;
ULONG block;
BOOL b;
-
+
DPRINT("Ext2ScanDir(dir %x, filename %s, ret %x)\n",dir,filename,ret);
-
+
buffer = ExAllocatePool(NonPagedPool, BLOCKSIZE);
-
+
for (i=0; i<((*StartIndex)/BLOCKSIZE); i++);
for (; (block = Ext2BlockMap(DeviceExt, dir, i)) != 0; i++)
{
DbgPrint("ext2fs:%s:%d: Disk io failed\n", __FILE__, __LINE__);
return(FALSE);
}
-
+
offset = (*StartIndex)%BLOCKSIZE;
while (offset < BLOCKSIZE)
{
current = &buffer[offset];
-
+
strncpy(name,current->name,current->name_len);
name[current->name_len]=0;
-
+
DPRINT("Scanning offset %d inode %d name %s\n",
offset,current->inode,name);
ExFreePool(buffer);
return(TRUE);
}
-
+
offset = offset + current->rec_len;
ASSERT(current->rec_len != 0);
DPRINT("offset %d\n",offset);
*StringA = 0;
}
-NTSTATUS Ext2OpenFile(PDEVICE_EXTENSION DeviceExt, PFILE_OBJECT FileObject,
+NTSTATUS Ext2OpenFile(PDEVICE_EXTENSION DeviceExt, PFILE_OBJECT FileObject,
PWSTR FileName)
/*
* FUNCTION: Opens a file
char* current_segment;
PEXT2_FCB Fcb;
ULONG StartIndex = 0;
-
+
DPRINT("Ext2OpenFile(DeviceExt %x, FileObject %x, FileName %S)\n",
DeviceExt,FileObject,FileName);
-
+
Fcb = ExAllocatePool(NonPagedPool, sizeof(EXT2_FCB));
-
+
unicode_to_ansi(name,FileName);
DPRINT("name %s\n",name);
DPRINT("strtok %x\n",strtok);
&parent_inode);
}
DPRINT("Found file\n");
-
+
Fcb->inode = current_inode;
CcRosInitializeFileCache(FileObject, &Fcb->Bcb, PAGE_SIZE*3);
FileObject->FsContext = Fcb;
-
+
return(STATUS_SUCCESS);
}
PFILE_OBJECT FileObject = Stack->FileObject;
NTSTATUS Status;
PDEVICE_EXTENSION DeviceExt;
-
+
DPRINT("Ext2Create(DeviceObject %x, Irp %x)\n",DeviceObject,Irp);
-
+
DeviceExt = DeviceObject->DeviceExtension;
Status = Ext2OpenFile(DeviceExt,FileObject,FileObject->FileName.Buffer);
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(Status);
}
* the incompatible feature set is that if there is a bit set
* in the incompatible feature set that the kernel doesn't
* know about, it should refuse to mount the filesystem.
- *
+ *
* e2fsck's requirements are more strict; if it doesn't know
* about a feature in either the compatible or incompatible
* feature set, it must abort and not try to meddle with
#define EXT2_APPEND_FL 0x00000020 /* writes to file may only append */
#define EXT2_NODUMP_FL 0x00000040 /* do not dump file */
#define EXT2_RESERVED_FL 0x80000000 /* reserved for ext2 lib */
-
+
/*
* Structure of a blocks group descriptor
ULONG Ext2BlockMap(PDEVICE_EXTENSION DeviceExt,
struct ext2_inode* inode,
ULONG offset);
-NTSTATUS Ext2OpenFile(PDEVICE_EXTENSION DeviceExt, PFILE_OBJECT FileObject,
+NTSTATUS Ext2OpenFile(PDEVICE_EXTENSION DeviceExt, PFILE_OBJECT FileObject,
PWSTR FileName);
-NTSTATUS Ext2ReadFile(PDEVICE_EXTENSION DeviceExt,
+NTSTATUS Ext2ReadFile(PDEVICE_EXTENSION DeviceExt,
PFILE_OBJECT FileObject,
- PVOID Buffer,
- ULONG Length,
+ PVOID Buffer,
+ ULONG Length,
LARGE_INTEGER Offset);
NTSTATUS STDCALL Ext2Create(PDEVICE_OBJECT DeviceObject, PIRP Irp);
NTSTATUS STDCALL Ext2DirectoryControl(PDEVICE_OBJECT DeviceObject, PIRP Irp);
* FILE: services/fs/ext2/super.c
* PURPOSE: ext2 filesystem
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
ULONG block;
PULONG TempBuffer;
BOOL b;
-
+
DPRINT("Ext2BlockMap(DeviceExt %x, inode %x, offset %d)\n",
DeviceExt,inode,offset);
if (offset < EXT2_NDIR_BLOCKS)
struct ext2_group_desc* buffer;
ULONG block;
struct ext2_group_desc* gdp;
-
+
buffer = ExAllocatePool(NonPagedPool, BLOCKSIZE);
-
+
block = block_group / (BLOCKSIZE / sizeof(struct ext2_group_desc));
-
+
Ext2ReadSectors(DeviceExt->StorageDevice,
2 + block,
1,
buffer);
-
+
gdp = &buffer[block_group % (BLOCKSIZE / sizeof(struct ext2_group_desc))];
-
+
DPRINT("gdp->bg_free_blocks_count %d\n",gdp->bg_free_blocks_count);
DPRINT("gdp->bg_inode_table %d\n",gdp->bg_inode_table);
-
+
return(gdp);
-
+
}
#define INODES_PER_PAGE (PAGE_SIZE / sizeof(struct ext2_inode))
{
ULONG block_group;
struct ext2_group_desc* gdp;
- ULONG offset;
+ ULONG offset;
ULONG dsec;
BOOLEAN Uptodate;
struct ext2_inode* ibuffer;
-
+
DPRINT("Ext2LoadInode(DeviceExt %x, ino %d, Inode %x)\n",
DeviceExt, ino, Inode);
-
+
block_group = (ino - 1) / DeviceExt->superblock->s_inodes_per_group;
-
+
DPRINT("block_group %d\n",block_group);
-
+
gdp = Ext2LoadGroupDesc(DeviceExt, block_group);
offset = (ino - 1) % DeviceExt->superblock->s_inodes_per_group;
-
+
DPRINT("offset %d\n", offset);
-
+
dsec = (gdp->bg_inode_table + (offset / INODES_PER_BLOCK)) * BLOCKSIZE;
-
- DPRINT("dsec %d (dsec/BLOCKSIZE) %d PAGE_ROUND_DOWN(dsec) %d\n",
+
+ DPRINT("dsec %d (dsec/BLOCKSIZE) %d PAGE_ROUND_DOWN(dsec) %d\n",
dsec, (dsec/BLOCKSIZE), PAGE_ROUND_DOWN(dsec));
-
+
CcRequestCachePage(DeviceExt->Bcb,
PAGE_ROUND_DOWN(dsec),
&Inode->BaseAddress,
DPRINT("Inode->BaseAddress 0x%x ibuffer 0x%x\n",
Inode->BaseAddress, ibuffer);
Inode->inode = &ibuffer[offset % INODES_PER_PAGE];
-
+
DPRINT("inode->i_uid %d\n",Inode->inode->i_uid);
DPRINT("inode->i_links_count %d\n",Inode->inode->i_links_count);
DPRINT("inode->i_blocks %d\n",Inode->inode->i_blocks);
-
+
DPRINT("Ext2LoadInode() finished\n");
}
Inode->BaseAddress = NULL;
Inode->inode = NULL;
}
-
+
VOID Ext2ReadInode(PDEVICE_EXTENSION DeviceExt,
ULONG ino,
struct ext2_inode* inode)
struct ext2_group_desc* gdp;
ULONG offset;
struct ext2_inode* buffer;
-
+
DPRINT("Ext2ReadInode(DeviceExt %x, ino %d, inode %x)\n",
DeviceExt,ino,inode);
-
+
block_group = (ino - 1) / DeviceExt->superblock->s_inodes_per_group;
-
+
gdp = Ext2LoadGroupDesc(DeviceExt, block_group);
-
-
+
+
offset = (ino - 1) % DeviceExt->superblock->s_inodes_per_group;
-
+
buffer = ExAllocatePool(NonPagedPool, BLOCKSIZE);
Ext2ReadSectors(DeviceExt->StorageDevice,
gdp->bg_inode_table + (offset / INODES_PER_BLOCK),
1,
buffer);
memcpy(inode,&buffer[offset % INODES_PER_BLOCK],sizeof(struct ext2_inode));
-
+
DPRINT("inode->i_uid %d\n",inode->i_uid);
DPRINT("inode->i_links_count %d\n",inode->i_links_count);
DPRINT("inode->i_blocks %d\n",inode->i_blocks);
-
+
}
* FILE: services/fs/ext2/quota.c
* PURPOSE: Quota support
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
Ext2QueryQuota(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
NTSTATUS Status;
-
+
Status = STATUS_NOT_IMPLEMENTED;
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(Status);
}
Ext2SetQuota(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
NTSTATUS Status;
-
+
Status = STATUS_NOT_IMPLEMENTED;
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(Status);
}
* FILE: services/fs/ext2/super.c
* PURPOSE: ext2 filesystem
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
ULONG Offset)
{
ULONG block, i;
-
+
for (i=0; i<4; i++)
{
- block = Ext2BlockMap(DeviceExt,
- Fcb->i.inode,
+ block = Ext2BlockMap(DeviceExt,
+ Fcb->i.inode,
Offset + i);
Ext2ReadSectors(DeviceExt->StorageDevice,
block,
return(STATUS_SUCCESS);
}
-NTSTATUS Ext2ReadFile(PDEVICE_EXTENSION DeviceExt,
+NTSTATUS Ext2ReadFile(PDEVICE_EXTENSION DeviceExt,
PFILE_OBJECT FileObject,
- PVOID Buffer,
- ULONG Length,
+ PVOID Buffer,
+ ULONG Length,
LARGE_INTEGER OffsetL)
{
PVOID BaseAddress;
Ext2LoadInode(DeviceExt,
Fcb->inode,
&Fcb->i);
-
+
if (Offset >= Fcb->i.inode->i_size)
{
DPRINT("Returning end of file\n");
{
Length = Fcb->i.inode->i_size - Offset;
}
-
+
Ext2ReleaseInode(DeviceExt,
&Fcb->i);
-
+
if ((Offset % PAGE_SIZE) != 0)
{
Delta = min(PAGE_SIZE - (Offset % PAGE_SIZE),Length);
memcpy(Buffer, BaseAddress, PAGE_SIZE);
CcReleaseCachePage(Fcb->Bcb,
CacheSeg,
- TRUE);
+ TRUE);
Length = Length - PAGE_SIZE;
Offset = Offset + PAGE_SIZE;
Buffer = Buffer + PAGE_SIZE;
memcpy(Buffer,BaseAddress,Length);
CcReleaseCachePage(Fcb->Bcb,
CacheSeg,
- TRUE);
+ TRUE);
}
CHECKPOINT;
-
+
return(STATUS_SUCCESS);
}
Ext2Write(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
DPRINT("Ext2Write(DeviceObject %x Irp %x)\n",DeviceObject,Irp);
-
+
Irp->IoStatus.Status = STATUS_UNSUCCESSFUL;
Irp->IoStatus.Information = 0;
return(STATUS_UNSUCCESSFUL);
Ext2FlushBuffers(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
DPRINT("Ext2FlushBuffers(DeviceObject %x Irp %x)\n",DeviceObject,Irp);
-
+
Irp->IoStatus.Status = STATUS_NOT_IMPLEMENTED;
Irp->IoStatus.Information = 0;
return(STATUS_UNSUCCESSFUL);
Ext2Shutdown(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
DPRINT("Ext2Shutdown(DeviceObject %x Irp %x)\n",DeviceObject,Irp);
-
+
Irp->IoStatus.Status = STATUS_NOT_IMPLEMENTED;
Irp->IoStatus.Information = 0;
return(STATUS_UNSUCCESSFUL);
Ext2Cleanup(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
DbgPrint("Ext2Cleanup(DeviceObject %x Irp %x)\n",DeviceObject,Irp);
-
+
Irp->IoStatus.Status = STATUS_NOT_IMPLEMENTED;
Irp->IoStatus.Information = 0;
-
+
DbgPrint("Ext2Cleanup() finished\n");
-
+
return(STATUS_UNSUCCESSFUL);
}
PFILE_OBJECT FileObject = Stack->FileObject;
PDEVICE_EXTENSION DeviceExt = DeviceObject->DeviceExtension;
NTSTATUS Status;
-
+
DPRINT("Ext2Read(DeviceObject %x, FileObject %x, Irp %x)\n",
DeviceObject, FileObject, Irp);
-
+
Length = Stack->Parameters.Read.Length;
CHECKPOINT;
Buffer = MmGetSystemAddressForMdl(Irp->MdlAddress);
CHECKPOINT;
CHECKPOINT;
-
+
Status = Ext2ReadFile(DeviceExt,FileObject,Buffer,Length,
Stack->Parameters.Read.ByteOffset);
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = Length;
IoCompleteRequest(Irp,IO_NO_INCREMENT);
-
+
return(Status);
}
* FILE: services/fs/ext2/security.c
* PURPOSE: Security support
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
Ext2QuerySecurity(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
DPRINT("Ext2QuerySecurity(DeviceObject %x Irp %x)\n",DeviceObject,Irp);
-
+
Irp->IoStatus.Status = STATUS_NOT_IMPLEMENTED;
Irp->IoStatus.Information = 0;
return(STATUS_UNSUCCESSFUL);
Ext2SetSecurity(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
DPRINT("Ext2SetSecurity(DeviceObject %x Irp %x)\n",DeviceObject,Irp);
-
+
Irp->IoStatus.Status = STATUS_NOT_IMPLEMENTED;
Irp->IoStatus.Information = 0;
return(STATUS_UNSUCCESSFUL);
* FILE: services/fs/ext2/super.c
* PURPOSE: ext2 filesystem
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
PDEVICE_EXTENSION DeviceExtension;
NTSTATUS Status;
PEXT2_FCB Fcb;
-
+
DbgPrint("Ext2Close(DeviceObject %x, Irp %x)\n",DeviceObject,Irp);
-
+
Stack = IoGetCurrentIrpStackLocation(Irp);
FileObject = Stack->FileObject;
DeviceExtension = DeviceObject->DeviceExtension;
-
+
if (FileObject == DeviceExtension->FileObject)
{
Status = STATUS_SUCCESS;
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(Status);
}
ExFreePool(Fcb);
FileObject->FsContext = NULL;
}
-
+
Status = STATUS_SUCCESS;
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(Status);
}
{
PDEVICE_OBJECT DeviceObject;
PDEVICE_EXTENSION DeviceExt;
- PVOID BlockBuffer;
+ PVOID BlockBuffer;
struct ext2_super_block* superblock;
-
+
DPRINT("Ext2Mount(DeviceToMount %x)\n",DeviceToMount);
-
+
BlockBuffer = ExAllocatePool(NonPagedPool,BLOCKSIZE);
Ext2ReadSectors(DeviceToMount,
1,
1,
BlockBuffer);
superblock = BlockBuffer;
-
+
if (superblock->s_magic != EXT2_SUPER_MAGIC)
{
ExFreePool(BlockBuffer);
DPRINT("Volume recognized\n");
DPRINT("s_inodes_count %d\n",superblock->s_inodes_count);
DPRINT("s_blocks_count %d\n",superblock->s_blocks_count);
-
+
IoCreateDevice(DriverObject,
sizeof(DEVICE_EXTENSION),
NULL,
CcRosInitializeFileCache(DeviceExt->FileObject,
&DeviceExt->Bcb,
PAGE_SIZE * 3);
-
+
DPRINT("Ext2Mount() = STATUS_SUCCESS\n");
-
+
return(STATUS_SUCCESS);
}
PVPB vpb = Stack->Parameters.Mount.Vpb;
PDEVICE_OBJECT DeviceToMount = Stack->Parameters.Mount.DeviceObject;
NTSTATUS Status;
-
+
Status = Ext2Mount(DeviceToMount);
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(Status);
}
PDEVICE_OBJECT DeviceObject;
NTSTATUS ret;
UNICODE_STRING DeviceName = ROS_STRING_INITIALIZER(L"\\Device\\Ext2Fsd");
-
+
DbgPrint("Ext2 FSD 0.0.1\n");
-
+
DriverObject = _DriverObject;
-
+
ret = IoCreateDevice(DriverObject,
0,
&DeviceName,
Ext2FileSystemControl;
DriverObject->MajorFunction[IRP_MJ_DIRECTORY_CONTROL] =
Ext2DirectoryControl;
- DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] =
+ DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] =
Ext2QueryInformation;
DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION] = Ext2SetInformation;
DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = Ext2FlushBuffers;
DriverObject->MajorFunction[IRP_MJ_SET_SECURITY] = Ext2SetSecurity;
DriverObject->MajorFunction[IRP_MJ_QUERY_QUOTA] = Ext2QueryQuota;
DriverObject->MajorFunction[IRP_MJ_SET_QUOTA] = Ext2SetQuota;
-
+
DriverObject->DriverUnload = NULL;
-
+
IoRegisterFileSystem(DeviceObject);
-
+
return(STATUS_SUCCESS);
}
DPRINT("FsRecDeviceIoControl faild (%x)\n", Status);
return Status;
}
-
+
if (PartitionInfo.PartitionType)
{
if (PartitionInfo.PartitionType == PARTITION_FAT_12 ||
return STATUS_INSUFFICIENT_RESOURCES;
}
- Status = FsRecReadSectors(DeviceObject,
- 0,
+ Status = FsRecReadSectors(DeviceObject,
+ 0,
1,
- DiskGeometry.BytesPerSector,
+ DiskGeometry.BytesPerSector,
(PUCHAR) Boot);
if (!NT_SUCCESS(Status))
{
return Status;
}
-
+
if (Boot->Signatur1 != 0xaa55)
{
RecognizedFS=FALSE;
if (RecognizedFS &&
Boot->BytesPerSector != 512 &&
Boot->BytesPerSector != 1024 &&
- Boot->BytesPerSector != 2048 &&
+ Boot->BytesPerSector != 2048 &&
Boot->BytesPerSector == 4096)
{
RecognizedFS=FALSE;
}
if (RecognizedFS &&
- Boot->FATCount != 1 &&
+ Boot->FATCount != 1 &&
Boot->FATCount != 2)
{
RecognizedFS=FALSE;
}
if (RecognizedFS &&
- Boot->Media != 0xf0 &&
+ Boot->Media != 0xf0 &&
Boot->Media != 0xf8 &&
Boot->Media != 0xf9 &&
- Boot->Media != 0xfa &&
+ Boot->Media != 0xfa &&
Boot->Media != 0xfb &&
Boot->Media != 0xfc &&
Boot->Media != 0xfd &&
- Boot->Media != 0xfe &&
+ Boot->Media != 0xfe &&
Boot->Media != 0xff)
{
RecognizedFS=FALSE;
if (RecognizedFS &&
Boot->SectorsPerCluster != 1 &&
Boot->SectorsPerCluster != 2 &&
- Boot->SectorsPerCluster != 4 &&
+ Boot->SectorsPerCluster != 4 &&
Boot->SectorsPerCluster != 8 &&
Boot->SectorsPerCluster != 16 &&
- Boot->SectorsPerCluster != 32 &&
+ Boot->SectorsPerCluster != 32 &&
Boot->SectorsPerCluster != 64 &&
Boot->SectorsPerCluster != 128)
{
{
unsigned long * p = ((unsigned long *) addr) + (offset >> 5);
int set = 0, bit = offset & 31, res;
-
+
if (bit) {
/*
* Look for zero in first byte
* FILE: services/fs/minix/minix.c
* PURPOSE: Minix FSD
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
static unsigned int MinixGetBlock(PDEVICE_OBJECT DeviceObject,
PMINIX_DEVICE_EXTENSION DeviceExt,
- struct minix_inode* inode,
+ struct minix_inode* inode,
ULONG FileOffset)
{
int block;
PVOID BaseAddress;
ULONG blk;
-
+
blk = FileOffset / BLOCKSIZE;
-
+
DPRINT("MinixGetBlock(inode %x, blk %d)\n",inode,blk);
-
+
/*
* The first few blocks are available in the inode
*/
return(block);
}
blk = blk - 7;
-
+
/*
* Retrieve a single-indirect block
*/
if (blk < 512)
{
block = inode->i_zone[7];
-
+
BaseAddress = ExAllocatePool(NonPagedPool, 512);
-
+
MinixReadSector(DeviceObject,
- block,
+ block,
BaseAddress);
-
+
block = ((PUSHORT)(BaseAddress))[blk];
ExFreePool(BaseAddress);
-
+
return(block);
}
-
+
/*
* Get a double indirect block
*/
blk = blk - 512;
block = inode->i_zone[8];
-
+
BaseAddress = ExAllocatePool(NonPagedPool, 512);
-
+
MinixReadSector(DeviceObject,
block,
BaseAddress);
-
+
block = ((PUSHORT)BaseAddress)[(blk>>9)&511];
ExFreePool(BaseAddress);
-
-
+
+
BaseAddress = ExAllocatePool(NonPagedPool, 512);
-
+
MinixReadSector(DeviceObject,
block,
BaseAddress);
-
+
block = ((PUSHORT)BaseAddress)[blk&512];
ExFreePool(BaseAddress);
-
+
return(block);
}
NTSTATUS MinixReadBlock(PDEVICE_OBJECT DeviceObject,
PMINIX_DEVICE_EXTENSION DeviceExt,
- struct minix_inode* inode,
+ struct minix_inode* inode,
ULONG FileOffset,
PULONG DiskOffset)
{
unsigned int block;
-
+
DPRINT("MinixReadBlock()\n");
-
+
block = MinixGetBlock(DeviceObject, DeviceExt,inode, FileOffset);
-
+
(*DiskOffset) = block * BLOCKSIZE;
return(STATUS_SUCCESS);
* FILE: services/fs/minix/minix.c
* PURPOSE: Minix FSD
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
{
ULONG i;
BOOLEAN Result;
-
+
for (i=0; i<4; i++)
{
Result = MinixReadSector(DeviceObject,
NTSTATUS status;
ULONG sectorSize;
PULONG mbr;
-
+
DPRINT("MinixReadSector(pDeviceObject %x, DiskSector %d, Buffer %x)\n",
pDeviceObject,DiskSector,Buffer);
-
+
sectorNumber.u.HighPart = 0;
sectorNumber.u.LowPart = DiskSector * BLOCKSIZE;
KEVENT event;
NTSTATUS status;
ULONG sectorSize;
-
+
DPRINT("MinixWriteSector(pDeviceObject %x, DiskSector %d, Buffer %x)\n",
pDeviceObject,DiskSector,Buffer);
-
+
sectorNumber.u.HighPart = 0;
sectorNumber.u.LowPart = DiskSector * BLOCKSIZE;
* FILE: services/fs/minix/cache.c
* PURPOSE: Minix FSD
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
PCACHE_SEGMENT* CacheSeg)
{
BOOLEAN UptoDate;
-
+
CcRosRequestCacheSegment(Bcb,
FileOffset,
BaseAddress,
MinixReadPage(DeviceObject,
PAGE_ROUND_DOWN(FileOffset),
BaseAddress);
- }
+ }
BaseAddress = BaseAddress + (FileOffset % PAGE_SIZE);
-
+
return(STATUS_SUCCESS);
}
* FILE: services/fs/minix/minix.c
* PURPOSE: Minix FSD
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
/* FUNCTIONS ****************************************************************/
-BOOLEAN MinixCompareUnicodeStringToAnsi(PCH AnsiStr,
+BOOLEAN MinixCompareUnicodeStringToAnsi(PCH AnsiStr,
PWCHAR UnicodeStr,
ULONG MaxLen)
{
unsigned int i = 0;
-
+
while (i<MaxLen)
{
if ((*AnsiStr)!=(*UnicodeStr))
unsigned int inode;
PVOID Block;
ULONG DiskOffset;
-
+
DPRINT("MinixDirLookup(DeviceExt %x, dir %x, Name %S)\n",DeviceExt,dir,
Name);
-
+
Block = ExAllocatePool(NonPagedPool, 512);
-
+
for (i=0;i<(dir->i_size/MINIX_DIR_ENTRY_SIZE);i++)
{
CHECKPOINT;
PWSTR string;
struct minix_inode current_dir;
unsigned int current_ino;
-
- string = ExAllocatePool(NonPagedPool,
+
+ string = ExAllocatePool(NonPagedPool,
2*(wcslen(FileObject->FileName.Buffer)+1));
wcscpy(string, FileObject->FileName.Buffer);
-
+
DbgPrint("MinixOpen(DeviceObject %x, DeviceName %S, result %x)\n",
DeviceObject,string,result);
-
-
+
+
next = &string[0];
current = next+1;
-
+
current_ino = MINIX_ROOT_INO;
-
+
while (next != NULL && current_ino != 0)
- {
+ {
MinixReadInode(DeviceObject,DeviceExt,current_ino,¤t_dir);
DPRINT("current %S next %x\n",current,next);
-
+
*next = '\\';
current = next+1;
next = wcschr(next+1,'\\');
{
*next=0;
}
-
+
current_ino = MinixDirLookup(DeviceExt,
DeviceObject,
¤t_dir,
}
if (next == NULL && current_ino != 0)
{
- MinixReadInode(DeviceObject,DeviceExt,current_ino,¤t_dir);
+ MinixReadInode(DeviceObject,DeviceExt,current_ino,¤t_dir);
}
else
{
(*Information) = FILE_DOES_NOT_EXIST;
return(STATUS_UNSUCCESSFUL);
}
-
+
result = ExAllocatePool(NonPagedPool, sizeof(MINIX_FSCONTEXT));
memcpy(&result->inode,¤t_dir,sizeof(struct minix_inode));
-
+
DPRINT("MinxOpen() = STATUS_SUCCESS\n",0);
return(STATUS_SUCCESS);
}
PFILE_OBJECT FileObject = Stack->FileObject;
DPRINT("MinixClose(DeviceObject %x Irp %x)\n",DeviceObject,Irp);
-
+
ExFreePool(FileObject->FsContext);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(STATUS_SUCCESS);
}
{
PIO_STACK_LOCATION Stack = IoGetCurrentIrpStackLocation(Irp);
// PFILE_OBJECT FileObject = Stack->FileObject;
-
+
if (Stack->MinorFunction != IRP_MN_QUERY_DIRECTORY)
{
return(STATUS_NOT_IMPLEMENTED);
}
-
+
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(STATUS_SUCCESS);
}
NTSTATUS Status;
PMINIX_FSCONTEXT result;
MINIX_DEVICE_EXTENSION* DeviceExt;
-
+
DPRINT("MinixCreate(DeviceObject %x, Irp %x)\n",DeviceObject,Irp);
DPRINT("Opening file %x %S\n",FileObject->FileName.Buffer,
FileObject->FileName.Buffer);
DPRINT("FileObject->FileName.Buffer %x\n",
FileObject->FileName.Buffer);
-
+
DeviceExt = (MINIX_DEVICE_EXTENSION *)DeviceObject->DeviceExtension;
result = ExAllocatePool(NonPagedPool,sizeof(struct minix_inode));
DPRINT("result %x\n",result);
FileObject,
result,
&Irp->IoStatus.Information);
-
+
if (NT_SUCCESS(Status))
{
FileObject->FsContext = result;
}
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
-
+
DPRINT("Finished MinixCreate()\n");
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(Status);
}
* FILE: services/fs/minix/minix.c
* PURPOSE: Minix FSD
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
{
PULONG Buffer;
ULONG off;
-
+
Buffer = ExAllocatePool(NonPagedPool,BLOCKSIZE);
MinixReadSector(Volume, (ino / 8192)+2, (PVOID)Buffer);
off = ino % 8192;
ULONG i;
PULONG Buffer;
ULONG ino;
-
+
Buffer = ExAllocatePool(NonPagedPool,BLOCKSIZE);
for (i=0; i<DeviceExt->sb->s_imap_blocks; i++)
{
struct minix_inode* new_inode)
{
ULONG ino;
-
+
ino = MinixAllocateInode(Volume,DeviceExt);
if (ino == 0)
{
NTSTATUS MinixWriteInode(PDEVICE_OBJECT Volume,
MINIX_DEVICE_EXTENSION* DeviceExt,
- ULONG ino,
+ ULONG ino,
struct minix_inode* result)
{
int block;
char* buffer;
struct minix_inode* inodes;
-
+
DPRINT("MinixWriteInode(ino %x, result %x)\n",ino,result);
-
+
buffer = ExAllocatePool(NonPagedPool,1024);
inodes = (struct minix_inode *)buffer;
-
- block = 2 + DeviceExt->sb->s_imap_blocks + DeviceExt->sb->s_zmap_blocks
+
+ block = 2 + DeviceExt->sb->s_imap_blocks + DeviceExt->sb->s_zmap_blocks
+ ((ino-1) / MINIX_INODES_PER_BLOCK);
MinixReadSector(Volume,block,buffer);
memcpy(&inodes[(ino-1)%MINIX_INODES_PER_BLOCK],result,
sizeof(struct minix_inode));
MinixWriteSector(Volume,block,buffer);
-
+
ExFreePool(buffer);
return(STATUS_SUCCESS);
}
NTSTATUS MinixReadInode(PDEVICE_OBJECT DeviceObject,
MINIX_DEVICE_EXTENSION* DeviceExt,
- ULONG ino,
+ ULONG ino,
struct minix_inode* result)
{
int block;
struct minix_inode* inodes;
PVOID BaseAddress;
-
+
DPRINT("MinixReadInode(ino %x, result %x)\n",ino,result);
-
- block = 2 + DeviceExt->sb->s_imap_blocks + DeviceExt->sb->s_zmap_blocks
+
+ block = 2 + DeviceExt->sb->s_imap_blocks + DeviceExt->sb->s_zmap_blocks
+ ((ino-1) / MINIX_INODES_PER_BLOCK);
DPRINT("Reading block %x offset %x\n",block,block*BLOCKSIZE);
DPRINT("Index %x\n",(ino-1)%MINIX_INODES_PER_BLOCK);
-
+
BaseAddress = ExAllocatePool(NonPagedPool, PAGE_SIZE);
-
+
MinixReadPage(DeviceObject,
block,
BaseAddress);
inodes = (struct minix_inode *)(BaseAddress + ((block % 4) * 512));
-
+
memcpy(result,
&inodes[(ino-1)%MINIX_INODES_PER_BLOCK],
sizeof(struct minix_inode));
DPRINT("result->i_uid %x\n",result->i_uid);
DPRINT("result->i_size %x\n",result->i_size);
-
+
ExFreePool(BaseAddress);
return(STATUS_SUCCESS);
struct minix_inode* new_inode);
NTSTATUS MinixWriteInode(PDEVICE_OBJECT Volume,
MINIX_DEVICE_EXTENSION* DeviceExt,
- ULONG ino,
+ ULONG ino,
struct minix_inode* result);
NTSTATUS MinixReadInode(PDEVICE_OBJECT DeviceObject,
MINIX_DEVICE_EXTENSION* DeviceExt,
- ULONG ino,
+ ULONG ino,
struct minix_inode* result);
NTSTATUS MinixDeleteInode(PDEVICE_OBJECT Volume,
MINIX_DEVICE_EXTENSION* DeviceExt,
NTSTATUS MinixReadBlock(PDEVICE_OBJECT DeviceObject,
PMINIX_DEVICE_EXTENSION DeviceExt,
- struct minix_inode* inode,
+ struct minix_inode* inode,
ULONG FileOffset,
PULONG DiskOffset);
* FILE: services/fs/minix/minix.c
* PURPOSE: Minix FSD
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
NTSTATUS Status;
char* superblock_buf;
struct minix_super_block* sb;
-
+
DbgPrint("MinixFileSystemControl(DeviceObject %x, Irp %x)\n",DeviceObject,
Irp);
DPRINT("DeviceToMount %x\n",DeviceToMount);
superblock_buf = ExAllocatePool(NonPagedPool,BLOCKSIZE);
-
+
DPRINT("MinixReadSector %x\n",MinixReadSector);
MinixReadSector(DeviceToMount,1,superblock_buf);
sb = (struct minix_super_block *)superblock_buf;
DPRINT("%s() = STATUS_UNRECOGNIZED_VOLUME\n",__FUNCTION__);
Status = STATUS_UNRECOGNIZED_VOLUME;
}
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return(Status);
}
PDEVICE_OBJECT DeviceObject;
NTSTATUS ret;
UNICODE_STRING DeviceName;
-
+
DbgPrint("Minix FSD 0.0.1\n");
-
+
DriverObject = _DriverObject;
-
+
RtlInitUnicodeString(&DeviceName,
L"\\Device\\Minix");
ret = IoCreateDevice(DriverObject,
DriverObject->MajorFunction[IRP_MJ_CREATE] = MinixCreate;
DriverObject->MajorFunction[IRP_MJ_READ] = MinixRead;
DriverObject->MajorFunction[IRP_MJ_WRITE] = MinixWrite;
- DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] =
+ DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] =
MinixFileSystemControl;
- DriverObject->MajorFunction[IRP_MJ_DIRECTORY_CONTROL] =
+ DriverObject->MajorFunction[IRP_MJ_DIRECTORY_CONTROL] =
MinixDirectoryControl;
DriverObject->DriverUnload = NULL;
IoRegisterFileSystem(DeviceObject);
-
+
return(STATUS_SUCCESS);
}
* FILE: services/fs/minix/rw.c
* PURPOSE: Minix FSD
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
MinixWrite(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
DPRINT("MinixWrite(DeviceObject %x Irp %x)\n",DeviceObject,Irp);
-
+
Irp->IoStatus.Status = STATUS_UNSUCCESSFUL;
Irp->IoStatus.Information = 0;
return(STATUS_UNSUCCESSFUL);
PMINIX_FSCONTEXT FsContext = (PMINIX_FSCONTEXT)FileObject->FsContext;
unsigned int i;
PVOID DiskBuffer;
-
+
DPRINT("MinixRead(DeviceObject %x, Irp %x)\n",DeviceObject,Irp);
-
+
Length = Stack->Parameters.Read.Length;
Buffer = MmGetSystemAddressForMdl(Irp->MdlAddress);
Offset = Stack->Parameters.Read.ByteOffset.u.LowPart;
-
+
DPRINT("Length %d Buffer %x Offset %x\n",Length,Buffer,Offset);
-
+
CurrentOffset=Offset;
-
+
DPRINT("inode->i_size %d\n",inode->i_size);
-
+
if (Offset > FsContext->inode.i_size)
{
Irp->IoStatus.Status = STATUS_UNSUCCESSFUL;
{
Length = FsContext->inode.i_size - Offset;
}
-
+
if ((Offset%PAGE_SIZE)!=0)
{
CurrentOffset = Offset - (Offset%PAGE_SIZE);
-
+
MinixReadFilePage(DeviceObject,
DeviceExt,
FsContext,
memcpy(Buffer,
DiskBuffer+(Offset%PAGE_SIZE),
min(PAGE_SIZE - (Offset%PAGE_SIZE),Length));
-
+
ExFreePool(DiskBuffer);
-
+
DPRINT("(BLOCKSIZE - (Offset%BLOCKSIZE)) %d\n",
(BLOCKSIZE - (Offset%BLOCKSIZE)));
DPRINT("Length %d\n",Length);
for (i=0;i<(Length/PAGE_SIZE);i++)
{
CHECKPOINT;
-
+
DPRINT("Length %d\n",Length);
-
+
MinixReadFilePage(DeviceObject,
DeviceExt,
FsContext,
CurrentOffset,
&DiskBuffer);
memcpy(Buffer, DiskBuffer, PAGE_SIZE);
-
+
ExFreePool(DiskBuffer);
-
+
CurrentOffset = CurrentOffset + PAGE_SIZE;
Buffer = Buffer + PAGE_SIZE;
}
if ((Length%PAGE_SIZE) > 0)
{
CHECKPOINT;
-
+
DPRINT("Length %x Buffer %x\n",(Length%PAGE_SIZE),Buffer);
-
+
MinixReadFilePage(DeviceObject,
DeviceExt,
FsContext,
ExFreePool(DiskBuffer);
}
-
+
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = Length;
IoCompleteRequest(Irp,IO_NO_INCREMENT);
{
RtlFreeUnicodeString(&Mailslot->Name);
ExFreePool(Mailslot);
-
+
Mailslot = current;
}
else
PMSFS_FCB Fcb;
PMSFS_MESSAGE Message;
KIRQL oldIrql;
-
+
DPRINT("MsfsClose(DeviceObject %p Irp %p)\n", DeviceObject, Irp);
-
+
IoStack = IoGetCurrentIrpStackLocation(Irp);
DeviceExtension = DeviceObject->DeviceExtension;
FileObject = IoStack->FileObject;
-
+
KeLockMutex(&DeviceExtension->MailslotListLock);
-
+
if (DeviceExtension->MailslotListHead.Flink == &DeviceExtension->MailslotListHead)
{
KeUnlockMutex(&DeviceExtension->MailslotListLock);
-
+
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return(STATUS_SUCCESS);
}
-
+
Fcb = FileObject->FsContext;
Mailslot = Fcb->Mailslot;
-
+
DPRINT("Mailslot name: %wZ\n", &Mailslot->Name);
-
+
Mailslot->ReferenceCount--;
if (Mailslot->ServerFcb == Fcb)
{
/* delete all messages from message-list */
KeAcquireSpinLock(&Mailslot->MessageListLock, &oldIrql);
-
+
while (Mailslot->MessageListHead.Flink != &Mailslot->MessageListHead)
{
Message = CONTAINING_RECORD(Mailslot->MessageListHead.Flink,
ExFreePool(Message);
}
Mailslot->MessageCount = 0;
-
+
KeReleaseSpinLock(&Mailslot->MessageListLock, oldIrql);
Mailslot->ServerFcb = NULL;
}
-
+
KeAcquireSpinLock(&Mailslot->FcbListLock, &oldIrql);
RemoveEntryList(&Fcb->FcbListEntry);
KeReleaseSpinLock(&Mailslot->FcbListLock, oldIrql);
ExFreePool(Fcb);
FileObject->FsContext = NULL;
-
+
if (Mailslot->ReferenceCount == 0)
{
DPRINT1("ReferenceCount == 0: Deleting mailslot data\n");
RemoveEntryList(&Mailslot->MailslotListEntry);
ExFreePool(Mailslot);
}
-
+
KeUnlockMutex(&DeviceExtension->MailslotListLock);
-
+
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return(STATUS_SUCCESS);
}
Buffer->NextSize = 0;
}
KeReleaseSpinLock(&Mailslot->MessageListLock, oldIrql);
-
+
*BufferLength -= sizeof(FILE_MAILSLOT_QUERY_INFORMATION);
-
+
return(STATUS_SUCCESS);
}
PMSFS_MAILSLOT Mailslot;
PMSFS_FCB Fcb;
NTSTATUS Status;
-
+
DPRINT1("MsfsFileSystemControl(DeviceObject %p Irp %p)\n", DeviceObject, Irp);
-
+
IoStack = IoGetCurrentIrpStackLocation(Irp);
FileObject = IoStack->FileObject;
Fcb = FileObject->FsContext;
Mailslot = Fcb->Mailslot;
-
+
DPRINT1("Mailslot name: %wZ\n", &Mailslot->Name);
-
+
switch (IoStack->Parameters.FileSystemControl.FsControlCode)
{
#if 0
case FSCTL_WAIT_PIPE:
break;
-
+
case FSCTL_LISTEN:
break;
-
+
case FSCTL_SET_STATE:
break;
-
+
case FSCTL_GET_STATE:
{
-
-
+
+
break;
}
-
+
#endif
default:
Status = STATUS_NOT_IMPLEMENTED;
}
-
+
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = 0;
IoCompleteRequest (Irp, IO_NO_INCREMENT);
-
+
return(Status);
}
PDEVICE_OBJECT DeviceObject;
UNICODE_STRING DeviceName;
NTSTATUS Status;
-
+
DPRINT("Mailslot FSD 0.0.1\n");
-
+
DriverObject->Flags = 0;
DriverObject->MajorFunction[IRP_MJ_CREATE] = MsfsCreate;
DriverObject->MajorFunction[IRP_MJ_CREATE_MAILSLOT] =
// MsfsDirectoryControl;
// DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = MsfsFlushBuffers;
// DriverObject->MajorFunction[IRP_MJ_SHUTDOWN] = MsfsShutdown;
-// DriverObject->MajorFunction[IRP_MJ_QUERY_SECURITY] =
+// DriverObject->MajorFunction[IRP_MJ_QUERY_SECURITY] =
// MsfsQuerySecurity;
// DriverObject->MajorFunction[IRP_MJ_SET_SECURITY] =
// MsfsSetSecurity;
DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] =
MsfsFileSystemControl;
-
+
DriverObject->DriverUnload = NULL;
-
+
RtlInitUnicodeString(&DeviceName,
L"\\Device\\MailSlot");
Status = IoCreateDevice(DriverObject,
InitializeListHead(&DeviceExtension->MailslotListHead);
KeInitializeMutex(&DeviceExtension->MailslotListLock,
0);
-
+
return(STATUS_SUCCESS);
}
KIRQL oldIrql;
ULONG Length;
PVOID Buffer;
-
+
DPRINT("MsfsWrite(DeviceObject %p Irp %p)\n", DeviceObject, Irp);
-
+
IoStack = IoGetCurrentIrpStackLocation (Irp);
FileObject = IoStack->FileObject;
Fcb = (PMSFS_FCB)FileObject->FsContext;
Mailslot = Fcb->Mailslot;
-
+
DPRINT("MailslotName: %wZ\n", &Mailslot->Name);
-
+
/* writing is not permitted on server side */
if (Fcb->Mailslot->ServerFcb == Fcb)
{
Irp->IoStatus.Status = STATUS_ACCESS_DENIED;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return(STATUS_ACCESS_DENIED);
}
Buffer = MmGetSystemAddressForMdl (Irp->MdlAddress);
else
Buffer = Irp->UserBuffer;
-
+
DPRINT("Length: %lu Message: %s\n", Length, (PUCHAR)Buffer);
-
+
/* Allocate new message */
Message = ExAllocatePool(NonPagedPool,
sizeof(MSFS_MESSAGE) + Length);
{
Irp->IoStatus.Status = STATUS_NO_MEMORY;
Irp->IoStatus.Information = 0;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return(STATUS_NO_MEMORY);
}
-
+
Message->Size = Length;
memcpy(&Message->Buffer, Buffer, Length);
-
+
KeAcquireSpinLock(&Mailslot->MessageListLock, &oldIrql);
InsertTailList(&Mailslot->MessageListHead, &Message->MessageListEntry);
KeReleaseSpinLock(&Mailslot->MessageListLock, oldIrql);
-
+
Mailslot->MessageCount++;
if (Mailslot->MessageCount == 1)
{
0,
FALSE);
}
-
+
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = Length;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return(STATUS_SUCCESS);
}
if (Waiter->Fcb->PipeState == FILE_PIPE_LISTENING_STATE)
{
DPRINT("Server found! Fcb %p\n", Waiter->Fcb);
-
+
IoAcquireCancelSpinLock(&oldIrql);
if (!Irp->Cancel)
{
if (Pipe != NULL)
{
/*
- * Found Pipe with the same name. Check if we are
+ * Found Pipe with the same name. Check if we are
* allowed to use it.
*/
KeUnlockMutex(&DeviceExt->PipeListLock);
Pipe->MaximumInstances = Buffer->MaximumInstances;
Pipe->CurrentInstances = 0;
Pipe->TimeOut = Buffer->DefaultTimeout;
- if (!(IoStack->Parameters.Create.Options & FILE_PIPE_OUTBOUND) ||
+ if (!(IoStack->Parameters.Create.Options & FILE_PIPE_OUTBOUND) ||
IoStack->Parameters.Create.Options & FILE_PIPE_FULL_DUPLEX)
{
if (Buffer->InboundQuota == 0)
{
PLIST_ENTRY Entry;
PNPFS_WAITER_ENTRY WaitEntry = NULL;
- BOOLEAN Complete = FALSE;
+ BOOLEAN Complete = FALSE;
KIRQL oldIrql;
PIRP tmpIrp;
RtlZeroMemory(Info,
sizeof(FILE_PIPE_INFORMATION));
-// Info->PipeMode =
-// Info->CompletionMode =
+// Info->PipeMode =
+// Info->CompletionMode =
*BufferLength -= sizeof(FILE_PIPE_INFORMATION);
return STATUS_SUCCESS;
return STATUS_PENDING;
}
IoReleaseCancelSpinLock(oldIrql);
-
+
RemoveEntryList(&Entry->Entry);
-
+
Irp->IoStatus.Status = STATUS_CANCELLED;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
{
PLIST_ENTRY Entry;
PNPFS_WAITER_ENTRY WaitEntry = NULL;
- BOOLEAN Complete = FALSE;
+ BOOLEAN Complete = FALSE;
PIRP Irp = NULL;
Entry = Fcb->Pipe->WaiterListHead.Flink;
if (Status != STATUS_PENDING)
{
Irp->IoStatus.Status = Status;
-
+
IoCompleteRequest(Irp, IO_NO_INCREMENT);
}
PDEVICE_OBJECT DeviceObject;
UNICODE_STRING DeviceName;
NTSTATUS Status;
-
+
DPRINT("Named Pipe FSD 0.0.2\n");
ASSERT (sizeof(NPFS_CONTEXT) <= sizeof (((PIRP)NULL)->Tail.Overlay.DriverContext));
ASSERT (sizeof(NPFS_WAITER_ENTRY) <= sizeof(((PIRP)NULL)->Tail.Overlay.DriverContext));
-
+
DriverObject->MajorFunction[IRP_MJ_CREATE] = NpfsCreate;
DriverObject->MajorFunction[IRP_MJ_CREATE_NAMED_PIPE] =
NpfsCreateNamedPipe;
NpfsQueryInformation;
DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION] =
NpfsSetInformation;
- DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] =
+ DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] =
NpfsQueryVolumeInformation;
DriverObject->MajorFunction[IRP_MJ_CLEANUP] = NpfsCleanup;
DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = NpfsFlushBuffers;
// NpfsDirectoryControl;
DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] =
NpfsFileSystemControl;
-// DriverObject->MajorFunction[IRP_MJ_QUERY_SECURITY] =
+// DriverObject->MajorFunction[IRP_MJ_QUERY_SECURITY] =
// NpfsQuerySecurity;
// DriverObject->MajorFunction[IRP_MJ_SET_SECURITY] =
// NpfsSetSecurity;
-
+
DriverObject->DriverUnload = NULL;
-
+
RtlInitUnicodeString(&DeviceName, L"\\Device\\NamedPipe");
Status = IoCreateDevice(DriverObject,
sizeof(NPFS_DEVICE_EXTENSION),
DPRINT("Failed to create named pipe device! (Status %x)\n", Status);
return Status;
}
-
+
/* initialize the device object */
DeviceObject->Flags = DO_DIRECT_IO;
-
+
/* initialize the device extension */
DeviceExtension = DeviceObject->DeviceExtension;
InitializeListHead(&DeviceExtension->PipeListHead);
}
#endif
-static VOID STDCALL
+static VOID STDCALL
NpfsReadWriteCancelRoutine(IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp)
{
KeLockMutex(&DeviceExt->PipeListLock);
ExAcquireFastMutex(&Fcb->DataListLock);
- switch(IoStack->MajorFunction)
+ switch(IoStack->MajorFunction)
{
case IRP_MJ_READ:
if (Fcb->ReadRequestListHead.Flink != &Context->ListEntry)
NextIrp = CONTAINING_RECORD(NextContext, IRP, Tail.Overlay.DriverContext);
ThreadContext->WaitIrpArray[ThreadContext->Count] = NextIrp;
ThreadContext->Count++;
- ThreadContext->DeviceExt->EmptyWaiterCount--;
+ ThreadContext->DeviceExt->EmptyWaiterCount--;
}
break;
default:
KEBUGCHECK(0);
}
ExReleaseFastMutex(&Fcb->DataListLock);
- }
+ }
}
else
- {
+ {
/* someone has add a new wait request */
Irp = NULL;
}
KIRQL oldIrql;
PNPFS_CONTEXT Context = (PNPFS_CONTEXT)&Irp->Tail.Overlay.DriverContext;
- PNPFS_DEVICE_EXTENSION DeviceExt = (PNPFS_DEVICE_EXTENSION)DeviceObject->DeviceExtension;;
+ PNPFS_DEVICE_EXTENSION DeviceExt = (PNPFS_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
DPRINT("NpfsAddWaitingReadWriteRequest(DeviceObject %p, Irp %p)\n", DeviceObject, Irp);
ThreadContext->Count = 1;
ThreadContext->WaitObjectArray[0] = &ThreadContext->Event;
-
+
DPRINT("Creating a new system thread for waiting read/write requests\n");
-
+
Status = PsCreateSystemThread(&hThread,
THREAD_ALL_ACCESS,
NULL,
return Status;
}
InsertHeadList(&DeviceExt->ThreadListHead, &ThreadContext->ListEntry);
- DeviceExt->EmptyWaiterCount += MAXIMUM_WAIT_OBJECTS - 1;
+ DeviceExt->EmptyWaiterCount += MAXIMUM_WAIT_OBJECTS - 1;
}
IoMarkIrpPending(Irp);
else
{
PNPFS_CONTEXT Context = (PNPFS_CONTEXT)&Irp->Tail.Overlay.DriverContext;
-
+
Context->WaitEvent = &Fcb->ReadEvent;
Status = NpfsAddWaitingReadWriteRequest(DeviceObject, Irp);
-
+
if (NT_SUCCESS(Status))
{
Status = STATUS_PENDING;
ExAcquireFastMutex(&Fcb->DataListLock);
break;
}
- }
+ }
if (Fcb->Pipe->ReadMode == FILE_PIPE_BYTE_STREAM_MODE)
{
DPRINT("Byte stream mode\n");
break;
}
}
- }
+ }
Irp->IoStatus.Information = Information;
Irp->IoStatus.Status = Status;
Context = CONTAINING_RECORD(Fcb->ReadRequestListHead.Flink, NPFS_CONTEXT, ListEntry);
Irp = CONTAINING_RECORD(Context, IRP, Tail.Overlay.DriverContext);
}
- }
+ }
done:
Irp->IoStatus.Status = Status;
ExReleaseFastMutex(&ReaderFcb->DataListLock);
DPRINT("Waiting for buffer space (%S)\n", Pipe->PipeName.Buffer);
- Status = KeWaitForSingleObject(&Fcb->WriteEvent,
+ Status = KeWaitForSingleObject(&Fcb->WriteEvent,
UserRequest,
KernelMode,
FALSE,
* FILE: drivers/fs/ntfs/attrib.c
* PURPOSE: NTFS filesystem driver
* PROGRAMMER: Eric Kohl
- * Updated by Valentin Verkhovsky 2003/09/12
+ * Updated by Valentin Verkhovsky 2003/09/12
*/
/* INCLUDES *****************************************************************/
UCHAR n2 = (*run >> 4) & 0x0f;
LONGLONG lcn = (n2 == 0) ? 0 : (CHAR)(run[n1 + n2]);
LONG i = 0;
-
+
for (i = n1 +n2 - 1; i > n1; i--)
lcn = (lcn << 8) + run[i];
return lcn;
* FILE: services/fs/ntfs/close.c
* PURPOSE: NTFS filesystem driver
* PROGRAMMER: Art Yerkes
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
*/
{
PCCB Ccb;
-
+
DPRINT("NtfsCloseFile(DeviceExt %x, FileObject %x)\n",
DeviceExt,
FileObject);
DPRINT1("Stopped!\n");
break;
}
-
+
DPRINT("RecordLength %u ExtAttrRecordLength %u NameLength %u\n",
Record->RecordLength, Record->ExtAttrRecordLength, Record->FileIdLength);
DPRINT("RecordLength == 0 Stopped!\n");
break;
}
-
+
DPRINT("RecordLength %u ExtAttrRecordLength %u NameLength %u\n",
Record->RecordLength, Record->ExtAttrRecordLength, Record->FileIdLength);
if (*BufferLength < sizeof(FILE_POSITION_INFORMATION))
return(STATUS_BUFFER_OVERFLOW);
- PositionInfo->CurrentByteOffset.QuadPart =
+ PositionInfo->CurrentByteOffset.QuadPart =
0;
// FileObject->CurrentByteOffset.QuadPart;
static NTSTATUS
NtfsHasFileSystem(PDEVICE_OBJECT DeviceToMount)
/*
- * FUNCTION: Tests if the device contains a filesystem that can be mounted
+ * FUNCTION: Tests if the device contains a filesystem that can be mounted
* by this fsd
*/
{
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
if (PageUptodate(page)) {
if (!buffer_uptodate(bh))
set_buffer_uptodate(bh);
- continue;
+ continue;
}
/*
* The page is not uptodate. The buffer is mapped. If it is not
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
*/
if (((rlpos + 3) * sizeof(*old_rl)) > rlsize) {
run_list_element *rl2;
-
+
rl2 = ntfs_malloc_nofs(rlsize + (int)PAGE_SIZE);
if (unlikely(!rl2)) {
ntfs_free(rl);
/**
* map_run_list - map (a part of) a run list of an ntfs inode
- * @ni: ntfs inode for which to map (part of) a run list
+ * @ni: ntfs inode for which to map (part of) a run list
* @vcn: map run list part containing this vcn
*
* Map the part of a run list containing the @vcn of an the ntfs inode @ni.
attr_search_context *ctx;
MFT_RECORD *mrec;
int err = 0;
-
+
ntfs_debug("Mapping run list part containing vcn 0x%Lx.",
(long long)vcn);
ni->run_list.rl = rl;
}
up_write(&ni->run_list.lock);
-
+
put_attr_search_ctx(ctx);
err_out:
unmap_mft_record(base_ni);
break;
if (a->type != type)
continue;
- /*
+ /*
* If @name is present, compare the two names. If @name is
* missing, assume we want an unnamed attribute.
*/
(uchar_t*)((u8*)a + le16_to_cpu(a->name_offset)),
a->name_length, ic, upcase, upcase_len)) {
register int rc;
-
+
rc = ntfs_collate_names(name, name_len,
(uchar_t*)((u8*)a +
le16_to_cpu(a->name_offset)),
if (lowest_vcn && (u8*)next_al_entry >= al_start &&
(u8*)next_al_entry + 6 < al_end &&
(u8*)next_al_entry + le16_to_cpu(
- next_al_entry->length) <= al_end &&
+ next_al_entry->length) <= al_end &&
sle64_to_cpu(next_al_entry->lowest_vcn) <=
sle64_to_cpu(lowest_vcn) &&
next_al_entry->type == al_entry->type &&
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
continue;
}
- /*
+ /*
* We have a phrase token. Make sure it is not the first tag in
* the sb as this is illegal and would confuse the code below.
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* Search all file name attributes in the inode described by the attribute
* search context @ctx and check if any of the names are in the $Extend system
* directory.
- *
+ *
* Return values:
* 1: file is in $Extend directory
* 0: file is not in $Extend directory
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* be found on the last sector of the partition (not normally accessible
* from within Windows as the bootsector contained number of sectors
* value is one less than the actual value!).
- * On versions of NT 3.51 and earlier, the backup copy was located at
+ * On versions of NT 3.51 and earlier, the backup copy was located at
* number of sectors/2 (integer divide), i.e. in the middle of the volume.
*/
} NTFS_SYSTEM_FILES;
/*
- * These are the so far known MFT_RECORD_* flags (16-bit) which contain
+ * These are the so far known MFT_RECORD_* flags (16-bit) which contain
* information about the mft record in which they are present.
*/
typedef enum {
/*
* mft references (aka file references or file record segment references) are
* used whenever a structure needs to refer to a record in the mft.
- *
+ *
* A reference consists of a 48-bit index into the mft and a 16-bit sequence
* number used to detect stale references.
*
* Do I hear screams "we want 64-bit inodes!" ?!? (-;
*
* FIXME: The mft zone is defined as the first 12% of the volume. This space is
- * reserved so that the mft can grow contiguously and hence doesn't become
+ * reserved so that the mft can grow contiguously and hence doesn't become
* fragmented. Volume free space includes the empty part of the mft zone and
* when the volume's free 88% are used up, the mft zone is shrunk by a factor
* of 2, thus making more space available for more files/data. This process is
above.) NOTE: The increment (skipping zero)
is done when the file is deleted. NOTE: If
this is zero it is left zero. */
-/* 18*/ u16 link_count; /* Number of hard links, i.e. the number of
+/* 18*/ u16 link_count; /* Number of hard links, i.e. the number of
directory entries referencing this record.
NOTE: Only used in mft base records.
NOTE: When deleting a directory entry we
} __attribute__ ((__packed__)) ATTR_DEF;
/*
- * Attribute flags (16-bit).
+ * Attribute flags (16-bit).
*/
typedef enum {
ATTR_IS_COMPRESSED = const_cpu_to_le16(0x0001),
boundary. */
/* 12*/ ATTR_FLAGS flags; /* Flags describing the attribute. */
/* 14*/ u16 instance; /* The instance of this attribute record. This
- number is unique within this mft record (see
+ number is unique within this mft record (see
MFT_RECORD/next_attribute_instance notes in
in mft.h for more details). */
/* 16*/ union {
/* 20 */ u16 value_offset; /* Byte offset of the attribute
value from the start of the
attribute record. When creating,
- align to 8-byte boundary if we
+ align to 8-byte boundary if we
have a name present as this might
not have a length of a multiple
of 8-bytes. */
FILE_ATTR_ENCRYPTED = const_cpu_to_le32(0x00004000),
FILE_ATTR_VALID_FLAGS = const_cpu_to_le32(0x00007fb7),
- /* FILE_ATTR_VALID_FLAGS masks out the old DOS VolId and the
+ /* FILE_ATTR_VALID_FLAGS masks out the old DOS VolId and the
FILE_ATTR_DEVICE and preserves everything else. This mask
is used to obtain all flags that are valid for reading. */
FILE_ATTR_VALID_SET_FLAGS = const_cpu_to_le32(0x000031a7),
* itself. The list is sorted: first by attribute type, second by attribute
* name (if present), third by instance number. The extents of one
* non-resident attribute (if present) immediately follow after the initial
- * extent. They are ordered by lowest_vcn and have their instace set to zero.
+ * extent. They are ordered by lowest_vcn and have their instace set to zero.
* It is not allowed to have two attributes with all sorting keys equal.
- * - Further restrictions:
+ * - Further restrictions:
* - If not resident, the vcn to lcn mapping array has to fit inside the
* base mft record.
* - The attribute list attribute value has a maximum size of 256kb. This
*/
typedef enum {
FILE_NAME_POSIX = 0x00,
- /* This is the largest namespace. It is case sensitive and
+ /* This is the largest namespace. It is case sensitive and
allows all Unicode characters except for: '\0' and '/'.
Beware that in WinNT/2k files which eg have the same name
except for their case will not be distinguished by the
both "filename" and "fileName" without warning. */
FILE_NAME_WIN32 = 0x01,
/* The standard WinNT/2k NTFS long filenames. Case insensitive.
- All Unicode chars except: '\0', '"', '*', '/', ':', '<',
+ All Unicode chars except: '\0', '"', '*', '/', ':', '<',
'>', '?', '\' and '|'. Further, names cannot end with a '.'
or a space. */
FILE_NAME_DOS = 0x02,
/* The standard DOS filenames (8.3 format). Uppercase only.
All 8-bit characters greater space, except: '"', '*', '+',
',', '/', ':', ';', '<', '=', '>', '?' and '\'. */
- FILE_NAME_WIN32_AND_DOS = 0x03,
+ FILE_NAME_WIN32_AND_DOS = 0x03,
/* 3 means that both the Win32 and the DOS filenames are
identical and hence have been saved in this single filename
record. */
} __attribute__ ((__packed__)) FILE_NAME_ATTR;
/*
- * GUID structures store globally unique identifiers (GUID). A GUID is a
+ * GUID structures store globally unique identifiers (GUID). A GUID is a
* 128-bit value consisting of one group of eight hexadecimal digits, followed
* by three groups of four hexadecimal digits each, followed by one group of
* twelve hexadecimal digits. GUIDs are Microsoft's implementation of the
/*
* These relative identifiers (RIDs) are used with the above identifier
* authorities to make up universal well-known SIDs.
- *
+ *
* Note: The relative identifier (RID) refers to the portion of a SID, which
* identifies a user or group in relation to the authority that issued the SID.
* For example, the universal well-known SID Creator Owner ID (S-1-3-0) is
SECURITY_NULL_RID = 0, /* S-1-0 */
SECURITY_WORLD_RID = 0, /* S-1-1 */
SECURITY_LOCAL_RID = 0, /* S-1-2 */
-
+
SECURITY_CREATOR_OWNER_RID = 0, /* S-1-3 */
SECURITY_CREATOR_GROUP_RID = 1, /* S-1-3 */
SECURITY_AUTHENTICATED_USER_RID = 0xb,
SECURITY_RESTRICTED_CODE_RID = 0xc,
SECURITY_TERMINAL_SERVER_RID = 0xd,
-
+
SECURITY_LOGON_IDS_RID = 5,
SECURITY_LOGON_IDS_RID_COUNT = 3,
-
+
SECURITY_LOCAL_SYSTEM_RID = 0x12,
SECURITY_NT_NON_UNIQUE = 0x15,
/*
* Well-known domain relative sub-authority values (RIDs).
*/
-
+
/* Users. */
DOMAIN_USER_RID_ADMIN = 0x1f4,
DOMAIN_USER_RID_GUEST = 0x1f5,
DOMAIN_USER_RID_KRBTGT = 0x1f6,
-
+
/* Groups. */
DOMAIN_GROUP_RID_ADMINS = 0x200,
DOMAIN_GROUP_RID_USERS = 0x201,
DOMAIN_ALIAS_RID_USERS = 0x221,
DOMAIN_ALIAS_RID_GUESTS = 0x222,
DOMAIN_ALIAS_RID_POWER_USERS = 0x223,
-
+
DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224,
DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225,
DOMAIN_ALIAS_RID_PRINT_OPS = 0x226,
DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227,
-
+
DOMAIN_ALIAS_RID_REPLICATOR = 0x228,
DOMAIN_ALIAS_RID_RAS_SERVERS = 0x229,
DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 0x22a,
* (Non-unique IDs) S-1-4
*
* NT well-known SIDs:
- *
+ *
* NT_AUTHORITY_SID S-1-5
* DIALUP_SID S-1-5-1
*
/*
* The SID structure is a variable-length structure used to uniquely identify
* users or groups. SID stands for security identifier.
- *
+ *
* The standard textual representation of the SID is of the form:
* S-R-I-S-S...
* Where:
* either in decimal or hexadecimal (if the later, prefixed by "0x").
* - I is the 48-bit identifier_authority, expressed as digits as R above.
* - S... is one or more sub_authority values, expressed as digits as above.
- *
+ *
* Example SID; the domain-relative SID of the local Administrators group on
* Windows NT/2k:
* S-1-5-32-544
ACCESS_ALLOWED_COMPOUND_ACE_TYPE= 4,
ACCESS_MAX_MS_V3_ACE_TYPE = 4,
-
+
/* The following are Win2k only. */
ACCESS_MIN_MS_OBJECT_ACE_TYPE = 5,
ACCESS_ALLOWED_OBJECT_ACE_TYPE = 5,
*/
/* Specific rights for files and directories are as follows: */
-
+
/* Right to read data from the file. (FILE) */
FILE_READ_DATA = const_cpu_to_le32(0x00000001),
/* Right to list contents of a directory. (DIRECTORY) */
FILE_LIST_DIRECTORY = const_cpu_to_le32(0x00000001),
-
+
/* Right to write data to the file. (FILE) */
FILE_WRITE_DATA = const_cpu_to_le32(0x00000002),
/* Right to create a file in the directory. (DIRECTORY) */
FILE_ADD_FILE = const_cpu_to_le32(0x00000002),
-
+
/* Right to append data to the file. (FILE) */
FILE_APPEND_DATA = const_cpu_to_le32(0x00000004),
/* Right to create a subdirectory. (DIRECTORY) */
FILE_ADD_SUBDIRECTORY = const_cpu_to_le32(0x00000004),
-
+
/* Right to read extended attributes. (FILE/DIRECTORY) */
FILE_READ_EA = const_cpu_to_le32(0x00000008),
-
+
/* Right to write extended attributes. (FILE/DIRECTORY) */
FILE_WRITE_EA = const_cpu_to_le32(0x00000010),
-
+
/* Right to execute a file. (FILE) */
FILE_EXECUTE = const_cpu_to_le32(0x00000020),
/* Right to traverse the directory. (DIRECTORY) */
FILE_TRAVERSE = const_cpu_to_le32(0x00000020),
-
+
/*
* Right to delete a directory and all the files it contains (its
* children), even if the files are read-only. (DIRECTORY)
/* Right to read file attributes. (FILE/DIRECTORY) */
FILE_READ_ATTRIBUTES = const_cpu_to_le32(0x00000080),
-
+
/* Right to change file attributes. (FILE/DIRECTORY) */
FILE_WRITE_ATTRIBUTES = const_cpu_to_le32(0x00000100),
-
+
/*
* The standard rights (bits 16 to 23). Are independent of the type of
* object being secured.
* The following STANDARD_RIGHTS_* are combinations of the above for
* convenience and are defined by the Win32 API.
*/
-
+
/* These are currently defined to READ_CONTROL. */
STANDARD_RIGHTS_READ = const_cpu_to_le32(0x00020000),
STANDARD_RIGHTS_WRITE = const_cpu_to_le32(0x00020000),
STANDARD_RIGHTS_EXECUTE = const_cpu_to_le32(0x00020000),
-
+
/* Combines DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER access. */
STANDARD_RIGHTS_REQUIRED = const_cpu_to_le32(0x000f0000),
-
+
/*
* Combines DELETE, READ_CONTROL, WRITE_DAC, WRITE_OWNER, and
* SYNCHRONIZE access.
/*
* The generic mapping array. Used to denote the mapping of each generic
* access right to a specific access mask.
- *
+ *
* FIXME: What exactly is this and what is it for? (AIA)
*/
typedef struct {
SE_SACL_PRESENT is set in the control field. If
SE_SACL_PRESENT is set but sacl is NULL, a NULL ACL
is specified. */
- u32 dacl; /* Byte offset to a discretionary ACL. Only valid, if
+ u32 dacl; /* Byte offset to a discretionary ACL. Only valid, if
SE_DACL_PRESENT is set in the control field. If
SE_DACL_PRESENT is set but dacl is NULL, a NULL ACL
(unconditionally granting access) is specified. */
typedef struct {
u8 revision; /* Revision level of the security descriptor. */
u8 alignment;
- SECURITY_DESCRIPTOR_CONTROL control; /* Flags qualifying the type of
+ SECURITY_DESCRIPTOR_CONTROL control; /* Flags qualifying the type of
the descriptor as well as the following fields. */
SID *owner; /* Points to a SID representing an object's owner. If
this is NULL, no owner SID is present in the
SE_SACL_PRESENT is set in the control field. If
SE_SACL_PRESENT is set but sacl is NULL, a NULL ACL
is specified. */
- ACL *dacl; /* Points to a discretionary ACL. Only valid, if
+ ACL *dacl; /* Points to a discretionary ACL. Only valid, if
SE_DACL_PRESENT is set in the control field. If
SE_DACL_PRESENT is set but dacl is NULL, a NULL ACL
(unconditionally granting access) is specified. */
/*
* On NTFS 3.0+, all security descriptors are stored in FILE_Secure. Only one
* referenced instance of each unique security descriptor is stored.
- *
+ *
* FILE_Secure contains no unnamed data attribute, i.e. it has zero length. It
* does, however, contain two indexes ($SDH and $SII) as well as a named data
* stream ($SDS).
- *
+ *
* Every unique security descriptor is assigned a unique security identifier
* (security_id, not to be confused with a SID). The security_id is unique for
* the NTFS volume and is used as an index into the $SII index, which maps
* new security descriptor is already present in the $SDS data stream), if a
* matching hash is found, but the security descriptors do not match, the
* search in the $SDH index is continued, searching for a next matching hash.
- *
+ *
* When a precise match is found, the security_id coresponding to the security
* descriptor in the $SDS attribute is read from the found $SDH index entry and
* is stored in the $STANDARD_INFORMATION attribute of the file/directory to
* which the security descriptor is being applied. The $STANDARD_INFORMATION
- * attribute is present in all base mft records (i.e. in all files and
+ * attribute is present in all base mft records (i.e. in all files and
* directories).
*
* If a match is not found, the security descriptor is assigned a new unique
* Note: Entries are never deleted from FILE_Secure, even if nothing
* references an entry any more.
*/
-
+
/*
* This header precedes each security descriptor in the $SDS data stream.
* This is also the index entry data part of both the $SII and $SDH indexes.
/*
* The index entry key used in the $SII index. The collation type is
- * COLLATION_NTOFS_ULONG.
+ * COLLATION_NTOFS_ULONG.
*/
typedef struct {
u32 security_id; /* The security_id assigned to the descriptor. */
/*
* Attribute: Volume name (0x60).
- *
+ *
* NOTE: Always resident.
* NOTE: Present only in FILE_Volume.
*/
the index allocation attribute), when
an index block is >= than a cluster,
otherwise this will be the log of
- the size (like how the encoding of
+ the size (like how the encoding of
the mft record size and the index
record size found in the boot sector
work). Has to be a power of 2. */
* Attribute: Index allocation (0xa0).
*
* NOTE: Always non-resident (doesn't make sense to be resident anyway!).
- *
+ *
* This is an array of index blocks. Each index block starts with an
* INDEX_BLOCK structure containing an index header, followed by a sequence of
* index entries (INDEX_ENTRY structures), as described by the INDEX_HEADER.
QUOTA_FLAG_USER_MASK = const_cpu_to_le32(0x00000007),
/* Bit mask for user quota flags. */
-
+
/* These flags are only present in the quota defaults index entry,
i.e. in the entry where owner_id = QUOTA_DEFAULTS_ID. */
QUOTA_FLAG_TRACKING_ENABLED = const_cpu_to_le32(0x00000010),
*
* The $Q index contains one entry for each existing user_id on the volume. The
* index key is the user_id of the user/group owning this quota control entry,
- * i.e. the key is the owner_id. The user_id of the owner of a file, i.e. the
+ * i.e. the key is the owner_id. The user_id of the owner of a file, i.e. the
* owner_id, is found in the standard information attribute. The collation rule
* for $Q is COLLATION_NTOFS_ULONG.
*
IO_REPARSE_TAG_IS_ALIAS = const_cpu_to_le32(0x20000000),
IO_REPARSE_TAG_IS_HIGH_LATENCY = const_cpu_to_le32(0x40000000),
IO_REPARSE_TAG_IS_MICROSOFT = const_cpu_to_le32(0x80000000),
-
+
IO_REPARSE_TAG_RESERVED_ZERO = const_cpu_to_le32(0x00000000),
IO_REPARSE_TAG_RESERVED_ONE = const_cpu_to_le32(0x00000001),
IO_REPARSE_TAG_RESERVED_RANGE = const_cpu_to_le32(0x00000001),
* Attribute: Extended attribute (EA) (0xe0).
*
* NOTE: Always non-resident. (Is this true?)
- *
- * Like the attribute list and the index buffer list, the EA attribute value is
+ *
+ * Like the attribute list and the index buffer list, the EA attribute value is
* a sequence of EA_ATTR variable length records.
*
* FIXME: It appears weird that the EA name is not unicode. Is it true?
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* post_read_mst_fixup - deprotect multi sector transfer protected data
* @b: pointer to the data to deprotect
* @size: size in bytes of @b
- *
+ *
* Perform the necessary post read multi sector transfer fixup and detect the
* presence of incomplete multi sector transfers. - In that case, overwrite the
* magic of the ntfs record header being processed with "BAAD" (in memory only!)
usa_ofs + (usa_count * 2) > size ||
(size >> NTFS_BLOCK_SIZE_BITS) != usa_count)
return 0;
- /* Position of usn in update sequence array. */
+ /* Position of usn in update sequence array. */
usa_pos = (u16*)b + usa_ofs/sizeof(u16);
- /*
+ /*
* The update sequence number which has to be equal to each of the
* u16 values before they are fixed up. Note no need to care for
* endianness since we are comparing and moving data for on disk
- * structures which means the data is consistent. - If it is
+ * structures which means the data is consistent. - If it is
* consistenty the wrong endianness it doesn't make any difference.
*/
usn = *usa_pos;
* pre_write_mst_fixup - apply multi sector transfer protection
* @b: pointer to the data to protect
* @size: size in bytes of @b
- *
+ *
* Perform the necessary pre write multi sector transfer fixup on the data
* pointer to by @b of @size.
*
usa_ofs + (usa_count * 2) > size ||
(size >> NTFS_BLOCK_SIZE_BITS) != usa_count)
return -EINVAL;
- /* Position of usn in update sequence array. */
+ /* Position of usn in update sequence array. */
usa_pos = (u16*)((u8*)b + usa_ofs);
/*
- * Cyclically increment the update sequence number
+ * Cyclically increment the update sequence number
* (skipping 0 and -1, i.e. 0xffff).
*/
usn = le16_to_cpup(usa_pos) + 1;
/* Fixup all sectors. */
while (usa_count--) {
/*
- * Increment the position in the usa and save the
+ * Increment the position in the usa and save the
* original data from the data buffer into the usa.
*/
*(++usa_pos) = *data_pos;
/**
* post_write_mst_fixup - fast deprotect multi sector transfer protected data
* @b: pointer to the data to deprotect
- *
+ *
* Perform the necessary post write multi sector transfer fixup, not checking
* for any errors, because we assume we have just used pre_write_mst_fixup(),
* thus the data will be fine or we would never have gotten here.
u16 usa_ofs = le16_to_cpu(b->usa_ofs);
u16 usa_count = le16_to_cpu(b->usa_count) - 1;
- /* Position of usn in update sequence array. */
+ /* Position of usn in update sequence array. */
usa_pos = (u16*)b + usa_ofs/sizeof(u16);
/* Position in protected data of first u16 that needs fixing up. */
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
if (*v) \
goto needs_val; \
} \
- }
+ }
#define NTFS_GETOPT(option, variable) \
if (!strcmp(p, option)) { \
if (!v || !*v) \
variable = simple_strtoul(ov = v, &v, 0); \
if (*v) \
goto needs_val; \
- }
+ }
#define NTFS_GETOPT_BOOL(option, variable) \
if (!strcmp(p, option)) { \
BOOL val; \
if (!simple_getbool(v, &val)) \
goto needs_bool; \
variable = val; \
- }
+ }
#define NTFS_GETOPT_OPTIONS_ARRAY(option, variable, opt_array) \
if (!strcmp(p, option)) { \
int _i; \
le32_to_cpu(b->bpb.large_sectors) || b->bpb.fats)
goto not_ntfs;
/* Check clusters per file mft record value is valid. */
- if ((u8)b->clusters_per_mft_record < 0xe1 ||
+ if ((u8)b->clusters_per_mft_record < 0xe1 ||
(u8)b->clusters_per_mft_record > 0xf7)
switch (b->clusters_per_mft_record) {
case 1: case 2: case 4: case 8: case 16: case 32: case 64:
goto not_ntfs;
}
/* Check clusters per index block value is valid. */
- if ((u8)b->clusters_per_index_record < 0xe1 ||
+ if ((u8)b->clusters_per_index_record < 0xe1 ||
(u8)b->clusters_per_index_record > 0xf7)
switch (b->clusters_per_index_record) {
case 1: case 2: case 4: case 8: case 16: case 32: case 64:
* parse_ntfs_boot_sector - parse the boot sector and store the data in @vol
* @vol: volume structure to initialise with data from boot sector
* @b: boot sector to parse
- *
+ *
* Parse the ntfs boot sector @b and store all imporant information therein in
* the ntfs super block @vol. Return TRUE on success and FALSE on error.
*/
ntfs_debug("vol->mft_record_size_mask = 0x%x",
vol->mft_record_size_mask);
ntfs_debug("vol->mft_record_size_bits = %i (0x%x)",
- vol->mft_record_size_bits, vol->mft_record_size_bits);
+ vol->mft_record_size_bits, vol->mft_record_size_bits);
clusters_per_index_record = b->clusters_per_index_record;
ntfs_debug("clusters_per_index_record = %i (0x%x)",
- clusters_per_index_record, clusters_per_index_record);
+ clusters_per_index_record, clusters_per_index_record);
if (clusters_per_index_record > 0)
vol->index_record_size = vol->cluster_size <<
(ffs(clusters_per_index_record) - 1);
vol->index_record_size_mask = vol->index_record_size - 1;
vol->index_record_size_bits = ffs(vol->index_record_size) - 1;
ntfs_debug("vol->index_record_size = %i (0x%x)",
- vol->index_record_size, vol->index_record_size);
+ vol->index_record_size, vol->index_record_size);
ntfs_debug("vol->index_record_size_mask = 0x%x",
vol->index_record_size_mask);
ntfs_debug("vol->index_record_size_bits = %i (0x%x)",
/*
* Get the inode for the attribute definitions file and parse the
* attribute definitions.
- */
+ */
tmp_ino = ntfs_iget(sb, FILE_AttrDef);
if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
if (!IS_ERR(tmp_ino))
ntfs_error(sb, "Not an NTFS volume.");
goto err_out_now;
}
-
+
/*
* Extract the data from the boot sector and setup the ntfs super block
* using it.
goto err_out_now;
}
- /*
+ /*
* TODO: When we start coping with sector sizes different from
* NTFS_BLOCK_SIZE, we now probably need to set the blocksize of the
* device (probably to NTFS_BLOCK_SIZE).
}
ntfs_inode_cache = kmem_cache_create(ntfs_inode_cache_name,
- sizeof(ntfs_inode), 0,
+ sizeof(ntfs_inode), 0,
SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT, NULL, NULL);
if (!ntfs_inode_cache) {
printk(KERN_CRIT "NTFS: Failed to create %s!\n",
}
ntfs_big_inode_cache = kmem_cache_create(ntfs_big_inode_cache_name,
- sizeof(big_ntfs_inode), 0,
+ sizeof(big_ntfs_inode), 0,
SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT,
ntfs_big_inode_init_once, NULL);
if (!ntfs_big_inode_cache) {
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* sysctl.h - Defines for sysctl handling in NTFS Linux kernel driver. Part of
* the Linux-NTFS project. Adapted from the old NTFS driver,
* Copyright (C) 1997 Martin von Löwis, Régis Duchesne.
- *
+ *
* Copyright (c) 2002 Anton Altaparmakov.
*
* This program/include file is free software; you can redistribute it and/or
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* @vcn: starting vcn of the current array element
* @lcn: starting lcn of the current array element
* @length: length in clusters of the current array element
- *
+ *
* The last vcn (in fact the last vcn + 1) is reached when length == 0.
- *
- * When lcn == -1 this means that the count vcns starting at vcn are not
+ *
+ * When lcn == -1 this means that the count vcns starting at vcn are not
* physically allocated (i.e. this is a hole / data is sparse).
*/
typedef struct { /* In memory vcn to lcn mapping structure element. */
* run_list - in memory vcn to lcn mapping array including a read/write lock
* @rl: pointer to an array of run list elements
* @lock: read/write spinlock for serializing access to @rl
- *
+ *
*/
typedef struct {
run_list_element *rl;
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
* @upcase_len: upcase table size (ignored if @ic is CASE_SENSITIVE)
*
* ntfs_collate_names collates two Unicode names and returns:
- *
+ *
* -1 if the first name collates before the second one,
* 0 if the names match,
* 1 if the second name collates before the first one, or
* Compare the first @n characters of the Unicode strings @s1 and @s2,
* The strings in little endian format and appropriate le16_to_cpu()
* conversion is performed on non-little endian machines.
- *
+ *
* The function returns an integer less than, equal to, or greater than zero
* if @s1 (or the first @n Unicode characters thereof) is found, respectively,
* to be less than, to match, or be greater than @s2.
* Compare the first @n characters of the Unicode strings @s1 and @s2,
* ignoring case. The strings in little endian format and appropriate
* le16_to_cpu() conversion is performed on non-little endian machines.
- *
+ *
* Each character is uppercased using the @upcase table before the comparison.
*
* The function returns an integer less than, equal to, or greater than zero
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program/include file is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+ * This program/include file 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 (in the main directory of the Linux-NTFS
+ * along with this program (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// readcount = (ULONG)(__min(runcount, left));
readcount = (ULONG)min (runcount, left);
-
+
ULONG n = readcount * Vcb->NtfsInfo.BytesPerCluster;
if (lcn == 0)
vcn += readcount;
bytes += n;
-
+
}
}
VOID
-ReadAttribute(PATTRIBUTE attr, PVOID buffer, PDEVICE_EXTENSION Vcb,
+ReadAttribute(PATTRIBUTE attr, PVOID buffer, PDEVICE_EXTENSION Vcb,
PDEVICE_OBJECT DeviceObject);
ULONG
* FILE: services/fs/cdfs/rw.c
* PURPOSE: CDROM (ISO 9660) filesystem driver
* PROGRAMMER: Art Yerkes
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
*LengthRead = Length;
if (Length + ReadOffset > Fcb->Entry.DataLengthL)
{
- memset(Buffer + Fcb->Entry.DataLengthL - ReadOffset,
+ memset(Buffer + Fcb->Entry.DataLengthL - ReadOffset,
0, Length + ReadOffset - Fcb->Entry.DataLengthL);
}
}
{
if (FileObject->Flags & FO_SYNCHRONOUS_IO)
{
- FileObject->CurrentByteOffset.QuadPart =
+ FileObject->CurrentByteOffset.QuadPart =
ReadOffset.QuadPart + ReturnedReadLength;
}
Irp->IoStatus.Information = ReturnedReadLength;
* FILE: services/fs/template/template.c
* PURPOSE: Bare filesystem template
* PROGRAMMER: David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
BOOLEAN STDCALL
FsdHasFileSystem(PDEVICE_OBJECT DeviceToMount)
/*
- * FUNCTION: Tests if the device contains a filesystem that can be mounted
+ * FUNCTION: Tests if the device contains a filesystem that can be mounted
* by this fsd
*/
{
* PURPOSE: Temporary sector reading support
* PROGRAMMER: David Welch (welch@cwcom.net)
* Hartmut Birr
- * UPDATE HISTORY:
+ * UPDATE HISTORY:
*/
/* INCLUDES *****************************************************************/
DPRINT ("Building asynchronous FSD Request...\n");
Buffer = (PCHAR)MmGetMdlVirtualAddress(IrpContext->Irp->MdlAddress) + BufferOffset;
-
+
Irp = IoAllocateIrp(IrpContext->DeviceExt->StorageDevice->StackSize, TRUE);
if (Irp == NULL)
{
{
PVFATFCB pFcb;
PFILE_OBJECT FileObject = IrpContext->FileObject;
-
+
DPRINT("VfatCleanupFile(DeviceExt %x, FileObject %x)\n",
IrpContext->DeviceExt, FileObject);
-
+
/* FIXME: handle file/directory deletion here */
pFcb = (PVFATFCB) FileObject->FsContext;
if (pFcb)
}
vfatReleaseFCB (DeviceExt, pFcb);
}
-
+
FileObject->FsContext2 = NULL;
FileObject->FsContext = NULL;
FileObject->SectionObjectPointer = NULL;
{
vfatDestroyCCB(pCcb);
}
-
+
return Status;
}
goto ByeBye;
}
#if 0
- /* There occurs a dead look at the call to CcRosDeleteFileCache/ObDereferenceObject/VfatClose
+ /* There occurs a dead look at the call to CcRosDeleteFileCache/ObDereferenceObject/VfatClose
in CmLazyCloseThreadMain if VfatClose is execute asynchronous in a worker thread. */
if (!ExAcquireResourceExclusiveLite (&IrpContext->DeviceExt->DirResource, IrpContext->Flags & IRPCONTEXT_CANWAIT))
#else
OEM_STRING StringA;
USHORT Length;
CHAR cString[12];
-
+
RtlCopyMemory(cString, pEntry->Filename, 11);
cString[11] = 0;
if (cString[0] == 0x05)
{
cString[0] = 0xe5;
- }
+ }
StringA.Buffer = cString;
- for (StringA.Length = 0;
+ for (StringA.Length = 0;
StringA.Length < 8 && StringA.Buffer[StringA.Length] != ' ';
StringA.Length++);
StringA.MaximumLength = StringA.Length;
-
+
RtlOemStringToUnicodeString(NameU, &StringA, FALSE);
if (pEntry->lCase & VFAT_CASE_LOWER_BASE)
}
NameU->Length = 0;
NameU->MaximumLength -= Length;
-
+
StringA.Buffer = &cString[8];
- for (StringA.Length = 0;
+ for (StringA.Length = 0;
StringA.Length < 3 && StringA.Buffer[StringA.Length] != ' ';
StringA.Length++);
StringA.MaximumLength = StringA.Length;
NameU.MaximumLength = sizeof(Vpb->VolumeLabel);
*(Vpb->VolumeLabel) = 0;
Vpb->VolumeLabelLength = 0;
-
+
if (DeviceExt->Flags & VCB_IS_FATX)
{
SizeDirEntry = sizeof(FATX_DIR_ENTRY);
{
break;
}
- DirIndex++;
+ DirIndex++;
Entry = (PDIR_ENTRY)((ULONG_PTR)Entry + SizeDirEntry);
if ((DirIndex % EntriesPerPage) == 0)
{
UNICODE_STRING FileToFindUpcase;
BOOLEAN WildCard;
- DPRINT ("FindFile(Parent %x, FileToFind '%wZ', DirIndex: %d)\n",
+ DPRINT ("FindFile(Parent %x, FileToFind '%wZ', DirIndex: %d)\n",
Parent, FileToFindU, DirContext->DirIndex);
DPRINT ("FindFile: Path %wZ)\n",&Parent->PathNameU);
-
+
PathNameBufferLength = LONGNAME_MAX_LENGTH * sizeof(WCHAR);
PathNameBuffer = ExAllocatePool(NonPagedPool, PathNameBufferLength + sizeof(WCHAR));
if (!PathNameBuffer)
ExFreePool(PathNameBuffer);
return Status;
}
-
+
while(TRUE)
{
Status = DeviceExt->GetNextDirEntry(&Context, &Page, Parent, DirContext, First);
0,
FALSE);
- if (Status == STATUS_VERIFY_REQUIRED)
+ if (Status == STATUS_VERIFY_REQUIRED)
{
PDEVICE_OBJECT DeviceToVerify;
DPRINT ("Device %p\n", DeviceExt->StorageDevice);
DeviceToVerify = IoGetDeviceToVerify (PsGetCurrentThread ());
-
+
IoSetDeviceToVerify (PsGetCurrentThread (),
NULL);
Status = IoVerifyVolume (DeviceExt->StorageDevice,
LARGE_INTEGER AllocationSize;
BOOLEAN Dots;
UNICODE_STRING FileNameU;
-
+
/* Unpack the various parameters. */
Stack = IoGetCurrentIrpStackLocation (Irp);
RequestedDisposition = ((Stack->Parameters.Create.Options >> 24) & 0xff);
}
/* This a open operation for the volume itself */
- if (FileObject->FileName.Length == 0 &&
+ if (FileObject->FileName.Length == 0 &&
FileObject->RelatedFileObject == NULL)
- {
+ {
if (RequestedDisposition == FILE_CREATE ||
RequestedDisposition == FILE_OVERWRITE_IF ||
RequestedDisposition == FILE_SUPERSEDE)
Dots = FALSE;
}
- if (*c != '\\' && vfatIsLongIllegal(*c))
+ if (*c != '\\' && vfatIsLongIllegal(*c))
{
return(STATUS_OBJECT_NAME_INVALID);
}
{
ULONG Attributes;
Attributes = Stack->Parameters.Create.FileAttributes;
-
+
vfatSplitPathName(&FileObject->FileName, NULL, &FileNameU);
- Status = VfatAddEntry (DeviceExt, &FileNameU, &pFcb, ParentFcb, RequestedOptions,
+ Status = VfatAddEntry (DeviceExt, &FileNameU, &pFcb, ParentFcb, RequestedOptions,
(UCHAR)(Attributes & FILE_ATTRIBUTE_VALID_FLAGS));
vfatReleaseFCB (DeviceExt, ParentFcb);
if (NT_SUCCESS (Status))
{
vfatAttachFCBToFileObject (DeviceExt, pFcb, FileObject);
-
+
Irp->IoStatus.Information = FILE_CREATED;
-
- VfatSetAllocationSizeInformation(FileObject,
+
+ VfatSetAllocationSizeInformation(FileObject,
pFcb,
DeviceExt,
&Irp->Overlay.AllocationSize);
- VfatSetExtendedAttributes(FileObject,
+ VfatSetExtendedAttributes(FileObject,
Irp->AssociatedIrp.SystemBuffer,
Stack->Parameters.Create.EaLength);
FileObject,
&pFcb->FCBShareAccess,
FALSE);
- if (!NT_SUCCESS(Status))
+ if (!NT_SUCCESS(Status))
{
VfatCloseFile (DeviceExt, FileObject);
return(Status);
/*
* Check the file has the requested attributes
*/
- if (RequestedOptions & FILE_NON_DIRECTORY_FILE &&
+ if (RequestedOptions & FILE_NON_DIRECTORY_FILE &&
*pFcb->Attributes & FILE_ATTRIBUTE_DIRECTORY)
{
VfatCloseFile (DeviceExt, FileObject);
return(STATUS_FILE_IS_A_DIRECTORY);
}
- if (RequestedOptions & FILE_DIRECTORY_FILE &&
+ if (RequestedOptions & FILE_DIRECTORY_FILE &&
!(*pFcb->Attributes & FILE_ATTRIBUTE_DIRECTORY))
{
VfatCloseFile (DeviceExt, FileObject);
if (PagingFileCreate)
{
/* FIXME:
- * Do more checking for page files. It is possible,
- * that the file was opened and closed previously
- * as a normal cached file. In this case, the cache
- * manager has referenced the fileobject and the fcb
- * is held in memory. Try to remove the fileobject
+ * Do more checking for page files. It is possible,
+ * that the file was opened and closed previously
+ * as a normal cached file. In this case, the cache
+ * manager has referenced the fileobject and the fcb
+ * is held in memory. Try to remove the fileobject
* from cache manager and use the fcb.
*/
if (pFcb->RefCount > 1)
return(STATUS_INVALID_PARAMETER);
}
}
-
+
if (RequestedDisposition == FILE_OVERWRITE ||
RequestedDisposition == FILE_OVERWRITE_IF)
return(Status);
}
}
-
-
+
+
/* Supersede the file */
if (RequestedDisposition == FILE_SUPERSEDE)
{
FileObject,
&pFcb->FCBShareAccess
);
-
+
}
pFcb->OpenHandleCount++;
-
+
/* FIXME : test write access if requested */
return(Status);
ExReleaseResourceLite (&IrpContext->DeviceExt->DirResource);
IrpContext->Irp->IoStatus.Status = Status;
- IoCompleteRequest (IrpContext->Irp,
+ IoCompleteRequest (IrpContext->Irp,
(CCHAR)(NT_SUCCESS(Status) ? IO_DISK_INCREMENT : IO_NO_INCREMENT));
VfatFreeIrpContext(IrpContext);
return(Status);
{
if ((sizeof (FILE_BOTH_DIR_INFORMATION) + DirContext->LongNameU.Length) > BufferLength)
return STATUS_BUFFER_OVERFLOW;
-
+
if (DeviceExt->Flags & VCB_IS_FATX)
{
pInfo->FileNameLength = DirContext->LongNameU.Length;
RtlCopyMemory(pInfo->FileName, DirContext->LongNameU.Buffer, DirContext->LongNameU.Length);
- pInfo->NextEntryOffset =
+ pInfo->NextEntryOffset =
ULONG_ROUND_UP (sizeof (FILE_BOTH_DIR_INFORMATION) + DirContext->LongNameU.Length);
pInfo->ShortName[0] = 0;
pInfo->ShortNameLength = 0;
else
{
pInfo->FileNameLength = DirContext->LongNameU.Length;
- pInfo->NextEntryOffset =
+ pInfo->NextEntryOffset =
ULONG_ROUND_UP (sizeof (FILE_BOTH_DIR_INFORMATION) + DirContext->LongNameU.Length);
RtlCopyMemory(pInfo->ShortName, DirContext->ShortNameU.Buffer, DirContext->ShortNameU.Length);
pInfo->ShortNameLength = (CCHAR)DirContext->ShortNameU.Length;
#if 0
/* Do not probe the user buffer until SEH is available */
if (IrpContext->Irp->RequestorMode != KernelMode &&
- IrpContext->Irp->MdlAddress == NULL &&
+ IrpContext->Irp->MdlAddress == NULL &&
IrpContext->Irp->UserBuffer != NULL)
{
ProbeForWrite(IrpContext->Irp->UserBuffer, BufferLength, 1);
while (RC == STATUS_SUCCESS && BufferLength > 0)
{
- RC = FindFile (IrpContext->DeviceExt, pFcb,
+ RC = FindFile (IrpContext->DeviceExt, pFcb,
&pCcb->SearchPattern, &DirContext, FirstCall);
pCcb->Entry = DirContext.DirIndex;
DPRINT ("Found %wZ, RC=%x, entry %x\n", &DirContext.LongNameU, RC, pCcb->Entry);
{
case FileNameInformation:
RC = VfatGetFileNameInformation (&DirContext,
- (PFILE_NAMES_INFORMATION) Buffer,
+ (PFILE_NAMES_INFORMATION) Buffer,
BufferLength);
break;
case FileDirectoryInformation:
- RC = VfatGetFileDirectoryInformation (&DirContext,
+ RC = VfatGetFileDirectoryInformation (&DirContext,
IrpContext->DeviceExt,
- (PFILE_DIRECTORY_INFORMATION) Buffer,
+ (PFILE_DIRECTORY_INFORMATION) Buffer,
BufferLength);
break;
case FileFullDirectoryInformation:
- RC = VfatGetFileFullDirectoryInformation (&DirContext,
+ RC = VfatGetFileFullDirectoryInformation (&DirContext,
IrpContext->DeviceExt,
- (PFILE_FULL_DIR_INFORMATION) Buffer,
+ (PFILE_FULL_DIR_INFORMATION) Buffer,
BufferLength);
break;
case FileBothDirectoryInformation:
- RC = VfatGetFileBothInformation (&DirContext,
+ RC = VfatGetFileBothInformation (&DirContext,
IrpContext->DeviceExt,
- (PFILE_BOTH_DIR_INFORMATION) Buffer,
+ (PFILE_BOTH_DIR_INFORMATION) Buffer,
BufferLength);
break;
default:
#define NDEBUG
#include "vfat.h"
-ULONG
+ULONG
vfatDirEntryGetFirstCluster (PDEVICE_EXTENSION pDeviceExt,
PDIR_ENTRY pFatDirEntry)
{
if (pDeviceExt->FatInfo.FatType == FAT32)
{
- cluster = pFatDirEntry->Fat.FirstCluster +
+ cluster = pFatDirEntry->Fat.FirstCluster +
pFatDirEntry->Fat.FirstClusterHigh * 65536;
}
else if (pDeviceExt->Flags & VCB_IS_FATX)
PFAT_DIR_ENTRY fatDirEntry;
slot * longNameEntry;
ULONG index;
-
+
UCHAR CheckSum, shortCheckSum;
USHORT i;
BOOLEAN Valid = TRUE;
if (First)
{
- /* This is the first call to vfatGetNextDirEntry. Possible the start index points
- * into a long name or points to a short name with an assigned long name.
+ /* This is the first call to vfatGetNextDirEntry. Possible the start index points
+ * into a long name or points to a short name with an assigned long name.
* We must go back to the real start of the entry */
- while (DirContext->DirIndex > 0 &&
- !FAT_ENTRY_END(fatDirEntry) &&
- !FAT_ENTRY_DELETED(fatDirEntry) &&
- ((!FAT_ENTRY_LONG(fatDirEntry) && !Back) ||
+ while (DirContext->DirIndex > 0 &&
+ !FAT_ENTRY_END(fatDirEntry) &&
+ !FAT_ENTRY_DELETED(fatDirEntry) &&
+ ((!FAT_ENTRY_LONG(fatDirEntry) && !Back) ||
(FAT_ENTRY_LONG(fatDirEntry) && !(longNameEntry->id & 0x40))))
{
DirContext->DirIndex--;
}
}
- if (Back && !FAT_ENTRY_END(fatDirEntry) &&
+ if (Back && !FAT_ENTRY_END(fatDirEntry) &&
(FAT_ENTRY_DELETED(fatDirEntry) || !FAT_ENTRY_LONG(fatDirEntry)))
{
DirContext->DirIndex++;
{
CcUnpinData(*pContext);
FileOffset.u.LowPart += PAGE_SIZE;
- if (FileOffset.u.LowPart >= pDirFcb->RFCB.FileSize.u.LowPart ||
+ if (FileOffset.u.LowPart >= pDirFcb->RFCB.FileSize.u.LowPart ||
!CcMapData(pDirFcb->FileObject, &FileOffset, PAGE_SIZE, TRUE, pContext, pPage))
{
CHECKPOINT;
RtlCopyMemory(pName, longNameEntry->name0_4, 5 * sizeof(WCHAR));
RtlCopyMemory(pName + 5, longNameEntry->name5_10, 6 * sizeof(WCHAR));
RtlCopyMemory(pName + 11, longNameEntry->name11_12, 2 * sizeof(WCHAR));
-
+
DPRINT (" longName: [%S]\n", DirContext->LongNameU.Buffer);
if (CheckSum != longNameEntry->alias_checksum)
{
{
DirContext->LongNameU.Buffer[0] = 0;
}
-
+
RtlCopyMemory (&DirContext->DirEntry.Fat, fatDirEntry, sizeof (FAT_DIR_ENTRY));
break;
}
ULONG DirIndex = DirContext->DirIndex;
FileOffset.u.HighPart = 0;
-
+
if (!vfatFCBIsRoot(pDirFcb))
{
/* need to add . and .. entries */
CcUnpinData(*pContext);
*pContext = NULL;
return STATUS_NO_MORE_ENTRIES;
- }
+ }
if (!FATX_ENTRY_DELETED(fatxDirEntry))
{
#define NDEBUG
#include "vfat.h"
-NTSTATUS
+NTSTATUS
VfatUpdateEntry (PVFATFCB pFcb)
/*
* update an existing FAT entry
ASSERT(pFcb);
ASSERT(pFcb->parentFcb);
-
+
if (pFcb->Flags & FCB_IS_FATX_ENTRY)
{
SizeDirEntry = sizeof(FATX_DIR_ENTRY);
}
ASSERT (pFcb->parentFcb);
-
+
Offset.u.HighPart = 0;
Offset.u.LowPart = dirIndex * SizeDirEntry;
if (CcPinRead (pFcb->parentFcb->FileObject, &Offset, SizeDirEntry,
NTSTATUS Status;
ULONG SizeDirEntry;
FileOffset.QuadPart = 0;
-
+
if (DeviceExt->Flags & VCB_IS_FATX)
SizeDirEntry = sizeof(FATX_DIR_ENTRY);
else
SizeDirEntry = sizeof(FAT_DIR_ENTRY);
-
+
count = pDirFcb->RFCB.FileSize.u.LowPart / SizeDirEntry;
size = DeviceExt->FatInfo.BytesPerCluster / SizeDirEntry;
for (i = 0; i < count; i++, pFatEntry = (PDIR_ENTRY)((ULONG_PTR)pFatEntry + SizeDirEntry))
FATAddEntry (PDEVICE_EXTENSION DeviceExt,
PUNICODE_STRING NameU,
PVFATFCB* Fcb,
- PVFATFCB ParentFcb,
+ PVFATFCB ParentFcb,
ULONG RequestedOptions,
UCHAR ReqAttr)
/*
NTSTATUS Status = STATUS_SUCCESS;
ULONG size;
long i;
-
+
OEM_STRING NameA;
CHAR aName[13];
BOOLEAN IsNameLegal;
DPRINT ("addEntry: Name='%wZ', Dir='%wZ'\n", NameU, &ParentFcb->PathNameU);
DirContext.LongNameU = *NameU;
-
+
nbSlots = (DirContext.LongNameU.Length / sizeof(WCHAR) + 12) / 13 + 1; //nb of entry needed for long name+normal entry
DPRINT ("NameLen= %d, nbSlots =%d\n", DirContext.LongNameU.Length / sizeof(WCHAR), nbSlots);
Buffer = ExAllocatePool (NonPagedPool, (nbSlots - 1) * sizeof (FAT_DIR_ENTRY));
if (Buffer == NULL)
{
return STATUS_INSUFFICIENT_RESOURCES;
- }
+ }
RtlZeroMemory (Buffer, (nbSlots - 1) * sizeof (FAT_DIR_ENTRY));
pSlots = (slot *) Buffer;
/* check if the name and the extension contains upper case characters */
RtlDowncaseUnicodeString(&DirContext.ShortNameU, &DirContext.LongNameU, FALSE);
DirContext.ShortNameU.Buffer[DirContext.ShortNameU.Length / sizeof(WCHAR)] = 0;
- uCaseBase = wcsncmp(DirContext.LongNameU.Buffer,
+ uCaseBase = wcsncmp(DirContext.LongNameU.Buffer,
DirContext.ShortNameU.Buffer, posCar) ? TRUE : FALSE;
if (posCar < DirContext.LongNameU.Length/sizeof(WCHAR))
{
i = DirContext.LongNameU.Length / sizeof(WCHAR) - posCar;
- uCaseExt = wcsncmp(DirContext.LongNameU.Buffer + posCar,
+ uCaseExt = wcsncmp(DirContext.LongNameU.Buffer + posCar,
DirContext.ShortNameU.Buffer + posCar, i) ? TRUE : FALSE;
}
else
/* check if the name and the extension contains lower case characters */
RtlUpcaseUnicodeString(&DirContext.ShortNameU, &DirContext.LongNameU, FALSE);
DirContext.ShortNameU.Buffer[DirContext.ShortNameU.Length / sizeof(WCHAR)] = 0;
- lCaseBase = wcsncmp(DirContext.LongNameU.Buffer,
+ lCaseBase = wcsncmp(DirContext.LongNameU.Buffer,
DirContext.ShortNameU.Buffer, posCar) ? TRUE : FALSE;
if (posCar < DirContext.LongNameU.Length / sizeof(WCHAR))
{
i = DirContext.LongNameU.Length / sizeof(WCHAR) - posCar;
- lCaseExt = wcsncmp(DirContext.LongNameU.Buffer + posCar,
+ lCaseExt = wcsncmp(DirContext.LongNameU.Buffer + posCar,
DirContext.ShortNameU.Buffer + posCar, i) ? TRUE : FALSE;
}
else
needLong = TRUE;
}
}
- DPRINT ("'%s', '%wZ', needTilde=%d, needLong=%d\n",
+ DPRINT ("'%s', '%wZ', needTilde=%d, needLong=%d\n",
aName, &DirContext.LongNameU, needTilde, needLong);
memset(DirContext.DirEntry.Fat.Filename, ' ', 11);
for (i = 0; i < 8 && aName[i] && aName[i] != '.'; i++)
DirContext.LongNameU.Buffer = LongNameBuffer;
DirContext.LongNameU.MaximumLength = sizeof(LongNameBuffer);
DirContext.LongNameU.Buffer[DirContext.LongNameU.Length / sizeof(WCHAR)] = 0;
- memset(DirContext.LongNameU.Buffer + DirContext.LongNameU.Length / sizeof(WCHAR) + 1, 0xff,
+ memset(DirContext.LongNameU.Buffer + DirContext.LongNameU.Length / sizeof(WCHAR) + 1, 0xff,
DirContext.LongNameU.MaximumLength - DirContext.LongNameU.Length - sizeof(WCHAR));
}
else
{
TIME_FIELDS tf;
RtlTimeToTimeFields (&SystemTime, &tf);
- DPRINT1("%d.%d.%d %02d:%02d:%02d.%03d '%wZ'\n",
- tf.Day, tf.Month, tf.Year, tf.Hour,
+ DPRINT1("%d.%d.%d %02d:%02d:%02d.%03d '%wZ'\n",
+ tf.Day, tf.Month, tf.Year, tf.Hour,
tf.Minute, tf.Second, tf.Milliseconds,
NameU);
}
OEM_STRING NameA;
VFAT_DIRENTRY_CONTEXT DirContext;
PFATX_DIR_ENTRY pFatXDirEntry;
-
+
DPRINT ("addEntry: Name='%wZ', Dir='%wZ'\n", NameU, &ParentFcb->PathNameU);
-
+
DirContext.LongNameU = *NameU;
-
+
if (DirContext.LongNameU.Length / sizeof(WCHAR) > 42)
{
/* name too long */
CHECKPOINT;
return STATUS_NAME_TOO_LONG;
}
-
+
/* try to find 1 entry free in directory */
if (!vfatFindDirSpace(DeviceExt, ParentFcb, 1, &DirContext.StartIndex))
{
DirContext.DirIndex += 2;
DirContext.StartIndex += 2;
}
-
+
DirContext.ShortNameU.Buffer = 0;
DirContext.ShortNameU.Length = 0;
DirContext.ShortNameU.MaximumLength = 0;
memset(DirContext.DirEntry.FatX.Filename, 0xff, 42);
DirContext.DirEntry.FatX.FirstCluster = 0;
DirContext.DirEntry.FatX.FileSize = 0;
-
+
/* set file name */
NameA.Buffer = (PCHAR)DirContext.DirEntry.FatX.Filename;
NameA.Length = 0;
NameA.MaximumLength = 42;
RtlUnicodeStringToOemString(&NameA, &DirContext.LongNameU, FALSE);
DirContext.DirEntry.FatX.FilenameLength = (unsigned char)NameA.Length;
-
+
/* set attributes */
DirContext.DirEntry.FatX.Attrib = ReqAttr;
if (RequestedOptions & FILE_DIRECTORY_FILE)
{
DirContext.DirEntry.FatX.Attrib |= FILE_ATTRIBUTE_DIRECTORY;
}
-
+
/* set dates and times */
KeQuerySystemTime (&SystemTime);
FsdSystemTimeToDosDateTime(DeviceExt, &SystemTime, &DirContext.DirEntry.FatX.CreationDate,
DirContext.DirEntry.FatX.UpdateTime = DirContext.DirEntry.FatX.CreationTime;
DirContext.DirEntry.FatX.AccessDate = DirContext.DirEntry.FatX.CreationDate;
DirContext.DirEntry.FatX.AccessTime = DirContext.DirEntry.FatX.CreationTime;
-
+
/* add entry into parent directory */
FileOffset.u.HighPart = 0;
FileOffset.u.LowPart = DirContext.StartIndex * sizeof(FATX_DIR_ENTRY);
RtlCopyMemory(pFatXDirEntry, &DirContext.DirEntry.FatX, sizeof(FATX_DIR_ENTRY));
CcSetDirtyPinnedData(Context, NULL);
CcUnpinData(Context);
-
+
/* FIXME: check status */
vfatMakeFCBFromDirEntry(DeviceExt, ParentFcb, &DirContext, Fcb);
-
+
DPRINT("addentry ok\n");
return STATUS_SUCCESS;
}
PVOID Context = NULL;
LARGE_INTEGER Offset;
PFATX_DIR_ENTRY pDirEntry;
- ULONG StartIndex;
+ ULONG StartIndex;
ASSERT(pFcb);
ASSERT(pFcb->parentFcb);
ASSERT(pFcb->Flags & FCB_IS_FATX_ENTRY);
-
+
StartIndex = pFcb->startIndex;
DPRINT ("delEntry PathName \'%wZ\'\n", &pFcb->PathNameU);
(PDIR_ENTRY)pDirEntry);
CcSetDirtyPinnedData(Context, NULL);
CcUnpinData(Context);
-
+
while (CurrentCluster && CurrentCluster != 0xffffffff)
{
GetNextCluster (DeviceExt, CurrentCluster, &NextCluster);
/* FUNCTIONS *****************************************************************/
-NTSTATUS
-VfatSetExtendedAttributes(PFILE_OBJECT FileObject,
+NTSTATUS
+VfatSetExtendedAttributes(PFILE_OBJECT FileObject,
PVOID Ea,
ULONG EaLength)
{
ULONG vfatNameHash(ULONG hash, PUNICODE_STRING NameU)
{
- PWCHAR last;
+ PWCHAR last;
PWCHAR curr;
register WCHAR c;
vfatInitFcb(PVFATFCB Fcb, PUNICODE_STRING NameU)
{
USHORT PathNameBufferLength;
-
+
if (NameU)
PathNameBufferLength = NameU->Length + sizeof(WCHAR);
else
PathNameBufferLength = 0;
-
+
Fcb->PathNameBuffer = ExAllocatePool(NonPagedPool, PathNameBufferLength);
if (!Fcb->PathNameBuffer)
{
DPRINT1("Unable to initialize FCB for filename '%wZ'\n", NameU);
KEBUGCHECKEX(0, (ULONG_PTR)Fcb, (ULONG_PTR)NameU, 0, 0);
}
-
+
Fcb->PathNameU.Length = 0;
Fcb->PathNameU.Buffer = Fcb->PathNameBuffer;
Fcb->PathNameU.MaximumLength = PathNameBufferLength;
{
Fcb->DirNameU.Buffer = Fcb->LongNameU.Buffer = NULL;
Fcb->DirNameU.MaximumLength = Fcb->DirNameU.Length = 0;
- Fcb->LongNameU.MaximumLength = Fcb->LongNameU.Length = 0;
+ Fcb->LongNameU.MaximumLength = Fcb->LongNameU.Length = 0;
}
RtlZeroMemory(&Fcb->FCBShareAccess, sizeof(SHARE_ACCESS));
Fcb->OpenHandleCount = 0;
-}
+}
PVFATFCB
vfatNewFCB(PDEVICE_EXTENSION pVCB, PUNICODE_STRING pFileNameU)
rcFCB->ShortHash.self = rcFCB;
ExInitializeResourceLite(&rcFCB->PagingIoResource);
ExInitializeResourceLite(&rcFCB->MainResource);
- FsRtlInitializeFileLock(&rcFCB->FileLock, NULL, NULL);
+ FsRtlInitializeFileLock(&rcFCB->FileLock, NULL, NULL);
ExInitializeFastMutex(&rcFCB->LastMutex);
rcFCB->RFCB.PagingIoResource = &rcFCB->PagingIoResource;
rcFCB->RFCB.Resource = &rcFCB->MainResource;
return rcFCB;
}
-VOID
+VOID
vfatDestroyCCB(PVFATCCB pCcb)
{
if (pCcb->SearchPattern.Buffer)
VOID
vfatDestroyFCB(PVFATFCB pFCB)
{
- FsRtlUninitializeFileLock(&pFCB->FileLock);
+ FsRtlUninitializeFileLock(&pFCB->FileLock);
ExFreePool(pFCB->PathNameBuffer);
ExDeleteResourceLite(&pFCB->PagingIoResource);
ExDeleteResourceLite(&pFCB->MainResource);
if (pFCB->RefCount == 0)
{
tmpFcb = pFCB->parentFcb;
- RemoveEntryList (&pFCB->FcbListEntry);
+ RemoveEntryList (&pFCB->FcbListEntry);
if (pFCB->Hash.Hash != pFCB->ShortHash.Hash)
{
entry = pVCB->FcbHashTable[ShortIndex];
ShortIndex = pFCB->ShortHash.Hash % pVCB->HashTableSize;
InsertTailList (&pVCB->FcbListHead, &pFCB->FcbListEntry);
-
+
pFCB->Hash.next = pVCB->FcbHashTable[Index];
pVCB->FcbHashTable[Index] = &pFCB->Hash;
if (pFCB->Hash.Hash != pFCB->ShortHash.Hash)
UNICODE_STRING DirNameU;
UNICODE_STRING FileNameU;
PUNICODE_STRING FcbNameU;
-
- HASHENTRY* entry;
+
+ HASHENTRY* entry;
DPRINT("'%wZ'\n", PathNameU);
-
+
Hash = vfatNameHash(0, PathNameU);
entry = pVCB->FcbHashTable[Hash % pVCB->HashTableSize];
USHORT PathNameLength;
ULONG Size;
ULONG hash;
-
+
UNICODE_STRING NameU;
PathNameLength = directoryFCB->PathNameU.Length + max(DirContext->LongNameU.Length, DirContext->ShortNameU.Length);
{
PathNameLength += sizeof(WCHAR);
}
-
+
if (PathNameLength > LONGNAME_MAX_LENGTH * sizeof(WCHAR))
{
return STATUS_OBJECT_NAME_INVALID;
RtlAppendUnicodeStringToString(&NameU, &DirContext->ShortNameU);
}
NameU.Buffer[NameU.Length / sizeof(WCHAR)] = 0;
-
+
rcFCB = vfatNewFCB (vcb, &NameU);
RtlCopyMemory (&rcFCB->entry, &DirContext->DirEntry, sizeof (DIR_ENTRY));
RtlCopyUnicodeString(&rcFCB->ShortNameU, &DirContext->ShortNameU);
PVOID Page = NULL;
BOOLEAN First = TRUE;
VFAT_DIRENTRY_CONTEXT DirContext;
- /* This buffer must have a size of 260 characters, because
+ /* This buffer must have a size of 260 characters, because
vfatMakeFCBFromDirEntry can copy 20 name entries with 13 characters. */
WCHAR LongNameBuffer[260];
WCHAR ShortNameBuffer[13];
while (TRUE)
{
status = pDeviceExt->GetNextDirEntry(&Context,
- &Page,
+ &Page,
pDirectoryFCB,
&DirContext,
First);
{
curr--;
}
-
+
if (curr > pFileNameU->Buffer)
{
NameU.Buffer = pFileNameU->Buffer;
vfatReleaseFCB (pVCB, FCB);
return STATUS_OBJECT_NAME_INVALID;
}
- RtlMoveMemory(pFileNameU->Buffer + FCB->PathNameU.Length / sizeof(WCHAR),
+ RtlMoveMemory(pFileNameU->Buffer + FCB->PathNameU.Length / sizeof(WCHAR),
curr, pFileNameU->Length - Length);
pFileNameU->Length += (USHORT)(FCB->PathNameU.Length - Length);
curr = pFileNameU->Buffer + FCB->PathNameU.Length / sizeof(WCHAR);
FCB = vfatOpenRootFCB(pVCB);
curr = pFileNameU->Buffer;
}
-
+
parentFCB = NULL;
prev = curr;
}
vfatReleaseFCB (pVCB, parentFCB);
return STATUS_OBJECT_NAME_INVALID;
}
- RtlMoveMemory(prev + parentFCB->LongNameU.Length / sizeof(WCHAR), curr,
+ RtlMoveMemory(prev + parentFCB->LongNameU.Length / sizeof(WCHAR), curr,
pFileNameU->Length - (curr - pFileNameU->Buffer) * sizeof(WCHAR));
pFileNameU->Length += (USHORT)(parentFCB->LongNameU.Length - Length);
curr = prev + parentFCB->LongNameU.Length / sizeof(WCHAR);
}
RtlCopyMemory(prev, parentFCB->LongNameU.Buffer, parentFCB->LongNameU.Length);
}
- curr++;
+ curr++;
prev = curr;
while (*curr != L'\\' && curr <= last)
{
/* GLOBALS ******************************************************************/
-const char* FileInformationClassNames[] =
+const char* FileInformationClassNames[] =
{
"??????",
"FileDirectoryInformation",
{
PDEVICE_EXTENSION DeviceExt;
DPRINT("VfatGetBasicInformation()\n");
-
+
DeviceExt = (PDEVICE_EXTENSION)DeviceObject->DeviceExtension;
if (*BufferLength < sizeof(FILE_BASIC_INFORMATION))
FileObject->DeletePending = FALSE;
return STATUS_SUCCESS;
}
-
+
if (FCB->Flags & FCB_DELETE_PENDING)
{
/* stream already marked for deletion. just update the file object */
FileObject->DeletePending = TRUE;
return STATUS_SUCCESS;
}
-
- if (*FCB->Attributes & FILE_ATTRIBUTE_READONLY)
+
+ if (*FCB->Attributes & FILE_ATTRIBUTE_READONLY)
{
return STATUS_CANNOT_DELETE;
}
- if (vfatFCBIsRoot(FCB) ||
+ if (vfatFCBIsRoot(FCB) ||
(FCB->LongNameU.Length == sizeof(WCHAR) && FCB->LongNameU.Buffer[0] == L'.') ||
(FCB->LongNameU.Length == 2 * sizeof(WCHAR) && FCB->LongNameU.Buffer[0] == L'.' && FCB->LongNameU.Buffer[1] == L'.'))
{
if (!MmFlushImageSection (FileObject->SectionObjectPointer, MmFlushForDelete))
{
/* can't delete a file if its mapped into a process */
-
+
DPRINT("MmFlushImageSection returned FALSE\n");
- return STATUS_CANNOT_DELETE;
+ return STATUS_CANNOT_DELETE;
}
if (vfatFCBIsDirectory(FCB) && !VfatIsDirectoryEmpty(FCB))
{
/* can't delete a non-empty directory */
-
+
return STATUS_DIRECTORY_NOT_EMPTY;
}
/* all good */
FCB->Flags |= FCB_DELETE_PENDING;
FileObject->DeletePending = TRUE;
-
+
return STATUS_SUCCESS;
}
{
NTSTATUS Status;
ULONG InitialBufferLength = *BufferLength;
-
+
ASSERT(Info);
ASSERT(Fcb);
/* Name Information */
Status = VfatGetNameInformation(FileObject, Fcb, DeviceObject, &Info->NameInformation, BufferLength);
if (!NT_SUCCESS(Status)) return Status;
-
+
*BufferLength = InitialBufferLength - (sizeof(FILE_ALL_INFORMATION) + Fcb->PathNameU.Length + sizeof(WCHAR));
-
+
return STATUS_SUCCESS;
}
if (!vfatFCBIsDirectory(Fcb))
{
if (Fcb->Flags & FCB_IS_FATX_ENTRY)
- Fcb->entry.FatX.FileSize = Size;
+ Fcb->entry.FatX.FileSize = Size;
else
- Fcb->entry.Fat.FileSize = Size;
+ Fcb->entry.Fat.FileSize = Size;
}
Fcb->RFCB.FileSize.QuadPart = Size;
Fcb->RFCB.ValidDataLength.QuadPart = Size;
}
NTSTATUS
-VfatSetAllocationSizeInformation(PFILE_OBJECT FileObject,
+VfatSetAllocationSizeInformation(PFILE_OBJECT FileObject,
PVFATFCB Fcb,
PDEVICE_EXTENSION DeviceExt,
PLARGE_INTEGER AllocationSize)
}
FirstCluster = vfatDirEntryGetFirstCluster (DeviceExt, &Fcb->entry);
-
+
if (NewSize > Fcb->RFCB.AllocationSize.u.LowPart)
{
AllocSizeChanged = TRUE;
{
return STATUS_DISK_FULL;
}
- Status = OffsetToCluster(DeviceExt, FirstCluster,
+ Status = OffsetToCluster(DeviceExt, FirstCluster,
ROUND_DOWN(NewSize - 1, ClusterSize),
&NCluster, TRUE);
if (NCluster == 0xffffffff || !NT_SUCCESS(Status))
if (Fcb->LastCluster > 0 &&
(Fcb->RFCB.AllocationSize.u.LowPart - ClusterSize) > Fcb->LastOffset)
{
- Status = OffsetToCluster(DeviceExt, Fcb->LastCluster,
+ Status = OffsetToCluster(DeviceExt, Fcb->LastCluster,
Fcb->RFCB.AllocationSize.u.LowPart -
ClusterSize - Fcb->LastOffset,
&Cluster, FALSE);
}
else
{
- Status = OffsetToCluster(DeviceExt, FirstCluster,
+ Status = OffsetToCluster(DeviceExt, FirstCluster,
Fcb->RFCB.AllocationSize.u.LowPart - ClusterSize,
&Cluster, FALSE);
}
/* FIXME: Check status */
/* Cluster points now to the last cluster within the chain */
- Status = OffsetToCluster(DeviceExt, FirstCluster,
+ Status = OffsetToCluster(DeviceExt, FirstCluster,
ROUND_DOWN(NewSize - 1, ClusterSize),
&NCluster, TRUE);
if (NCluster == 0xffffffff || !NT_SUCCESS(Status))
{
/* disk is full */
- NCluster = Cluster;
+ NCluster = Cluster;
Status = NextCluster (DeviceExt, FirstCluster, &NCluster, FALSE);
WriteCluster(DeviceExt, Cluster, 0xffffffff);
Cluster = NCluster;
UpdateFileSize(FileObject, Fcb, NewSize, ClusterSize);
if (NewSize > 0)
{
- Status = OffsetToCluster(DeviceExt, FirstCluster,
+ Status = OffsetToCluster(DeviceExt, FirstCluster,
ROUND_DOWN(NewSize - 1, ClusterSize),
&Cluster, FALSE);
FileInformationClass = IrpContext->Stack->Parameters.QueryFile.FileInformationClass;
FCB = (PVFATFCB) IrpContext->FileObject->FsContext;
- DPRINT("VfatQueryInformation is called for '%s'\n",
+ DPRINT("VfatQueryInformation is called for '%s'\n",
FileInformationClass >= FileMaximumInformation - 1 ? "????" : FileInformationClassNames[FileInformationClass]);
NTSTATUS RC = STATUS_SUCCESS;
PVOID SystemBuffer;
BOOLEAN CanWait = (IrpContext->Flags & IRPCONTEXT_CANWAIT) != 0;
-
+
/* PRECONDITION */
ASSERT(IrpContext);
-
+
DPRINT("VfatSetInformation(IrpContext %x)\n", IrpContext);
-
+
/* INITIALIZATION */
- FileInformationClass =
+ FileInformationClass =
IrpContext->Stack->Parameters.SetFile.FileInformationClass;
FCB = (PVFATFCB) IrpContext->FileObject->FsContext;
SystemBuffer = IrpContext->Irp->AssociatedIrp.SystemBuffer;
- DPRINT("VfatSetInformation is called for '%s'\n",
+ DPRINT("VfatSetInformation is called for '%s'\n",
FileInformationClass >= FileMaximumInformation - 1 ? "????" : FileInformationClassNames[ FileInformationClass]);
-
+
DPRINT("FileInformationClass %d\n", FileInformationClass);
DPRINT("SystemBuffer %x\n", SystemBuffer);
IrpContext->DeviceObject,
SystemBuffer);
break;
- case FileAllocationInformation:
+ case FileAllocationInformation:
case FileEndOfFileInformation:
RC = VfatSetAllocationSizeInformation(IrpContext->FileObject,
FCB,
IrpContext->DeviceExt,
(PLARGE_INTEGER)SystemBuffer);
- break;
+ break;
case FileBasicInformation:
RC = VfatSetBasicInformation(IrpContext->FileObject,
FCB,
}
/* FIXME: Stop flushing if this is a removable media and the media was removed */
}
-
+
Fcb = (PVFATFCB) DeviceExt->FATFileObject->FsContext;
-
+
ExAcquireResourceExclusiveLite(&DeviceExt->FatResource, TRUE);
Status = VfatFlushFile(DeviceExt, Fcb);
ExReleaseResourceLite(&DeviceExt->FatResource);
else
{
*RecognizedFS = TRUE;
- }
+ }
if (*RecognizedFS)
{
}
Offset.QuadPart = 0;
-
+
/* Try to recognize FAT12/FAT16/FAT32 partitions */
Status = VfatReadDisk(DeviceToMount, &Offset, DiskGeometry.BytesPerSector, (PUCHAR) Boot, FALSE);
if (NT_SUCCESS(Status))
if (*RecognizedFS &&
Boot->BytesPerSector != 512 &&
Boot->BytesPerSector != 1024 &&
- Boot->BytesPerSector != 2048 &&
+ Boot->BytesPerSector != 2048 &&
Boot->BytesPerSector != 4096)
{
DPRINT1("BytesPerSector %d\n", Boot->BytesPerSector);
}
if (*RecognizedFS &&
- Boot->FATCount != 1 &&
+ Boot->FATCount != 1 &&
Boot->FATCount != 2)
{
DPRINT1("FATCount %d\n", Boot->FATCount);
}
if (*RecognizedFS &&
- Boot->Media != 0xf0 &&
+ Boot->Media != 0xf0 &&
Boot->Media != 0xf8 &&
Boot->Media != 0xf9 &&
- Boot->Media != 0xfa &&
+ Boot->Media != 0xfa &&
Boot->Media != 0xfb &&
Boot->Media != 0xfc &&
Boot->Media != 0xfd &&
- Boot->Media != 0xfe &&
+ Boot->Media != 0xfe &&
Boot->Media != 0xff)
{
DPRINT1("Media %02x\n", Boot->Media);
if (*RecognizedFS &&
Boot->SectorsPerCluster != 1 &&
Boot->SectorsPerCluster != 2 &&
- Boot->SectorsPerCluster != 4 &&
+ Boot->SectorsPerCluster != 4 &&
Boot->SectorsPerCluster != 8 &&
Boot->SectorsPerCluster != 16 &&
- Boot->SectorsPerCluster != 32 &&
+ Boot->SectorsPerCluster != 32 &&
Boot->SectorsPerCluster != 64 &&
Boot->SectorsPerCluster != 128)
{
CHECKPOINT1;
*RecognizedFS = FALSE;
}
-
+
if (pFatInfo && *RecognizedFS)
{
*pFatInfo = FatInfo;
}
Offset.QuadPart = 0;
-
+
/* Try to recognize FATX16/FATX32 partitions (Xbox) */
Status = VfatReadDisk(DeviceToMount, &Offset, sizeof(struct _BootSectorFatX), (PUCHAR) BootFatX, FALSE);
if (NT_SUCCESS(Status))
DPRINT1("SysType %c%c%c%c\n", BootFatX->SysType[0], BootFatX->SysType[1], BootFatX->SysType[2], BootFatX->SysType[3]);
*RecognizedFS=FALSE;
}
-
+
if (*RecognizedFS &&
BootFatX->SectorsPerCluster != 1 &&
BootFatX->SectorsPerCluster != 2 &&
- BootFatX->SectorsPerCluster != 4 &&
+ BootFatX->SectorsPerCluster != 4 &&
BootFatX->SectorsPerCluster != 8 &&
BootFatX->SectorsPerCluster != 16 &&
- BootFatX->SectorsPerCluster != 32 &&
+ BootFatX->SectorsPerCluster != 32 &&
BootFatX->SectorsPerCluster != 64 &&
BootFatX->SectorsPerCluster != 128)
{
DPRINT1("SectorsPerCluster %lu\n", BootFatX->SectorsPerCluster);
*RecognizedFS=FALSE;
}
-
+
if (*RecognizedFS)
{
FatInfo.BytesPerSector = DiskGeometry.BytesPerSector;
FatInfo.VolumeID = BootFatX->VolumeID;
FatInfo.FATStart = sizeof(struct _BootSectorFatX) / DiskGeometry.BytesPerSector;
FatInfo.FATCount = BootFatX->FATCount;
- FatInfo.FATSectors =
+ FatInfo.FATSectors =
ROUND_UP(FatInfo.Sectors / FatInfo.SectorsPerCluster * (FatInfo.FatType == FATX16 ? 2 : 4), 4096) /
FatInfo.BytesPerSector;
FatInfo.rootStart = FatInfo.FATStart + FatInfo.FATCount * FatInfo.FATSectors;
FatInfo.dataStart = FatInfo.rootStart + FatInfo.rootDirectorySectors;
FatInfo.NumberOfClusters = (FatInfo.Sectors - FatInfo.dataStart) / FatInfo.SectorsPerCluster;
-
+
if (pFatInfo && *RecognizedFS)
{
*pFatInfo = FatInfo;
}
ExFreePool(BootFatX);
}
-
+
DPRINT("VfatHasFileSystem done\n");
return Status;
}
DeviceExt->CleanShutBitMask = 0x80000000;
break;
}
-
+
if (DeviceExt->FatInfo.FatType == FATX16
|| DeviceExt->FatInfo.FatType == FATX32)
{
/* read volume label */
ReadVolumeLabel(DeviceExt, DeviceObject->Vpb);
-
+
/* read clean shutdown bit status */
Status = GetNextCluster(DeviceExt, 1, &eocMark);
if (NT_SUCCESS(Status))
{
/*
* FIXME:
- * Preformated floppy disks have very often a serial number of 0000:0000.
- * We should calculate a crc sum over the sectors from the root directory as secondary volume number.
+ * Preformated floppy disks have very often a serial number of 0000:0000.
+ * We should calculate a crc sum over the sectors from the root directory as secondary volume number.
* Each write to the root directory must update this crc sum.
*/
-
+
}
else
{
Status = STATUS_WRONG_VOLUME;
}
}
-
+
return Status;
}
}
-static NTSTATUS
+static NTSTATUS
VfatGetRetrievalPointers(PVFAT_IRP_CONTEXT IrpContext)
{
PIO_STACK_LOCATION Stack;
Fcb = FileObject->FsContext;
ExAcquireResourceSharedLite(&Fcb->MainResource, TRUE);
-
+
Vcn = *(PLARGE_INTEGER)Stack->Parameters.DeviceIoControl.Type3InputBuffer;
RetrievalPointers = IrpContext->Irp->UserBuffer;
}
CurrentCluster = FirstCluster = vfatDirEntryGetFirstCluster(DeviceExt, &Fcb->entry);
- Status = OffsetToCluster(DeviceExt, FirstCluster,
- Vcn.u.LowPart * DeviceExt->FatInfo.BytesPerCluster,
+ Status = OffsetToCluster(DeviceExt, FirstCluster,
+ Vcn.u.LowPart * DeviceExt->FatInfo.BytesPerCluster,
&CurrentCluster, FALSE);
if (!NT_SUCCESS(Status))
{
{
goto ByeBye;
}
-
+
if (LastCluster + 1 != CurrentCluster)
{
RetrievalPointers->Extents[RetrievalPointers->ExtentCount].NextVcn = Vcn;
}
}
}
-
+
IrpContext->Irp->IoStatus.Information = sizeof(RETRIEVAL_POINTERS_BUFFER) + (sizeof(RetrievalPointers->Extents[0]) * (RetrievalPointers->ExtentCount - 1));
Status = STATUS_SUCCESS;
VfatIsVolumeDirty(PVFAT_IRP_CONTEXT IrpContext)
{
PULONG Flags;
-
+
DPRINT("VfatIsVolumeDirty(IrpContext %x)\n", IrpContext);
-
+
if (IrpContext->Stack->Parameters.FileSystemControl.OutputBufferLength != sizeof(ULONG))
return STATUS_INVALID_BUFFER_SIZE;
else if (!IrpContext->Irp->AssociatedIrp.SystemBuffer)
return STATUS_INVALID_USER_BUFFER;
-
+
Flags = (PULONG)IrpContext->Irp->AssociatedIrp.SystemBuffer;
*Flags = 0;
-
+
if (IrpContext->DeviceExt->VolumeFcb->Flags & VCB_IS_DIRTY
&& !(IrpContext->DeviceExt->VolumeFcb->Flags & VCB_CLEAR_DIRTY))
{
*Flags |= VOLUME_IS_DIRTY;
}
-
+
return STATUS_SUCCESS;
}
ULONG eocMark;
PDEVICE_EXTENSION DeviceExt;
NTSTATUS Status = STATUS_SUCCESS;
-
+
DPRINT("VfatMarkVolumeDirty(IrpContext %x)\n", IrpContext);
DeviceExt = IrpContext->DeviceExt;
-
+
if (!(DeviceExt->VolumeFcb->Flags & VCB_IS_DIRTY))
{
Status = GetNextCluster(DeviceExt, 1, &eocMark);
Status = WriteCluster(DeviceExt, 1, eocMark);
}
}
-
+
DeviceExt->VolumeFcb->Flags &= ~VCB_CLEAR_DIRTY;
-
+
return Status;
}
DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] = VfatBuildRequest;
DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION] = VfatBuildRequest;
DriverObject->MajorFunction[IRP_MJ_DIRECTORY_CONTROL] = VfatBuildRequest;
- DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] =
+ DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] =
VfatBuildRequest;
- DriverObject->MajorFunction[IRP_MJ_SET_VOLUME_INFORMATION] =
+ DriverObject->MajorFunction[IRP_MJ_SET_VOLUME_INFORMATION] =
VfatBuildRequest;
DriverObject->MajorFunction[IRP_MJ_SHUTDOWN] = VfatShutdown;
DriverObject->MajorFunction[IRP_MJ_LOCK_CONTROL] = VfatBuildRequest;
DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = VfatBuildRequest;
DriverObject->DriverUnload = NULL;
-
+
/* Cache manager */
VfatGlobalData->CacheMgrCallbacks.AcquireForLazyWrite = VfatAcquireForLazyWrite;
VfatGlobalData->CacheMgrCallbacks.ReleaseFromLazyWrite = VfatReleaseFromLazyWrite;
VfatGlobalData->CacheMgrCallbacks.AcquireForReadAhead = VfatAcquireForReadAhead;
VfatGlobalData->CacheMgrCallbacks.ReleaseFromReadAhead = VfatReleaseFromReadAhead;
-
+
/* Fast I/O */
VfatInitFastIoRoutines(&VfatGlobalData->FastIoDispatch);
DriverObject->FastIoDispatch = &VfatGlobalData->FastIoDispatch;
/* Private lists */
- ExInitializeNPagedLookasideList(&VfatGlobalData->FcbLookasideList,
+ ExInitializeNPagedLookasideList(&VfatGlobalData->FcbLookasideList,
NULL, NULL, 0, sizeof(VFATFCB), TAG_FCB, 0);
- ExInitializeNPagedLookasideList(&VfatGlobalData->CcbLookasideList,
+ ExInitializeNPagedLookasideList(&VfatGlobalData->CcbLookasideList,
NULL, NULL, 0, sizeof(VFATCCB), TAG_CCB, 0);
- ExInitializeNPagedLookasideList(&VfatGlobalData->IrpContextLookasideList,
+ ExInitializeNPagedLookasideList(&VfatGlobalData->IrpContextLookasideList,
NULL, NULL, 0, sizeof(VFAT_IRP_CONTEXT), TAG_IRP, 0);
ExInitializeResourceLite(&VfatGlobalData->VolumeListLock);
return Status;
}
-NTSTATUS
+NTSTATUS
VfatDispatchRequest (IN PVFAT_IRP_CONTEXT IrpContext)
{
- DPRINT ("VfatDispatchRequest (IrpContext %x), is called for %s\n", IrpContext,
+ DPRINT ("VfatDispatchRequest (IrpContext %x), is called for %s\n", IrpContext,
IrpContext->MajorFunction >= IRP_MJ_MAXIMUM_FUNCTION ? "????" : MajorFunctionNames[IrpContext->MajorFunction]);
ASSERT(IrpContext);
DPRINT1("Vfat is entered at irql = %d\n", KeGetCurrentIrql());
}
Status = VfatDispatchRequest (IrpContext);
-
+
if (KeGetCurrentIrql() <= PASSIVE_LEVEL)
{
FsRtlExitFileSystem();
}
-
+
}
return Status;
}
NTSTATUS Status;
/*
DPRINT("OffsetToCluster(DeviceExt %x, Fcb %x, FirstCluster %x,"
- " FileOffset %x, Cluster %x, Extend %d)\n", DeviceExt,
+ " FileOffset %x, Cluster %x, Extend %d)\n", DeviceExt,
Fcb, FirstCluster, FileOffset, Cluster, Extend);
*/
if (FirstCluster == 0)
*Cluster = CurrentCluster;
}
return(STATUS_SUCCESS);
- }
+ }
}
NTSTATUS
-VfatReadFileData (PVFAT_IRP_CONTEXT IrpContext,
- ULONG Length,
- LARGE_INTEGER ReadOffset,
+VfatReadFileData (PVFAT_IRP_CONTEXT IrpContext,
+ ULONG Length,
+ LARGE_INTEGER ReadOffset,
PULONG LengthRead)
/*
* FUNCTION: Reads data from a file
ReadOffset.u.LowPart += DeviceExt->FatInfo.rootStart * BytesPerSector;
// Fire up the read command
-
+
Status = VfatReadDiskPartial (IrpContext, &ReadOffset, Length, 0, TRUE);
if (NT_SUCCESS(Status))
{
LastCluster = Fcb->LastCluster;
LastOffset = Fcb->LastOffset;
ExReleaseFastMutex(&Fcb->LastMutex);
-
+
/*
* Find the cluster to start the read from
*/
return Status;
}
-NTSTATUS
+NTSTATUS
VfatWriteFileData(PVFAT_IRP_CONTEXT IrpContext,
ULONG Length,
LARGE_INTEGER WriteOffset)
Status = STATUS_SUCCESS;
goto ByeBye;
}
-
+
if (Fcb->Flags & FCB_IS_VOLUME)
{
Resource = &IrpContext->DeviceExt->DirResource;
if (!(IrpContext->Irp->Flags & IRP_PAGING_IO) &&
FsRtlAreThereCurrentFileLocks(&Fcb->FileLock))
{
- if (!FsRtlCheckLockForReadAccess(&Fcb->FileLock, IrpContext->Irp))
+ if (!FsRtlCheckLockForReadAccess(&Fcb->FileLock, IrpContext->Irp))
{
Status = STATUS_FILE_LOCK_CONFLICT;
goto ByeBye;
if (!(IrpContext->Irp->Flags & IRP_PAGING_IO) &&
FsRtlAreThereCurrentFileLocks(&Fcb->FileLock))
{
- if (!FsRtlCheckLockForWriteAccess(&Fcb->FileLock, IrpContext->Irp))
+ if (!FsRtlCheckLockForWriteAccess(&Fcb->FileLock, IrpContext->Irp))
{
Status = STATUS_FILE_LOCK_CONFLICT;
goto ByeBye;
}
- if (!(Fcb->Flags & (FCB_IS_FAT|FCB_IS_VOLUME)) &&
+ if (!(Fcb->Flags & (FCB_IS_FAT|FCB_IS_VOLUME)) &&
!(IrpContext->Irp->Flags & IRP_PAGING_IO) &&
ByteOffset.u.LowPart + Length > Fcb->RFCB.FileSize.u.LowPart)
{
Irp->IoStatus.Status = Status;
}
ExReleaseResourceLite(&VfatGlobalData->VolumeListLock);
-
+
/* FIXME: Free all global acquired resources */
Status = Irp->IoStatus.Status;
const WCHAR *long_illegals = L"\"*\\<>/?:|";
-BOOLEAN
+BOOLEAN
vfatIsLongIllegal(WCHAR c)
{
return wcschr(long_illegals, c) ? TRUE : FALSE;
ULONG LastAvailableCluster;
ULONG AvailableClusters;
BOOLEAN AvailableClustersValid;
- ULONG Flags;
+ ULONG Flags;
struct _VFATFCB * VolumeFcb;
/* Pointers to functions for manipulating FAT. */
PFIND_AND_MARK_AVAILABLE_CLUSTER FindAndMarkAvailableCluster;
PWRITE_CLUSTER WriteCluster;
ULONG CleanShutBitMask;
-
+
/* Pointers to functions for manipulating directory entries. */
PGET_NEXT_DIR_ENTRY GetNextDirEntry;
-
+
ULONG BaseDateYear;
LIST_ENTRY VolumeListEntry;
/* directory entry for this file or directory */
DIR_ENTRY entry;
-
+
/* Pointer to attributes in entry */
PUCHAR Attributes;
NTSTATUS VfatSetInformation (PVFAT_IRP_CONTEXT IrpContext);
NTSTATUS
-VfatSetAllocationSizeInformation(PFILE_OBJECT FileObject,
+VfatSetAllocationSizeInformation(PFILE_OBJECT FileObject,
PVFATFCB Fcb,
PDEVICE_EXTENSION DeviceExt,
PLARGE_INTEGER AllocationSize);
/* -------------------------------------------------------- string.c */
VOID
-vfatSplitPathName(PUNICODE_STRING PathNameU,
- PUNICODE_STRING DirNameU,
+vfatSplitPathName(PUNICODE_STRING PathNameU,
+ PUNICODE_STRING DirNameU,
PUNICODE_STRING FileNameU);
BOOLEAN vfatIsLongIllegal(WCHAR c);
NTSTATUS VfatLockUserBuffer(IN PIRP, IN ULONG,
IN LOCK_OPERATION);
-NTSTATUS
-VfatSetExtendedAttributes(PFILE_OBJECT FileObject,
+NTSTATUS
+VfatSetExtendedAttributes(PFILE_OBJECT FileObject,
PVOID Ea,
ULONG EaLength);
/* ------------------------------------------------------------- flush.c */
CHAR cString[43];
ULONG SizeDirEntry;
ULONG EntriesPerPage;
-
+
DPRINT("FsdSetFsLabelInformation()\n");
-
+
DeviceExt = (PDEVICE_EXTENSION)DeviceObject->DeviceExtension;
-
+
if (sizeof(DeviceObject->Vpb->VolumeLabel) < FsLabelInfo->VolumeLabelLength)
{
CHECKPOINT;
return STATUS_NAME_TOO_LONG;
}
-
+
if (DeviceExt->Flags & VCB_IS_FATX)
{
if (FsLabelInfo->VolumeLabelLength / sizeof(WCHAR) > 42)
SizeDirEntry = sizeof(FAT_DIR_ENTRY);
EntriesPerPage = FAT_ENTRIES_PER_PAGE;
}
-
+
/* Create Volume label dir entry */
LabelLen = FsLabelInfo->VolumeLabelLength / sizeof(WCHAR);
RtlZeroMemory(&VolumeLabelDirEntry, SizeDirEntry);
memset(&VolumeLabelDirEntry.Fat.Filename[LabelLen], ' ', 11 - LabelLen);
VolumeLabelDirEntry.Fat.Attrib = 0x08;
}
-
+
pRootFcb = vfatOpenRootFCB(DeviceExt);
-
+
/* Search existing volume entry on disk */
FileOffset.QuadPart = 0;
if (CcPinRead(pRootFcb->FileObject, &FileOffset, PAGE_SIZE, TRUE, &Context, (PVOID*)&Entry))
Status = STATUS_SUCCESS;
}
}
-
+
vfatReleaseFCB(DeviceExt, pRootFcb);
if (!NT_SUCCESS(Status))
{
return Status;
}
-
+
/* Update volume label in memory */
DeviceObject->Vpb->VolumeLabelLength = (USHORT)FsLabelInfo->VolumeLabelLength;
RtlCopyMemory(DeviceObject->Vpb->VolumeLabel, FsLabelInfo->VolumeLabel, DeviceObject->Vpb->VolumeLabelLength);
-
+
return Status;
}
UCHAR Value,
UCHAR SelectCmd)
{
- if (SelectCmd)
+ if (SelectCmd)
if (!I8042Write(DevExt, I8042_CTRL_PORT, SelectCmd))
return;
UINT ResendIterations = DevExt->Settings.ResendIterations + 1;
do {
- if (Port)
+ if (Port)
if (!I8042Write(DevExt, I8042_DATA_PORT, Port))
return STATUS_TIMEOUT;
BOOLEAN IsKbd;
DPRINT("HookWorkItem\n");
-
+
FdoDevExt = (PFDO_DEVICE_EXTENSION)
DeviceObject->DeviceExtension;
TRUE,
&Event,
&IoStatus);
-
+
if (!NewIrp) {
DPRINT("IOCTL_INTERNAL_(device)_CONNECT: "
"Can't allocate IRP\n");
- WorkItemData->Irp->IoStatus.Status =
+ WorkItemData->Irp->IoStatus.Status =
STATUS_INSUFFICIENT_RESOURCES;
goto hookworkitemdone;
}
DevExt->HighestDIRQLInterrupt);
I8042Write(DevExt, I8042_CTRL_PORT, 0xD4);
- I8042Write(DevExt, I8042_DATA_PORT, 0xFF);
+ I8042Write(DevExt, I8042_DATA_PORT, 0xFF);
KeReleaseInterruptSpinLock(DevExt->HighestDIRQLInterrupt, Irql);
}
do {
Status = I8042ReadDataWait(DevExt, &Value);
} while ((Counter--) && (STATUS_TIMEOUT == Status));
-
+
if (Status != STATUS_SUCCESS)
return Status;
if (Value != 0x55) {
DPRINT1("Got %x instead of 55\n", Value);
return STATUS_IO_DEVICE_ERROR;
- }
+ }
if (!I8042Write(DevExt, I8042_CTRL_PORT, KBD_LINE_TEST))
return STATUS_TIMEOUT;
} else {
DevExt->KeyboardExists = FALSE;
}
-
+
if (!I8042Write(DevExt, I8042_CTRL_PORT, MOUSE_LINE_TEST))
return STATUS_TIMEOUT;
} else {
DevExt->MouseExists = FALSE;
}
-
+
return STATUS_SUCCESS;
}
Fdo->Flags |= DO_BUFFERED_IO;
DevExt->MouseObject = Fdo;
-
+
DevExt->MouseBuffer = ExAllocatePoolWithTag(
NonPagedPool,
DevExt->MouseAttributes.InputDataQueueLength *
LevelSensitive,
FALSE,
Affinity,
- FALSE);
+ FALSE);
DPRINT("Mouse Irq Status: %x\n", Status);
}
return(STATUS_SUCCESS);
}
-NTSTATUS STDCALL DriverEntry(PDRIVER_OBJECT DriverObject,
+NTSTATUS STDCALL DriverEntry(PDRIVER_OBJECT DriverObject,
PUNICODE_STRING RegistryPath)
/*
* FUNCTION: Module entry point
DPRINT("I8042 Driver 0.0.1\n");
DriverObject->MajorFunction[IRP_MJ_CREATE] = I8042CreateDispatch;
- DriverObject->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] =
- I8042InternalDeviceControl;
+ DriverObject->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] =
+ I8042InternalDeviceControl;
DriverObject->DriverStartIo = I8042StartIo;
DriverObject->DriverExtension->AddDevice = I8042AddDevice;
BOOLEAN KeyboardExists;
BOOLEAN KeyboardIsAT;
BOOLEAN MouseExists;
-
+
BOOLEAN KeyboardClaimed;
BOOLEAN MouseClaimed;
{
return I8042SynchWritePort((PDEVICE_EXTENSION)Context,
0,
- Value,
+ Value,
WaitForAck);
}
InputData->Flags |= KEY_BREAK;
else
InputData->Flags |= KEY_MAKE;
-
+
InputData->MakeCode = Output & 0x7f;
I8042QueueKeyboardPacket(DevExt->KeyboardObject);
return TRUE;
}
-
+
VOID STDCALL I8042DpcRoutineKbd(PKDPC Dpc,
PVOID DeferredContext,
PVOID SystemArgument1,
/* Test for TAB (debugging) */
if (DevExt->Settings.CrashSysRq) {
- PKEYBOARD_INPUT_DATA InputData = DevExt->KeyboardBuffer +
+ PKEYBOARD_INPUT_DATA InputData = DevExt->KeyboardBuffer +
KeysInBufferCopy - 1;
if (InputData->MakeCode == 0x0F) {
DPRINT("Tab!\n");
static USHORT I8042GetTypematicByte(USHORT Rate, USHORT Delay)
{
USHORT ret;
-
+
if (Rate < 3) {
ret = 0x0;
} else if (Rate > 26) {
PDEVICE_EXTENSION DevExt = FdoDevExt->PortDevExt;
Stk = IoGetCurrentIrpStackLocation(Irp);
-
+
switch (Stk->Parameters.DeviceIoControl.IoControlCode) {
case IOCTL_INTERNAL_I8042_KEYBOARD_WRITE_BUFFER:
I8042StartPacket(
Irp->IoStatus.Information = 0;
Stk = IoGetCurrentIrpStackLocation(Irp);
-
+
switch (Stk->Parameters.DeviceIoControl.IoControlCode) {
case IOCTL_INTERNAL_KEYBOARD_CONNECT:
DPRINT("IOCTL_INTERNAL_KEYBOARD_CONNECT\n");
- if (Stk->Parameters.DeviceIoControl.InputBufferLength <
+ if (Stk->Parameters.DeviceIoControl.InputBufferLength <
sizeof(CONNECT_DATA)) {
DPRINT1("Keyboard IOCTL_INTERNAL_KEYBOARD_CONNECT "
"invalid buffer size\n");
Stk->Parameters.DeviceIoControl.Type3InputBuffer,
sizeof(CONNECT_DATA));
DevExt->KeyboardHook.IsrWritePort = I8042IsrWritePortKbd;
- DevExt->KeyboardHook.QueueKeyboardPacket =
+ DevExt->KeyboardHook.QueueKeyboardPacket =
I8042QueueKeyboardPacket;
DevExt->KeyboardHook.CallContext = DevExt;
if (!WorkItem) {
DPRINT ("IOCTL_INTERNAL_KEYBOARD_CONNECT: "
"Can't allocate work item\n");
- Irp->IoStatus.Status =
+ Irp->IoStatus.Status =
STATUS_INSUFFICIENT_RESOURCES;
goto intcontfailure;
}
if (!WorkItemData) {
DPRINT ("IOCTL_INTERNAL_KEYBOARD_CONNECT: "
"Can't allocate work item data\n");
- Irp->IoStatus.Status =
+ Irp->IoStatus.Status =
STATUS_INSUFFICIENT_RESOURCES;
IoFreeWorkItem(WorkItem);
goto intcontfailure;
}
WorkItemData->WorkItem = WorkItem;
- WorkItemData->Target =
+ WorkItemData->Target =
DevExt->KeyboardData.ClassDeviceObject;
WorkItemData->Irp = Irp;
break;
case IOCTL_KEYBOARD_QUERY_ATTRIBUTES:
DPRINT("IOCTL_KEYBOARD_QUERY_ATTRIBUTES\n");
- if (Stk->Parameters.DeviceIoControl.OutputBufferLength <
+ if (Stk->Parameters.DeviceIoControl.OutputBufferLength <
sizeof(KEYBOARD_ATTRIBUTES)) {
DPRINT("Keyboard IOCTL_KEYBOARD_QUERY_ATTRIBUTES "
"invalid buffer size\n");
break;
case IOCTL_KEYBOARD_QUERY_INDICATORS:
DPRINT("IOCTL_KEYBOARD_QUERY_INDICATORS\n");
- if (Stk->Parameters.DeviceIoControl.OutputBufferLength <
+ if (Stk->Parameters.DeviceIoControl.OutputBufferLength <
sizeof(KEYBOARD_INDICATOR_PARAMETERS)) {
DPRINT("Keyboard IOCTL_KEYBOARD_QUERY_INDICATORS "
"invalid buffer size\n");
break;
case IOCTL_KEYBOARD_QUERY_TYPEMATIC:
DPRINT("IOCTL_KEYBOARD_QUERY_TYPEMATIC\n");
- if (Stk->Parameters.DeviceIoControl.OutputBufferLength <
+ if (Stk->Parameters.DeviceIoControl.OutputBufferLength <
sizeof(KEYBOARD_TYPEMATIC_PARAMETERS)) {
DPRINT("Keyboard IOCTL_KEYBOARD_QUERY_TYPEMATIC "
"invalid buffer size\n");
break;
case IOCTL_KEYBOARD_SET_INDICATORS:
DPRINT("IOCTL_KEYBOARD_SET_INDICATORS\n");
- if (Stk->Parameters.DeviceIoControl.InputBufferLength <
+ if (Stk->Parameters.DeviceIoControl.InputBufferLength <
sizeof(KEYBOARD_INDICATOR_PARAMETERS)) {
DPRINT("Keyboard IOCTL_KEYBOARD_SET_INDICTATORS "
"invalid buffer size\n");
break;
case IOCTL_KEYBOARD_SET_TYPEMATIC:
DPRINT("IOCTL_KEYBOARD_SET_TYPEMATIC\n");
- if (Stk->Parameters.DeviceIoControl.InputBufferLength <
+ if (Stk->Parameters.DeviceIoControl.InputBufferLength <
sizeof(KEYBOARD_TYPEMATIC_PARAMETERS)) {
DPRINT("Keyboard IOCTL_KEYBOARD_SET_TYPEMATIC "
"invalid buffer size\n");
/* We should check the UnitID, but it's kind of pointless as
* all keyboards are supposed to have the same one
*/
- if (Stk->Parameters.DeviceIoControl.OutputBufferLength <
+ if (Stk->Parameters.DeviceIoControl.OutputBufferLength <
sizeof(LOCAL_KEYBOARD_INDICATOR_TRANSLATION)) {
DPRINT("IOCTL_KEYBOARD_QUERY_INDICATOR_TRANSLATION: "
"invalid buffer size (expected)\n");
/* debug stuff */
VOID STDCALL
-KdpServiceDispatcher(ULONG Code, PVOID Context1, PVOID Context2);
+KdpServiceDispatcher(ULONG Code, PVOID Context1, PVOID Context2);
static VOID STDCALL I8042DebugWorkItem(PDEVICE_OBJECT DeviceObject,
PVOID Context)
DevExt->MouseLogiBuffer[2] = *Value;
/* Now MouseLogiBuffer is a set of info. If the second
* byte is 0, the mouse didn't understand the magic
- * code. Otherwise, it it a Logitech and the second byte
- * is the number of buttons, bit 7 of the first byte tells
+ * code. Otherwise, it it a Logitech and the second byte
+ * is the number of buttons, bit 7 of the first byte tells
* if it understands special E7 commands, the rest is an ID.
*/
if (DevExt->MouseLogiBuffer[1]) {
DevExt->MouseAttributes.NumberOfButtons =
DevExt->MouseLogiBuffer[1];
/* For some reason the ID is the wrong way around */
- DevExt->MouseLogitechID =
+ DevExt->MouseLogitechID =
((DevExt->MouseLogiBuffer[0] >> 4) & 0x07) |
((DevExt->MouseLogiBuffer[0] << 3) & 0x78);
DevExt->MouseType = Ps2pp;
/*
* Prepare for reading the next packet and queue the dpc for handling
* this one.
- *
+ *
* Context is the device object.
*/
VOID STDCALL I8042QueueMousePacket(PVOID Context)
PDEVICE_EXTENSION DevExt = FdoDevExt->PortDevExt;
Stk = IoGetCurrentIrpStackLocation(Irp);
-
+
switch (Stk->Parameters.DeviceIoControl.IoControlCode) {
case IOCTL_INTERNAL_I8042_MOUSE_WRITE_BUFFER:
I8042StartPacket(
Irp->IoStatus.Information = 0;
Stk = IoGetCurrentIrpStackLocation(Irp);
-
+
switch (Stk->Parameters.DeviceIoControl.IoControlCode) {
case IOCTL_INTERNAL_MOUSE_CONNECT:
DPRINT("IOCTL_INTERNAL_MOUSE_CONNECT\n");
- if (Stk->Parameters.DeviceIoControl.InputBufferLength <
+ if (Stk->Parameters.DeviceIoControl.InputBufferLength <
sizeof(CONNECT_DATA)) {
DPRINT1("Mouse IOCTL_INTERNAL_MOUSE_CONNECT "
"invalid buffer size\n");
Stk->Parameters.DeviceIoControl.Type3InputBuffer,
sizeof(CONNECT_DATA));
DevExt->MouseHook.IsrWritePort = I8042IsrWritePortMouse;
- DevExt->MouseHook.QueueMousePacket =
+ DevExt->MouseHook.QueueMousePacket =
I8042QueueMousePacket;
DevExt->MouseHook.CallContext = DevExt;
if (!WorkItem) {
DPRINT ("IOCTL_INTERNAL_MOUSE_CONNECT: "
"Can't allocate work item\n");
- Irp->IoStatus.Status =
+ Irp->IoStatus.Status =
STATUS_INSUFFICIENT_RESOURCES;
goto intcontfailure;
}
if (!WorkItemData) {
DPRINT ("IOCTL_INTERNAL_MOUSE_CONNECT: "
"Can't allocate work item data\n");
- Irp->IoStatus.Status =
+ Irp->IoStatus.Status =
STATUS_INSUFFICIENT_RESOURCES;
IoFreeWorkItem(WorkItem);
goto intcontfailure;
}
WorkItemData->WorkItem = WorkItem;
- WorkItemData->Target =
+ WorkItemData->Target =
DevExt->MouseData.ClassDeviceObject;
WorkItemData->Irp = Irp;
break;
case IOCTL_MOUSE_QUERY_ATTRIBUTES:
DPRINT("IOCTL_MOUSE_QUERY_ATTRIBUTES\n");
- if (Stk->Parameters.DeviceIoControl.InputBufferLength <
+ if (Stk->Parameters.DeviceIoControl.InputBufferLength <
sizeof(MOUSE_ATTRIBUTES)) {
DPRINT("Mouse IOCTL_MOUSE_QUERY_ATTRIBUTES "
"invalid buffer size\n");
return FALSE;
}
- I8042Flush();
+ I8042Flush();
/* Just to be (kind of) sure; if the mouse would
* say something while we are disabling it, these bytes would
* block the keyboard.
/* INCLUDES ****************************************************************/
#include <ddk/ntddk.h>
-
+
#include <ddk/ntddkbd.h>
#include <ddk/ntdd8042.h>
*
* Otherwise, the packet is different, like this:
* 1: E 1 b3 b2 x x x x
- * 2: x x b1 b0 x1 x0 1 0
+ * 2: x x b1 b0 x1 x0 1 0
* 3: x x x x x x x1 x0
*
* b3-0 form a code that specifies the packet type:
- *
+ *
* 0 Device Type
* 1 Rollers and buttons
* 2 Reserved
* 3 Reserved
- * 4 Device ID
+ * 4 Device ID
* 5 Channel & Battery
* 6 Wireless notifications
* 7 Reserved
DevExt->MouseLogiBuffer[DevExt->MouseState] = Input;
DevExt->MouseState++;
break;
-
+
case YMovement:
DevExt->MouseLogiBuffer[2] = Input;
DevExt->MouseState = MouseIdle;
I8042MouseHandle(DevExt, DevExt->MouseLogiBuffer[2]);
/* We could care about wether MouseState really
* advances, but we don't need to because we're
- * only doing three bytes anyway, so the packet
+ * only doing three bytes anyway, so the packet
* will never complete if it's broken.
*/
return;
* already read that in the initialization
* sequence. Ignore it.
*/
- return;
+ return;
case 1:
RtlZeroMemory(MouseInput, sizeof(MOUSE_INPUT_DATA));
if (DevExt->MouseLogiBuffer[2] & 0x10)
if (DevExt->MouseLogiBuffer[2] & 0x0F) {
MouseInput->ButtonFlags |= MOUSE_WHEEL;
if (DevExt->MouseLogiBuffer[2] & 0x08)
- MouseInput->ButtonData =
+ MouseInput->ButtonData =
(DevExt->MouseLogiBuffer[2] & 0x07) -
8;
else
- MouseInput->ButtonData =
+ MouseInput->ButtonData =
DevExt->MouseLogiBuffer[2] & 0x07;
}
I8042MouseHandleButtons(DevExt, MOUSE_BUTTON_4_DOWN |
* Jason Filby (jasonfilby@yahoo.com)
* Tinus
*/
-
+
/* INCLUDES ****************************************************************/
-
+
#include <ddk/ntddk.h>
#include <string.h>
#include <ntos/keyboard.h>
#include <ntos/minmax.h>
#include <rosrtl/string.h>
-
+
#include <ddk/ntddkbd.h>
#include <ddk/ntdd8042.h>
-
+
#define NDEBUG
#include <debug.h>
-
+
#include "i8042prt.h"
-
+
/* FUNCTIONS *****************************************************************/
-
+
/*
* Read the registry keys associated with this device. The RegistryPath
* var is a hack. This should be more like what microsoft does, but I
*/
VOID STDCALL I8042ReadRegistry(PDRIVER_OBJECT DriverObject,
PDEVICE_EXTENSION DevExt)
-
+
{
RTL_QUERY_REGISTRY_TABLE Parameters[19];
UNICODE_STRING ParametersPath;
-
+
PWSTR RegistryPath = L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\i8042Prt\\Parameters";
-
+
NTSTATUS Status;
-
+
DWORD DefaultHeadless = 0;
DWORD DefaultCrashScroll = 0;
DWORD DefaultCrashSysRq = 0;
DWORD DefaultSampleRate = 60;
DWORD DefaultNumberOfButtons = 2;
DWORD DefaultEnableWheelDetection = 1;
-
+
RtlInitUnicodeString(&ParametersPath, NULL);
ParametersPath.MaximumLength = (wcslen(RegistryPath) *
sizeof(WCHAR)) +
sizeof(UNICODE_NULL);
-
+
ParametersPath.Buffer = ExAllocatePoolWithTag(PagedPool,
ParametersPath.MaximumLength,
TAG_I8042);
-
+
if (!ParametersPath.Buffer) {
DPRINT1("No buffer space for reading registry\n");
return;
}
-
+
RtlZeroMemory(ParametersPath.Buffer, ParametersPath.MaximumLength);
RtlAppendUnicodeToString(&ParametersPath, RegistryPath);
-
+
RtlZeroMemory(Parameters, sizeof(Parameters));
-
+
Parameters[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[0].Name = L"Headless";
Parameters[0].EntryContext = &DevExt->Settings.Headless;
Parameters[0].DefaultType = REG_DWORD;
Parameters[0].DefaultData = &DefaultHeadless;
Parameters[0].DefaultLength = sizeof(ULONG);
-
+
Parameters[1].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[1].Name = L"CrashOnCtrlScroll";
Parameters[1].EntryContext = &DevExt->Settings.CrashScroll;
Parameters[1].DefaultType = REG_DWORD;
Parameters[1].DefaultData = &DefaultCrashScroll;
Parameters[1].DefaultLength = sizeof(ULONG);
-
+
Parameters[2].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[2].Name = L"BreakOnSysRq";
Parameters[2].EntryContext = &DevExt->Settings.CrashSysRq;
Parameters[2].DefaultType = REG_DWORD;
Parameters[2].DefaultData = &DefaultCrashSysRq;
Parameters[2].DefaultLength = sizeof(ULONG);
-
+
Parameters[3].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[3].Name = L"ReportResetErrors";
Parameters[3].EntryContext = &DevExt->Settings.ReportResetErrors;
Parameters[3].DefaultType = REG_DWORD;
Parameters[3].DefaultData = &DefaultReportResetErrors;
Parameters[3].DefaultLength = sizeof(ULONG);
-
+
Parameters[4].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[4].Name = L"PollStatusIterations";
Parameters[4].EntryContext = &DevExt->Settings.PollStatusIterations;
Parameters[4].DefaultType = REG_DWORD;
Parameters[4].DefaultData = &DefaultPollStatusIterations;
Parameters[4].DefaultLength = sizeof(ULONG);
-
+
Parameters[5].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[5].Name = L"ResendIterations";
Parameters[5].EntryContext = &DevExt->Settings.ResendIterations;
Parameters[5].DefaultType = REG_DWORD;
Parameters[5].DefaultData = &DefaultResendIterations;
Parameters[5].DefaultLength = sizeof(ULONG);
-
+
Parameters[6].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[6].Name = L"PollingIterations";
Parameters[6].EntryContext = &DevExt->Settings.PollingIterations;
Parameters[6].DefaultType = REG_DWORD;
Parameters[6].DefaultData = &DefaultPollingIterations;
Parameters[6].DefaultLength = sizeof(ULONG);
-
+
Parameters[7].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[7].Name = L"PollingIterationsMaximum";
Parameters[7].EntryContext = &DevExt->Settings.PollingIterationsMaximum;
Parameters[7].DefaultType = REG_DWORD;
Parameters[7].DefaultData = &DefaultPollingIterationsMaximum;
Parameters[7].DefaultLength = sizeof(ULONG);
-
+
Parameters[8].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[8].Name = L"KeyboardDataQueueSize";
Parameters[8].EntryContext =
Parameters[8].DefaultType = REG_DWORD;
Parameters[8].DefaultData = &DefaultKeyboardDataQueueSize;
Parameters[8].DefaultLength = sizeof(ULONG);
-
+
Parameters[9].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[9].Name = L"OverrideKeyboardType";
Parameters[9].EntryContext = &DevExt->Settings.OverrideKeyboardType;
Parameters[9].DefaultType = REG_DWORD;
Parameters[9].DefaultData = &DefaultOverrideKeyboardType;
Parameters[9].DefaultLength = sizeof(ULONG);
-
+
Parameters[10].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[10].Name = L"OverrideKeyboardSubtype";
Parameters[10].EntryContext = &DevExt->Settings.OverrideKeyboardSubtype;
Parameters[10].DefaultType = REG_DWORD;
Parameters[10].DefaultData = &DefaultOverrideKeyboardSubtype;
Parameters[10].DefaultLength = sizeof(ULONG);
-
+
Parameters[11].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[11].Name = L"MouseDataQueueSize";
Parameters[11].EntryContext =
Parameters[11].DefaultType = REG_DWORD;
Parameters[11].DefaultData = &DefaultMouseDataQueueSize;
Parameters[11].DefaultLength = sizeof(ULONG);
-
+
Parameters[12].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[12].Name = L"MouseResendStallTime";
Parameters[12].EntryContext = &DevExt->Settings.MouseResendStallTime;
Parameters[12].DefaultType = REG_DWORD;
Parameters[12].DefaultData = &DefaultMouseResendStallTime;
Parameters[12].DefaultLength = sizeof(ULONG);
-
+
Parameters[13].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[13].Name = L"MouseSynchIn100ns";
Parameters[13].EntryContext = &DevExt->Settings.MouseSynchIn100ns;
Parameters[13].DefaultType = REG_DWORD;
Parameters[13].DefaultData = &DefaultMouseSynchIn100ns;
Parameters[13].DefaultLength = sizeof(ULONG);
-
+
Parameters[14].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[14].Name = L"MouseResolution";
Parameters[14].EntryContext = &DevExt->Settings.MouseResolution;
Parameters[14].DefaultType = REG_DWORD;
Parameters[14].DefaultData = &DefaultMouseResolution;
Parameters[14].DefaultLength = sizeof(ULONG);
-
+
Parameters[15].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[15].Name = L"SampleRate";
Parameters[15].EntryContext = &DevExt->MouseAttributes.SampleRate;
Parameters[15].DefaultType = REG_DWORD;
Parameters[15].DefaultData = &DefaultSampleRate;
Parameters[15].DefaultLength = sizeof(ULONG);
-
+
Parameters[16].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[16].Name = L"NumberOfButtons";
Parameters[16].EntryContext = &DevExt->Settings.NumberOfButtons;
Parameters[16].DefaultType = REG_DWORD;
Parameters[16].DefaultData = &DefaultNumberOfButtons;
Parameters[16].DefaultLength = sizeof(ULONG);
-
+
Parameters[17].Flags = RTL_QUERY_REGISTRY_DIRECT;
Parameters[17].Name = L"EnableWheelDetection";
Parameters[17].EntryContext = &DevExt->Settings.EnableWheelDetection;
Parameters[17].DefaultType = REG_DWORD;
Parameters[17].DefaultData = &DefaultEnableWheelDetection;
Parameters[17].DefaultLength = sizeof(ULONG);
-
+
Status = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE |
RTL_REGISTRY_OPTIONAL,
ParametersPath.Buffer,
Parameters,
NULL,
NULL);
-
+
if (Status != STATUS_SUCCESS) {
DPRINT1 ("Can't read registry: %x\n", Status);
/* Actually, the defaults are not set when the function
Current++;
}
DPRINT1 ("Manually set defaults\n");
-
+
}
ExFreePoolWithTag(ParametersPath.Buffer, TAG_I8042);
-
+
if (DevExt->Settings.MouseResolution > 3)
DevExt->Settings.MouseResolution = 3;
-
+
DPRINT("Done reading registry\n");
}
DPRINT("DeviceObject %x\n",DeviceObject);
DPRINT("Irp %x\n",Irp);
-
+
DPRINT("Dispatch: stk->MajorFunction %d\n", stk->MajorFunction);
DPRINT("AlreadyOpened %d\n",AlreadyOpened);
-
+
switch (stk->MajorFunction) {
case IRP_MJ_CREATE:
if (AlreadyOpened == TRUE) {
DPRINT("SendConnect done\n");
}
-NTSTATUS STDCALL DriverEntry(PDRIVER_OBJECT DriverObject,
+NTSTATUS STDCALL DriverEntry(PDRIVER_OBJECT DriverObject,
PUNICODE_STRING RegistryPath)
/*
* FUNCTION: Module entry point
UNICODE_STRING DeviceName = ROS_STRING_INITIALIZER(L"\\Device\\Keyboard");
UNICODE_STRING SymlinkName = ROS_STRING_INITIALIZER(L"\\??\\Keyboard");
UNICODE_STRING I8042Name = ROS_STRING_INITIALIZER(L"\\Device\\KeyboardClass0");
-
+
DPRINT("Keyboard Class Driver 0.0.1\n");
DriverObject->MajorFunction[IRP_MJ_CREATE] = KbdDispatch;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = KbdDispatch;
DriverObject->MajorFunction[IRP_MJ_READ] = KbdDispatch;
- DriverObject->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] =
+ DriverObject->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] =
KbdInternalDeviceControl;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = KbdDeviceControl;
0,
TRUE,
&DeviceObject);
-
+
RtlZeroMemory(DeviceObject->DeviceExtension, sizeof(DEVICE_EXTENSION));
DevExt = DeviceObject->DeviceExtension;
DevExt->DeviceObject = DeviceObject;
DeviceObject->Flags = DeviceObject->Flags | DO_BUFFERED_IO;
DeviceObject->StackSize = 1 + DevExt->I8042Device->StackSize;
-
+
IoCreateSymbolicLink(&SymlinkName, &DeviceName);
KbdClassSendConnect(DevExt);
-
+
return(STATUS_SUCCESS);
}
/* A filter driver might have consumed all the data already; I'm
* not sure if they are supposed to move the packets when they
* consume them though.
- */
+ */
if (ClassDeviceExtension->ReadIsPending == TRUE &&
InputCount)
{
Stack->Parameters.Read.Length = sizeof(MOUSE_INPUT_DATA);
IoStartNextPacket(ClassDeviceObject, FALSE);
- IoCompleteRequest(Irp, IO_MOUSE_INCREMENT);
+ IoCompleteRequest(Irp, IO_MOUSE_INCREMENT);
ClassDeviceExtension->ReadIsPending = FALSE;
/* Skip the packet we just sent away */
case IRP_MJ_CREATE:
Status = STATUS_SUCCESS;
break;
-
+
case IRP_MJ_CLOSE:
Status = STATUS_SUCCESS;
break;
if (DeviceExtension->PacketBufferPosition >= 3)
{
Queue = DeviceExtension->ActiveQueue % 2;
-
+
/* Prevent buffer overflow */
if (DeviceExtension->InputDataCount[Queue] == MOUSE_BUFFER_SIZE)
continue;
/* Retrieve change in x and y from packet */
Input->LastX = (signed char)(PacketBuffer[1] | ((PacketBuffer[0] & 0x03) << 6));
Input->LastY = (signed char)(PacketBuffer[2] | ((PacketBuffer[0] & 0x0c) << 4));
-
+
/* Determine the current state of the buttons */
Input->RawButtons = (DeviceExtension->PreviousButtons & MOUSE_BUTTON_MIDDLE) |
((UCHAR)(PacketBuffer[0] & LEFT_BUTTON_MASK) >> LEFT_BUTTON_SHIFT) |
*(PMOUSE_ATTRIBUTES)Irp->AssociatedIrp.SystemBuffer =
DeviceExtension->AttributesInformation;
Irp->IoStatus.Information = sizeof(MOUSE_ATTRIBUTES);
- Status = STATUS_SUCCESS;
+ Status = STATUS_SUCCESS;
} else {
Status = STATUS_BUFFER_TOO_SMALL;
}
/* Enable interrupts */
WRITE_PORT_UCHAR((PUCHAR)(Port) + 1, 1);
-
+
ClearMouse(Port);
/* Enable RTS, DTR and OUT2 */
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
For more information on these sources, see the manual.
- To get some idea how the block sorting algorithms in this file
- work, read my paper
+ To get some idea how the block sorting algorithms in this file
+ work, read my paper
On the Performance of BWT Sorting Algorithms
in Proceedings of the IEEE Data Compression Conference 2000,
Snowbird, Utah, USA, 27-30 March 2000. The main sort in this
/*---------------------------------------------*/
/*---------------------------------------------*/
-static
+static
__inline__
-void fallbackSimpleSort ( UInt32* fmap,
- UInt32* eclass,
- Int32 lo,
+void fallbackSimpleSort ( UInt32* fmap,
+ UInt32* eclass,
+ Int32 lo,
Int32 hi )
{
Int32 i, j, tmp;
static
-void fallbackQSort3 ( UInt32* fmap,
+void fallbackQSort3 ( UInt32* fmap,
UInt32* eclass,
- Int32 loSt,
+ Int32 loSt,
Int32 hiSt )
{
Int32 unLo, unHi, ltLo, gtHi, n, m;
}
/* Random partitioning. Median of 3 sometimes fails to
- avoid bad cases. Median of 9 seems to help but
+ avoid bad cases. Median of 9 seems to help but
looks rather expensive. This too seems to work but
- is cheaper. Guidance for the magic constants
+ is cheaper. Guidance for the magic constants
7621 and 32768 is taken from Sedgewick's algorithms
book, chapter 35.
*/
while (1) {
if (unLo > unHi) break;
n = (Int32)eclass[fmap[unLo]] - (Int32)med;
- if (n == 0) {
- fswap(fmap[unLo], fmap[ltLo]);
- ltLo++; unLo++;
- continue;
+ if (n == 0) {
+ fswap(fmap[unLo], fmap[ltLo]);
+ ltLo++; unLo++;
+ continue;
};
if (n > 0) break;
unLo++;
while (1) {
if (unLo > unHi) break;
n = (Int32)eclass[fmap[unHi]] - (Int32)med;
- if (n == 0) {
- fswap(fmap[unHi], fmap[gtHi]);
- gtHi--; unHi--;
- continue;
+ if (n == 0) {
+ fswap(fmap[unHi], fmap[gtHi]);
+ gtHi--; unHi--;
+ continue;
};
if (n < 0) break;
unHi--;
#define UNALIGNED_BH(zz) ((zz) & 0x01f)
static
-void fallbackSort ( UInt32* fmap,
- UInt32* eclass,
+void fallbackSort ( UInt32* fmap,
+ UInt32* eclass,
UInt32* bhtab,
Int32 nblock,
Int32 verb )
--*/
/*-- set sentinel bits for block-end detection --*/
- for (i = 0; i < 32; i++) {
+ for (i = 0; i < 32; i++) {
SET_BH(nblock + 2*i);
CLEAR_BH(nblock + 2*i + 1);
}
H = 1;
while (1) {
- if (verb >= 4)
+ if (verb >= 4)
VPrintf1 ( " depth %6d has ", H );
j = 0;
}
}
- if (verb >= 4)
+ if (verb >= 4)
VPrintf1 ( "%6d unresolved strings\n", nNotDone );
H *= 2;
if (H > nblock || nNotDone == 0) break;
}
- /*--
+ /*--
Reconstruct the original block in
eclass8 [0 .. nblock-1], since the
previous phase destroyed it.
/*---------------------------------------------*/
static
__inline__
-Bool mainGtU ( UInt32 i1,
+Bool mainGtU ( UInt32 i1,
UInt32 i2,
- UChar* block,
+ UChar* block,
UInt16* quadrant,
UInt32 nblock,
Int32* budget )
UChar* block,
UInt16* quadrant,
Int32 nblock,
- Int32 lo,
- Int32 hi,
+ Int32 lo,
+ Int32 hi,
Int32 d,
Int32* budget )
{
if (i > hi) break;
v = ptr[i];
j = i;
- while ( mainGtU (
- ptr[j-h]+d, v+d, block, quadrant, nblock, budget
+ while ( mainGtU (
+ ptr[j-h]+d, v+d, block, quadrant, nblock, budget
) ) {
ptr[j] = ptr[j-h];
j = j - h;
if (i > hi) break;
v = ptr[i];
j = i;
- while ( mainGtU (
- ptr[j-h]+d, v+d, block, quadrant, nblock, budget
+ while ( mainGtU (
+ ptr[j-h]+d, v+d, block, quadrant, nblock, budget
) ) {
ptr[j] = ptr[j-h];
j = j - h;
if (i > hi) break;
v = ptr[i];
j = i;
- while ( mainGtU (
- ptr[j-h]+d, v+d, block, quadrant, nblock, budget
+ while ( mainGtU (
+ ptr[j-h]+d, v+d, block, quadrant, nblock, budget
) ) {
ptr[j] = ptr[j-h];
j = j - h;
} \
}
-static
+static
__inline__
UChar mmed3 ( UChar a, UChar b, UChar c )
{
UChar t;
if (a > b) { t = a; a = b; b = t; };
- if (b > c) {
+ if (b > c) {
b = c;
if (a > b) b = a;
}
UChar* block,
UInt16* quadrant,
Int32 nblock,
- Int32 loSt,
- Int32 hiSt,
+ Int32 loSt,
+ Int32 hiSt,
Int32 dSt,
Int32* budget )
{
AssertH ( sp < MAIN_QSORT_STACK_SIZE, 1001 );
mpop ( lo, hi, d );
- if (hi - lo < MAIN_QSORT_SMALL_THRESH ||
+ if (hi - lo < MAIN_QSORT_SMALL_THRESH ||
d > MAIN_QSORT_DEPTH_THRESH) {
mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget );
if (*budget < 0) return;
continue;
}
- med = (Int32)
+ med = (Int32)
mmed3 ( block[ptr[ lo ]+d],
block[ptr[ hi ]+d],
block[ptr[ (lo+hi)>>1 ]+d] );
while (True) {
if (unLo > unHi) break;
n = ((Int32)block[ptr[unLo]+d]) - med;
- if (n == 0) {
- mswap(ptr[unLo], ptr[ltLo]);
- ltLo++; unLo++; continue;
+ if (n == 0) {
+ mswap(ptr[unLo], ptr[ltLo]);
+ ltLo++; unLo++; continue;
};
if (n > 0) break;
unLo++;
while (True) {
if (unLo > unHi) break;
n = ((Int32)block[ptr[unHi]+d]) - med;
- if (n == 0) {
- mswap(ptr[unHi], ptr[gtHi]);
- gtHi--; unHi--; continue;
+ if (n == 0) {
+ mswap(ptr[unHi], ptr[gtHi]);
+ gtHi--; unHi--; continue;
};
if (n < 0) break;
unHi--;
#define CLEARMASK (~(SETMASK))
static
-void mainSort ( UInt32* ptr,
+void mainSort ( UInt32* ptr,
UChar* block,
- UInt16* quadrant,
+ UInt16* quadrant,
UInt32* ftab,
Int32 nblock,
Int32 verb,
/*--
Step 1:
Complete the big bucket [ss] by quicksorting
- any unsorted small buckets [ss, j], for j != ss.
+ any unsorted small buckets [ss, j], for j != ss.
Hopefully previous pointer-scanning phases have already
completed many of the small buckets [ss, j], so
we don't have to sort them at all.
VPrintf4 ( " qsort [0x%x, 0x%x] "
"done %d this %d\n",
ss, j, numQSorted, hi - lo + 1 );
- mainQSort3 (
- ptr, block, quadrant, nblock,
- lo, hi, BZ_N_RADIX, budget
- );
+ mainQSort3 (
+ ptr, block, quadrant, nblock,
+ lo, hi, BZ_N_RADIX, budget
+ );
numQSorted += (hi - lo + 1);
if (*budget < 0) return;
}
for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) {
k = ptr[j]-1; if (k < 0) k += nblock;
c1 = block[k];
- if (!bigDone[c1])
+ if (!bigDone[c1])
ptr[ copyEnd[c1]-- ] = k;
}
}
updating for the last bucket is pointless.
The quadrant array provides a way to incrementally
- cache sort orderings, as they appear, so as to
+ cache sort orderings, as they appear, so as to
make subsequent comparisons in fullGtU() complete
faster. For repetitive blocks this makes a big
difference (but not big enough to be able to avoid
for 0 <= i < nblock and 0 <= j <= nblock
- if block[i] != block[j],
+ if block[i] != block[j],
- then the relative values of quadrant[i] and
+ then the relative values of quadrant[i] and
quadrant[j] are meaningless.
else {
*/
void BZ2_blockSort ( EState* s )
{
- UInt32* ptr = s->ptr;
+ UInt32* ptr = s->ptr;
UChar* block = s->block;
UInt32* ftab = s->ftab;
Int32 nblock = s->nblock;
quadrant = (UInt16*)(&(block[i]));
/* (wfact-1) / 3 puts the default-factor-30
- transition point at very roughly the same place as
- with v0.1 and v0.9.0.
+ transition point at very roughly the same place as
+ with v0.1 and v0.9.0.
Not that it particularly matters any more, since the
resulting compressed stream is now the same regardless
of whether or not we use the main sort or fallback sort.
budget = budgetInit;
mainSort ( ptr, block, quadrant, ftab, nblock, verb, &budget );
- if (verb >= 3)
+ if (verb >= 3)
VPrintf3 ( " %d work, %d block, ratio %5.2f\n",
budgetInit - budget,
- nblock,
+ nblock,
(float)(budgetInit - budget) /
- (float)(nblock==0 ? 1 : nblock) );
+ (float)(nblock==0 ? 1 : nblock) );
if (budget < 0) {
- if (verb >= 2)
+ if (verb >= 2)
VPrintf0 ( " too repetitive; using fallback"
" sorting algorithm\n" );
fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb );
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
/*--
WARNING:
- This program and library (attempts to) compress data by
- performing several non-trivial transformations on it.
- Unless you are 100% familiar with *all* the algorithms
- contained herein, and with the consequences of modifying them,
- you should NOT meddle with the compression or decompression
- machinery. Incorrect changes can and very likely *will*
+ This program and library (attempts to) compress data by
+ performing several non-trivial transformations on it.
+ Unless you are 100% familiar with *all* the algorithms
+ contained herein, and with the consequences of modifying them,
+ you should NOT meddle with the compression or decompression
+ machinery. Incorrect changes can and very likely *will*
lead to disasterous loss of data.
DISCLAIMER:
of various special cases in the code which occur with very low
but non-zero probability make it impossible to rule out the
possibility of bugs remaining in the program. DO NOT COMPRESS
- ANY DATA WITH THIS PROGRAM AND/OR LIBRARY UNLESS YOU ARE PREPARED
- TO ACCEPT THE POSSIBILITY, HOWEVER SMALL, THAT THE DATA WILL
+ ANY DATA WITH THIS PROGRAM AND/OR LIBRARY UNLESS YOU ARE PREPARED
+ TO ACCEPT THE POSSIBILITY, HOWEVER SMALL, THAT THE DATA WILL
NOT BE RECOVERABLE.
That is not to say this program is inherently unreliable.
has been carefully constructed and extensively tested.
PATENTS:
- To the best of my knowledge, bzip2/libbzip2 does not use any
- patented algorithms. However, I do not have the resources
- available to carry out a full patent search. Therefore I cannot
+ To the best of my knowledge, bzip2/libbzip2 does not use any
+ patented algorithms. However, I do not have the resources
+ available to carry out a full patent search. Therefore I cannot
give any guarantee of the above statement.
--*/
typedef unsigned int UInt32;
typedef short Int16;
typedef unsigned short UInt16;
-
+
#define True ((Bool)1)
#define False ((Bool)0)
/*---------------------------------------------------*/
typedef
- struct { UChar b[8]; }
+ struct { UChar b[8]; }
UInt64;
static
for (ia = 0; ia < 8; ia++) {
carry = 0;
for (ib = 0; ib < 8; ib++) {
- carry += ( ((Int32)sum[ia+ib])
+ carry += ( ((Int32)sum[ia+ib])
+ ((Int32)a->b[ia]) * ((Int32)b->b[ib]) );
sum[ia+ib] = (UChar)(carry & 0xFF);
carry >>= 8;
Int32 i;
UInt64 tmp1, tmp2, n_orig, zero_point_eight;
- zero_point_eight.b[1] = zero_point_eight.b[2] =
- zero_point_eight.b[3] = zero_point_eight.b[4] =
- zero_point_eight.b[5] = zero_point_eight.b[6] =
+ zero_point_eight.b[1] = zero_point_eight.b[2] =
+ zero_point_eight.b[3] = zero_point_eight.b[4] =
+ zero_point_eight.b[5] = zero_point_eight.b[6] =
zero_point_eight.b[7] = 0xCC;
zero_point_eight.b[0] = 0xCD;
n_orig = *n;
- /* divide n by 10,
+ /* divide n by 10,
by multiplying by 0.8 and then shifting right 3 times */
uInt64_mul ( n, &zero_point_eight, &tmp1, &tmp2 );
- uInt64_shr1(&tmp1); uInt64_shr1(&tmp1); uInt64_shr1(&tmp1);
+ uInt64_shr1(&tmp1); uInt64_shr1(&tmp1); uInt64_shr1(&tmp1);
*n = tmp1;
-
+
/* tmp1 = 8*n, tmp2 = 2*n */
uInt64_shl1(&tmp1); uInt64_shl1(&tmp1); uInt64_shl1(&tmp1);
tmp2 = *n; uInt64_shl1(&tmp2);
uInt64_sub ( &tmp1, &n_orig );
/* n_orig should now hold quotient, in range 0 .. 9 */
- for (i = 7; i >= 1; i--)
+ for (i = 7; i >= 1; i--)
if (n_orig.b[i] != 0) panic ( "uInt64_qrm10(1)" );
if (n_orig.b[0] > 9)
panic ( "uInt64_qrm10(2)" );
/*---------------------------------------------------*/
/*---------------------------------------------*/
-static
+static
Bool myfeof ( FILE* f )
{
Int32 c = fgetc ( f );
/*---------------------------------------------*/
-static
+static
void compressStream ( FILE *stream, FILE *zStream )
{
BZFILE* bzf = NULL;
if (ferror(stream)) goto errhandler_io;
if (ferror(zStream)) goto errhandler_io;
- bzf = BZ2_bzWriteOpen ( &bzerr, zStream,
- blockSize100k, verbosity, workFactor );
+ bzf = BZ2_bzWriteOpen ( &bzerr, zStream,
+ blockSize100k, verbosity, workFactor );
if (bzerr != BZ_OK) goto errhandler;
if (verbosity >= 2) fprintf ( stderr, "\n" );
}
- BZ2_bzWriteClose64 ( &bzerr, bzf, 0,
+ BZ2_bzWriteClose64 ( &bzerr, bzf, 0,
&nbytes_in_lo32, &nbytes_in_hi32,
&nbytes_out_lo32, &nbytes_out_hi32 );
if (bzerr != BZ_OK) goto errhandler;
ret = fclose ( stream );
if (ret == EOF) goto errhandler_io;
- if (nbytes_in_lo32 == 0 && nbytes_in_hi32 == 0)
+ if (nbytes_in_lo32 == 0 && nbytes_in_hi32 == 0)
nbytes_in_lo32 = 1;
if (verbosity >= 1) {
Char buf_nin[32], buf_nout[32];
UInt64 nbytes_in, nbytes_out;
double nbytes_in_d, nbytes_out_d;
- uInt64_from_UInt32s ( &nbytes_in,
+ uInt64_from_UInt32s ( &nbytes_in,
nbytes_in_lo32, nbytes_in_hi32 );
- uInt64_from_UInt32s ( &nbytes_out,
+ uInt64_from_UInt32s ( &nbytes_out,
nbytes_out_lo32, nbytes_out_hi32 );
nbytes_in_d = uInt64_to_double ( &nbytes_in );
nbytes_out_d = uInt64_to_double ( &nbytes_out );
return;
errhandler:
- BZ2_bzWriteClose64 ( &bzerr_dummy, bzf, 1,
+ BZ2_bzWriteClose64 ( &bzerr_dummy, bzf, 1,
&nbytes_in_lo32, &nbytes_in_hi32,
&nbytes_out_lo32, &nbytes_out_hi32 );
switch (bzerr) {
/*---------------------------------------------*/
-static
+static
Bool uncompressStream ( FILE *zStream, FILE *stream )
{
BZFILE* bzf = NULL;
while (True) {
- bzf = BZ2_bzReadOpen (
- &bzerr, zStream, verbosity,
+ bzf = BZ2_bzReadOpen (
+ &bzerr, zStream, verbosity,
(int)smallMode, unused, nUnused
);
if (bzf == NULL || bzerr != BZ_OK) goto errhandler;
return False;
} else {
if (noisy)
- fprintf ( stderr,
+ fprintf ( stderr,
"\n%s: %s: trailing garbage after EOF ignored\n",
progName, inName );
- return True;
+ return True;
}
default:
panic ( "decompress:unexpected error" );
/*---------------------------------------------*/
-static
+static
Bool testStream ( FILE *zStream )
{
BZFILE* bzf = NULL;
while (True) {
- bzf = BZ2_bzReadOpen (
- &bzerr, zStream, verbosity,
+ bzf = BZ2_bzReadOpen (
+ &bzerr, zStream, verbosity,
(int)smallMode, unused, nUnused
);
if (bzf == NULL || bzerr != BZ_OK) goto errhandler;
errhandler:
BZ2_bzReadClose ( &bzerr_dummy, bzf );
- if (verbosity == 0)
+ if (verbosity == 0)
fprintf ( stderr, "%s: %s: ", progName, inName );
switch (bzerr) {
case BZ_CONFIG_ERROR:
case BZ_DATA_ERROR_MAGIC:
if (zStream != stdin) fclose(zStream);
if (streamNo == 1) {
- fprintf ( stderr,
+ fprintf ( stderr,
"bad magic number (file not created by bzip2)\n" );
return False;
} else {
if (noisy)
- fprintf ( stderr,
+ fprintf ( stderr,
"trailing garbage after EOF ignored\n" );
- return True;
+ return True;
}
default:
panic ( "test:unexpected error" );
/*---------------------------------------------*/
-static
+static
void cadvise ( void )
{
if (noisy)
/*---------------------------------------------*/
-static
+static
void showFileNames ( void )
{
if (noisy)
fprintf (
stderr,
"\tInput file = %s, output file = %s\n",
- inName, outName
+ inName, outName
);
}
/*---------------------------------------------*/
-static
+static
void cleanUpAndFail ( Int32 ec )
{
IntNative retVal;
- if ( srcMode == SM_F2F
+ if ( srcMode == SM_F2F
&& opMode != OM_TEST
&& deleteOutputOnInterrupt ) {
if (noisy)
progName );
}
if (noisy && numFileNames > 0 && numFilesProcessed < numFileNames) {
- fprintf ( stderr,
+ fprintf ( stderr,
"%s: WARNING: some files have not been processed:\n"
"\t%d specified on command line, %d not processed yet.\n\n",
- progName, numFileNames,
+ progName, numFileNames,
numFileNames - numFilesProcessed );
}
setExit(ec);
/*---------------------------------------------*/
-static
+static
void panic ( Char* s )
{
fprintf ( stderr,
/*---------------------------------------------*/
-static
+static
void crcError ( void )
{
fprintf ( stderr,
/*---------------------------------------------*/
-static
+static
void compressedStreamEOF ( void )
{
fprintf ( stderr,
/*---------------------------------------------*/
-static
+static
void ioError ( void )
{
fprintf ( stderr,
/*---------------------------------------------*/
-static
+static
void mySignalCatcher ( IntNative n )
{
fprintf ( stderr,
/*---------------------------------------------*/
-static
+static
void mySIGSEGVorSIGBUScatcher ( IntNative n )
{
if (opMode == OM_Z)
- fprintf (
+ fprintf (
stderr,
"\n%s: Caught a SIGSEGV or SIGBUS whilst compressing.\n"
"\n"
"\n",
progName );
else
- fprintf (
+ fprintf (
stderr,
"\n%s: Caught a SIGSEGV or SIGBUS whilst decompressing.\n"
"\n"
/*---------------------------------------------*/
-static
+static
void outOfMemory ( void )
{
fprintf ( stderr,
/*---------------------------------------------*/
-static
+static
void configError ( void )
{
fprintf ( stderr,
/*---------------------------------------------------*/
/*---------------------------------------------*/
-static
+static
void pad ( Char *s )
{
Int32 i;
/*---------------------------------------------*/
-static
-void copyFileName ( Char* to, Char* from )
+static
+void copyFileName ( Char* to, Char* from )
{
if ( strlen(from) > FILE_NAME_LEN-10 ) {
fprintf (
/*---------------------------------------------*/
-static
+static
Bool fileExists ( Char* name )
{
FILE *tmp = fopen ( name, "rb" );
/*--
if in doubt, return True
--*/
-static
+static
Bool notAStandardFile ( Char* name )
{
IntNative i;
/*--
rac 11/21/98 see if file has hard links to it
--*/
-static
+static
Int32 countHardLinks ( Char* name )
-{
+{
IntNative i;
struct MY_STAT statBuf;
/*---------------------------------------------*/
-static
+static
void copyDatePermissionsAndOwner ( Char *srcName, Char *dstName )
{
#if BZ_UNIX
/*---------------------------------------------*/
-static
+static
void setInterimPermissions ( Char *dstName )
{
#if BZ_UNIX
/*---------------------------------------------*/
-static
+static
Bool containsDubiousChars ( Char* name )
{
Bool cdc = False;
/*---------------------------------------------*/
#define BZ_N_SUFFIX_PAIRS 4
-Char* zSuffix[BZ_N_SUFFIX_PAIRS]
+Char* zSuffix[BZ_N_SUFFIX_PAIRS]
= { ".bz2", ".bz", ".tbz2", ".tbz" };
-Char* unzSuffix[BZ_N_SUFFIX_PAIRS]
+Char* unzSuffix[BZ_N_SUFFIX_PAIRS]
= { "", "", ".tar", ".tar" };
-static
+static
Bool hasSuffix ( Char* s, Char* suffix )
{
Int32 ns = strlen(s);
return False;
}
-static
-Bool mapSuffix ( Char* name,
+static
+Bool mapSuffix ( Char* name,
Char* oldSuffix, Char* newSuffix )
{
if (!hasSuffix(name,oldSuffix)) return False;
/*---------------------------------------------*/
-static
+static
void compress ( Char *name )
{
FILE *inStr;
panic ( "compress: bad modes\n" );
switch (srcMode) {
- case SM_I2O:
+ case SM_I2O:
copyFileName ( inName, "(stdin)" );
- copyFileName ( outName, "(stdout)" );
+ copyFileName ( outName, "(stdout)" );
break;
- case SM_F2F:
+ case SM_F2F:
copyFileName ( inName, name );
copyFileName ( outName, name );
- strcat ( outName, ".bz2" );
+ strcat ( outName, ".bz2" );
break;
- case SM_F2O:
+ case SM_F2O:
copyFileName ( inName, name );
- copyFileName ( outName, "(stdout)" );
+ copyFileName ( outName, "(stdout)" );
break;
}
for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++) {
if (hasSuffix(inName, zSuffix[i])) {
if (noisy)
- fprintf ( stderr,
+ fprintf ( stderr,
"%s: Input file %s already has %s suffix.\n",
progName, inName, zSuffix[i] );
setExit(1);
/*---------------------------------------------*/
-static
+static
void uncompress ( Char *name )
{
FILE *inStr;
cantGuess = False;
switch (srcMode) {
- case SM_I2O:
+ case SM_I2O:
copyFileName ( inName, "(stdin)" );
- copyFileName ( outName, "(stdout)" );
+ copyFileName ( outName, "(stdout)" );
break;
- case SM_F2F:
+ case SM_F2F:
copyFileName ( inName, name );
copyFileName ( outName, name );
for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++)
if (mapSuffix(outName,zSuffix[i],unzSuffix[i]))
- goto zzz;
+ goto zzz;
cantGuess = True;
strcat ( outName, ".out" );
break;
- case SM_F2O:
+ case SM_F2O:
copyFileName ( inName, name );
- copyFileName ( outName, "(stdout)" );
+ copyFileName ( outName, "(stdout)" );
break;
}
}
if ( /* srcMode == SM_F2F implied && */ cantGuess ) {
if (noisy)
- fprintf ( stderr,
+ fprintf ( stderr,
"%s: Can't guess original name for %s -- using %s\n",
progName, inName, outName );
/* just a warning, no return */
- }
+ }
if ( srcMode == SM_F2F && !forceOverwrite && fileExists ( outName ) ) {
fprintf ( stderr, "%s: Output file %s already exists.\n",
progName, outName );
/*---------------------------------------------*/
-static
+static
void testf ( Char *name )
{
FILE *inStr;
/*---------------------------------------------*/
-static
+static
void license ( void )
{
fprintf ( stderr,
/*---------------------------------------------*/
-static
+static
void usage ( Char *fullProgName )
{
fprintf (
/*---------------------------------------------*/
-static
+static
void redundant ( Char* flag )
{
- fprintf (
- stderr,
+ fprintf (
+ stderr,
"%s: %s is redundant in versions 0.9.5 and above\n",
progName, flag );
}
implement a linked list of command-line arguments,
into which main() copies argv[1 .. argc-1].
- The purpose of this exercise is to facilitate
- the expansion of wildcard characters * and ? in
+ The purpose of this exercise is to facilitate
+ the expansion of wildcard characters * and ? in
filenames for OSs which don't know how to do it
themselves, like MSDOS, Windows 95 and NT.
/*---------------------------------------------*/
-static
+static
void *myMalloc ( Int32 n )
{
void* p;
/*---------------------------------------------*/
-static
+static
Cell *mkCell ( void )
{
Cell *c;
/*---------------------------------------------*/
-static
+static
Cell *snocString ( Cell *root, Char *name )
{
if (root == NULL) {
/*---------------------------------------------*/
-static
-void addFlagsFromEnvVar ( Cell** argList, Char* varName )
+static
+void addFlagsFromEnvVar ( Cell** argList, Char* varName )
{
Int32 i, j, k;
Char *envbase, *p;
if (*tmp == PATH_SEP) progName = tmp + 1;
- /*-- Copy flags from env var BZIP2, and
+ /*-- Copy flags from env var BZIP2, and
expand filename wildcards in arg list.
--*/
argList = NULL;
}
}
}
-
+
/*-- And again ... --*/
for (aa = argList; aa != NULL; aa = aa->link) {
if (ISFLAG("--")) break;
if (ISFLAG("--quiet")) noisy = False; else
if (ISFLAG("--version")) license(); else
if (ISFLAG("--license")) license(); else
- if (ISFLAG("--exponential")) workFactor = 1; else
+ if (ISFLAG("--exponential")) workFactor = 1; else
if (ISFLAG("--repetitive-best")) redundant(aa->name); else
if (ISFLAG("--repetitive-fast")) redundant(aa->name); else
if (ISFLAG("--verbose")) verbosity++; else
}
if (verbosity > 4) verbosity = 4;
- if (opMode == OM_Z && smallMode && blockSize100k > 2)
+ if (opMode == OM_Z && smallMode && blockSize100k > 2)
blockSize100k = 2;
if (opMode == OM_TEST && srcMode == SM_F2O) {
compress ( aa->name );
}
}
- }
+ }
else
if (opMode == OM_UNZ) {
if (aa->name[0] == '-' && decode) continue;
numFilesProcessed++;
uncompress ( aa->name );
- }
+ }
}
- if (unzFailsExist) {
- setExit(2);
+ if (unzFailsExist) {
+ setExit(2);
exit(exitValue);
}
- }
+ }
else {
testFailsExist = False;
}
}
- /* Free the argument list memory to mollify leak detectors
+ /* Free the argument list memory to mollify leak detectors
(eg) Purify, Checker. Serves no other useful purpose.
*/
aa = argList;
/*-----------------------------------------------------------*/
/*--
- This program is bzip2recover, a program to attempt data
+ This program is bzip2recover, a program to attempt data
salvage from damaged files created by the accompanying
bzip2-1.0 program.
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
}
buffHi = (buffHi << 1) | (buffLo >> 31);
buffLo = (buffLo << 1) | (b & 1);
- if ( ( (buffHi & 0x0000ffff) == BLOCK_HEADER_HI
+ if ( ( (buffHi & 0x0000ffff) == BLOCK_HEADER_HI
&& buffLo == BLOCK_HEADER_LO)
- ||
- ( (buffHi & 0x0000ffff) == BLOCK_ENDMARK_HI
+ ||
+ ( (buffHi & 0x0000ffff) == BLOCK_ENDMARK_HI
&& buffLo == BLOCK_ENDMARK_LO)
) {
if (bitsRead > 49)
if (b == 2) break;
buffHi = (buffHi << 1) | (buffLo >> 31);
buffLo = (buffLo << 1) | (b & 1);
- if (bitsRead == 47+rbStart[wrBlock])
+ if (bitsRead == 47+rbStart[wrBlock])
blockCRC = (buffHi << 16) | (buffLo >> 16);
if (outFile != NULL && bitsRead >= rbStart[wrBlock]
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
#ifndef BZ_NO_STDIO
void BZ2_bz__AssertH__fail ( int errcode )
{
- fprintf(stderr,
+ fprintf(stderr,
"\n\nbzip2/libbzip2: internal error number %d.\n"
"This is a bug in bzip2/libbzip2, %s.\n"
"Please report it to me at: jseward@acm.org. If this happened\n"
/*---------------------------------------------------*/
-int BZ_API(BZ2_bzCompressInit)
- ( bz_stream* strm,
+int BZ_API(BZ2_bzCompressInit)
+ ( bz_stream* strm,
int blockSize100k,
int verbosity,
int workFactor )
if (!bz_config_ok()) return BZ_CONFIG_ERROR;
- if (strm == NULL ||
+ if (strm == NULL ||
blockSize100k < 1 || blockSize100k > 9 ||
workFactor < 0 || workFactor > 250)
return BZ_PARAM_ERROR;
/*-- no input? --*/
if (s->strm->avail_in == 0) break;
progress_in = True;
- ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) );
+ ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) );
s->strm->next_in++;
s->strm->avail_in--;
s->strm->total_in_lo32++;
/*-- flush/finish end? --*/
if (s->avail_in_expect == 0) break;
progress_in = True;
- ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) );
+ ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) );
s->strm->next_in++;
s->strm->avail_in--;
s->strm->total_in_lo32++;
Bool progress_in = False;
Bool progress_out = False;
EState* s = strm->state;
-
+
while (True) {
if (s->state == BZ_S_OUTPUT) {
progress_out |= copy_output_until_stop ( s );
if (s->state_out_pos < s->numZ) break;
- if (s->mode == BZ_M_FINISHING &&
+ if (s->mode == BZ_M_FINISHING &&
s->avail_in_expect == 0 &&
isempty_RL(s)) break;
prepare_new_block ( s );
s->state = BZ_S_INPUT;
- if (s->mode == BZ_M_FLUSHING &&
+ if (s->mode == BZ_M_FLUSHING &&
s->avail_in_expect == 0 &&
isempty_RL(s)) break;
}
if (action == BZ_RUN) {
progress = handle_compress ( strm );
return progress ? BZ_RUN_OK : BZ_PARAM_ERROR;
- }
+ }
else
if (action == BZ_FLUSH) {
s->avail_in_expect = strm->avail_in;
s->mode = BZ_M_FINISHING;
goto preswitch;
}
- else
+ else
return BZ_PARAM_ERROR;
case BZ_M_FLUSHING:
if (action != BZ_FLUSH) return BZ_SEQUENCE_ERROR;
- if (s->avail_in_expect != s->strm->avail_in)
+ if (s->avail_in_expect != s->strm->avail_in)
return BZ_SEQUENCE_ERROR;
progress = handle_compress ( strm );
if (s->avail_in_expect > 0 || !isempty_RL(s) ||
case BZ_M_FINISHING:
if (action != BZ_FINISH) return BZ_SEQUENCE_ERROR;
- if (s->avail_in_expect != s->strm->avail_in)
+ if (s->avail_in_expect != s->strm->avail_in)
return BZ_SEQUENCE_ERROR;
progress = handle_compress ( strm );
if (!progress) return BZ_SEQUENCE_ERROR;
if (s->ftab != NULL) BZFREE(s->ftab);
BZFREE(strm->state);
- strm->state = NULL;
+ strm->state = NULL;
return BZ_OK;
}
/*---------------------------------------------------*/
/*---------------------------------------------------*/
-int BZ_API(BZ2_bzDecompressInit)
- ( bz_stream* strm,
+int BZ_API(BZ2_bzDecompressInit)
+ ( bz_stream* strm,
int verbosity,
int small )
{
s->strm->total_out_lo32++;
if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++;
}
-
+
/* can a new run be started? */
if (s->nblock_used == s->save_nblock+1) return;
-
-
+
+
s->state_out_len = 1;
s->state_out_ch = s->k0;
- BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
+ BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; };
-
+
s->state_out_len = 2;
- BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
+ BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; };
-
+
s->state_out_len = 3;
- BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
+ BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; };
-
- BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
+
+ BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++;
s->state_out_len = ((Int32)k1) + 4;
- BZ_GET_FAST(s->k0); BZ_RAND_UPD_MASK;
+ BZ_GET_FAST(s->k0); BZ_RAND_UPD_MASK;
s->k0 ^= BZ_RAND_MASK; s->nblock_used++;
}
}
s_state_out_len_eq_one:
{
- if (cs_avail_out == 0) {
+ if (cs_avail_out == 0) {
c_state_out_len = 1; goto return_notr;
};
*( (UChar*)(cs_next_out) ) = c_state_out_ch;
cs_next_out++;
cs_avail_out--;
}
- }
+ }
/* can a new run be started? */
if (c_nblock_used == s_save_nblockPP) {
c_state_out_len = 0; goto return_notr;
- };
+ };
c_state_out_ch = c_k0;
BZ_GET_FAST_C(k1); c_nblock_used++;
- if (k1 != c_k0) {
- c_k0 = k1; goto s_state_out_len_eq_one;
+ if (k1 != c_k0) {
+ c_k0 = k1; goto s_state_out_len_eq_one;
};
- if (c_nblock_used == s_save_nblockPP)
+ if (c_nblock_used == s_save_nblockPP)
goto s_state_out_len_eq_one;
-
+
c_state_out_len = 2;
BZ_GET_FAST_C(k1); c_nblock_used++;
if (c_nblock_used == s_save_nblockPP) continue;
if (k1 != c_k0) { c_k0 = k1; continue; };
-
+
c_state_out_len = 3;
BZ_GET_FAST_C(k1); c_nblock_used++;
if (c_nblock_used == s_save_nblockPP) continue;
if (k1 != c_k0) { c_k0 = k1; continue; };
-
+
BZ_GET_FAST_C(k1); c_nblock_used++;
c_state_out_len = ((Int32)k1) + 4;
BZ_GET_FAST_C(c_k0); c_nblock_used++;
s->strm->total_out_lo32++;
if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++;
}
-
+
/* can a new run be started? */
if (s->nblock_used == s->save_nblock+1) return;
-
-
+
+
s->state_out_len = 1;
s->state_out_ch = s->k0;
- BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
+ BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; };
-
+
s->state_out_len = 2;
- BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
+ BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; };
-
+
s->state_out_len = 3;
- BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
+ BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; };
-
- BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
+
+ BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++;
s->state_out_len = ((Int32)k1) + 4;
- BZ_GET_SMALL(s->k0); BZ_RAND_UPD_MASK;
+ BZ_GET_SMALL(s->k0); BZ_RAND_UPD_MASK;
s->k0 ^= BZ_RAND_MASK; s->nblock_used++;
}
s->strm->total_out_lo32++;
if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++;
}
-
+
/* can a new run be started? */
if (s->nblock_used == s->save_nblock+1) return;
-
+
s->state_out_len = 1;
s->state_out_ch = s->k0;
BZ_GET_SMALL(k1); s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; };
-
+
s->state_out_len = 2;
BZ_GET_SMALL(k1); s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; };
-
+
s->state_out_len = 3;
BZ_GET_SMALL(k1); s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; };
-
+
BZ_GET_SMALL(k1); s->nblock_used++;
s->state_out_len = ((Int32)k1) + 4;
BZ_GET_SMALL(s->k0); s->nblock_used++;
#endif
if (s->nblock_used == s->save_nblock+1 && s->state_out_len == 0) {
BZ_FINALISE_CRC ( s->calculatedBlockCRC );
- if (s->verbosity >= 3)
- VPrintf2 ( " {0x%x, 0x%x}", s->storedBlockCRC,
+ if (s->verbosity >= 3)
+ VPrintf2 ( " {0x%x, 0x%x}", s->storedBlockCRC,
s->calculatedBlockCRC );
if (s->verbosity >= 2) VPrintf0 ( "]" );
if (s->calculatedBlockCRC != s->storedBlockCRC)
return BZ_DATA_ERROR;
- s->calculatedCombinedCRC
- = (s->calculatedCombinedCRC << 1) |
+ s->calculatedCombinedCRC
+ = (s->calculatedCombinedCRC << 1) |
(s->calculatedCombinedCRC >> 31);
s->calculatedCombinedCRC ^= s->calculatedBlockCRC;
s->state = BZ_X_BLKHDR_1;
Int32 r = BZ2_decompress ( s );
if (r == BZ_STREAM_END) {
if (s->verbosity >= 3)
- VPrintf2 ( "\n combined CRCs: stored = 0x%x, computed = 0x%x",
+ VPrintf2 ( "\n combined CRCs: stored = 0x%x, computed = 0x%x",
s->storedCombinedCRC, s->calculatedCombinedCRC );
if (s->calculatedCombinedCRC != s->storedCombinedCRC)
return BZ_DATA_ERROR;
if (bzf != NULL) bzf->lastErr = eee; \
}
-typedef
+typedef
struct {
FILE* handle;
Char buf[BZ_MAX_UNUSED];
/*---------------------------------------------------*/
-BZFILE* BZ_API(BZ2_bzWriteOpen)
- ( int* bzerror,
- FILE* f,
- int blockSize100k,
+BZFILE* BZ_API(BZ2_bzWriteOpen)
+ ( int* bzerror,
+ FILE* f,
+ int blockSize100k,
int verbosity,
int workFactor )
{
bzf->strm.opaque = NULL;
if (workFactor == 0) workFactor = 30;
- ret = BZ2_bzCompressInit ( &(bzf->strm), blockSize100k,
+ ret = BZ2_bzCompressInit ( &(bzf->strm), blockSize100k,
verbosity, workFactor );
if (ret != BZ_OK)
{ BZ_SETERR(ret); free(bzf); return NULL; };
bzf->strm.avail_in = 0;
bzf->initialisedOk = True;
- return bzf;
+ return bzf;
}
/*---------------------------------------------------*/
void BZ_API(BZ2_bzWrite)
- ( int* bzerror,
- BZFILE* b,
- void* buf,
+ ( int* bzerror,
+ BZFILE* b,
+ void* buf,
int len )
{
Int32 n, n2, ret;
if (bzf->strm.avail_out < BZ_MAX_UNUSED) {
n = BZ_MAX_UNUSED - bzf->strm.avail_out;
- n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar),
+ n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar),
n, bzf->handle );
if (n != n2 || ferror(bzf->handle))
{ BZ_SETERR(BZ_IO_ERROR); return; };
/*---------------------------------------------------*/
void BZ_API(BZ2_bzWriteClose)
- ( int* bzerror,
- BZFILE* b,
+ ( int* bzerror,
+ BZFILE* b,
int abandon,
unsigned int* nbytes_in,
unsigned int* nbytes_out )
{
- BZ2_bzWriteClose64 ( bzerror, b, abandon,
+ BZ2_bzWriteClose64 ( bzerror, b, abandon,
nbytes_in, NULL, nbytes_out, NULL );
}
void BZ_API(BZ2_bzWriteClose64)
- ( int* bzerror,
- BZFILE* b,
+ ( int* bzerror,
+ BZFILE* b,
int abandon,
unsigned int* nbytes_in_lo32,
unsigned int* nbytes_in_hi32,
if (bzf->strm.avail_out < BZ_MAX_UNUSED) {
n = BZ_MAX_UNUSED - bzf->strm.avail_out;
- n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar),
+ n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar),
n, bzf->handle );
if (n != n2 || ferror(bzf->handle))
{ BZ_SETERR(BZ_IO_ERROR); return; };
/*---------------------------------------------------*/
-BZFILE* BZ_API(BZ2_bzReadOpen)
- ( int* bzerror,
- FILE* f,
+BZFILE* BZ_API(BZ2_bzReadOpen)
+ ( int* bzerror,
+ FILE* f,
int verbosity,
int small,
void* unused,
BZ_SETERR(BZ_OK);
- if (f == NULL ||
+ if (f == NULL ||
(small != 0 && small != 1) ||
(verbosity < 0 || verbosity > 4) ||
(unused == NULL && nUnused != 0) ||
{ BZ_SETERR(BZ_IO_ERROR); return NULL; };
bzf = malloc ( sizeof(bzFile) );
- if (bzf == NULL)
+ if (bzf == NULL)
{ BZ_SETERR(BZ_MEM_ERROR); return NULL; };
BZ_SETERR(BZ_OK);
bzf->strm.bzalloc = NULL;
bzf->strm.bzfree = NULL;
bzf->strm.opaque = NULL;
-
+
while (nUnused > 0) {
bzf->buf[bzf->bufN] = *((UChar*)(unused)); bzf->bufN++;
unused = ((void*)( 1 + ((UChar*)(unused)) ));
bzf->strm.next_in = bzf->buf;
bzf->initialisedOk = True;
- return bzf;
+ return bzf;
}
/*---------------------------------------------------*/
-int BZ_API(BZ2_bzRead)
- ( int* bzerror,
- BZFILE* b,
- void* buf,
+int BZ_API(BZ2_bzRead)
+ ( int* bzerror,
+ BZFILE* b,
+ void* buf,
int len )
{
Int32 n, ret;
while (True) {
- if (ferror(bzf->handle))
+ if (ferror(bzf->handle))
{ BZ_SETERR(BZ_IO_ERROR); return 0; };
if (bzf->strm.avail_in == 0 && !myfeof(bzf->handle)) {
- n = fread ( bzf->buf, sizeof(UChar),
+ n = fread ( bzf->buf, sizeof(UChar),
BZ_MAX_UNUSED, bzf->handle );
if (ferror(bzf->handle))
{ BZ_SETERR(BZ_IO_ERROR); return 0; };
if (ret != BZ_OK && ret != BZ_STREAM_END)
{ BZ_SETERR(ret); return 0; };
- if (ret == BZ_OK && myfeof(bzf->handle) &&
+ if (ret == BZ_OK && myfeof(bzf->handle) &&
bzf->strm.avail_in == 0 && bzf->strm.avail_out > 0)
{ BZ_SETERR(BZ_UNEXPECTED_EOF); return 0; };
return len - bzf->strm.avail_out; };
if (bzf->strm.avail_out == 0)
{ BZ_SETERR(BZ_OK); return len; };
-
+
}
return 0; /*not reached*/
/*---------------------------------------------------*/
-void BZ_API(BZ2_bzReadGetUnused)
- ( int* bzerror,
- BZFILE* b,
- void** unused,
+void BZ_API(BZ2_bzReadGetUnused)
+ ( int* bzerror,
+ BZFILE* b,
+ void** unused,
int* nUnused )
{
bzFile* bzf = (bzFile*)b;
/*---------------------------------------------------*/
/*---------------------------------------------------*/
-int BZ_API(BZ2_bzBuffToBuffCompress)
- ( char* dest,
+int BZ_API(BZ2_bzBuffToBuffCompress)
+ ( char* dest,
unsigned int* destLen,
- char* source,
+ char* source,
unsigned int sourceLen,
- int blockSize100k,
- int verbosity,
+ int blockSize100k,
+ int verbosity,
int workFactor )
{
bz_stream strm;
int ret;
CHECKPOINT;
- if (dest == NULL || destLen == NULL ||
+ if (dest == NULL || destLen == NULL ||
source == NULL ||
blockSize100k < 1 || blockSize100k > 9 ||
verbosity < 0 || verbosity > 4 ||
- workFactor < 0 || workFactor > 250)
+ workFactor < 0 || workFactor > 250)
return BZ_PARAM_ERROR;
if (workFactor == 0) workFactor = 30;
strm.bzfree = NULL;
strm.opaque = NULL;
CHECKPOINT;
- ret = BZ2_bzCompressInit ( &strm, blockSize100k,
+ ret = BZ2_bzCompressInit ( &strm, blockSize100k,
verbosity, workFactor );
if (ret != BZ_OK) return ret;
CHECKPOINT;
if (ret != BZ_STREAM_END) goto errhandler;
/* normal termination */
- *destLen -= strm.avail_out;
+ *destLen -= strm.avail_out;
CHECKPOINT;
BZ2_bzCompressEnd ( &strm );
return BZ_OK;
#endif // BZ_DECOMPRESS_0NLY
/*---------------------------------------------------*/
-int BZ_API(BZ2_bzBuffToBuffDecompress)
- ( char* dest,
+int BZ_API(BZ2_bzBuffToBuffDecompress)
+ ( char* dest,
unsigned int* destLen,
- char* source,
+ char* source,
unsigned int sourceLen,
int small,
int verbosity )
bz_stream strm;
int ret;
- if (dest == NULL || destLen == NULL ||
+ if (dest == NULL || destLen == NULL ||
source == NULL ||
(small != 0 && small != 1) ||
- verbosity < 0 || verbosity > 4)
+ verbosity < 0 || verbosity > 4)
return BZ_PARAM_ERROR;
strm.bzalloc = NULL;
} else {
BZ2_bzDecompressEnd ( &strm );
return BZ_OUTBUFF_FULL;
- };
+ };
errhandler:
BZ2_bzDecompressEnd ( &strm );
- return ret;
+ return ret;
}
int verbosity = 0;
int workFactor = 30;
int smallMode = 0;
- int nUnused = 0;
+ int nUnused = 0;
if (mode == NULL) return NULL;
while (*mode) {
if (writing) {
/* Guard against total chaos and anarchy -- JRS */
if (blockSize100k < 1) blockSize100k = 1;
- if (blockSize100k > 9) blockSize100k = 9;
+ if (blockSize100k > 9) blockSize100k = 9;
bzfp = BZ2_bzWriteOpen(&bzerr,fp,blockSize100k,
verbosity,workFactor);
} else {
{
int bzerr;
FILE *fp = ((bzFile *)b)->handle;
-
+
if (b==NULL) {return;}
if(((bzFile*)b)->writing){
BZ2_bzWriteClose(&bzerr,b,0,NULL,NULL);
/*---------------------------------------------------*/
/*--
- return last error code
+ return last error code
--*/
static char *bzerrorstrings[] = {
"OK"
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
#define BZ_OUTBUFF_FULL (-8)
#define BZ_CONFIG_ERROR (-9)
-typedef
+typedef
struct {
char *next_in;
unsigned int avail_in;
void *(*bzalloc)(void *,int,int);
void (*bzfree)(void *,void *);
void *opaque;
- }
+ }
bz_stream;
/*-- Core (low-level) library functions --*/
-BZ_EXTERN int BZ_API(BZ2_bzCompressInit) (
- bz_stream* strm,
- int blockSize100k,
- int verbosity,
- int workFactor
+BZ_EXTERN int BZ_API(BZ2_bzCompressInit) (
+ bz_stream* strm,
+ int blockSize100k,
+ int verbosity,
+ int workFactor
);
-BZ_EXTERN int BZ_API(BZ2_bzCompress) (
- bz_stream* strm,
- int action
+BZ_EXTERN int BZ_API(BZ2_bzCompress) (
+ bz_stream* strm,
+ int action
);
-BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) (
- bz_stream* strm
+BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) (
+ bz_stream* strm
);
-BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) (
- bz_stream *strm,
- int verbosity,
+BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) (
+ bz_stream *strm,
+ int verbosity,
int small
);
-BZ_EXTERN int BZ_API(BZ2_bzDecompress) (
- bz_stream* strm
+BZ_EXTERN int BZ_API(BZ2_bzDecompress) (
+ bz_stream* strm
);
-BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) (
- bz_stream *strm
+BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) (
+ bz_stream *strm
);
typedef void BZFILE;
-BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) (
- int* bzerror,
- FILE* f,
- int verbosity,
+BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) (
+ int* bzerror,
+ FILE* f,
+ int verbosity,
int small,
- void* unused,
- int nUnused
+ void* unused,
+ int nUnused
);
-BZ_EXTERN void BZ_API(BZ2_bzReadClose) (
- int* bzerror,
- BZFILE* b
+BZ_EXTERN void BZ_API(BZ2_bzReadClose) (
+ int* bzerror,
+ BZFILE* b
);
-BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) (
- int* bzerror,
- BZFILE* b,
- void** unused,
- int* nUnused
+BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) (
+ int* bzerror,
+ BZFILE* b,
+ void** unused,
+ int* nUnused
);
-BZ_EXTERN int BZ_API(BZ2_bzRead) (
- int* bzerror,
- BZFILE* b,
- void* buf,
- int len
+BZ_EXTERN int BZ_API(BZ2_bzRead) (
+ int* bzerror,
+ BZFILE* b,
+ void* buf,
+ int len
);
-BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) (
- int* bzerror,
- FILE* f,
- int blockSize100k,
- int verbosity,
- int workFactor
+BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) (
+ int* bzerror,
+ FILE* f,
+ int blockSize100k,
+ int verbosity,
+ int workFactor
);
-BZ_EXTERN void BZ_API(BZ2_bzWrite) (
- int* bzerror,
- BZFILE* b,
- void* buf,
- int len
+BZ_EXTERN void BZ_API(BZ2_bzWrite) (
+ int* bzerror,
+ BZFILE* b,
+ void* buf,
+ int len
);
-BZ_EXTERN void BZ_API(BZ2_bzWriteClose) (
- int* bzerror,
- BZFILE* b,
- int abandon,
- unsigned int* nbytes_in,
- unsigned int* nbytes_out
+BZ_EXTERN void BZ_API(BZ2_bzWriteClose) (
+ int* bzerror,
+ BZFILE* b,
+ int abandon,
+ unsigned int* nbytes_in,
+ unsigned int* nbytes_out
);
-BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) (
- int* bzerror,
- BZFILE* b,
- int abandon,
- unsigned int* nbytes_in_lo32,
- unsigned int* nbytes_in_hi32,
- unsigned int* nbytes_out_lo32,
+BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) (
+ int* bzerror,
+ BZFILE* b,
+ int abandon,
+ unsigned int* nbytes_in_lo32,
+ unsigned int* nbytes_in_hi32,
+ unsigned int* nbytes_out_lo32,
unsigned int* nbytes_out_hi32
);
#endif
/*-- Utility functions --*/
-BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) (
- char* dest,
+BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) (
+ char* dest,
unsigned int* destLen,
- char* source,
+ char* source,
unsigned int sourceLen,
- int blockSize100k,
- int verbosity,
- int workFactor
+ int blockSize100k,
+ int verbosity,
+ int workFactor
);
-BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) (
- char* dest,
+BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) (
+ char* dest,
unsigned int* destLen,
- char* source,
+ char* source,
unsigned int sourceLen,
- int small,
- int verbosity
+ int small,
+ int verbosity
);
int fd,
const char *mode
);
-
+
BZ_EXTERN int BZ_API(BZ2_bzread) (
- BZFILE* b,
- void* buf,
- int len
+ BZFILE* b,
+ void* buf,
+ int len
);
BZ_EXTERN int BZ_API(BZ2_bzwrite) (
- BZFILE* b,
- void* buf,
- int len
+ BZFILE* b,
+ void* buf,
+ int len
);
BZ_EXTERN int BZ_API(BZ2_bzflush) (
);
BZ_EXTERN const char * BZ_API(BZ2_bzerror) (
- BZFILE *b,
+ BZFILE *b,
int *errnum
);
#endif
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
#ifndef __GNUC__
#define __inline__ /* */
-#endif
+#endif
#ifndef BZ_NO_STDIO
extern void BZ2_bz__AssertH__fail ( int errcode );
/*-- externs for compression. --*/
-extern void
+extern void
BZ2_blockSort ( EState* );
-extern void
+extern void
BZ2_compressBlock ( EState*, Bool );
-extern void
+extern void
BZ2_bsInitWrite ( EState* );
-extern void
+extern void
BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 );
-extern void
+extern void
BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 );
Int32 save_N;
Int32 save_curr;
Int32 save_zt;
- Int32 save_zn;
+ Int32 save_zn;
Int32 save_zvec;
Int32 save_zj;
Int32 save_gSel;
/*-- externs for decompression. --*/
-extern Int32
+extern Int32
BZ2_indexIntoF ( Int32, Int32* );
-extern Int32
+extern Int32
BZ2_decompress ( DState* );
-extern void
+extern void
BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*,
Int32, Int32, Int32 );
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
0.9.0a/b -- no changes in this file.
0.9.0c
- * changed setting of nGroups in sendMTFValues() so as to
+ * changed setting of nGroups in sendMTFValues() so as to
do a bit better on small files
--*/
Int32 wr;
Int32 EOB;
- /*
+ /*
After sorting (eg, here),
s->arr1 [ 0 .. s->nblock-1 ] holds sorted order,
and
- ((UChar*)s->arr2) [ 0 .. s->nblock-1 ]
+ ((UChar*)s->arr2) [ 0 .. s->nblock-1 ]
holds the original block data.
The first thing to do is generate the MTF values,
(UChar*) (&((UChar*)s->arr2)[s->nblock])
These storage aliases are set up in bzCompressInit(),
- except for the last one, which is arranged in
+ except for the last one, which is arranged in
compressBlock().
*/
UInt32* ptr = s->ptr;
ll_i = s->unseqToSeq[block[j]];
AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" );
- if (yy[0] == ll_i) {
+ if (yy[0] == ll_i) {
zPend++;
} else {
zPend--;
while (True) {
if (zPend & 1) {
- mtfv[wr] = BZ_RUNB; wr++;
- s->mtfFreq[BZ_RUNB]++;
+ mtfv[wr] = BZ_RUNB; wr++;
+ s->mtfFreq[BZ_RUNB]++;
} else {
- mtfv[wr] = BZ_RUNA; wr++;
- s->mtfFreq[BZ_RUNA]++;
+ mtfv[wr] = BZ_RUNA; wr++;
+ s->mtfFreq[BZ_RUNA]++;
}
if (zPend < 2) break;
zPend = (zPend - 2) / 2;
zPend--;
while (True) {
if (zPend & 1) {
- mtfv[wr] = BZ_RUNB; wr++;
- s->mtfFreq[BZ_RUNB]++;
+ mtfv[wr] = BZ_RUNB; wr++;
+ s->mtfFreq[BZ_RUNB]++;
} else {
- mtfv[wr] = BZ_RUNA; wr++;
- s->mtfFreq[BZ_RUNA]++;
+ mtfv[wr] = BZ_RUNA; wr++;
+ s->mtfFreq[BZ_RUNA]++;
}
if (zPend < 2) break;
zPend = (zPend - 2) / 2;
if (s->verbosity >= 3)
VPrintf3( " %d in block, %d after MTF & 1-2 coding, "
- "%d+2 syms in use\n",
+ "%d+2 syms in use\n",
s->nblock, s->nMTF, s->nInUse );
alphaSize = s->nInUse+2;
nGroups = 6;
/*--- Generate an initial set of coding tables ---*/
- {
+ {
Int32 nPart, remF, tFreq, aFreq;
nPart = nGroups;
aFreq += s->mtfFreq[ge];
}
- if (ge > gs
- && nPart != nGroups && nPart != 1
+ if (ge > gs
+ && nPart != nGroups && nPart != 1
&& ((nGroups-nPart) % 2 == 1)) {
aFreq -= s->mtfFreq[ge];
ge--;
if (s->verbosity >= 3)
VPrintf5( " initial group %d, [%d .. %d], "
"has %d syms (%4.1f%%)\n",
- nPart, gs, ge, aFreq,
+ nPart, gs, ge, aFreq,
(100.0 * (float)aFreq) / (float)(s->nMTF) );
-
+
for (v = 0; v < alphaSize; v++)
- if (v >= gs && v <= ge)
+ if (v >= gs && v <= ge)
s->len[nPart-1][v] = BZ_LESSER_ICOST; else
s->len[nPart-1][v] = BZ_GREATER_ICOST;
-
+
nPart--;
gs = ge+1;
remF -= aFreq;
}
}
- /*---
+ /*---
Iterate up to BZ_N_ITERS times to improve the tables.
---*/
for (iter = 0; iter < BZ_N_ITERS; iter++) {
/*---
Set up an auxiliary length table which is used to fast-track
- the common case (nGroups == 6).
+ the common case (nGroups == 6).
---*/
if (nGroups == 6) {
for (v = 0; v < alphaSize; v++) {
/*--- Set group start & end marks. --*/
if (gs >= s->nMTF) break;
- ge = gs + BZ_G_SIZE - 1;
+ ge = gs + BZ_G_SIZE - 1;
if (ge >= s->nMTF) ge = s->nMTF-1;
- /*--
+ /*--
Calculate the cost of this group as coded
by each of the coding tables.
--*/
} else {
/*--- slow version which correctly handles all situations ---*/
- for (i = gs; i <= ge; i++) {
+ for (i = gs; i <= ge; i++) {
UInt16 icv = mtfv[i];
for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv];
}
}
-
- /*--
+
+ /*--
Find the coding table which is best for this group,
and record its identity in the selector table.
--*/
s->selector[nSelectors] = bt;
nSelectors++;
- /*--
+ /*--
Increment the symbol frequencies for the selected table.
--*/
if (nGroups == 6 && 50 == ge-gs+1) {
gs = ge+1;
}
if (s->verbosity >= 3) {
- VPrintf2 ( " pass %d: size is %d, grp uses are ",
+ VPrintf2 ( " pass %d: size is %d, grp uses are ",
iter+1, totc/8 );
for (t = 0; t < nGroups; t++)
VPrintf1 ( "%d ", fave[t] );
Recompute the tables based on the accumulated frequencies.
--*/
for (t = 0; t < nGroups; t++)
- BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]),
+ BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]),
alphaSize, 20 );
}
}
AssertH ( !(maxLen > 20), 3004 );
AssertH ( !(minLen < 1), 3005 );
- BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]),
+ BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]),
minLen, maxLen, alphaSize );
}
/*--- Transmit the mapping table. ---*/
- {
+ {
Bool inUse16[16];
for (i = 0; i < 16; i++) {
inUse16[i] = False;
for (j = 0; j < 16; j++)
if (s->inUse[i * 16 + j]) inUse16[i] = True;
}
-
+
nBytes = s->numZ;
for (i = 0; i < 16; i++)
if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0);
if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0);
}
- if (s->verbosity >= 3)
+ if (s->verbosity >= 3)
VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes );
}
nBytes = s->numZ;
bsW ( s, 3, nGroups );
bsW ( s, 15, nSelectors );
- for (i = 0; i < nSelectors; i++) {
+ for (i = 0; i < nSelectors; i++) {
for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1);
bsW(s,1,0);
}
gs = 0;
while (True) {
if (gs >= s->nMTF) break;
- ge = gs + BZ_G_SIZE - 1;
+ ge = gs + BZ_G_SIZE - 1;
if (ge >= s->nMTF) ge = s->nMTF-1;
AssertH ( s->selector[selCtr] < nGroups, 3006 );
if (nGroups == 6 && 50 == ge-gs+1) {
/*--- fast track the common case ---*/
UInt16 mtfv_i;
- UChar* s_len_sel_selCtr
+ UChar* s_len_sel_selCtr
= &(s->len[s->selector[selCtr]][0]);
Int32* s_code_sel_selCtr
= &(s->code[s->selector[selCtr]][0]);
} else {
/*--- slow version which correctly handles all situations ---*/
for (i = gs; i <= ge; i++) {
- bsW ( s,
+ bsW ( s,
s->len [s->selector[selCtr]] [mtfv[i]],
s->code [s->selector[selCtr]] [mtfv[i]] );
}
/*-- Now the block's CRC, so it is in a known place. --*/
bsPutUInt32 ( s, s->blockCRC );
- /*--
- Now a single bit indicating (non-)randomisation.
+ /*--
+ Now a single bit indicating (non-)randomisation.
As of version 0.9.5, we use a better sorting algorithm
which makes randomisation unnecessary. So always set
the randomised bit to 'no'. Of course, the decoder
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
Int32 N;
Int32 curr;
Int32 zt;
- Int32 zn;
+ Int32 zn;
Int32 zvec;
Int32 zj;
Int32 gSel;
N = s->save_N;
curr = s->save_curr;
zt = s->save_zt;
- zn = s->save_zn;
+ zn = s->save_zn;
zvec = s->save_zvec;
zj = s->save_zj;
gSel = s->save_gSel;
if (uc != 'h') RETURN(BZ_DATA_ERROR_MAGIC);
GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)
- if (s->blockSize100k < '1' ||
+ if (s->blockSize100k < '1' ||
s->blockSize100k > '9') RETURN(BZ_DATA_ERROR_MAGIC);
s->blockSize100k -= '0';
if (s->smallDecompress) {
s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );
- s->ll4 = BZALLOC(
- ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar)
+ s->ll4 = BZALLOC(
+ ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar)
);
if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);
} else {
s->currBlockNo++;
if (s->verbosity >= 2)
VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo );
-
+
s->storedBlockCRC = 0;
GET_UCHAR(BZ_X_BCRC_1, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
if (s->origPtr < 0)
RETURN(BZ_DATA_ERROR);
- if (s->origPtr > 10 + 100000*s->blockSize100k)
+ if (s->origPtr > 10 + 100000*s->blockSize100k)
RETURN(BZ_DATA_ERROR);
/*--- Receive the mapping table ---*/
for (i = 0; i < 16; i++) {
GET_BIT(BZ_X_MAPPING_1, uc);
- if (uc == 1)
- s->inUse16[i] = True; else
+ if (uc == 1)
+ s->inUse16[i] = True; else
s->inUse16[i] = False;
}
{
UChar pos[BZ_N_GROUPS], tmp, v;
for (v = 0; v < nGroups; v++) pos[v] = v;
-
+
for (i = 0; i < nSelectors; i++) {
v = s->selectorMtf[i];
tmp = pos[v];
if (s->len[t][i] > maxLen) maxLen = s->len[t][i];
if (s->len[t][i] < minLen) minLen = s->len[t][i];
}
- BZ2_hbCreateDecodeTables (
- &(s->limit[t][0]),
- &(s->base[t][0]),
- &(s->perm[t][0]),
+ BZ2_hbCreateDecodeTables (
+ &(s->limit[t][0]),
+ &(s->base[t][0]),
+ &(s->perm[t][0]),
&(s->len[t][0]),
minLen, maxLen, alphaSize
);
s->mtfa[(z)-3] = s->mtfa[(z)-4];
nn -= 4;
}
- while (nn > 0) {
- s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--;
+ while (nn > 0) {
+ s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--;
};
s->mtfa[pp] = uc;
- } else {
+ } else {
/* general case */
lno = nn / MTFL_SIZE;
off = nn % MTFL_SIZE;
pp = s->mtfbase[lno] + off;
uc = s->mtfa[pp];
- while (pp > s->mtfbase[lno]) {
- s->mtfa[pp] = s->mtfa[pp-1]; pp--;
+ while (pp > s->mtfbase[lno]) {
+ s->mtfa[pp] = s->mtfa[pp-1]; pp--;
};
s->mtfbase[lno]++;
while (lno > 0) {
s->mtfbase[lno]--;
- s->mtfa[s->mtfbase[lno]]
+ s->mtfa[s->mtfbase[lno]]
= s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];
lno--;
}
if (s->blockRandomised) {
BZ_RAND_INIT_MASK;
BZ_GET_SMALL(s->k0); s->nblock_used++;
- BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
+ BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
} else {
BZ_GET_SMALL(s->k0); s->nblock_used++;
}
if (s->blockRandomised) {
BZ_RAND_INIT_MASK;
BZ_GET_FAST(s->k0); s->nblock_used++;
- BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
+ BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
} else {
BZ_GET_FAST(s->k0); s->nblock_used++;
}
s->save_gBase = gBase;
s->save_gPerm = gPerm;
- return retVal;
+ return retVal;
}
#ifdef _WIN32
-#define BZ2_LIBNAME "libbz2-1.0.0.DLL"
+#define BZ2_LIBNAME "libbz2-1.0.0.DLL"
#include <windows.h>
static int BZ2DLLLoaded = 0;
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
/*---------------------------------------------------*/
-void BZ2_hbMakeCodeLengths ( UChar *len,
+void BZ2_hbMakeCodeLengths ( UChar *len,
Int32 *freq,
Int32 alphaSize,
Int32 maxLen )
Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ];
Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ];
- Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ];
+ Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ];
for (i = 0; i < alphaSize; i++)
weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
}
AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 );
-
+
while (nHeap > 1) {
n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
len[i-1] = j;
if (j > maxLen) tooLong = True;
}
-
+
if (! tooLong) break;
for (i = 1; i < alphaSize; i++) {
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 2. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
- 4. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior written
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
/*---------------------------------------------*/
-Int32 BZ2_rNums[512] = {
- 619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
- 985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
- 733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
- 419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
- 878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
- 862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
- 150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
- 170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
- 73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
- 909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
- 641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
- 161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
- 382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
- 98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
- 227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
- 469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
- 184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
- 715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
- 951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
- 652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
- 645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
- 609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
- 653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
- 411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
- 170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
- 857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
- 669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
- 944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
- 344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
- 897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
- 433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
- 686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
- 946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
- 978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
- 680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
- 707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
- 297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
- 134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
- 343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
- 140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
- 170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
- 369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
- 804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
- 896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
- 661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
- 768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
- 61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
- 372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
- 780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
- 920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
- 645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
+Int32 BZ2_rNums[512] = {
+ 619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
+ 985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
+ 733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
+ 419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
+ 878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
+ 862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
+ 150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
+ 170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
+ 73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
+ 909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
+ 641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
+ 161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
+ 382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
+ 98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
+ 227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
+ 469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
+ 184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
+ 715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
+ 951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
+ 652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
+ 645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
+ 609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
+ 653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
+ 411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
+ 170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
+ 857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
+ 669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
+ 944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
+ 344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
+ 897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
+ 433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
+ 686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
+ 946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
+ 978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
+ 680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
+ 707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
+ 297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
+ 134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
+ 343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
+ 140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
+ 170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
+ 369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
+ 804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
+ 896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
+ 661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
+ 768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
+ 61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
+ 372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
+ 780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
+ 920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
+ 645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
936, 638
};
support for large files (> 2GB) in a reasonable amount of time.
I suggest you use the undocumented --exponential option to
bzip2 when compressing the resulting file; this saves a bit of
- time. Note: *don't* bother with --exponential when compressing
+ time. Note: *don't* bother with --exponential when compressing
Real Files; it'll just waste a lot of CPU time :-)
(but is otherwise harmless).
*/
/* A test program written to test robustness to decompression of
- corrupted data. Usage is
+ corrupted data. Usage is
unzcrash filename
and the program will read the specified file, compress it (in memory),
and then repeatedly decompress it, each time with a different bit of
the compressed data inverted, so as to test all possible one-bit errors.
- This should not cause any invalid memory accesses. If it does,
+ This should not cause any invalid memory accesses. If it does,
I want to know about it!
p.s. As you can see from the above description, the process is
return 1;
} else {
for (i = 0; i < nOut; i++)
- if (inbuf[i] != outbuf[i]) {
- fprintf(stderr, "mismatch at %d\n", i );
- return 1;
+ if (inbuf[i] != outbuf[i]) {
+ fprintf(stderr, "mismatch at %d\n", i );
+ return 1;
}
if (i == nOut) fprintf(stderr, "really ok!\n" );
}
*
* There are a couple of subtle races that this library is designed to avoid.
* Please read the code (particularly IoCsqInsertIrpEx and IoCsqRemoveIrp) for
- * some details.
+ * some details.
*
- * In general, we try here to avoid the race between these queue/dequeue
+ * In general, we try here to avoid the race between these queue/dequeue
* interfaces and our own cancel routine. This library supplies a cancel
* routine that is used in all IRPs that are queued to it. The major race
* conditions surround the proper handling of in-between cases, such as in-progress
{
PIO_CSQ_IRP_CONTEXT Context = (PIO_CSQ_IRP_CONTEXT)Csq;
Csq = Context->Csq;
-
+
/* clean up context while we're here */
Context->Irp = NULL;
}
* 2) We get an IRP, and the IO manager cancels it before we're done here
* 3) We get an IRP, queue it, and the IO manager cancels it.
*
- * #2 is is a booger.
+ * #2 is is a booger.
*
* When the IO manger receives a request to cancel an IRP, it sets the cancel
* bit in the IRP's control byte to TRUE. Then, it looks to see if a cancel
*
* If we set a routine first and then test for cancel, we race with our completion
* routine: We set the routine, the IO Manager sets cancel, we test cancel and find
- * it is TRUE. Meanwhile the IO manager has called our cancel routine already, so
+ * it is TRUE. Meanwhile the IO manager has called our cancel routine already, so
* we can't complete the IRP because it'll rip it out from under the cancel routine.
*
* The IO manager does us a favor though: it nulls out the cancel routine in the IRP
* We have to go through all of this mess because this API guarantees that we will
* never return having left a canceled IRP in the queue.
*/
-
+
/* Step 1: Queue the IRP */
if(Csq->Type == IO_TYPE_CSQ)
Csq->CsqInsertIrp(Csq, Irp);
if(!Irp->Cancel)
break;
- /*
- * Since we're canceled, see if our cancel routine is already running
- * If this is NULL, the IO Manager has already called our cancel routine
+ /*
+ * Since we're canceled, see if our cancel routine is already running
+ * If this is NULL, the IO Manager has already called our cancel routine
*/
if(!IoSetCancelRoutine(Irp, NULL))
break;
/* OK, looks like we have to de-queue and complete this ourselves */
Csq->CsqRemoveIrp(Csq, Irp);
Csq->CsqCompleteCanceledIrp(Csq, Irp);
-
+
if(Context)
Context->Irp = NULL;
}
* RETURNS:
* - Pointer to an IRP if we found it
* NOTES:
- * - Don't forget that we can be canceled any time up to the point
+ * - Don't forget that we can be canceled any time up to the point
* where we unset our cancel routine
*/
{
/* Unset the cancel routine and see if it has already been canceled */
if(!IoSetCancelRoutine(Irp, NULL))
{
- /*
+ /*
* already gone, return NULL --> NOTE that we cannot touch this IRP *or* the context,
* since the context is being simultaneously twiddled by the cancel routine
- */
+ */
Irp = NULL;
break;
}
while((Irp = Csq->CsqPeekNextIrp(Csq, Irp, PeekContext)))
{
- /*
+ /*
* If the cancel routine is gone, we're already canceled,
* and are spinning on the queue lock in our own cancel
* routine. Move on to the next candidate. It'll get
if(Context && Context->Type == IO_TYPE_CSQ_IRP_CONTEXT)
Context->Irp = NULL;
-
+
break;
}
switch (Address->Type) {
case IP_ADDRESS_V4:
ip = DN2H(Address->Address.IPv4Address);
- sprintf(p, "%d.%d.%d.%d",
- (INT)((ip >> 24) & 0xFF),
- (INT)((ip >> 16) & 0xFF),
- (INT)((ip >> 8) & 0xFF),
+ sprintf(p, "%d.%d.%d.%d",
+ (INT)((ip >> 24) & 0xFF),
+ (INT)((ip >> 16) & 0xFF),
+ (INT)((ip >> 8) & 0xFF),
(INT)(ip & 0xFF));
break;
-
+
case IP_ADDRESS_V6:
/* FIXME: IPv6 is not supported */
strcpy(p, "(IPv6 address not supported)");
}
ULONG IPv4NToHl( ULONG Address ) {
- return
+ return
((Address & 0xff) << 24) |
((Address & 0xff00) << 8) |
((Address >> 8) & 0xff00) |
UINT Prefix = 0;
if( Netmask->Type == IP_ADDRESS_V4 ) {
ULONG BitTest = 0x80000000;
-
+
/* The mask has been read in network order. Put it in host order
* in order to scan it. */
ULONG TestMask = IPv4NToHl(Netmask->Address.IPv4Address);
-
+
while( (BitTest & TestMask) == BitTest ) {
Prefix++;
BitTest >>= 1;
}
return Prefix;
} else {
- TI_DbgPrint(DEBUG_DATALINK, ("Don't know address type %d\n",
+ TI_DbgPrint(DEBUG_DATALINK, ("Don't know address type %d\n",
Netmask->Type));
return 0;
}
}
-VOID AddrWidenAddress( PIP_ADDRESS Network, PIP_ADDRESS Source,
+VOID AddrWidenAddress( PIP_ADDRESS Network, PIP_ADDRESS Source,
PIP_ADDRESS Netmask ) {
if( Netmask->Type == IP_ADDRESS_V4 ) {
Network->Type = Netmask->Type;
- Network->Address.IPv4Address =
+ Network->Address.IPv4Address =
Source->Address.IPv4Address & Netmask->Address.IPv4Address;
} else {
- TI_DbgPrint(DEBUG_DATALINK, ("Don't know address type %d\n",
+ TI_DbgPrint(DEBUG_DATALINK, ("Don't know address type %d\n",
Netmask->Type));
*Network = *Source;
- }
+ }
}
VOID IPAddressFree(
}
if (TdiAddress->AddressLength < TDI_ADDRESS_LENGTH_IP) {
TI_DbgPrint
- (MID_TRACE,("AddressLength %x, Not valid (expected %x)\n",
+ (MID_TRACE,("AddressLength %x, Not valid (expected %x)\n",
TdiAddress->AddressLength, TDI_ADDRESS_LENGTH_IP));
return STATUS_INVALID_ADDRESS;
}
/*
* Convert an ansi string dotted-quad address to a ulong
* NOTES:
- * - this isn't quite like the real inet_addr() - * it doesn't
+ * - this isn't quite like the real inet_addr() - * it doesn't
* handle "10.1" and similar - but it's good enough.
* - Returns in *host* byte order, unlike real inet_addr()
*/
/* Prepare ARP packet */
Size = MaxLLHeaderSize +
- sizeof(ARP_HEADER) +
+ sizeof(ARP_HEADER) +
2 * LinkAddressLength + /* Hardware address length */
2 * ProtoAddressLength; /* Protocol address length */
Size = MAX(Size, MinLLFrameSize);
PC(NdisPacket)->DLComplete = ARPTransmitComplete;
TI_DbgPrint(DEBUG_ARP,("Sending ARP Packet\n"));
-
+
(*Interface->Transmit)(Interface->Context, NdisPacket,
MaxLLHeaderSize, NULL, LAN_PROTO_ARP);
TargetProtoAddress = (PVOID)((ULONG_PTR)SenderProtoAddress +
Header->ProtoAddrLen + Header->HWAddrLen);
- if( !AddrLocateADEv4( *((PIPv4_RAW_ADDRESS)TargetProtoAddress),
+ if( !AddrLocateADEv4( *((PIPv4_RAW_ADDRESS)TargetProtoAddress),
&Address) ) {
TI_DbgPrint(DEBUG_ARP, ("Target address (0x%X) is not mine.\n", *((PULONG)TargetProtoAddress)));
return;
AddrInitIPv4(&Address, *((PULONG)SenderProtoAddress));
NCE = NBLocateNeighbor(&Address);
if (NCE) {
- /* We know the sender. Update the hardware address
+ /* We know the sender. Update the hardware address
and state in our neighbor address cache */
NBUpdateNeighbor(NCE, SenderHWAddress, NUD_REACHABLE);
} else {
/* Allocate NDIS packet */
NdisStatus = AllocatePacketWithBuffer( &NdisPacket, NULL, Size );
-
+
if( !NT_SUCCESS(NdisStatus) ) return NULL;
IPPacket->NdisPacket = NdisPacket;
- GetDataPtr( IPPacket->NdisPacket, MaxLLHeaderSize,
+ GetDataPtr( IPPacket->NdisPacket, MaxLLHeaderSize,
(PCHAR *)&IPPacket->Header, &IPPacket->ContigSize );
IPPacket->Data = ((PCHAR)IPPacket->Header) + IPPacket->HeaderSize;
TI_DbgPrint(MID_TRACE,("Leaving\n"));
-
+
return IPPacket;
}
break;
default:
- TI_DbgPrint(DEBUG_ICMP,
+ TI_DbgPrint(DEBUG_ICMP,
("Discarded ICMP datagram of unknown type %d.\n",
ICMPHeader->Type));
/* Discard packet */
PayloadSize = 576;
DataSize = PayloadSize + sizeof(ICMP_HEADER);
}
-
- if( !PrepareICMPPacket(Interface, &NewPacket, &IPPacket->SrcAddr,
+
+ if( !PrepareICMPPacket(Interface, &NewPacket, &IPPacket->SrcAddr,
IPPacket->Data, DataSize) ) return;
((PICMP_HEADER)NewPacket.Data)->Type = Type;
#include "precomp.h"
-NTSTATUS GetInterfaceIPv4Address( PIP_INTERFACE Interface,
+NTSTATUS GetInterfaceIPv4Address( PIP_INTERFACE Interface,
ULONG TargetType,
PULONG Address ) {
switch( TargetType ) {
IF_LIST_ITER(CurrentIF);
TcpipAcquireSpinLock(&InterfaceListLock, &OldIrql);
-
+
ForEachInterface(CurrentIF) {
Count++;
} EndFor(CurrentIF);
PLAN_ADAPTER IF = (PLAN_ADAPTER)Interface->Context;
*Speed = IF->Speed;
-
+
return STATUS_SUCCESS;
}
-NTSTATUS GetInterfaceName( PIP_INTERFACE Interface,
+NTSTATUS GetInterfaceName( PIP_INTERFACE Interface,
PCHAR NameBuffer,
UINT Len ) {
ULONG ResultSize = 0;
- NTSTATUS Status =
- RtlUnicodeToMultiByteN( NameBuffer,
- Len,
- &ResultSize,
+ NTSTATUS Status =
+ RtlUnicodeToMultiByteN( NameBuffer,
+ Len,
+ &ResultSize,
Interface->Name.Buffer,
Interface->Name.Length );
-
- if( NT_SUCCESS(Status) )
+
+ if( NT_SUCCESS(Status) )
NameBuffer[ResultSize] = 0;
else
NameBuffer[0] = 0;
IF_LIST_ITER(CurrentIF);
TcpipAcquireSpinLock(&InterfaceListLock, &OldIrql);
-
+
ForEachInterface(CurrentIF) {
if( AddrIsEqualIPv4( &CurrentIF->Unicast, MatchAddress ) ) {
Address->Address.IPv4Address = MatchAddress;
if (*pAddress++ != *pPrefix++)
return FALSE;
Length -= 8;
- }
+ }
/* Check any remaining bits */
if ((Length > 0) && ((*pAddress >> (8 - Length)) != (*pPrefix >> (8 - Length))))
{
/* FIXME: Is this needed? */
RtlZeroMemory(IPPacket, sizeof(IP_PACKET));
-
+
INIT_TAG(IPPacket, TAG('I','P','K','T'));
-
+
IPPacket->Free = DontFreePacket;
IPPacket->Type = Type;
-
+
return IPPacket;
}
/* Check if datagram fragments have taken too long to assemble */
IPDatagramReassemblyTimeout();
-
+
/* Clean possible outdated cached neighbor addresses */
NBTimeout();
-
+
/* Call upper layer timeout routines */
TCPTimeout();
}
(*ProtocolTable[Protocol])(Interface, IPPacket);
/* Special case for ICMP -- ICMP can be caught by a SOCK_RAW but also
* must be handled here. */
- if( Protocol == IPPROTO_ICMP )
+ if( Protocol == IPPROTO_ICMP )
ICMPReceive( Interface, IPPacket );
}
IP_ADDRESS NetworkAddress;
/* Add a permanent neighbor for this NTE */
- NCE = NBAddNeighbor(IF, &IF->Unicast,
- IF->Address, IF->AddressLength,
+ NCE = NBAddNeighbor(IF, &IF->Unicast,
+ IF->Address, IF->AddressLength,
NUD_PERMANENT);
if (!NCE) {
TI_DbgPrint(MIN_TRACE, ("Could not create NCE.\n"));
}
-
+
AddrWidenAddress( &NetworkAddress, &IF->Unicast, &IF->Netmask );
if (!RouterAddRoute(&NetworkAddress, &IF->Netmask, NCE, 1)) {
}
} EndFor(Interface);
} while( !IndexHasBeenChosen );
-
+
IF->Index = ChosenIndex;
IPAddInterfaceRoute( IF );
-
+
/* Add interface to the global interface list */
- TcpipInterlockedInsertTailList(&InterfaceListHead,
- &IF->ListEntry,
+ TcpipInterlockedInsertTailList(&InterfaceListHead,
+ &IF->ListEntry,
&InterfaceListLock);
TcpipReleaseSpinLock(&IF->Lock, OldIrql);
AddrWidenAddress(&GeneralRoute,&IF->Unicast,&IF->Netmask);
RouterRemoveRoute(&GeneralRoute, &IF->Unicast);
-
+
/* Remove permanent NCE, but first we have to find it */
NCE = NBLocateNeighbor(&IF->Unicast);
if (NCE)
IP_PACKET IPPacket;
TI_DbgPrint(DEBUG_DATALINK, ("Called.\n"));
-
- while( (ListEntry =
+
+ while( (ListEntry =
ExInterlockedRemoveHeadList( &LoopWorkList, &LoopWorkLock )) ) {
WorkItem = CONTAINING_RECORD(ListEntry, LAN_WQ_ITEM, ListEntry);
LoopReceiveWorkerBusy = FALSE;
}
-VOID LoopSubmitReceiveWork(
+VOID LoopSubmitReceiveWork(
NDIS_HANDLE BindingContext,
PNDIS_PACKET Packet,
NDIS_STATUS Status,
KIRQL OldIrql;
TcpipAcquireSpinLock( &LoopWorkLock, &OldIrql );
-
+
WQItem = ExAllocatePool( NonPagedPool, sizeof(LAN_WQ_ITEM) );
if( !WQItem ) {
TcpipReleaseSpinLock( &LoopWorkLock, OldIrql );
ASSERT_KM_POINTER(NdisPacket);
ASSERT_KM_POINTER(PC(NdisPacket));
ASSERT_KM_POINTER(PC(NdisPacket)->DLComplete);
-
+
TI_DbgPrint(MAX_TRACE, ("Called (NdisPacket = %x)\n", NdisPacket));
GetDataPtr( NdisPacket, MaxLLHeaderSize, &PacketBuffer, &PacketLength );
InitializeListHead( &LoopWorkList );
ExInitializeWorkItem( &LoopWorkItem, LoopReceiveWorker, NULL );
-
+
/* Bind the adapter to network (IP) layer */
BindInfo.Context = NULL;
BindInfo.HeaderSize = 0;
BindInfo.Address = NULL;
BindInfo.AddressLength = 0;
BindInfo.Transmit = LoopTransmit;
-
+
Loopback = IPCreateInterface(&BindInfo);
-
+
Loopback->Name.Buffer = L"Loopback";
- Loopback->Name.MaximumLength = Loopback->Name.Length =
+ Loopback->Name.MaximumLength = Loopback->Name.Length =
wcslen(Loopback->Name.Buffer) * sizeof(WCHAR);
AddrInitIPv4(&Loopback->Unicast, LOOPBACK_ADDRESS_IPv4);
AddrInitIPv4(&Loopback->Netmask, LOOPBACK_ADDRMASK_IPv4);
-
+
IPRegisterInterface(Loopback);
TI_DbgPrint(MAX_TRACE, ("Leaving.\n"));
InitializeListHead( &AllocatedObjectsList );
}
-VOID ShowTrackedThing( PCHAR What, PALLOCATION_TRACKER Thing,
+VOID ShowTrackedThing( PCHAR What, PALLOCATION_TRACKER Thing,
PCHAR File, UINT Line ) {
/* if( ShowTag( Thing->Tag ) ) */
if( File ) {
- TI_DbgPrint(MAX_TRACE,
- ("[%s] Thing %08x %c%c%c%c (%s:%d) (Called from %s:%d)\n",
+ TI_DbgPrint(MAX_TRACE,
+ ("[%s] Thing %08x %c%c%c%c (%s:%d) (Called from %s:%d)\n",
What,
Thing->Thing,
((PCHAR)&Thing->Tag)[3],
File, Line));
} else {
TI_DbgPrint(MAX_TRACE,
- ( "[%s] Thing %08x %c%c%c%c (%s:%d)\n",
+ ( "[%s] Thing %08x %c%c%c%c (%s:%d)\n",
What,
Thing->Thing,
((PCHAR)&Thing->Tag)[3],
}
VOID TrackWithTag( DWORD Tag, PVOID Thing, PCHAR FileName, DWORD LineNo ) {
- PALLOCATION_TRACKER TrackedThing =
+ PALLOCATION_TRACKER TrackedThing =
PoolAllocateBuffer( sizeof(*TrackedThing) );
KIRQL OldIrql;
ThingInList = CONTAINING_RECORD(Entry, ALLOCATION_TRACKER, Entry);
if( ThingInList->Thing == Thing ) {
RemoveEntryList(Entry);
-
+
TcpipReleaseSpinLock( &AllocatedObjectsLock, OldIrql );
ShowTrackedThing( "Alloc", ThingInList, FileName, LineNo );
PoolFreeBuffer( ThingInList );
TrackedThing->Thing = Thing;
TrackedThing->FileName = FileName;
TrackedThing->LineNo = LineNo;
-
-
+
+
InsertTailList( &AllocatedObjectsList, &TrackedThing->Entry );
ShowTrackedThing( "Alloc", TrackedThing, FileName, LineNo );
}
UINT i;
for( i = 0; TagsToShow[i] && TagsToShow[i] != Tag; i++ );
-
+
return TagsToShow[i] ? TRUE : FALSE;
}
ThingInList = CONTAINING_RECORD(Entry, ALLOCATION_TRACKER, Entry);
if( ThingInList->Thing == Thing ) {
RemoveEntryList(Entry);
-
+
ShowTrackedThing( "Free ", ThingInList, File, Line );
-
+
PoolFreeBuffer( ThingInList );
TcpipReleaseSpinLock( &AllocatedObjectsLock, OldIrql );
/* TrackDumpFL( File, Line ); */
NEIGHBOR_CACHE_TABLE NeighborCache[NB_HASHMASK + 1];
-VOID NBCompleteSend( PVOID Context,
- PNDIS_PACKET NdisPacket,
+VOID NBCompleteSend( PVOID Context,
+ PNDIS_PACKET NdisPacket,
NDIS_STATUS Status ) {
PNEIGHBOR_PACKET Packet = (PNEIGHBOR_PACKET)Context;
TI_DbgPrint(MID_TRACE, ("Called\n"));
ASSERT_KM_POINTER(Packet);
ASSERT_KM_POINTER(Packet->Complete);
Packet->Complete( Packet->Context, Packet->Packet, STATUS_SUCCESS );
- TI_DbgPrint(MID_TRACE, ("Completed\n"));
+ TI_DbgPrint(MID_TRACE, ("Completed\n"));
PoolFreeBuffer( Packet );
TI_DbgPrint(MID_TRACE, ("Freed\n"));
}
TI_DbgPrint
(MID_TRACE,
- ("PacketEntry: %x, NdisPacket %x\n",
+ ("PacketEntry: %x, NdisPacket %x\n",
PacketEntry, Packet->Packet));
PC(Packet->Packet)->DLComplete = NBCompleteSend;
}
/* Must be called with table lock acquired */
-VOID NBFlushPacketQueue( PNEIGHBOR_CACHE_ENTRY NCE,
+VOID NBFlushPacketQueue( PNEIGHBOR_CACHE_ENTRY NCE,
BOOL CallComplete,
NTSTATUS ErrorCode ) {
PLIST_ENTRY PacketEntry;
PNEIGHBOR_PACKET Packet;
-
+
while( !IsListEmpty(&NCE->PacketQueue) ) {
PacketEntry = RemoveHeadList(&NCE->PacketQueue);
Packet = CONTAINING_RECORD
( PacketEntry, NEIGHBOR_PACKET, Next );
ASSERT_KM_POINTER(Packet);
-
+
TI_DbgPrint
(MID_TRACE,
- ("PacketEntry: %x, NdisPacket %x\n",
+ ("PacketEntry: %x, NdisPacket %x\n",
PacketEntry, Packet->Packet));
if( CallComplete )
Packet->Packet,
NDIS_STATUS_REQUEST_ABORTED );
}
-
+
PoolFreeBuffer( Packet );
}
}
{
TI_DbgPrint(DEBUG_NCACHE, ("Called. NCE (0x%X).\n", NCE));
TI_DbgPrint(DEBUG_NCACHE, ("NCE->State is (0x%X).\n", NCE->State));
-
+
switch (NCE->State)
{
case NUD_INCOMPLETE:
if (NCE->EventCount++ > MAX_MULTICAST_SOLICIT)
{
/* We have retransmitted too many times */
-
+
/* Calling IPSendComplete with cache lock held is not
a great thing to do. We don't get here very often
so maybe it's not that big a problem */
-
+
/* Flush packet queue */
NBFlushPacketQueue( NCE, TRUE, NDIS_STATUS_REQUEST_ABORTED );
NCE->EventCount = 0;
NBSendSolicit(NCE);
}
break;
-
+
case NUD_DELAY:
/* FIXME: Delayed state */
TI_DbgPrint(DEBUG_NCACHE, ("NCE delay state.\n"));
break;
-
+
case NUD_PROBE:
/* FIXME: Probe state */
TI_DbgPrint(DEBUG_NCACHE, ("NCE probe state.\n"));
*/
{
UINT i;
-
+
TI_DbgPrint(DEBUG_NCACHE, ("Called.\n"));
-
+
for (i = 0; i <= NB_HASHMASK; i++) {
NeighborCache[i].Cache = NULL;
TcpipInitializeSpinLock(&NeighborCache[i].Lock);
*/
{
TI_DbgPrint(DEBUG_NCACHE, ("Called. NCE (0x%X).\n", NCE));
-
+
if (NCE->State == NUD_INCOMPLETE)
{
/* This is the first solicitation of this neighbor. Broadcast
a request for the neighbor */
-
+
TI_DbgPrint(MID_TRACE,("NCE: %x\n", NCE));
ARPTransmit(&NCE->Address, NCE->Interface);
KIRQL OldIrql;
TI_DbgPrint
- (DEBUG_NCACHE,
+ (DEBUG_NCACHE,
("Called. Interface (0x%X) Address (0x%X) "
"LinkAddress (0x%X) LinkAddressLength (%d) State (0x%X)\n",
Interface, Address, LinkAddress, LinkAddressLength, State));
NCE->Table = &NeighborCache[HashValue];
TcpipAcquireSpinLock(&NeighborCache[HashValue].Lock, &OldIrql);
-
+
NCE->Next = NeighborCache[HashValue].Cache;
NeighborCache[HashValue].Cache = NCE;
*/
{
KIRQL OldIrql;
-
+
TI_DbgPrint(DEBUG_NCACHE, ("Called. NCE (0x%X) LinkAddress (0x%X) State (0x%X).\n", NCE, LinkAddress, State));
-
+
TcpipAcquireSpinLock(&NCE->Table->Lock, &OldIrql);
-
+
RtlCopyMemory(NCE->LinkAddress, LinkAddress, NCE->LinkAddressLength);
NCE->State = State;
-
+
TcpipReleaseSpinLock(&NCE->Table->Lock, OldIrql);
-
+
if( NCE->State & NUD_CONNECTED )
NBSendPackets( NCE );
}
NCE->EventTimer = 0;
NCE->EventCount = 0;
} else {
- NCE = NBAddNeighbor(Interface, Address, NULL,
+ NCE = NBAddNeighbor(Interface, Address, NULL,
Interface->AddressLength, NUD_INCOMPLETE);
NCE->EventTimer = 1;
NCE->EventCount = 0;
PKSPIN_LOCK Lock;
KIRQL OldIrql;
PNEIGHBOR_PACKET Packet;
-
+
TI_DbgPrint
- (DEBUG_NCACHE,
+ (DEBUG_NCACHE,
("Called. NCE (0x%X) NdisPacket (0x%X).\n", NCE, NdisPacket));
Packet = PoolAllocateBuffer( sizeof(NEIGHBOR_PACKET) );
#include "precomp.h"
-VOID PortsStartup( PPORT_SET PortSet,
+VOID PortsStartup( PPORT_SET PortSet,
UINT StartingPort,
UINT PortsToManage ) {
PortSet->StartingPort = StartingPort;
PortSet->PortsToOversee = PortsToManage;
- PortSet->ProtoBitBuffer =
+ PortSet->ProtoBitBuffer =
PoolAllocateBuffer( (PortSet->PortsToOversee + 7) / 8 );
- RtlInitializeBitMap( &PortSet->ProtoBitmap,
+ RtlInitializeBitMap( &PortSet->ProtoBitmap,
PortSet->ProtoBitBuffer,
PortSet->PortsToOversee );
RtlClearAllBits( &PortSet->ProtoBitmap );
NPAGED_LOOKASIDE_LIST IPFragmentList;
NPAGED_LOOKASIDE_LIST IPHoleList;
-VOID ReflectPacketComplete(
- PVOID Context,
- PNDIS_PACKET Packet,
+VOID ReflectPacketComplete(
+ PVOID Context,
+ PNDIS_PACKET Packet,
NDIS_STATUS Status ) {
}
}
/* Copy the header into the buffer */
- RtlCopyMemory(IPPacket->Header, &IPDR->IPv4Header, IPDR->HeaderSize);
-
+ RtlCopyMemory(IPPacket->Header, &IPDR->IPv4Header, IPDR->HeaderSize);
+
Data = IPPacket->Header + IPDR->HeaderSize;
IPPacket->Data = Data;
/* Position here is an offset from the NdisPacket start, not the header */
TI_DbgPrint(DEBUG_IP, ("Fragment data buffer allocated at (0x%X) Size (%d) Pos (%d).\n",
Fragment->Data, Fragment->Size, IPPacket->Position));
-
+
/* Copy datagram data into fragment buffer */
CopyPacketToBuffer(Fragment->Data,
IPPacket->NdisPacket,
IPPacket->Position,
Fragment->Size);
Fragment->Offset = FragFirst;
-
+
/* If this is the last fragment, compute and save the datagram data size */
if (!MoreFragments)
IPDR->DataSize = FragFirst + Fragment->Size;
*/
{
TI_DbgPrint(DEBUG_IP, ("Received IPv4 datagram.\n"));
-
+
IPPacket->HeaderSize = (((PIPv4_HEADER)IPPacket->Header)->VerIHL & 0x0F) << 2;
TI_DbgPrint(DEBUG_IP, ("IPPacket->HeaderSize = %d\n", IPPacket->HeaderSize));
if (IPPacket->HeaderSize > IPv4_MAX_HEADER_SIZE) {
TI_DbgPrint
- (MIN_TRACE,
+ (MIN_TRACE,
("Datagram received with incorrect header size (%d).\n",
IPPacket->HeaderSize));
/* Discard packet */
return;
}
-
+
/* Checksum IPv4 header */
if (!IPv4CorrectChecksum(IPPacket->Header, IPPacket->HeaderSize)) {
TI_DbgPrint
- (MIN_TRACE,
+ (MIN_TRACE,
("Datagram received with bad checksum. Checksum field (0x%X)\n",
WN2H(((PIPv4_HEADER)IPPacket->Header)->Checksum)));
/* Discard packet */
return;
}
-
+
IPPacket->TotalSize = WN2H(((PIPv4_HEADER)IPPacket->Header)->TotalLength);
-
+
AddrInitIPv4(&IPPacket->SrcAddr, ((PIPv4_HEADER)IPPacket->Header)->SrcAddr);
AddrInitIPv4(&IPPacket->DstAddr, ((PIPv4_HEADER)IPPacket->Header)->DstAddr);
-
+
IPPacket->Position += IPPacket->HeaderSize;
IPPacket->Data = (PVOID)((ULONG_PTR)IPPacket->Header + IPPacket->HeaderSize);
-
+
TI_DbgPrint(MID_TRACE,("IPPacket->Position = %d\n",
IPPacket->Position));
//OskitDumpBuffer(IPPacket->Header, IPPacket->TotalSize);
/* FIXME: Possibly forward packets with multicast addresses */
-
+
/* FIXME: Should we allow packets to be received on the wrong interface? */
/* XXX Find out if this packet is destined for us */
ProcessFragment(IF, IPPacket);
} else {
/* This packet is not destined for us. If we are a router,
try to find a route and forward the packet */
-
+
/* FIXME: Check if acting as a router */
NCE = NULL;
if (NCE) {
} else {
TI_DbgPrint(MIN_TRACE, ("No route to destination (0x%X).\n",
IPPacket->DstAddr.Address.IPv4Address));
-
+
/* FIXME: Send ICMP error code */
}
}
FibCount++;
}
- return FibCount;
+ return FibCount;
}
"Router (0x%X) Metric (%d).\n", NetworkAddress, Netmask, Router, Metric));
TI_DbgPrint(DEBUG_ROUTER, ("NetworkAddress (%s) Netmask (%s) Router (%s).\n",
- A2S(NetworkAddress),
- A2S(Netmask),
+ A2S(NetworkAddress),
+ A2S(Netmask),
A2S(&Router->Address)));
FIBE = PoolAllocateBuffer(sizeof(FIB_ENTRY));
INIT_TAG(Router, TAG('R','O','U','T'));
- RtlCopyMemory( &FIBE->NetworkAddress, NetworkAddress,
+ RtlCopyMemory( &FIBE->NetworkAddress, NetworkAddress,
sizeof(FIBE->NetworkAddress) );
- RtlCopyMemory( &FIBE->Netmask, Netmask,
+ RtlCopyMemory( &FIBE->Netmask, Netmask,
sizeof(FIBE->Netmask) );
FIBE->Router = Router;
FIBE->Metric = Metric;
Length = CommonPrefixLength(Destination, &Current->NetworkAddress);
MaskLength = AddrCountPrefixBits(&Current->Netmask);
- TI_DbgPrint(DEBUG_ROUTER,("This-Route: %s (Sharing %d bits)\n",
+ TI_DbgPrint(DEBUG_ROUTER,("This-Route: %s (Sharing %d bits)\n",
A2S(&NCE->Address), Length));
-
+
if(Length >= MaskLength && (Length > BestLength || !BestLength)) {
/* This seems to be a better router */
BestNCE = NCE;
/* Destination is not on any subnets we're on. Find a router to use */
NCE = RouterGetRoute(Destination);
}
-
- if( NCE )
+
+ if( NCE )
TI_DbgPrint(DEBUG_ROUTER,("Interface->MTU: %d\n", NCE->Interface->MTU));
return NCE;
PNEIGHBOR_CACHE_ENTRY NCE;
TI_DbgPrint(DEBUG_ROUTER, ("Called\n"));
-
+
TcpipAcquireSpinLock(&FIBLock, &OldIrql);
CurrentEntry = FIBListHead.Flink;
}
TcpipReleaseSpinLock(&FIBLock, OldIrql);
-
+
TI_DbgPrint(DEBUG_ROUTER, ("Leaving\n"));
return Found ? STATUS_NO_SUCH_FILE : STATUS_SUCCESS;
*/
{
PIPFRAGMENT_CONTEXT IFC = (PIPFRAGMENT_CONTEXT)Context;
-
+
TI_DbgPrint
- (MAX_TRACE,
+ (MAX_TRACE,
("Called. Context (0x%X) NdisPacket (0x%X) NdisStatus (0x%X)\n",
Context, NdisPacket, NdisStatus));
IPSendFragment(IFC->NdisPacket, IFC->NCE, IFC);
} else {
TI_DbgPrint(MAX_TRACE, ("Calling completion handler.\n"));
-
+
/* There are no more fragments to transmit, so call completion handler */
FreeNdisPacket(IFC->NdisPacket);
IFC->Complete(IFC->Context, IFC->Datagram, NdisStatus);
MoreFragments = FALSE;
}
- TI_DbgPrint(MID_TRACE,("Copying data from %x to %x (%d)\n",
+ TI_DbgPrint(MID_TRACE,("Copying data from %x to %x (%d)\n",
IFC->DatagramData, IFC->Data, DataSize));
RtlCopyMemory(IFC->Data, IFC->DatagramData, DataSize); // SAFE
if( InSize < BufferSize ) BufferSize = InSize;
TI_DbgPrint(MAX_TRACE, ("Fragment buffer is %d bytes\n", BufferSize));
-
+
IFC = exAllocatePool(NonPagedPool, sizeof(IPFRAGMENT_CONTEXT));
if (IFC == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
IFC->Complete = Complete;
IFC->Context = Context;
- TI_DbgPrint(MID_TRACE,("Copying header from %x to %x (%d)\n",
- IPPacket->Header, IFC->Header,
+ TI_DbgPrint(MID_TRACE,("Copying header from %x to %x (%d)\n",
+ IPPacket->Header, IFC->Header,
IPPacket->HeaderSize));
RtlCopyMemory( IFC->Header, IPPacket->Header, IPPacket->HeaderSize );
/* Fetch path MTU now, because it may change */
TI_DbgPrint(MID_TRACE,("PathMTU: %d\n", NCE->Interface->MTU));
-
+
if ((IPPacket->Flags & IP_PACKET_FLAG_RAW) == 0) {
/* Calculate checksum of IP header */
TI_DbgPrint(MID_TRACE,("-> not IP_PACKET_FLAG_RAW\n"));
((PIPv4_HEADER)IPPacket->Header)->Checksum = 0;
-
+
((PIPv4_HEADER)IPPacket->Header)->Checksum = (USHORT)
IPv4Checksum(IPPacket->Header, IPPacket->HeaderSize, 0);
TI_DbgPrint(MID_TRACE,("IP Check: %x\n", ((PIPv4_HEADER)IPPacket->Header)->Checksum));
-
+
TI_DbgPrint(MAX_TRACE, ("Sending packet (length is %d).\n",
WN2H(((PIPv4_HEADER)IPPacket->Header)->TotalLength)));
} else {
TI_DbgPrint(MAX_TRACE, ("Sending raw packet (flags are 0x%X).\n",
IPPacket->Flags));
}
-
- return SendFragments(IPPacket, NCE, NCE->Interface->MTU,
+
+ return SendFragments(IPPacket, NCE, NCE->Interface->MTU,
Complete, Context);
}
PDATAGRAM_RECEIVE_REQUEST Current = NULL;
BOOLEAN Found;
PTA_IP_ADDRESS RTAIPAddress;
-
+
TI_DbgPrint(MAX_TRACE, ("There is a receive request.\n"));
-
+
/* Search receive request list to find a match */
Found = FALSE;
CurrentEntry = AddrFile->ReceiveQueue.Flink;
while((CurrentEntry != &AddrFile->ReceiveQueue) && (!Found)) {
Current = CONTAINING_RECORD(CurrentEntry, DATAGRAM_RECEIVE_REQUEST, ListEntry);
-
+
if( DstPort == AddrFile->Port ) {
Found = TRUE;
/* Remove the request from the queue */
}
TcpipReleaseSpinLock(&AddrFile->Lock, OldIrql);
-
+
if (Found)
{
TI_DbgPrint(MAX_TRACE, ("Suitable receive request found.\n"));
- TI_DbgPrint(MAX_TRACE,
+ TI_DbgPrint(MAX_TRACE,
("Target Buffer: %x, Source Buffer: %x, Size %d\n",
Current->Buffer, DataBuffer, DataSize));
-
+
/* Copy the data into buffer provided by the user */
RtlCopyMemory( Current->Buffer,
DataBuffer,
RTAIPAddress->TAAddressCount = 1;
RTAIPAddress->Address->AddressType = TDI_ADDRESS_TYPE_IP;
RTAIPAddress->Address->Address->sin_port = SrcPort;
-
- TI_DbgPrint(MAX_TRACE, ("(A: %08x) Addr %08x Port %04x\n",
+
+ TI_DbgPrint(MAX_TRACE, ("(A: %08x) Addr %08x Port %04x\n",
RTAIPAddress,
SrcAddress->Address.IPv4Address, SrcPort));
- RtlCopyMemory( &RTAIPAddress->Address->Address->in_addr,
+ RtlCopyMemory( &RTAIPAddress->Address->Address->in_addr,
&SrcAddress->Address.IPv4Address,
sizeof(SrcAddress->Address.IPv4Address) );
UINT DataLength,
UINT Protocol,
UINT ExtraLength,
- PVOID *NextHeader )
+ PVOID *NextHeader )
/*
* FUNCTION: Adds an IPv4 and RawIp header to an IP packet
* ARGUMENTS:
{
PIPv4_HEADER IPHeader;
ULONG BufferSize;
-
- TI_DbgPrint(MID_TRACE, ("Packet: %x NdisPacket %x\n",
+
+ TI_DbgPrint(MID_TRACE, ("Packet: %x NdisPacket %x\n",
IPPacket, IPPacket->NdisPacket));
-
+
BufferSize = MaxLLHeaderSize + sizeof(IPv4_HEADER) + ExtraLength;
-
- GetDataPtr( IPPacket->NdisPacket,
- MaxLLHeaderSize,
- (PCHAR *)&IPPacket->Header,
+
+ GetDataPtr( IPPacket->NdisPacket,
+ MaxLLHeaderSize,
+ (PCHAR *)&IPPacket->Header,
&IPPacket->ContigSize );
-
+
IPPacket->HeaderSize = 20;
-
- TI_DbgPrint(MAX_TRACE, ("Allocated %d bytes for headers at 0x%X.\n",
+
+ TI_DbgPrint(MAX_TRACE, ("Allocated %d bytes for headers at 0x%X.\n",
BufferSize, IPPacket->Header));
TI_DbgPrint(MAX_TRACE, ("Packet total length %d\n", IPPacket->TotalSize));
-
+
/* Build IPv4 header */
IPHeader = (PIPv4_HEADER)IPPacket->Header;
/* Version = 4, Length = 5 DWORDs */
IPHeader->SrcAddr = LocalAddress->Address.IPv4Address;
/* Destination address. FIXME: IPv4 only */
IPHeader->DstAddr = RemoteAddress->Address.IPv4Address;
-
+
/* Build RawIp header */
*NextHeader = (((PCHAR)IPHeader) + sizeof(IPv4_HEADER));
IPPacket->Data = ((PCHAR)*NextHeader) + ExtraLength;
-
+
return STATUS_SUCCESS;
}
PIP_ADDRESS LocalAddress,
USHORT LocalPort,
PCHAR DataBuffer,
- UINT DataLen )
+ UINT DataLen )
/*
* FUNCTION: Builds an RawIp packet
* ARGUMENTS:
{
NTSTATUS Status;
PCHAR Payload;
-
+
TI_DbgPrint(MAX_TRACE, ("Called.\n"));
-
+
/* FIXME: Assumes IPv4 */
IPInitializePacket(Packet, IP_ADDRESS_V4);
if (!Packet)
return STATUS_INSUFFICIENT_RESOURCES;
-
+
Packet->TotalSize = sizeof(IPv4_HEADER) + DataLen;
-
+
/* Prepare packet */
Status = AllocatePacketWithBuffer( &Packet->NdisPacket,
NULL,
Packet->TotalSize + MaxLLHeaderSize );
-
+
if( !NT_SUCCESS(Status) ) return Status;
TI_DbgPrint(MID_TRACE, ("Allocated packet: %x\n", Packet->NdisPacket));
TI_DbgPrint(MID_TRACE, ("Local Addr : %s\n", A2S(LocalAddress)));
TI_DbgPrint(MID_TRACE, ("Remote Addr: %s\n", A2S(RemoteAddress)));
-
+
switch (RemoteAddress->Type) {
case IP_ADDRESS_V4:
Status = AddGenericHeaderIPv4
- (RemoteAddress, RemotePort,
+ (RemoteAddress, RemotePort,
LocalAddress, LocalPort, Packet, DataLen,
IPPROTO_ICMP, /* XXX Figure out a better way to do this */
0, (PVOID *)&Payload );
TI_DbgPrint(MIN_TRACE, ("Bad Address Type %d\n", RemoteAddress->Type));
break;
}
-
- TI_DbgPrint(MID_TRACE, ("Copying data (hdr %x data %x (%d))\n",
- Packet->Header, Packet->Data,
+
+ TI_DbgPrint(MID_TRACE, ("Copying data (hdr %x data %x (%d))\n",
+ Packet->Header, Packet->Data,
(PCHAR)Packet->Data - (PCHAR)Packet->Header));
-
+
RtlCopyMemory( Packet->Data, DataBuffer, DataLen );
-
+
TI_DbgPrint(MID_TRACE, ("Displaying packet\n"));
-
+
DISPLAY_IP_PACKET(Packet);
-
+
TI_DbgPrint(MID_TRACE, ("Leaving\n"));
-
+
return STATUS_SUCCESS;
}
PTDI_CONNECTION_INFORMATION ConnInfo,
PCHAR BufferData,
ULONG DataSize,
- PULONG DataUsed )
+ PULONG DataUsed )
/*
* FUNCTION: Sends an RawIp datagram to a remote address
* ARGUMENTS:
switch( RemoteAddressTa->Address[0].AddressType ) {
case TDI_ADDRESS_TYPE_IP:
RemoteAddress.Type = IP_ADDRESS_V4;
- RemoteAddress.Address.IPv4Address =
+ RemoteAddress.Address.IPv4Address =
RemoteAddressTa->Address[0].Address[0].in_addr;
RemotePort = RemoteAddressTa->Address[0].Address[0].sin_port;
break;
default:
return STATUS_UNSUCCESSFUL;
}
-
+
Status = BuildRawIpPacket( &Packet,
&RemoteAddress,
RemotePort,
AddrFile->Port,
BufferData,
DataSize );
-
- if( !NT_SUCCESS(Status) )
+
+ if( !NT_SUCCESS(Status) )
return Status;
TI_DbgPrint(MID_TRACE,("About to get route to destination\n"));
}
VOID RawIpReceiveComplete(PVOID Context, NTSTATUS Status, ULONG Count) {
- PDATAGRAM_RECEIVE_REQUEST ReceiveRequest =
+ PDATAGRAM_RECEIVE_REQUEST ReceiveRequest =
(PDATAGRAM_RECEIVE_REQUEST)Context;
TI_DbgPrint(MAX_TRACE,("Called\n"));
ReceiveRequest->UserComplete( ReceiveRequest->UserContext, Status, Count );
KIRQL OldIrql;
NTSTATUS Status;
PDATAGRAM_RECEIVE_REQUEST ReceiveRequest;
-
+
TI_DbgPrint(MAX_TRACE, ("Called.\n"));
-
+
TcpipAcquireSpinLock(&AddrFile->Lock, &OldIrql);
-
+
if (AF_IS_VALID(AddrFile))
{
ReceiveRequest = exAllocatePool(NonPagedPool, sizeof(DATAGRAM_RECEIVE_REQUEST));
if (ReceiveRequest)
{
/* Initialize a receive request */
-
+
/* Extract the remote address filter from the request (if any) */
- if ((ConnInfo->RemoteAddressLength != 0) &&
+ if ((ConnInfo->RemoteAddressLength != 0) &&
(ConnInfo->RemoteAddress))
{
Status = AddrGetAddress(ConnInfo->RemoteAddress,
ReceiveRequest->BufferSize = ReceiveLength;
ReceiveRequest->UserComplete = Complete;
ReceiveRequest->UserContext = Context;
- ReceiveRequest->Complete =
+ ReceiveRequest->Complete =
(PDATAGRAM_COMPLETION_ROUTINE)RawIpReceiveComplete;
ReceiveRequest->Context = ReceiveRequest;
-
+
/* Queue receive request */
InsertTailList(&AddrFile->ReceiveQueue, &ReceiveRequest->ListEntry);
AF_SET_PENDING(AddrFile, AFF_RECEIVE);
-
+
TcpipReleaseSpinLock(&AddrFile->Lock, OldIrql);
-
+
TI_DbgPrint(MAX_TRACE, ("Leaving (pending).\n"));
-
+
return STATUS_PENDING;
}
else
{
Status = STATUS_INVALID_ADDRESS;
}
-
+
TcpipReleaseSpinLock(&AddrFile->Lock, OldIrql);
-
+
TI_DbgPrint(MAX_TRACE, ("Leaving with errors (0x%X).\n", Status));
-
+
return Status;
}
* userland after we complete this irp */
WhoIsConnecting = (PTDI_CONNECTION_INFORMATION)
Request->ReturnConnectionInformation;
-
+
Status = TCPTranslateError
- ( OskitTCPAccept( Listener->SocketContext,
+ ( OskitTCPAccept( Listener->SocketContext,
&Connection->SocketContext,
&OutAddr,
sizeof(OutAddr),
&OutAddrLen,
Request->RequestFlags & TDI_QUERY_ACCEPT ? 0 : 1 ) );
-
+
TI_DbgPrint(DEBUG_TCP,("Status %x\n", Status));
if( NT_SUCCESS(Status) && Status != STATUS_PENDING ) {
RequestAddressReturn = WhoIsConnecting->RemoteAddress;
- TI_DbgPrint(DEBUG_TCP,("Copying address to %x (Who %x)\n",
+ TI_DbgPrint(DEBUG_TCP,("Copying address to %x (Who %x)\n",
RequestAddressReturn, WhoIsConnecting));
-
+
RequestAddressReturn->TAAddressCount = 1;
RequestAddressReturn->Address[0].AddressLength = OutAddrLen;
/* BSD uses the first byte of the sockaddr struct as a length.
* Since windows doesn't do that we strip it */
- RequestAddressReturn->Address[0].AddressType =
+ RequestAddressReturn->Address[0].AddressType =
(OutAddr.sin_family >> 8) & 0xff;
RtlCopyMemory( &RequestAddressReturn->Address[0].Address,
TI_DbgPrint(DEBUG_TCP,("Done copying\n"));
}
-
+
TI_DbgPrint(DEBUG_TCP,("Status %x\n", Status));
return Status;
ASSERT_KM_POINTER(Connection->AddressFile);
TcpipRecursiveMutexEnter( &TCPLock, TRUE );
-
+
AddressToBind.sin_family = AF_INET;
- memcpy( &AddressToBind.sin_addr,
+ memcpy( &AddressToBind.sin_addr,
&Connection->AddressFile->Address.Address.IPv4Address,
sizeof(AddressToBind.sin_addr) );
AddressToBind.sin_port = Connection->AddressFile->Port;
-
+
TI_DbgPrint(DEBUG_TCP,("AddressToBind - %x:%x\n", AddressToBind.sin_addr, AddressToBind.sin_port));
-
+
OskitTCPBind( Connection->SocketContext,
Connection,
&AddressToBind,
sizeof(AddressToBind) );
-
+
Status = TCPTranslateError( OskitTCPListen( Connection->SocketContext,
Backlog ) );
-
+
TcpipRecursiveMutexLeave( &TCPLock );
TI_DbgPrint(DEBUG_TCP,("TCPListen finished %x\n", Status));
-
+
return Status;
}
PCONNECTION_ENDPOINT Connection ) {
PLIST_ENTRY ListEntry;
PTDI_BUCKET Bucket;
-
+
TcpipRecursiveMutexEnter( &TCPLock, TRUE );
-
+
ListEntry = Listener->ListenRequest.Flink;
while ( ListEntry != &Listener->ListenRequest ) {
Bucket = CONTAINING_RECORD(ListEntry, TDI_BUCKET, Entry);
ExFreePool( Bucket );
}
}
-
+
TcpipRecursiveMutexLeave( &TCPLock );
}
TcpipRecursiveMutexEnter( &TCPLock, TRUE );
- Status = TCPServiceListeningSocket( Listener, Connection,
+ Status = TCPServiceListeningSocket( Listener, Connection,
(PTDI_REQUEST_KERNEL)Request );
if( Status == STATUS_PENDING ) {
#include "precomp.h"
int TCPSocketState(void *ClientData,
- void *WhichSocket,
+ void *WhichSocket,
void *WhichConnection,
OSK_UINT NewState ) {
PCONNECTION_ENDPOINT Connection = WhichConnection;
NewState & SEL_FIN ? 'F' : 'f',
NewState & SEL_ACCEPT ? 'A' : 'a'));
- TI_DbgPrint(DEBUG_TCP,("Called: NewState %x (Conn %x) (Change %x)\n",
+ TI_DbgPrint(DEBUG_TCP,("Called: NewState %x (Conn %x) (Change %x)\n",
NewState, Connection,
- Connection ? Connection->State ^ NewState :
+ Connection ? Connection->State ^ NewState :
NewState));
if( !Connection ) {
Connection = FileFindConnectionByContext( WhichSocket );
if( !Connection )
return 0;
- else
+ else
TI_DbgPrint(DEBUG_TCP,("Found socket %x\n", Connection));
}
- TI_DbgPrint(MID_TRACE,("Connection signalled: %d\n",
+ TI_DbgPrint(MID_TRACE,("Connection signalled: %d\n",
Connection->Signalled));
Connection->SignalState |= NewState;
return OSK_EADDRNOTAVAIL;
}
- NdisStatus = AllocatePacketWithBuffer( &Packet.NdisPacket, NULL,
+ NdisStatus = AllocatePacketWithBuffer( &Packet.NdisPacket, NULL,
MaxLLHeaderSize + len );
-
+
if (NdisStatus != NDIS_STATUS_SUCCESS) {
TI_DbgPrint(DEBUG_TCP, ("Error from NDIS: %08x\n", NdisStatus));
return STATUS_NO_MEMORY;
}
- GetDataPtr( Packet.NdisPacket, MaxLLHeaderSize,
+ GetDataPtr( Packet.NdisPacket, MaxLLHeaderSize,
(PCHAR *)&Packet.Header, &Packet.ContigSize );
RtlCopyMemory( Packet.Header, data, len );
Packet.DstAddr = RemoteAddress;
IPSendDatagram( &Packet, NCE, TCPPacketSendComplete, NULL );
-
+
if( !NT_SUCCESS(NdisStatus) ) return OSK_EINVAL;
else return 0;
}
int TCPSleep( void *ClientData, void *token, int priority, char *msg,
int tmio ) {
PSLEEPING_THREAD SleepingThread;
-
+
TI_DbgPrint(DEBUG_TCP,
("Called TSLEEP: tok = %x, pri = %d, wmesg = %s, tmio = %x\n",
token, priority, msg, tmio));
/*
* Copyright (c) 1997-1998 University of Utah and the Flux Group.
* All rights reserved.
- *
+ *
* This file is part of the Flux OSKit. The OSKit is free software, also known
* as "open source;" you can redistribute it and/or modify it under the terms
* of the GNU General Public License (GPL), version 2, as published by the Free
* Software Foundation (FSF). To explore alternate licensing terms, contact
* the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
- *
+ *
* The OSKit 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 GPL for more details. You should have
ifaddr->ifa_dstaddr = (struct sockaddr *)dstaddr_in;
/* XXX - Point-to-point interfaces not supported yet */
memset( &ifaddr->ifa_dstaddr, 0, sizeof( struct sockaddr ) );
-
+
ifaddr->ifa_addr = (struct sockaddr *)addr_in;
Status = GetInterfaceIPv4Address( IF,
ADE_UNICAST,
(PULONG)&addr_in->sin_addr.s_addr );
-
+
if( !NT_SUCCESS(Status) )
addr_in->sin_addr.s_addr = 0;
TI_DbgPrint(DEBUG_TCPIF,("Prepare interface %x : addr %x\n",
IF, addr_in->sin_addr.s_addr));
-
+
ifaddr->ifa_flags = 0; /* XXX what goes here? */
ifaddr->ifa_refcnt = 0; /* Anachronistic */
ifaddr->ifa_metric = 1; /* We can get it like in ninfo.c, if we want */
PNEIGHBOR_CACHE_ENTRY NCE;
IP_ADDRESS Destination;
struct sockaddr_in *addr_in = (struct sockaddr_in *)ReqAddr;
-
+
TI_DbgPrint(DEBUG_TCPIF,("called for type %d\n", FindType));
if( !ReqAddr ) {
TI_DbgPrint(DEBUG_TCPIF,("NCE: %x\n", NCE));
TI_DbgPrint(DEBUG_TCPIF,("NCE->Interface: %x\n", NCE->Interface));
- TI_DbgPrint(DEBUG_TCPIF,("NCE->Interface->TCPContext: %x\n",
+ TI_DbgPrint(DEBUG_TCPIF,("NCE->Interface->TCPContext: %x\n",
NCE->Interface->TCPContext));
addr_in = (struct sockaddr_in *)
((POSK_IFADDR)NCE->Interface->TCPContext)->ifa_addr;
TI_DbgPrint(DEBUG_TCPIF,("returning addr %x\n", addr_in->sin_addr.s_addr));
-
+
return NCE->Interface->TCPContext;
}
TI_DbgPrint(MID_TRACE,("Handling signalled state on %x (%x)\n",
Connection, Connection->SocketContext));
-
+
/* Things that can happen when we try the initial connection */
if( NewState & SEL_CONNECT ) {
while( !IsListEmpty( &Connection->ConnectRequest ) ) {
Connection->State |= NewState;
Entry = RemoveHeadList( &Connection->ConnectRequest );
TI_DbgPrint(DEBUG_TCP, ("Connect Event\n"));
-
+
Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
Complete = Bucket->Request.RequestNotifyObject;
TI_DbgPrint(DEBUG_TCP,
("Completing Request %x\n", Bucket->Request));
-
- if( (NewState & (SEL_CONNECT | SEL_FIN)) ==
- (SEL_CONNECT | SEL_FIN) )
+
+ if( (NewState & (SEL_CONNECT | SEL_FIN)) ==
+ (SEL_CONNECT | SEL_FIN) )
Status = STATUS_CONNECTION_REFUSED;
else
Status = STATUS_SUCCESS;
-
+
Complete( Bucket->Request.RequestContext, Status, 0 );
-
+
/* Frees the bucket allocated in TCPConnect */
PoolFreeBuffer( Bucket );
}
}
if( NewState & SEL_ACCEPT ) {
- /* Handle readable on a listening socket --
- * TODO: Implement filtering
+ /* Handle readable on a listening socket --
+ * TODO: Implement filtering
*/
TI_DbgPrint(DEBUG_TCP,("Accepting new connection on %x (Queue: %s)\n",
Connection,
- IsListEmpty(&Connection->ListenRequest) ?
+ IsListEmpty(&Connection->ListenRequest) ?
"empty" : "nonempty"));
while( !IsListEmpty( &Connection->ListenRequest ) ) {
Entry = RemoveHeadList( &Connection->ListenRequest );
Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
Complete = Bucket->Request.RequestNotifyObject;
-
+
Irp = Bucket->Request.RequestContext;
IrpSp = IoGetCurrentIrpStackLocation( Irp );
-
+
TI_DbgPrint(DEBUG_TCP,("Getting the socket\n"));
Status = TCPServiceListeningSocket
- ( Connection->AddressFile->Listener,
- Bucket->AssociatedEndpoint,
+ ( Connection->AddressFile->Listener,
+ Bucket->AssociatedEndpoint,
(PTDI_REQUEST_KERNEL)&IrpSp->Parameters );
TI_DbgPrint(DEBUG_TCP,("Socket: Status: %x\n"));
if( Status == STATUS_PENDING ) {
InsertHeadList( &Connection->ListenRequest, &Bucket->Entry );
break;
- } else
+ } else
Complete( Bucket->Request.RequestContext, Status, 0 );
}
}
TI_DbgPrint(DEBUG_TCP,("Readable: irp list %s\n",
IsListEmpty(&Connection->ReceiveRequest) ?
"empty" : "nonempty"));
-
+
while( !IsListEmpty( &Connection->ReceiveRequest ) ) {
OSK_UINT RecvLen = 0, Received = 0;
OSK_PCHAR RecvBuffer = 0;
TI_DbgPrint(DEBUG_TCP, ("Connection: %x\n", Connection));
TI_DbgPrint
- (DEBUG_TCP,
- ("Connection->SocketContext: %x\n",
+ (DEBUG_TCP,
+ ("Connection->SocketContext: %x\n",
Connection->SocketContext));
TI_DbgPrint(DEBUG_TCP, ("RecvBuffer: %x\n", RecvBuffer));
-
+
Status = TCPTranslateError
( OskitTCPRecv( Connection->SocketContext,
RecvBuffer,
0 ) );
TI_DbgPrint(DEBUG_TCP,("TCP Bytes: %d\n", Received));
-
+
if( Status == STATUS_SUCCESS ) {
TI_DbgPrint(DEBUG_TCP,("Received %d bytes with status %x\n",
Received, Status));
-
+
Complete( Bucket->Request.RequestContext,
STATUS_SUCCESS, Received );
} else if( Status == STATUS_PENDING ) {
UINT i;
TI_DbgPrint(DEBUG_TCP, ("EOF From socket\n"));
-
+
ListsToErase[0] = &Connection->ReceiveRequest;
IrpStatus [0] = STATUS_SUCCESS;
ListsToErase[1] = &Connection->ListenRequest;
}
PCONNECTION_ENDPOINT TCPAllocateConnectionEndpoint( PVOID ClientContext ) {
- PCONNECTION_ENDPOINT Connection =
+ PCONNECTION_ENDPOINT Connection =
ExAllocatePool(NonPagedPool, sizeof(CONNECTION_ENDPOINT));
if (!Connection)
return Connection;
-
+
TI_DbgPrint(DEBUG_CPOINT, ("Connection point file object allocated at (0x%X).\n", Connection));
-
+
RtlZeroMemory(Connection, sizeof(CONNECTION_ENDPOINT));
-
+
/* Initialize spin lock that protects the connection endpoint file object */
TcpipInitializeSpinLock(&Connection->Lock);
InitializeListHead(&Connection->ConnectRequest);
InitializeListHead(&Connection->ListenRequest);
InitializeListHead(&Connection->ReceiveRequest);
-
+
/* Save client context pointer */
Connection->ClientContext = ClientContext;
-
+
return Connection;
}
ExFreePool( Connection );
}
-NTSTATUS TCPSocket( PCONNECTION_ENDPOINT Connection,
+NTSTATUS TCPSocket( PCONNECTION_ENDPOINT Connection,
UINT Family, UINT Type, UINT Proto ) {
NTSTATUS Status;
* This is the low level interface for receiving TCP data
*/
{
- TI_DbgPrint(DEBUG_TCP,("Sending packet %d (%d) to oskit\n",
+ TI_DbgPrint(DEBUG_TCP,("Sending packet %d (%d) to oskit\n",
IPPacket->TotalSize,
IPPacket->HeaderSize));
TcpipRecursiveMutexEnter( &TCPLock, TRUE );
- OskitTCPReceiveDatagram( IPPacket->Header,
- IPPacket->TotalSize,
+ OskitTCPReceiveDatagram( IPPacket->Header,
+ IPPacket->TotalSize,
IPPacket->HeaderSize );
DrainSignals();
{
TcpipRecursiveMutexInit( &TCPLock );
ExInitializeFastMutex( &SleepingThreadsLock );
- InitializeListHead( &SleepingThreadsList );
+ InitializeListHead( &SleepingThreadsList );
InitializeListHead( &SignalledConnections );
PortsStartup( &TCPPorts, 1, 0xfffe );
RegisterOskitTCPEventHandlers( &EventHandlers );
InitOskitTCP();
-
+
/* Register this protocol with IP layer */
IPRegisterProtocol(IPPROTO_TCP, TCPReceive);
-
+
ExInitializeNPagedLookasideList(
&TCPSegmentList, /* Lookaside list */
NULL, /* Allocate routine */
sizeof(TCP_SEGMENT), /* Size of each entry */
TAG('T','C','P','S'), /* Tag */
0); /* Depth */
-
+
TCPInitialized = TRUE;
-
+
return STATUS_SUCCESS;
}
{
if (!TCPInitialized)
return STATUS_SUCCESS;
-
+
/* Deregister this protocol with IP layer */
IPRegisterProtocol(IPPROTO_TCP, NULL);
-
+
ExDeleteNPagedLookasideList(&TCPSegmentList);
-
+
TCPInitialized = FALSE;
DeinitOskitTCP();
TI_DbgPrint(DEBUG_TCP, ("Could not AddrBuildAddress in TCPConnect\n"));
return Status;
}
-
+
AddressToConnect.sin_family = AF_INET;
AddressToBind = AddressToConnect;
&AddressToBind,
sizeof(AddressToBind) );
- memcpy( &AddressToConnect.sin_addr,
+ memcpy( &AddressToConnect.sin_addr,
&RemoteAddress.Address.IPv4Address,
sizeof(AddressToConnect.sin_addr) );
AddressToConnect.sin_port = RemotePort;
Status = TCPTranslateError
( OskitTCPConnect( Connection->SocketContext,
Connection,
- &AddressToConnect,
+ &AddressToConnect,
sizeof(AddressToConnect) ) );
TcpipRecursiveMutexLeave( &TCPLock );
-
- if( Status == OSK_EINPROGRESS )
+
+ if( Status == OSK_EINPROGRESS )
return STATUS_PENDING;
else
return Status;
PTCP_COMPLETION_ROUTINE Complete,
PVOID Context ) {
NTSTATUS Status;
-
+
TI_DbgPrint(DEBUG_TCP,("started\n"));
TcpipRecursiveMutexEnter( &TCPLock, TRUE );
( OskitTCPShutdown( Connection->SocketContext, Flags ) );
TcpipRecursiveMutexLeave( &TCPLock );
-
+
TI_DbgPrint(DEBUG_TCP,("finished %x\n", Status));
return Status;
NTSTATUS TCPClose
( PCONNECTION_ENDPOINT Connection ) {
NTSTATUS Status;
-
+
TI_DbgPrint(DEBUG_TCP,("TCPClose started\n"));
TcpipRecursiveMutexEnter( &TCPLock, TRUE );
DrainSignals();
TcpipRecursiveMutexLeave( &TCPLock );
-
+
TI_DbgPrint(DEBUG_TCP,("TCPClose finished %x\n", Status));
return Status;
NTSTATUS Status;
PTDI_BUCKET Bucket;
- TI_DbgPrint(DEBUG_TCP,("Called for %d bytes (on socket %x)\n",
+ TI_DbgPrint(DEBUG_TCP,("Called for %d bytes (on socket %x)\n",
ReceiveLength, Connection->SocketContext));
ASSERT_KM_POINTER(Connection->SocketContext);
DataLen,
&Received,
ReceiveFlags ) );
-
+
TI_DbgPrint(DEBUG_TCP,("OskitTCPReceive: %x, %d\n", Status, Received));
/* Keep this request around ... there was no data yet */
TcpipRecursiveMutexLeave( &TCPLock );
return STATUS_NO_MEMORY;
}
-
+
Bucket->Request.RequestNotifyObject = Complete;
Bucket->Request.RequestContext = Context;
*BytesReceived = 0;
TI_DbgPrint(DEBUG_TCP,("Connection->SocketContext = %x\n",
Connection->SocketContext));
- Status = OskitTCPSend( Connection->SocketContext,
+ Status = OskitTCPSend( Connection->SocketContext,
(OSK_PCHAR)BufferData, PacketSize,
(PUINT)DataUsed, 0 );
return Status;
}
-VOID TCPTimeout(VOID) {
+VOID TCPTimeout(VOID) {
static int Times = 0;
TcpipRecursiveMutexEnter( &TCPLock, TRUE );
if( (Times++ % 5) == 0 ) {
UINT TCPAllocatePort( UINT HintPort ) {
if( HintPort ) {
- if( AllocatePort( &TCPPorts, HintPort ) ) return HintPort;
+ if( AllocatePort( &TCPPorts, HintPort ) ) return HintPort;
else {
TI_DbgPrint
(MID_TRACE,("We got a hint port but couldn't allocate it\n"));
AddressIP->Address[0].Address[0].in_addr = RemoteAddress;
TcpipRecursiveMutexLeave( &TCPLock );
-
+
return STATUS_SUCCESS;
}
PIP_ADDRESS LocalAddress,
USHORT LocalPort,
PIP_PACKET IPPacket,
- UINT DataLength)
+ UINT DataLength)
/*
* FUNCTION: Adds an IPv4 and UDP header to an IP packet
* ARGUMENTS:
*/
{
PUDP_HEADER UDPHeader;
-
- TI_DbgPrint(MID_TRACE, ("Packet: %x NdisPacket %x\n",
+
+ TI_DbgPrint(MID_TRACE, ("Packet: %x NdisPacket %x\n",
IPPacket, IPPacket->NdisPacket));
AddGenericHeaderIPv4
( RemoteAddress, RemotePort,
LocalAddress, LocalPort,
- IPPacket, DataLength, IPPROTO_UDP,
+ IPPacket, DataLength, IPPROTO_UDP,
sizeof(UDP_HEADER), (PVOID *)&UDPHeader );
-
+
/* Build UDP header */
UDPHeader = (PUDP_HEADER)(IPPacket->Data - sizeof(UDP_HEADER));
/* Port values are already big-endian values */
UDPHeader->Length = WH2N(DataLength + sizeof(UDP_HEADER));
IPPacket->Data = ((PCHAR)UDPHeader) + sizeof(UDP_HEADER);
-
+
TI_DbgPrint(MID_TRACE, ("Packet: %d ip %d udp %d payload\n",
(PCHAR)UDPHeader - (PCHAR)IPPacket->Header,
(PCHAR)IPPacket->Data - (PCHAR)UDPHeader,
PIP_ADDRESS LocalAddress,
USHORT LocalPort,
PCHAR DataBuffer,
- UINT DataLen )
+ UINT DataLen )
/*
* FUNCTION: Builds an UDP packet
* ARGUMENTS:
*/
{
NTSTATUS Status;
-
+
TI_DbgPrint(MAX_TRACE, ("Called.\n"));
-
+
/* FIXME: Assumes IPv4 */
IPInitializePacket(Packet, IP_ADDRESS_V4);
if (!Packet)
return STATUS_INSUFFICIENT_RESOURCES;
-
+
Packet->TotalSize = sizeof(IPv4_HEADER) + sizeof(UDP_HEADER) + DataLen;
-
+
/* Prepare packet */
Status = AllocatePacketWithBuffer( &Packet->NdisPacket,
NULL,
Packet->TotalSize + MaxLLHeaderSize );
-
+
if( !NT_SUCCESS(Status) ) return Status;
TI_DbgPrint(MID_TRACE, ("Allocated packet: %x\n", Packet->NdisPacket));
TI_DbgPrint(MID_TRACE, ("Local Addr : %s\n", A2S(LocalAddress)));
TI_DbgPrint(MID_TRACE, ("Remote Addr: %s\n", A2S(RemoteAddress)));
-
+
switch (RemoteAddress->Type) {
case IP_ADDRESS_V4:
- Status = AddUDPHeaderIPv4(RemoteAddress, RemotePort,
+ Status = AddUDPHeaderIPv4(RemoteAddress, RemotePort,
LocalAddress, LocalPort, Packet, DataLen);
break;
case IP_ADDRESS_V6:
break;
}
if (!NT_SUCCESS(Status)) {
- TI_DbgPrint(MIN_TRACE, ("Cannot add UDP header. Status = (0x%X)\n",
+ TI_DbgPrint(MIN_TRACE, ("Cannot add UDP header. Status = (0x%X)\n",
Status));
FreeNdisPacket(Packet->NdisPacket);
return Status;
}
-
- TI_DbgPrint(MID_TRACE, ("Copying data (hdr %x data %x (%d))\n",
- Packet->Header, Packet->Data,
+
+ TI_DbgPrint(MID_TRACE, ("Copying data (hdr %x data %x (%d))\n",
+ Packet->Header, Packet->Data,
(PCHAR)Packet->Data - (PCHAR)Packet->Header));
-
+
RtlCopyMemory( Packet->Data, DataBuffer, DataLen );
-
+
TI_DbgPrint(MID_TRACE, ("Displaying packet\n"));
-
+
DISPLAY_IP_PACKET(Packet);
-
+
TI_DbgPrint(MID_TRACE, ("Leaving\n"));
-
+
return STATUS_SUCCESS;
}
PTDI_CONNECTION_INFORMATION ConnInfo,
PCHAR BufferData,
ULONG DataSize,
- PULONG DataUsed )
+ PULONG DataUsed )
/*
* FUNCTION: Sends an UDP datagram to a remote address
* ARGUMENTS:
switch( RemoteAddressTa->Address[0].AddressType ) {
case TDI_ADDRESS_TYPE_IP:
RemoteAddress.Type = IP_ADDRESS_V4;
- RemoteAddress.Address.IPv4Address =
+ RemoteAddress.Address.IPv4Address =
RemoteAddressTa->Address[0].Address[0].in_addr;
RemotePort = RemoteAddressTa->Address[0].Address[0].sin_port;
break;
default:
return STATUS_UNSUCCESSFUL;
}
-
+
Status = BuildUDPPacket( &Packet,
&RemoteAddress,
RemotePort,
BufferData,
DataSize );
- if( !NT_SUCCESS(Status) )
+ if( !NT_SUCCESS(Status) )
return Status;
if(!(NCE = RouteGetRouteToDestination( &RemoteAddress )))
}
VOID UDPReceiveComplete(PVOID Context, NTSTATUS Status, ULONG Count) {
- PDATAGRAM_RECEIVE_REQUEST ReceiveRequest =
+ PDATAGRAM_RECEIVE_REQUEST ReceiveRequest =
(PDATAGRAM_RECEIVE_REQUEST)Context;
TI_DbgPrint(MAX_TRACE,("Called\n"));
ReceiveRequest->UserComplete( ReceiveRequest->UserContext, Status, Count );
KIRQL OldIrql;
NTSTATUS Status;
PDATAGRAM_RECEIVE_REQUEST ReceiveRequest;
-
+
TI_DbgPrint(MAX_TRACE, ("Called.\n"));
-
+
TcpipAcquireSpinLock(&AddrFile->Lock, &OldIrql);
-
+
if (AF_IS_VALID(AddrFile))
{
ReceiveRequest = exAllocatePool(NonPagedPool, sizeof(DATAGRAM_RECEIVE_REQUEST));
if (ReceiveRequest)
{
/* Initialize a receive request */
-
+
/* Extract the remote address filter from the request (if any) */
- if ((ConnInfo->RemoteAddressLength != 0) &&
+ if ((ConnInfo->RemoteAddressLength != 0) &&
(ConnInfo->RemoteAddress))
{
Status = AddrGetAddress(ConnInfo->RemoteAddress,
ReceiveRequest->BufferSize = ReceiveLength;
ReceiveRequest->UserComplete = Complete;
ReceiveRequest->UserContext = Context;
- ReceiveRequest->Complete =
+ ReceiveRequest->Complete =
(PDATAGRAM_COMPLETION_ROUTINE)UDPReceiveComplete;
ReceiveRequest->Context = ReceiveRequest;
-
+
/* Queue receive request */
InsertTailList(&AddrFile->ReceiveQueue, &ReceiveRequest->ListEntry);
AF_SET_PENDING(AddrFile, AFF_RECEIVE);
-
+
TcpipReleaseSpinLock(&AddrFile->Lock, OldIrql);
-
+
TI_DbgPrint(MAX_TRACE, ("Leaving (pending).\n"));
-
+
return STATUS_PENDING;
}
else
{
Status = STATUS_INVALID_ADDRESS;
}
-
+
TcpipReleaseSpinLock(&AddrFile->Lock, OldIrql);
-
+
TI_DbgPrint(MAX_TRACE, ("Leaving with errors (0x%X).\n", Status));
-
+
return Status;
}
if( AllocatePort( &UDPPorts, HintPort ) ) return HintPort;
else return (UINT)-1;
} else return AllocatePortFromRange
- ( &UDPPorts, UDP_STARTING_PORT,
+ ( &UDPPorts, UDP_STARTING_PORT,
UDP_STARTING_PORT + UDP_DYNAMIC_PORTS );
}
/*
* Copyright (c) 1997-1998 University of Utah and the Flux Group.
* All rights reserved.
- *
+ *
* This file is part of the Flux OSKit. The OSKit is free software, also known
* as "open source;" you can redistribute it and/or modify it under the terms
* of the GNU General Public License (GPL), version 2, as published by the Free
* Software Foundation (FSF). To explore alternate licensing terms, contact
* the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
- *
+ *
* The OSKit 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 GPL for more details. You should have
#ifndef _FAKE_VM_H
#define _FAKE_VM_H
-typedef void *vm_map_t;
+typedef void *vm_map_t;
#include <vm/vm_param.h>
*/
#define vtophys(va) va
-/*
- * ip_icmp.c and possibly other files rely on vm/vm.h to get sys/proc ...
+/*
+ * ip_icmp.c and possibly other files rely on vm/vm.h to get sys/proc ...
*/
#include <sys/proc.h>
#include <sys/queue.h>
/*
* Copyright (c) 1997-1998 University of Utah and the Flux Group.
* All rights reserved.
- *
+ *
* This file is part of the Flux OSKit. The OSKit is free software, also known
* as "open source;" you can redistribute it and/or modify it under the terms
* of the GNU General Public License (GPL), version 2, as published by the Free
* Software Foundation (FSF). To explore alternate licensing terms, contact
* the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
- *
+ *
* The OSKit 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 GPL for more details. You should have
* constraint because "i" isn't a valid constraint when the port
* isn't constant. This only matters for -O0 because otherwise
* the non-working version gets optimized away.
- *
+ *
* Use an expression-statement instead of a conditional expression
* because gcc-2.6.0 would promote the operands of the conditional
* and produce poor code for "if ((inb(var) & const1) == const2)".
/*
* Copyright (c) 1996-1999 University of Utah and the Flux Group.
* All rights reserved.
- *
+ *
* This file is part of the Flux OSKit. The OSKit is free software, also known
* as "open source;" you can redistribute it and/or modify it under the terms
* of the GNU General Public License (GPL), version 2, as published by the Free
* Software Foundation (FSF). To explore alternate licensing terms, contact
* the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
- *
+ *
* The OSKit 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 GPL for more details. You should have
GENERIC_SPL(clock)
GENERIC_SPL(tty)
GENERIC_SPL(softtty)
-/*
+/*
* this is used to reduce the clock spl to a softclock spl before
* calling the softclock handler directly. It will never call splx!
*/
/*
* functions to save and restore the current cpl
*/
-static __inline void save_cpl(unsigned *x)
+static __inline void save_cpl(unsigned *x)
{
*x = oskit_freebsd_cpl;
}
-static __inline void restore_cpl(unsigned x)
+static __inline void restore_cpl(unsigned x)
{
oskit_freebsd_cpl = x;
}
#define IP_FW_F_COUNT 0x0020 /* This is an accept rule */
#define IP_FW_F_PRN 0x0040 /* Print if this rule matches */
#define IP_FW_F_ICMPRPL 0x0080 /* Send back icmp unreachable packet */
-
+
#define IP_FW_F_SRNG 0x0100 /* The first two src ports are a min *
* and max range (stored in host byte *
* order). */
* Note: ipf_next must be at same offset as ipq_next above
*/
struct ipasfrag {
-#if BYTE_ORDER == LITTLE_ENDIAN
+#if BYTE_ORDER == LITTLE_ENDIAN
u_char ip_hl:4,
ip_v:4;
#endif
-#if BYTE_ORDER == BIG_ENDIAN
+#if BYTE_ORDER == BIG_ENDIAN
u_char ip_v:4,
ip_hl:4;
#endif
struct ip_moptions *));
int ip_next_mtu __P((int, int));
int ip_optcopy __P((struct ip *, struct ip *));
-int ip_output __P((struct mbuf *, struct mbuf *, struct route *, int,
+int ip_output __P((struct mbuf *, struct mbuf *, struct route *, int,
struct ip_moptions *));
int ip_pcbopts __P((struct mbuf **, struct mbuf *));
struct ip *
/*
* Copyright (c) 1997-1998 University of Utah and the Flux Group.
* All rights reserved.
- *
+ *
* This file is part of the Flux OSKit. The OSKit is free software, also known
* as "open source;" you can redistribute it and/or modify it under the terms
* of the GNU General Public License (GPL), version 2, as published by the Free
* Software Foundation (FSF). To explore alternate licensing terms, contact
* the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
- *
+ *
* The OSKit 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 GPL for more details. You should have
/* mbuf flags */
#if defined(OSKIT) && !defined(__REACTOS__)
#include <oskit/io/bufio.h>
-/*
+/*
* A small step for mankind, but a huge leap for BSD:
- * We consistently use oskit_bufios for external mbufs
+ * We consistently use oskit_bufios for external mbufs
*/
#endif
#define M_EXT 0x0001 /* has associated external storage */
/*
* Copyright (c) 1996-1998 University of Utah and the Flux Group.
* All rights reserved.
- *
+ *
* This file is part of the Flux OSKit. The OSKit is free software, also known
* as "open source;" you can redistribute it and/or modify it under the terms
* of the GNU General Public License (GPL), version 2, as published by the Free
* Software Foundation (FSF). To explore alternate licensing terms, contact
* the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
- *
+ *
* The OSKit 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 GPL for more details. You should have
osenv_sleeprec_t p_sr;
/*
* When selrecord is invoked, this points to an object used to
- * manage a set of listeners
+ * manage a set of listeners
*/
struct listener_mgr *p_sel;
#endif /* !OSKIT */
struct name { \
struct type *slh_first; /* first element */ \
}
-
+
#define SLIST_ENTRY(type) \
struct { \
struct type *sle_next; /* next element */ \
}
-
+
/*
* Singly-linked List functions.
*/
#define FreeNdisPacket(x) { TI_DbgPrint(MID_TRACE,("Deleting Packet %x\n", x)); FreeNdisPacketX(x); }
#define NdisFreePacket(x) { Untrack(x); NdisFreePacket(x); }
#define NdisFreeBuffer(x) { Untrack(x); NdisFreeBuffer(x); }
-#define exAllocatePool(x,y) ExAllocatePoolX(x,y,__FILE__,__LINE__)
+#define exAllocatePool(x,y) ExAllocatePoolX(x,y,__FILE__,__LINE__)
#define exAllocatePoolWithTag(x,y,z) ExAllocatePoolX(x,y,__FILE__,__LINE__)
#define exFreePool(x) ExFreePoolX(x,__FILE__,__LINE__)
( POSKITTCP_EVENT_HANDLERS EventHandlers );
extern void OskitTCPReceiveDatagram( OSK_PCHAR Data, OSK_UINT Len,
OSK_UINT IpHeaderLen );
-extern int OskitTCPReceive( void *socket,
+extern int OskitTCPReceive( void *socket,
void *Addr,
OSK_PCHAR Data,
OSK_UINT Len,
OSK_UINT *OutLen,
OSK_UINT Flags );
-extern int OskitTCPSend( void *socket,
+extern int OskitTCPSend( void *socket,
OSK_PCHAR Data,
OSK_UINT Len,
OSK_UINT *OutLen,
OSK_UINT Flags );
-extern int OskitTCPConnect( void *socket, void *connection,
+extern int OskitTCPConnect( void *socket, void *connection,
void *nam, OSK_UINT namelen );
extern int OskitTCPClose( void *socket );
void *nam, OSK_UINT namelen );
extern int OskitTCPAccept( void *socket, void **new_socket,
- void *addr_out,
+ void *addr_out,
OSK_UINT addr_len,
OSK_UINT *out_addr_len,
OSK_UINT finish_accept );
OSK_UINT *OutLen,
OSK_UINT Flags );
-void OskitTCPGetAddress( void *socket,
+void OskitTCPGetAddress( void *socket,
OSK_UINT *LocalAddress,
OSK_UI16 *LocalPort,
OSK_UINT *RemoteAddress,
/*
* Copyright (c) 1996-1998 University of Utah and the Flux Group.
* All rights reserved.
- *
+ *
* This file is part of the Flux OSKit. The OSKit is free software, also known
* as "open source;" you can redistribute it and/or modify it under the terms
* of the GNU General Public License (GPL), version 2, as published by the Free
* Software Foundation (FSF). To explore alternate licensing terms, contact
* the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
- *
+ *
* The OSKit 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 GPL for more details. You should have
#include "net/netisr.h"
int oskit_cpl; /* for machine/spl.h */
-int bootverbose; /* networking code wants to know whether booting
+int bootverbose; /* networking code wants to know whether booting
is to be verbose */
int securelevel = 3; /* used in ip_fw.c:ip_fw_ctl -- make it > 2 */
struct proc *
pfind(pid_t pid)
{
- printf("%s called, pid=%d, returning x%p\n",
+ printf("%s called, pid=%d, returning x%p\n",
"pfind", (int)pid, (void*)&proc0);
return &proc0;
}
/*
- * signal a process
+ * signal a process
*/
-void
+void
psignal (struct proc *p, int sig)
{
printf("%s called, proc=x%p sig=%d\n", "psignal", p, sig);
/*
* signal a process group
*/
-void
+void
gsignal (int pgid, int sig)
{
printf("%s called, pgid=%d sig=%d\n", "gsignal", pgid, sig);
/*
* copy in from userspace
*/
-int
+int
copyin (void *udaddr, void *kaddr, u_int len)
{
memcpy(kaddr, udaddr, len);
/*
* copy out to userspace
*/
-int
+int
copyout (void *kaddr, void *udaddr, u_int len)
{
memcpy(udaddr, kaddr, len);
}
/*
- * even though these functions have an odd signature,
+ * even though these functions have an odd signature,
* they only copy one byte
*/
int subyte (void *base, int byte)
/*
* log some information
*/
-void
+void
log (int level, const char *format, ...)
{
extern int vprintf(const char *, va_list);
/* ---------------------------------------------------------------------- */
-/*
- * do we have super user credentials?
+/*
+ * do we have super user credentials?
*/
/* ARGSUSED */
-int
+int
suser(struct ucred *ucred, u_short *acflag)
{
/* of course. */
}
/* ---------------------------------------------------------------------- */
-/*
+/*
* stuff stolen from kern/kern_sysctl.c
*/
-/*
+/*
* Validate parameters and get old / set new parameters
* for an integer-valued sysctl function.
*/
-int
+int
sysctl_int(oldp, oldlenp, newp, newlen, valp)
void *oldp;
size_t *oldlenp;
void *newp;
- size_t newlen;
+ size_t newlen;
int *valp;
-{
- int error = 0;
-
+{
+ int error = 0;
+
if (oldp && *oldlenp < sizeof(int))
return (ENOMEM);
if (newp && newlen != sizeof(int))
error = copyout(valp, oldp, sizeof(int));
if (error == 0 && newp)
error = copyin(newp, valp, sizeof(int));
- return (error);
-}
+ return (error);
+}
-/*
+/*
* Validate parameters and get old parameters
* for a structure oriented sysctl function.
*/
size_t *oldlenp;
void *newp, *sp;
int len;
-{
+{
int error = 0;
-
+
if (oldp && *oldlenp < len)
return (ENOMEM);
if (newp)
}
/* ---------------------------------------------------------------------- */
-/*
+/*
* normally, this is a builtin function in gcc
* net/if.c doesn't seem to get it, though
*/
u_short lport = 0;
int wild = 0, reuseport = (so->so_options & SO_REUSEPORT);
int error;
-
+
OS_DbgPrint(OSK_MID_TRACE,("Called\n"));
if( nam ) OskitDumpBuffer( nam->m_data, nam->m_len );
return (EADDRNOTAVAIL);
}
#endif
- if (inp->inp_lport || inp->inp_laddr.s_addr != INADDR_ANY)
+ if (inp->inp_lport || inp->inp_laddr.s_addr != INADDR_ANY)
return (EINVAL);
if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0 &&
((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0 ||
*lastport = IPPORT_RESERVED;
lport = htons(*lastport);
} while (in_pcblookup(head,
- zeroin_addr, 0, inp->inp_laddr,
+ zeroin_addr, 0, inp->inp_laddr,
lport, wild));
inp->inp_lport = lport;
in_pcbrehash(inp);
-
+
OS_DbgPrint(OSK_MID_TRACE,("Returning success\n"));
return (0);
}
* and exit to caller, that will do the lookup.
*/
*plocal_sin = (struct sockaddr_in *)ia->ia_ifa.ifa_addr;
- OS_DbgPrint(OSK_MID_TRACE,("plocal sin %x\n",
+ OS_DbgPrint(OSK_MID_TRACE,("plocal sin %x\n",
(*plocal_sin)->sin_addr.s_addr));
}
extern int in_inithead(void **, int);
struct domain inetdomain =
- { AF_INET, "internet", 0, 0, 0,
+ { AF_INET, "internet", 0, 0, 0,
inetsw, &inetsw[sizeof(inetsw)/sizeof(inetsw[0])], 0,
in_inithead, 32, sizeof(struct sockaddr_in)
};
void RegisterOskitTCPEventHandlers( POSKITTCP_EVENT_HANDLERS EventHandlers ) {
memcpy( &OtcpEvent, EventHandlers, sizeof(OtcpEvent) );
- if( OtcpEvent.PacketSend )
+ if( OtcpEvent.PacketSend )
OS_DbgPrint(OSK_MID_TRACE,("SendPacket handler registered: %x\n",
OtcpEvent.PacketSend));
}
/* From uipc_syscalls.c */
int OskitTCPSocket( void *context,
- void **aso,
- int domain,
- int type,
- int proto )
+ void **aso,
+ int domain,
+ int type,
+ int proto )
{
struct socket *so;
int error = socreate(domain, &so, type, proto);
iov.iov_base = Data;
OS_DbgPrint(OSK_MID_TRACE,("Reading %d bytes from TCP:\n", Len));
-
- error = soreceive( connection, NULL, &uio, NULL, NULL /* SCM_RIGHTS */,
+
+ error = soreceive( connection, NULL, &uio, NULL, NULL /* SCM_RIGHTS */,
&tcp_flags );
if( error == 0 ) {
return error;
}
-
+
static int
getsockaddr(namp, uaddr, len)
/* [<][>][^][v][top][bottom][index][help] */
sabuf.m_data = (void *)&addr;
sabuf.m_len = sizeof(addr);
-
+
addr.sa_family = addr.sa_len;
addr.sa_len = sizeof(struct sockaddr);
error = sobind(so, &sabuf);
OS_DbgPrint(OSK_MID_TRACE,("Ending: %08x\n", error));
- return (error);
+ return (error);
}
-int OskitTCPConnect( void *socket, void *connection,
+int OskitTCPConnect( void *socket, void *connection,
void *nam, OSK_UINT namelen ) {
struct socket *so = socket;
struct connect_args _uap = {
sabuf.m_data = (void *)&addr;
sabuf.m_len = sizeof(addr);
-
+
addr.sa_family = addr.sa_len;
addr.sa_len = sizeof(struct sockaddr);
done:
OS_DbgPrint(OSK_MID_TRACE,("Ending: %08x\n", error));
- return (error);
+ return (error);
}
int OskitTCPShutdown( void *socket, int disconn_type ) {
return 0;
}
-int OskitTCPSend( void *socket, OSK_PCHAR Data, OSK_UINT Len,
+int OskitTCPSend( void *socket, OSK_PCHAR Data, OSK_UINT Len,
OSK_UINT *OutLen, OSK_UINT flags ) {
struct mbuf* m = m_devget( Data, Len, 0, NULL, NULL );
int error = 0;
return error;
}
-int OskitTCPAccept( void *socket,
+int OskitTCPAccept( void *socket,
void **new_socket,
- void *AddrOut,
+ void *AddrOut,
OSK_UINT AddrLen,
OSK_UINT *OutAddrLen,
OSK_UINT FinishAccepting ) {
struct socket *head = (void *)socket;
struct sockaddr *name = (struct sockaddr *)AddrOut;
- struct socket **newso = (struct socket **)new_socket;
+ struct socket **newso = (struct socket **)new_socket;
struct socket *so = socket;
struct sockaddr_in sa;
struct mbuf mnam;
OS_DbgPrint(OSK_MID_TRACE,("OSKITTCP: Doing accept (Finish %d)\n",
FinishAccepting));
-
+
*OutAddrLen = AddrLen;
- if (name)
+ if (name)
/* that's a copyin actually */
namelen = *OutAddrLen;
}
#endif
- OS_DbgPrint(OSK_MID_TRACE,("head->so_q = %x, head->so_state = %x\n",
+ OS_DbgPrint(OSK_MID_TRACE,("head->so_q = %x, head->so_state = %x\n",
head->so_q, head->so_state));
if ((head->so_state & SS_NBIO) && head->so_q == NULL) {
error = EWOULDBLOCK;
goto out;
}
-
+
OS_DbgPrint(OSK_MID_TRACE,("error = %d\n", error));
while (head->so_q == NULL && head->so_error == 0) {
if (head->so_state & SS_CANTRCVMORE) {
inp = so ? (struct inpcb *)so->so_pcb : NULL;
if( inp ) {
- ((struct sockaddr_in *)AddrOut)->sin_addr.s_addr =
+ ((struct sockaddr_in *)AddrOut)->sin_addr.s_addr =
inp->inp_faddr.s_addr;
((struct sockaddr_in *)AddrOut)->sin_port = inp->inp_fport;
}
if( FinishAccepting ) {
head->so_q = so->so_q;
head->so_qlen--;
-
+
*newso = so;
-
+
/*so->so_state &= ~SS_COMP;*/
mnam.m_data = (char *)&sa;
mnam.m_len = sizeof(sa);
-
+
(void) soaccept(so, &mnam);
so->so_state = SS_NBIO | SS_ISCONNECTED;
}
/* The story so far
- *
+ *
* We have a packet. While we store the fields we want in host byte order
* outside the original packet, the bsd stack modifies them in place.
*/
-void OskitTCPReceiveDatagram( OSK_PCHAR Data, OSK_UINT Len,
+void OskitTCPReceiveDatagram( OSK_PCHAR Data, OSK_UINT Len,
OSK_UINT IpHeaderLen ) {
struct mbuf *Ip = m_devget( Data, Len, 0, NULL, NULL );
struct ip *iph;
-
+
if( !Ip ) return; /* drop the segment */
//memcpy( Ip->m_data, Data, Len );
NTOHS(iph->ip_len);
iph->ip_len -= sizeof(struct ip);
- OS_DbgPrint(OSK_MAX_TRACE,
+ OS_DbgPrint(OSK_MAX_TRACE,
("OskitTCPReceiveDatagram: %d (%d header) Bytes\n", Len,
IpHeaderLen));
int OskitTCPListen( void *socket, int backlog ) {
int error;
-
+
OS_DbgPrint(OSK_MID_TRACE,("Called, socket = %08x\n", socket));
error = solisten( socket, backlog );
OS_DbgPrint(OSK_MID_TRACE,("Ending: %08x\n", error));
return error;
}
-void OskitTCPSetAddress( void *socket,
+void OskitTCPSetAddress( void *socket,
OSK_UINT LocalAddress,
OSK_UI16 LocalPort,
OSK_UINT RemoteAddress,
inp->inp_fport = RemotePort;
}
-void OskitTCPGetAddress( void *socket,
+void OskitTCPGetAddress( void *socket,
OSK_UINT *LocalAddress,
OSK_UI16 *LocalPort,
OSK_UINT *RemoteAddress,
struct ifaddr *ifa_iffind(struct sockaddr *addr, int type)
{
- if( OtcpEvent.FindInterface )
+ if( OtcpEvent.FindInterface )
return OtcpEvent.FindInterface( OtcpEvent.ClientData,
PF_INET,
type,
{
sin = (struct sockaddr_in *)&ifaddr->ifa_addr;
- OS_DbgPrint(OSK_MID_TRACE,("ifaddr->addr = %x\n",
+ OS_DbgPrint(OSK_MID_TRACE,("ifaddr->addr = %x\n",
sin->sin_addr.s_addr));
}
}
#else
OS_DbgPrint(OSK_MID_TRACE,("Using default mtu of 1500\n"));
- len = (1500 - hlen) & ~7;
+ len = (1500 - hlen) & ~7;
#endif
{
m_free( new_m );
goto done;
}
-
+
OS_DbgPrint(OSK_MID_TRACE,("Error from upper layer: %d\n", error));
#endif
}
switch (optname) {
#ifndef __REACTOS__
- case IP_MULTICAST_VIF:
+ case IP_MULTICAST_VIF:
if (imo != NULL)
*(mtod(*mp, int *)) = imo->imo_multicast_vif;
else
/*
* Copyright (c) 1997-1998 University of Utah and the Flux Group.
* All rights reserved.
- *
+ *
* This file is part of the Flux OSKit. The OSKit is free software, also known
* as "open source;" you can redistribute it and/or modify it under the terms
* of the GNU General Public License (GPL), version 2, as published by the Free
* Software Foundation (FSF). To explore alternate licensing terms, contact
* the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
- *
+ *
* The OSKit 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 GPL for more details. You should have
/*
* Copyright (c) 1997-1998 University of Utah and the Flux Group.
* All rights reserved.
- *
+ *
* This file is part of the Flux OSKit. The OSKit is free software, also known
* as "open source;" you can redistribute it and/or modify it under the terms
* of the GNU General Public License (GPL), version 2, as published by the Free
* Software Foundation (FSF). To explore alternate licensing terms, contact
* the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
- *
+ *
* The OSKit 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 GPL for more details. You should have
#define MAXUSERS 64
int hz = HZ;
-int tick = 1000000 / HZ;
+int tick = 1000000 / HZ;
int nmbclusters = 512 + MAXUSERS * 16;
if (*m) (void)m_free(*m);
return(EINVAL);
}
- return (*ip_fw_ctl_ptr)(optname, m);
+ return (*ip_fw_ctl_ptr)(optname, m);
case IP_FW_ADD:
case IP_FW_DEL:
case IP_FW_FLUSH:
return(EINVAL);
}
- return (*ip_fw_ctl_ptr)(optname, m);
+ return (*ip_fw_ctl_ptr)(optname, m);
return(error);
case IP_RSVP_ON:
*/
rt2 = rtalloc1(dst, 0, RTF_PRCLONING);
if (rt2 && rt2->rt_parent) {
- rtrequest(RTM_DELETE,
+ rtrequest(RTM_DELETE,
(struct sockaddr *)rt_key(rt2),
rt2->rt_gateway,
rt_mask(rt2), rt2->rt_flags, 0);
int tsleep( void *token, int priority, char *wmesg, int tmio ) {
if( !OtcpEvent.Sleep ) panic("no sleep");
- return
+ return
OtcpEvent.Sleep( OtcpEvent.ClientData, token, priority, wmesg, tmio );
}
OSK_UINT flags = 0;
OS_DbgPrint
- (OSK_MID_TRACE,("XXX Bytes to receive: %d state %x\n",
+ (OSK_MID_TRACE,("XXX Bytes to receive: %d state %x\n",
so->so_rcv.sb_cc, so->so_state));
if( so->so_state & SS_ISCONNECTED ) {
token, so,
so->so_state));
- if( OtcpEvent.SocketState )
+ if( OtcpEvent.SocketState )
OtcpEvent.SocketState( OtcpEvent.ClientData,
so,
so ? so->so_connection : 0,
flags );
- if( OtcpEvent.Wakeup )
+ if( OtcpEvent.Wakeup )
OtcpEvent.Wakeup( OtcpEvent.ClientData, token );
OS_DbgPrint(OSK_MID_TRACE,("Wakeup done %x\n", token));
/* ---------------------------------------------------------------------- */
-static void
+static void
timeout_init(void)
{
int i;
/*
* functions to save and restore the current cpl
*/
-void save_cpl(unsigned *x)
+void save_cpl(unsigned *x)
{
*x = cpl;
}
-void restore_cpl(unsigned x)
+void restore_cpl(unsigned x)
{
cpl = x;
}
short ostate = 0;
#endif
bzero((char *)&to, sizeof(to));
-
+
tcpstat.tcps_rcvtotal++;
/*
* Get IP and TCP header together in first mbuf.
}
ti = mtod(m, struct tcpiphdr *);
}
-
+
/*
* Checksum extended TCP header and data.
*/
* Instead tcp_output calls ip_output which produces a packet
* and ends up in tcp_input and we're stuck in infinite loop.
* Normally the flags are masked out at the end of this function
- * and the incomming packets are processed then, but since
- * currently the loopback packet is delivered during the
+ * and the incomming packets are processed then, but since
+ * currently the loopback packet is delivered during the
* ip_output call, the function end is never reached...
*/
#ifdef __REACTOS__
/*
* Copyright (c) 1997-1998 University of Utah and the Flux Group.
* All rights reserved.
- *
+ *
* This file is part of the Flux OSKit. The OSKit is free software, also known
* as "open source;" you can redistribute it and/or modify it under the terms
* of the GNU General Public License (GPL), version 2, as published by the Free
* Software Foundation (FSF). To explore alternate licensing terms, contact
* the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
- *
+ *
* The OSKit 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 GPL for more details. You should have
npg = ncl * CLSIZE;
//printf("kmem_malloc(%d)\n", npg);
-
+
p = (caddr_t)kmem_malloc(mb_map, ctob(npg),
nowait ? M_NOWAIT : M_WAITOK);
-
+
//printf("kmem_malloc done\n");
/*
return (n);
}
-#ifndef OSKIT
+#ifndef OSKIT
/* currently not OS Kit approved, and shouldn't be needed in the first place */
-
+
/*
* Routine to copy from device local memory into mbufs.
*/
so->so_rcv.sb_mb = m->m_next;
m->m_next = 0;
m = so->so_rcv.sb_mb;
- } else
+ } else
#endif
{
MFREE(m, so->so_rcv.sb_mb);
register struct socket *so;
{
OS_DbgPrint(OSK_MID_TRACE,("Called %x\n", so));
-
+
so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE);
wakeup(so, (caddr_t)&so->so_timeo);
ExFreePool(Buffer);
}
-#define INIT_FUNCTION
+#define INIT_FUNCTION
VOID INIT_FUNCTION
ExpInitLookasideLists()
USHORT Depth)
{
DbgPrint("Initializing nonpaged lookaside list at 0x%X\n", Lookaside);
-
+
Lookaside->TotalAllocates = 0;
Lookaside->AllocateMisses = 0;
Lookaside->TotalFrees = 0;
Lookaside->FreeMisses = 0;
Lookaside->Type = NonPagedPool;
Lookaside->Tag = Tag;
-
+
/* We use a field of type SINGLE_LIST_ENTRY as a link to the next entry in
the lookaside list so we must allocate at least sizeof(SINGLE_LIST_ENTRY) */
if (Size < sizeof(SINGLE_LIST_ENTRY))
Lookaside->Size = sizeof(SINGLE_LIST_ENTRY);
else
Lookaside->Size = Size;
-
+
if (Allocate)
Lookaside->Allocate = Allocate;
else
Lookaside->Allocate = ExpDefaultAllocate;
-
+
if (Free)
Lookaside->Free = Free;
else
Lookaside->Free = ExpDefaultFree;
-
+
ExInitializeSListHead(&Lookaside->ListHead);
KeInitializeSpinLock(LookasideListLock(Lookaside));
-
+
/* Determine minimum and maximum number of entries on the lookaside list
using the configured algorithm */
(*ExpMinMaxRoutine)(
Lookaside->Size,
&Lookaside->Depth,
&Lookaside->MaximumDepth);
-
+
ExInterlockedInsertTailList(
&ExpNonPagedLookasideListHead,
&Lookaside->ListEntry,
static LIST_ENTRY WorkQueue = { &WorkQueue, &WorkQueue };
-VOID STDCALL ExQueueWorkItem( PWORK_QUEUE_ITEM WorkItem,
+VOID STDCALL ExQueueWorkItem( PWORK_QUEUE_ITEM WorkItem,
WORK_QUEUE_TYPE Type ) {
InsertTailList( &WorkQueue, &WorkItem->List );
}
BOOLEAN STDCALL KeCancelTimer( PKTIMER Timer ) {
PLIST_ENTRY ListEntry;
- for( ListEntry = Timers.Flink;
- ListEntry != &Timers;
+ for( ListEntry = Timers.Flink;
+ ListEntry != &Timers;
ListEntry = ListEntry->Flink ) {
if( ListEntry == &Timer->TimerListEntry ) {
RemoveEntryList( &Timer->TimerListEntry );
while( (ListEntry = RemoveHeadList( &Timers )) ) {
Timer = CONTAINING_RECORD( ListEntry, KTIMER, TimerListEntry );
if( Timer->DueTime.QuadPart < Time.QuadPart )
- (Timer->Dpc->DeferredRoutine)( Timer->Dpc,
+ (Timer->Dpc->DeferredRoutine)( Timer->Dpc,
Timer->Dpc->DeferredContext,
Timer->Dpc->SystemArgument1,
Timer->Dpc->SystemArgument2 );
/* Host uses this */
PWORK_QUEUE_ITEM GetWorkQueueItem() {
PLIST_ENTRY ListEntry = RemoveHeadList( &WorkQueue );
- if( ListEntry )
+ if( ListEntry )
return CONTAINING_RECORD(ListEntry, WORK_QUEUE_ITEM, List);
else
return NULL;
NdisQueryPacket(Packet, NULL, NULL, &NdisBuffer, NULL);
- if (!NdisBuffer)
+ if (!NdisBuffer)
{
NDIS_DbgPrint(MID_TRACE, ("Packet contains no buffers.\n"));
return FALSE;
/* FIXME: Should handle fragmented packets */
- switch (Adapter->NdisMiniportBlock.MediaType)
+ switch (Adapter->NdisMiniportBlock.MediaType)
{
case NdisMedium802_3:
Length = ETH_LENGTH_OF_ADDRESS;
return FALSE;
}
- if (BufferLength < Length)
+ if (BufferLength < Length)
{
NDIS_DbgPrint(MID_TRACE, ("Buffer is too small.\n"));
return FALSE;
Adapter->NdisMiniportBlock.MediaRequest = NdisRequest;
- switch (NdisRequest->RequestType)
+ switch (NdisRequest->RequestType)
{
case NdisRequestQueryInformation:
return (*Adapter->Miniport->Chars.QueryInformationHandler)(
/* KIRQL OldIrql; */
PLIST_ENTRY CurrentEntry;
PADAPTER_BINDING AdapterBinding;
-
+
NDIS_DbgPrint(DEBUG_MINIPORT, ("Called. Adapter (0x%X) HeaderBuffer (0x%X) "
"HeaderBufferSize (0x%X) LookaheadBuffer (0x%X) LookaheadBufferSize (0x%X).\n",
Adapter, HeaderBuffer, HeaderBufferSize, LookaheadBuffer, LookaheadBufferSize));
CurrentEntry = Adapter->ProtocolListHead.Flink;
NDIS_DbgPrint(DEBUG_MINIPORT, ("CurrentEntry = %x\n", CurrentEntry));
- if (CurrentEntry == &Adapter->ProtocolListHead)
+ if (CurrentEntry == &Adapter->ProtocolListHead)
{
NDIS_DbgPrint(DEBUG_MINIPORT, ("WARNING: No upper protocol layer.\n"));
}
- while (CurrentEntry != &Adapter->ProtocolListHead)
+ while (CurrentEntry != &Adapter->ProtocolListHead)
{
AdapterBinding = CONTAINING_RECORD(CurrentEntry, ADAPTER_BINDING, AdapterListEntry);
NDIS_DbgPrint(DEBUG_MINIPORT, ("AdapterBinding = %x\n", AdapterBinding));
#endif
NDIS_DbgPrint
- (MID_TRACE,
+ (MID_TRACE,
("XXX (%x) %x %x %x %x %x %x %x XXX\n",
*AdapterBinding->ProtocolBinding->Chars.u4.ReceiveHandler,
AdapterBinding->NdisOpenBlock.ProtocolBindingContext,
{
CurrentEntry = AdapterListHead.Flink;
- while (CurrentEntry != &AdapterListHead)
+ while (CurrentEntry != &AdapterListHead)
{
Adapter = CONTAINING_RECORD(CurrentEntry, LOGICAL_ADAPTER, ListEntry);
NDIS_DbgPrint(DEBUG_MINIPORT, ("AdapterName = %wZ\n", &AdapterName));
NDIS_DbgPrint(DEBUG_MINIPORT, ("DeviceName = %wZ\n", &Adapter->DeviceName));
- if (RtlCompareUnicodeString(AdapterName, &Adapter->DeviceName, TRUE) == 0)
+ if (RtlCompareUnicodeString(AdapterName, &Adapter->DeviceName, TRUE) == 0)
{
ReferenceObject(Adapter);
break;
if(Adapter)
{
- NDIS_DbgPrint(DEBUG_MINIPORT, ("Leaving. Adapter found at 0x%x\n", Adapter));
+ NDIS_DbgPrint(DEBUG_MINIPORT, ("Leaving. Adapter found at 0x%x\n", Adapter));
}
else
{
{
if (Buffer->ByteCount == 0)
return 1;
-
+
return ADDRESS_AND_SIZE_TO_SPAN_PAGES(
MmGetMdlVirtualAddress(Buffer),
MmGetMdlByteCount(Buffer));
NDIS_DbgPrint(MID_TRACE,("Free buffer -> %x\n", Temp));
Temp = Temp->Next;
}
-
+
NDIS_DbgPrint(MID_TRACE,("|:. <- End free buffers"));
#endif
Temp->Mdl.ByteOffset = (ULONG_PTR)(VirtualAddress - PAGE_ROUND_DOWN(VirtualAddress));
Temp->Mdl.ByteCount = Length;
Temp->Mdl.MappedSystemVa = VirtualAddress;
-
+
Temp->BufferPool = Pool;
*Buffer = (PNDIS_BUFFER)Temp;
/*
* FUNCTION: Copies data from a buffer to an NDIS buffer chain
* ARGUMENTS:
- * DstBuffer = Pointer to destination NDIS buffer
+ * DstBuffer = Pointer to destination NDIS buffer
* DstOffset = Destination start offset
* SrcData = Pointer to source buffer
* Length = Number of bytes to copy
DbgPrint("DstData 0x%X SrcBuffer 0x%X SrcOffset 0x%X Length %d\n",
DstData,SrcBuffer, SrcOffset, Length);
-
+
/* Skip SrcOffset bytes in the source buffer chain */
if (SkipToOffset(SrcBuffer, SrcOffset, &SrcData, &SrcSize) == -1)
return 0;
for (;;) {
BytesToCopy = MIN(SrcSize, Length);
- DbgPrint("Copying (%d) bytes from 0x%X to 0x%X\n",
+ DbgPrint("Copying (%d) bytes from 0x%X to 0x%X\n",
BytesToCopy, SrcData, DstData);
RtlCopyMemory((PVOID)DstData, (PVOID)SrcData, BytesToCopy);
UINT Count, Total;
DbgPrint("DstBuffer (0x%X) DstOffset (0x%X) SrcPacket (0x%X) "
- "SrcOffset (0x%X) Length (%d)\n",
+ "SrcOffset (0x%X) Length (%d)\n",
DstBuffer, DstOffset, SrcPacket, SrcOffset, Length);
/* Skip DstOffset bytes in the destination buffer chain */
NdisQueryPacket( SrcPacket, &SrcBuffer, 0, &SrcSize, &Total );
NdisQueryBuffer( SrcBuffer, (PVOID *)&SrcData, &SrcSize );
#if 0
- NdisGetFirstBufferFromPacket(SrcPacket, &SrcBuffer, (PVOID *)&SrcData,
+ NdisGetFirstBufferFromPacket(SrcPacket, &SrcBuffer, (PVOID *)&SrcData,
&SrcSize, &Total);
#endif
if (SkipToOffset(SrcBuffer, SrcOffset, &SrcData, &SrcSize) == -1)
}
void GetDataPtr( PNDIS_PACKET Packet,
- UINT Offset,
+ UINT Offset,
PCHAR *DataOut,
PUINT Size ) {
PNDIS_BUFFER Buffer;
PCHAR NewData;
NewData = ExAllocatePool( NonPagedPool, Len );
- if( !NewData ) return NDIS_STATUS_NOT_ACCEPTED; // XXX
+ if( !NewData ) return NDIS_STATUS_NOT_ACCEPTED; // XXX
TrackWithTag(EXALLOC_TAG, NewData, File, Line);
- if( Data )
+ if( Data )
RtlCopyMemory(NewData, Data, Len);
NdisAllocatePacket( &Status, &Packet, GlobalPacketPool );
Status = TdiOpenAddressFile
( &FCB->TdiDeviceName,
FCB->LocalAddress,
- &FCB->AddressFile.Handle,
+ &FCB->AddressFile.Handle,
&FCB->AddressFile.Object );
}
PFILE_OBJECT FileObject = IrpSp->FileObject;
PAFD_FCB FCB = FileObject->FsContext;
PAFD_BIND_DATA BindReq;
-
+
AFD_DbgPrint(MID_TRACE,("Called\n"));
-
+
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, FALSE );
- if( !(BindReq = LockRequest( Irp, IrpSp )) )
- return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY,
+ if( !(BindReq = LockRequest( Irp, IrpSp )) )
+ return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY,
Irp, 0, NULL, FALSE );
-
+
FCB->LocalAddress = TaCopyTransportAddress( &BindReq->Address );
- if( FCB->LocalAddress )
+ if( FCB->LocalAddress )
Status = WarmSocketForBind( FCB );
else Status = STATUS_NO_MEMORY;
- if( NT_SUCCESS(Status) )
+ if( NT_SUCCESS(Status) )
FCB->State = SOCKET_STATE_BOUND;
else return UnlockAndMaybeComplete( FCB, Status, Irp, 0, NULL, FALSE );
FCB->LocalAddress );
AFD_DbgPrint(MID_TRACE,("Calling TdiReceiveDatagram\n"));
-
+
Status = TdiReceiveDatagram
( &FCB->ReceiveIrp.InFlightRequest,
FCB->AddressFile.Object,
( &FCB->TdiDeviceName,
&FCB->Connection.Handle,
&FCB->Connection.Object );
-
+
if( NT_SUCCESS(Status) ) {
Status = TdiAssociateAddressFile
( FCB->AddressFile.Handle,
NTSTATUS Status = STATUS_NO_MEMORY;
/* Allocate the receive area and start receiving */
- FCB->Recv.Window =
+ FCB->Recv.Window =
ExAllocatePool( NonPagedPool, FCB->Recv.Size );
- FCB->Send.Window =
+ FCB->Send.Window =
ExAllocatePool( NonPagedPool, FCB->Send.Size );
FCB->State = SOCKET_STATE_CONNECTED;
-
+
if( FCB->Recv.Window ) {
Status = TdiReceive( &FCB->ReceiveIrp.InFlightRequest,
FCB->Connection.Object,
PLIST_ENTRY NextIrpEntry;
PIRP NextIrp;
- AFD_DbgPrint(MID_TRACE,("Called: FCB %x, FO %x\n",
+ AFD_DbgPrint(MID_TRACE,("Called: FCB %x, FO %x\n",
Context, FCB->FileObject));
/* I was wrong about this before as we can have pending writes to a not
* yet connected socket */
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, FALSE );
- AFD_DbgPrint(MID_TRACE,("Irp->IoStatus.Status = %x\n",
+ AFD_DbgPrint(MID_TRACE,("Irp->IoStatus.Status = %x\n",
Irp->IoStatus.Status));
if( NT_SUCCESS(Irp->IoStatus.Status) ) {
FCB->State = SOCKET_STATE_BOUND;
PollReeval( FCB->DeviceExt, FCB->FileObject );
}
-
+
/* Succeed pending irps on the FUNCTION_CONNECT list */
while( !IsListEmpty( &FCB->PendingIrpList[FUNCTION_CONNECT] ) ) {
NextIrpEntry = RemoveHeadList(&FCB->PendingIrpList[FUNCTION_CONNECT]);
if( NT_SUCCESS(Status) ) {
Status = MakeSocketIntoConnection( FCB );
- if( FCB->Send.Window &&
+ if( FCB->Send.Window &&
!IsListEmpty( &FCB->PendingIrpList[FUNCTION_SEND] ) ) {
NextIrpEntry = RemoveHeadList(&FCB->PendingIrpList[FUNCTION_SEND]);
- NextIrp = CONTAINING_RECORD(NextIrpEntry, IRP,
+ NextIrp = CONTAINING_RECORD(NextIrpEntry, IRP,
Tail.Overlay.ListEntry);
AFD_DbgPrint(MID_TRACE,("Launching send request %x\n", NextIrp));
Status = AfdConnectedSocketWriteData
SocketStateUnlock( FCB );
AFD_DbgPrint(MID_TRACE,("Returning %x\n", Status));
-
+
return Status;
}
AFD_DbgPrint(MID_TRACE,("Called on %x\n", FCB));
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, FALSE );
- if( !(ConnectReq = LockRequest( Irp, IrpSp )) )
- return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY, Irp,
+ if( !(ConnectReq = LockRequest( Irp, IrpSp )) )
+ return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY, Irp,
0, NULL, TRUE );
AFD_DbgPrint(MID_TRACE,("Connect request:\n"));
OskitDumpBuffer
- ( (PCHAR)ConnectReq,
+ ( (PCHAR)ConnectReq,
IrpSp->Parameters.DeviceIoControl.InputBufferLength );
switch( FCB->State ) {
return LeaveIrpUntilLater( FCB, Irp, FUNCTION_CONNECT );
case SOCKET_STATE_CREATED: {
- FCB->LocalAddress =
+ FCB->LocalAddress =
TaCopyTransportAddress( &ConnectReq->RemoteAddress );
if( FCB->LocalAddress ) {
- RtlZeroMemory( FCB->LocalAddress,
+ RtlZeroMemory( FCB->LocalAddress,
TaLengthOfTransportAddress
( &ConnectReq->RemoteAddress ) );
-
+
FCB->LocalAddress->TAAddressCount = 1;
- FCB->LocalAddress->Address[0].AddressType =
+ FCB->LocalAddress->Address[0].AddressType =
ConnectReq->RemoteAddress.Address[0].AddressType;
- FCB->LocalAddress->Address[0].AddressLength =
+ FCB->LocalAddress->Address[0].AddressLength =
ConnectReq->RemoteAddress.Address[0].AddressLength;
-
+
Status = WarmSocketForBind( FCB );
-
- if( NT_SUCCESS(Status) )
+
+ if( NT_SUCCESS(Status) )
FCB->State = SOCKET_STATE_BOUND;
else
- return UnlockAndMaybeComplete( FCB, Status, Irp, 0, NULL,
+ return UnlockAndMaybeComplete( FCB, Status, Irp, 0, NULL,
TRUE );
} else
return UnlockAndMaybeComplete
- ( FCB, STATUS_NO_MEMORY, Irp, 0, NULL, TRUE );
+ ( FCB, STATUS_NO_MEMORY, Irp, 0, NULL, TRUE );
} /* Drop through to SOCKET_STATE_BOUND */
-
+
case SOCKET_STATE_BOUND:
- FCB->RemoteAddress =
+ FCB->RemoteAddress =
TaCopyTransportAddress( &ConnectReq->RemoteAddress );
if( FCB->Flags & AFD_ENDPOINT_CONNECTIONLESS )
TdiBuildConnectionInfo
( &TargetAddress,
&ConnectReq->RemoteAddress );
-
+
if( TargetAddress ) {
- Status = TdiConnect( &FCB->ConnectIrp.InFlightRequest,
+ Status = TdiConnect( &FCB->ConnectIrp.InFlightRequest,
FCB->Connection.Object,
TargetAddress,
&FCB->ConnectIrp.Iosb,
ExFreePool( TargetAddress );
AFD_DbgPrint(MID_TRACE,("Queueing IRP %x\n", Irp));
-
- if( Status == STATUS_PENDING )
+
+ if( Status == STATUS_PENDING )
return LeaveIrpUntilLater( FCB, Irp, FUNCTION_CONNECT );
} else Status = STATUS_NO_MEMORY;
break;
FCB->State));
break;
}
-
+
return UnlockAndMaybeComplete( FCB, Status, Irp, 0, NULL, TRUE );
}
#include "debug.h"
NTSTATUS STDCALL
-AfdGetContext( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdGetContext( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
NTSTATUS Status = STATUS_INVALID_PARAMETER;
PFILE_OBJECT FileObject = IrpSp->FileObject;
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, TRUE );
if( FCB->ContextSize < ContextSize ) ContextSize = FCB->ContextSize;
-
+
if( FCB->Context ) {
RtlCopyMemory( Irp->UserBuffer,
FCB->Context,
}
NTSTATUS STDCALL
-AfdSetContext( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdSetContext( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
NTSTATUS Status = STATUS_NO_MEMORY;
PFILE_OBJECT FileObject = IrpSp->FileObject;
PAFD_FCB FCB = FileObject->FsContext;
-
+
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, TRUE );
- if( FCB->ContextSize <
+ if( FCB->ContextSize <
IrpSp->Parameters.DeviceIoControl.InputBufferLength ) {
if( FCB->Context )
ExFreePool( FCB->Context );
- FCB->Context =
+ FCB->Context =
ExAllocatePool
- ( PagedPool,
+ ( PagedPool,
IrpSp->Parameters.DeviceIoControl.InputBufferLength );
}
-
+
if( FCB->Context ) {
Status = STATUS_SUCCESS;
- RtlCopyMemory( FCB->Context,
+ RtlCopyMemory( FCB->Context,
IrpSp->Parameters.DeviceIoControl.Type3InputBuffer,
IrpSp->Parameters.DeviceIoControl.InputBufferLength );
}
AFD_DbgPrint(MAX_TRACE, ("Called.\n"));
- AFD_DbgPrint(MID_TRACE, ("Receiving (%d) bytes on socket\n",
+ AFD_DbgPrint(MID_TRACE, ("Receiving (%d) bytes on socket\n",
BytesAvailable));
ReceiveBuffer = ExAllocatePool(NonPagedPool, BytesAvailable);
#include "pseh.h"
NTSTATUS STDCALL
-AfdGetInfo( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdGetInfo( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
NTSTATUS Status = STATUS_SUCCESS;
PAFD_INFO InfoReq = IrpSp->Parameters.DeviceIoControl.Type3InputBuffer;
PFILE_OBJECT FileObject = IrpSp->FileObject;
PAFD_FCB FCB = FileObject->FsContext;
- AFD_DbgPrint(MID_TRACE,("Called %x %x\n", InfoReq,
+ AFD_DbgPrint(MID_TRACE,("Called %x %x\n", InfoReq,
InfoReq ? InfoReq->InformationClass : 0));
_SEH_TRY {
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, TRUE );
-
+
switch( InfoReq->InformationClass ) {
case AFD_INFO_RECEIVE_WINDOW_SIZE:
InfoReq->Information.Ulong = FCB->Recv.Size;
break;
-
+
case AFD_INFO_SEND_WINDOW_SIZE:
InfoReq->Information.Ulong = FCB->Send.Size;
AFD_DbgPrint(MID_TRACE,("Send window size %d\n", FCB->Send.Size));
break;
-
+
case AFD_INFO_GROUP_ID_TYPE:
InfoReq->Information.Ulong = 0; /* What is group id */
break;
case AFD_INFO_BLOCKING_MODE:
InfoReq->Information.Ulong = 0;
break;
-
+
default:
- AFD_DbgPrint(MID_TRACE,("Unknown info id %x\n",
+ AFD_DbgPrint(MID_TRACE,("Unknown info id %x\n",
InfoReq->InformationClass));
Status = STATUS_INVALID_PARAMETER;
break;
}
NTSTATUS STDCALL
-AfdGetSockOrPeerName( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdGetSockOrPeerName( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp, BOOLEAN Local ) {
NTSTATUS Status = STATUS_SUCCESS;
PFILE_OBJECT FileObject = IrpSp->FileObject;
}
Mdl = IoAllocateMdl
- ( Irp->UserBuffer,
+ ( Irp->UserBuffer,
IrpSp->Parameters.DeviceIoControl.OutputBufferLength,
FALSE,
FALSE,
} else {
if( !NT_SUCCESS
( Status = TdiBuildNullConnectionInfo
- ( &ConnInfo,
+ ( &ConnInfo,
FCB->LocalAddress->Address[0].AddressType ) ) ) {
SysMdl = IoAllocateMdl
- ( ConnInfo,
+ ( ConnInfo,
sizeof( TDI_CONNECTION_INFORMATION ) +
TaLengthOfTransportAddress
( ConnInfo->RemoteAddress ),
TDI_QUERY_CONNECTION_INFO,
SysMdl );
} else Status = STATUS_NO_MEMORY;
-
+
if( NT_SUCCESS(Status) ) {
- TransAddr =
+ TransAddr =
(PTRANSPORT_ADDRESS)MmMapLockedPages
( Mdl, IoModifyAccess );
}
-
- if( TransAddr )
+
+ if( TransAddr )
RtlCopyMemory( TransAddr, ConnInfo->RemoteAddress,
TaLengthOfTransportAddress
( ConnInfo->RemoteAddress ) );
-
+
if( ConnInfo ) ExFreePool( ConnInfo );
if( SysMdl ) IoFreeMdl( SysMdl );
}
}
-
+
/* MmUnlockPages( Mdl ); */
IoFreeMdl( Mdl );
} else {
Status = STATUS_INSUFFICIENT_RESOURCES;
}
-
+
AFD_DbgPrint(MID_TRACE,("Returning %x\n", Status));
return UnlockAndMaybeComplete( FCB, Status, Irp, 0, NULL, FALSE );
#include "debug.h"
VOID SatisfyAccept( PAFD_DEVICE_EXTENSION DeviceExt,
- PIRP Irp,
+ PIRP Irp,
PFILE_OBJECT NewFileObject,
PAFD_TDI_OBJECT_QELT Qelt ) {
PAFD_FCB FCB = NewFileObject->FsContext;
- if( !SocketAcquireStateLock( FCB ) ) return;
+ if( !SocketAcquireStateLock( FCB ) ) return;
/* Transfer the connection to the new socket, launch the opening read */
AFD_DbgPrint(MID_TRACE,("Completing a real accept (FCB %x)\n", FCB));
FCB->State = SOCKET_STATE_CONNECTED;
FCB->Connection = Qelt->Object;
- FCB->RemoteAddress =
+ FCB->RemoteAddress =
TaCopyTransportAddress( Qelt->ConnInfo->RemoteAddress );
Irp->IoStatus.Information = 0;
MakeSocketIntoConnection( FCB );
FCB->PollState |= AFD_EVENT_SEND;
PollReeval( DeviceExt, NewFileObject );
-
+
SocketStateUnlock( FCB );
}
VOID SatisfyPreAccept( PIRP Irp, PAFD_TDI_OBJECT_QELT Qelt ) {
- PAFD_RECEIVED_ACCEPT_DATA ListenReceive =
+ PAFD_RECEIVED_ACCEPT_DATA ListenReceive =
(PAFD_RECEIVED_ACCEPT_DATA)Irp->AssociatedIrp.SystemBuffer;
PTA_IP_ADDRESS IPAddr;
AFD_DbgPrint(MID_TRACE,("Giving SEQ %d to userland\n", Qelt->Seq));
AFD_DbgPrint(MID_TRACE,("Socket Address (K) %x (U) %x\n",
- &ListenReceive->Address,
+ &ListenReceive->Address,
Qelt->ConnInfo->RemoteAddress));
TaCopyTransportAddressInPlace( &ListenReceive->Address,
TdiCloseDevice( FCB->Connection.Handle,
FCB->Connection.Object );
} else {
- UINT AddressType =
+ UINT AddressType =
FCB->LocalAddress->Address[0].AddressType;
Qelt->Object = FCB->Connection;
Qelt->Seq = FCB->ConnSeq++;
- AFD_DbgPrint(MID_TRACE,("Address Type: %d (RA %x)\n",
- AddressType,
+ AFD_DbgPrint(MID_TRACE,("Address Type: %d (RA %x)\n",
+ AddressType,
FCB->ListenIrp.
ConnectionReturnInfo->RemoteAddress));
-
+
TdiBuildNullConnectionInfo( &Qelt->ConnInfo, AddressType );
TaCopyTransportAddressInPlace
( Qelt->ConnInfo->RemoteAddress,
/* Satisfy a pre-accept request if one is available */
if( !IsListEmpty( &FCB->PendingIrpList[FUNCTION_PREACCEPT] ) &&
!IsListEmpty( &FCB->PendingConnections ) ) {
- PLIST_ENTRY PendingIrp =
+ PLIST_ENTRY PendingIrp =
RemoveHeadList( &FCB->PendingIrpList[FUNCTION_PREACCEPT] );
PLIST_ENTRY PendingConn = FCB->PendingConnections.Flink;
SatisfyPreAccept
( CONTAINING_RECORD( PendingIrp, IRP,
Tail.Overlay.ListEntry ),
- CONTAINING_RECORD( PendingConn, AFD_TDI_OBJECT_QELT,
+ CONTAINING_RECORD( PendingConn, AFD_TDI_OBJECT_QELT,
ListEntry ) );
}
-
+
FCB->NeedsNewListen = TRUE;
/* Trigger a select return if appropriate */
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, TRUE );
- if( !(ListenReq = LockRequest( Irp, IrpSp )) )
- return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY, Irp,
+ if( !(ListenReq = LockRequest( Irp, IrpSp )) )
+ return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY, Irp,
0, NULL, FALSE );
-
+
if( FCB->State != SOCKET_STATE_BOUND ) {
Status = STATUS_UNSUCCESSFUL;
AFD_DbgPrint(MID_TRACE,("Could not listen an unbound socket\n"));
return UnlockAndMaybeComplete( FCB, Status, Irp, 0, NULL, TRUE );
}
-
+
FCB->DelayedAccept = ListenReq->UseDelayedAcceptance;
AFD_DbgPrint(MID_TRACE,("ADDRESSFILE: %x\n", FCB->AddressFile.Handle));
FCB->LocalAddress->Address[0].AddressType );
Status = TdiListen( &FCB->ListenIrp.InFlightRequest,
- FCB->Connection.Object,
+ FCB->Connection.Object,
&FCB->ListenIrp.ConnectionCallInfo,
&FCB->ListenIrp.ConnectionReturnInfo,
&FCB->ListenIrp.Iosb,
/* We have a pending connection ... complete this irp right away */
SatisfyPreAccept
- ( Irp,
+ ( Irp,
CONTAINING_RECORD
( PendingConn, AFD_TDI_OBJECT_QELT, ListEntry ) );
PIO_STACK_LOCATION IrpSp ) {
NTSTATUS Status = STATUS_SUCCESS;
PFILE_OBJECT FileObject = IrpSp->FileObject;
- PAFD_DEVICE_EXTENSION DeviceExt =
+ PAFD_DEVICE_EXTENSION DeviceExt =
(PAFD_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PAFD_FCB FCB = FileObject->FsContext;
PAFD_ACCEPT_DATA AcceptData = Irp->AssociatedIrp.SystemBuffer;
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, TRUE );
- FCB->EventsFired &= ~AFD_EVENT_ACCEPT;
+ FCB->EventsFired &= ~AFD_EVENT_ACCEPT;
if( FCB->NeedsNewListen ) {
AFD_DbgPrint(MID_TRACE,("ADDRESSFILE: %x\n", FCB->AddressFile.Handle));
/* Launch new accept socket */
Status = WarmSocketForConnection( FCB );
-
+
if( Status == STATUS_SUCCESS ) {
TdiBuildNullConnectionInfo
( &FCB->ListenIrp.ConnectionReturnInfo,
FCB->LocalAddress->Address[0].AddressType );
-
+
Status = TdiListen( &FCB->ListenIrp.InFlightRequest,
- FCB->Connection.Object,
+ FCB->Connection.Object,
&FCB->ListenIrp.ConnectionCallInfo,
&FCB->ListenIrp.ConnectionReturnInfo,
&FCB->ListenIrp.Iosb,
PAFD_TDI_OBJECT_QELT PendingConnObj =
CONTAINING_RECORD( PendingConn, AFD_TDI_OBJECT_QELT, ListEntry );
- AFD_DbgPrint(MID_TRACE,("Comparing Seq %d to Q %d\n",
- AcceptData->SequenceNumber,
+ AFD_DbgPrint(MID_TRACE,("Comparing Seq %d to Q %d\n",
+ AcceptData->SequenceNumber,
PendingConnObj->Seq));
if( PendingConnObj->Seq == AcceptData->SequenceNumber ) {
KernelMode,
(PVOID *)&NewFileObject,
NULL );
-
+
ASSERT(NewFileObject != FileObject);
ASSERT(NewFileObject->FsContext != FCB);
/* We have a pending connection ... complete this irp right away */
SatisfyAccept( DeviceExt, Irp, NewFileObject, PendingConnObj );
-
+
ObDereferenceObject( NewFileObject );
AFD_DbgPrint(MID_TRACE,("Completed a wait for accept\n"));
-
+
ExFreePool( PendingConnObj );
if( IsListEmpty( &FCB->PendingConnections ) )
FCB->PollState &= ~AFD_EVENT_ACCEPT;
-
+
SocketStateUnlock( FCB );
return Status;
}
/* Lock a method_neither request so it'll be available from DISPATCH_LEVEL */
PVOID LockRequest( PIRP Irp, PIO_STACK_LOCATION IrpSp ) {
- Irp->MdlAddress =
- IoAllocateMdl( IrpSp->Parameters.DeviceIoControl.Type3InputBuffer,
+ Irp->MdlAddress =
+ IoAllocateMdl( IrpSp->Parameters.DeviceIoControl.Type3InputBuffer,
IrpSp->Parameters.DeviceIoControl.InputBufferLength,
FALSE,
FALSE,
NULL );
if( Irp->MdlAddress ) {
MmProbeAndLockPages( Irp->MdlAddress, KernelMode, IoModifyAccess );
- IrpSp->Parameters.DeviceIoControl.Type3InputBuffer =
+ IrpSp->Parameters.DeviceIoControl.Type3InputBuffer =
MmMapLockedPages( Irp->MdlAddress, KernelMode );
return IrpSp->Parameters.DeviceIoControl.Type3InputBuffer;
} else return NULL;
* treat the address buffer as an ordinary client buffer. It's only used
* for datagrams. */
-PAFD_WSABUF LockBuffers( PAFD_WSABUF Buf, UINT Count,
+PAFD_WSABUF LockBuffers( PAFD_WSABUF Buf, UINT Count,
PVOID AddressBuf, PINT AddressLen,
BOOLEAN Write, BOOLEAN LockAddress ) {
UINT i;
}
} _SEH_HANDLE {
AFD_DbgPrint(MIN_TRACE,("Access violation copying buffer info "
- "from userland (%x %x)\n",
+ "from userland (%x %x)\n",
Buf, AddressLen));
ExFreePool( NewBuf );
return NULL;
i, NewBuf[i].buf, NewBuf[i].len));
if( NewBuf[i].len ) {
- NewMdl = IoAllocateMdl( NewBuf[i].buf,
+ NewMdl = IoAllocateMdl( NewBuf[i].buf,
NewBuf[i].len,
FALSE,
FALSE,
if( MapBuf[i].Mdl ) {
AFD_DbgPrint(MID_TRACE,("Probe and lock pages\n"));
- MmProbeAndLockPages( MapBuf[i].Mdl, KernelMode,
+ MmProbeAndLockPages( MapBuf[i].Mdl, KernelMode,
Write ? IoModifyAccess : IoReadAccess );
AFD_DbgPrint(MID_TRACE,("MmProbeAndLock finished\n"));
}
UINT i;
for( i = 0; i < HandleCount; i++ ) {
- if( HandleArray[i].Handle )
+ if( HandleArray[i].Handle )
ObDereferenceObject( (PVOID)HandleArray[i].Handle );
}
AFD_DbgPrint(MAX_TRACE,("Unlocked.\n"));
KePulseEvent( &FCB->StateLockedEvent, IO_NETWORK_INCREMENT, FALSE );
} else {
- AFD_DbgPrint(MAX_TRACE,("New lock count: %d (Thr: %x)\n",
+ AFD_DbgPrint(MAX_TRACE,("New lock count: %d (Thr: %x)\n",
FCB->LockCount, CurrentThread));
}
ExReleaseFastMutex( &FCB->Mutex );
NTSTATUS DDKAPI UnlockAndMaybeComplete
( PAFD_FCB FCB, NTSTATUS Status, PIRP Irp,
- UINT Information,
+ UINT Information,
PIO_COMPLETION_ROUTINE Completion,
BOOL ShouldUnlock ) {
SocketStateUnlock( FCB );
} else {
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = Information;
- if( Completion )
+ if( Completion )
Completion( FCB->DeviceExt->DeviceObject, Irp, FCB );
- if( ShouldUnlock )
+ if( ShouldUnlock )
UnlockRequest( Irp, IoGetCurrentIrpStackLocation( Irp ) );
IoCompleteRequest( Irp, IO_NETWORK_INCREMENT );
}
AFD_DbgPrint(MIN_TRACE,("Called.\n"));
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = Status;
- if( ShouldUnlockIrp )
+ if( ShouldUnlockIrp )
UnlockRequest( Irp, IoGetCurrentIrpStackLocation( Irp ) );
IoCompleteRequest( Irp, IO_NO_INCREMENT );
- return Status;
+ return Status;
}
NTSTATUS LeaveIrpUntilLater( PAFD_FCB FCB, PIRP Irp, UINT Function ) {
- InsertTailList( &FCB->PendingIrpList[Function],
+ InsertTailList( &FCB->PendingIrpList[Function],
&Irp->Tail.Overlay.ListEntry );
return UnlockAndMaybeComplete( FCB, STATUS_PENDING, Irp, 0, NULL, FALSE );
}
void OskitDumpBuffer( PCHAR Data, UINT Len ) {
unsigned int i;
-
+
for( i = 0; i < Len; i++ ) {
if( i && !(i & 0xf) ) DbgPrint( "\n" );
if( !(i & 0xf) ) DbgPrint( "%08x: ", (UINT)(Data + i) );
DeviceExt = DeviceObject->DeviceExtension;
FileObject = IrpSp->FileObject;
Disposition = (IrpSp->Parameters.Create.Options >> 24) & 0xff;
-
+
Irp->IoStatus.Information = 0;
-
+
EaInfo = Irp->AssociatedIrp.SystemBuffer;
-
+
if( EaInfo ) {
ConnectInfo = (PAFD_CREATE_PACKET)(EaInfo->EaName + EaInfo->EaNameLength + 1);
EaInfoValue = (PWCHAR)(((PCHAR)ConnectInfo) + sizeof(AFD_CREATE_PACKET));
-
+
EaLength = sizeof(FILE_FULL_EA_INFORMATION) +
EaInfo->EaNameLength +
EaInfo->EaValueLength;
-
- AFD_DbgPrint(MID_TRACE,("EaInfo: %x, EaInfoValue: %x\n",
+
+ AFD_DbgPrint(MID_TRACE,("EaInfo: %x, EaInfoValue: %x\n",
EaInfo, EaInfoValue));
}
InitializeListHead( &FCB->DatagramList );
InitializeListHead( &FCB->PendingConnections );
-
+
AFD_DbgPrint(MID_TRACE,("%x: Checking command channel\n", FCB));
if( ConnectInfo ) {
FCB->TdiDeviceName.Length = ConnectInfo->SizeOfTransportName;
FCB->TdiDeviceName.MaximumLength = FCB->TdiDeviceName.Length;
- FCB->TdiDeviceName.Buffer =
+ FCB->TdiDeviceName.Buffer =
ExAllocatePool( NonPagedPool, FCB->TdiDeviceName.Length );
RtlCopyMemory( FCB->TdiDeviceName.Buffer,
ConnectInfo->TransportName,
return STATUS_NO_MEMORY;
}
- AFD_DbgPrint(MID_TRACE,("Success: %s %wZ\n",
+ AFD_DbgPrint(MID_TRACE,("Success: %s %wZ\n",
EaInfo->EaName, &FCB->TdiDeviceName));
} else {
AFD_DbgPrint(MID_TRACE,("Success: Control connection\n"));
FCB->Recv.Window = ExAllocatePool( NonPagedPool, FCB->Recv.Size );
FCB->Send.Window = ExAllocatePool( NonPagedPool, FCB->Send.Size );
/* A datagram socket is always sendable */
- FCB->PollState |= AFD_EVENT_SEND;
+ FCB->PollState |= AFD_EVENT_SEND;
PollReeval( FCB->DeviceExt, FCB->FileObject );
}
/* Return early here because we might be called in the mean time. */
if( FCB->Critical ||
- FCB->ListenIrp.InFlightRequest ||
- FCB->ReceiveIrp.InFlightRequest ||
+ FCB->ListenIrp.InFlightRequest ||
+ FCB->ReceiveIrp.InFlightRequest ||
FCB->SendIrp.InFlightRequest ) {
AFD_DbgPrint(MIN_TRACE,("Leaving socket alive (%x %x %x)\n",
FCB->ListenIrp.InFlightRequest,
SocketStateUnlock( FCB );
if( ReturnEarly ) return;
-
- if( FCB->Recv.Window )
+
+ if( FCB->Recv.Window )
ExFreePool( FCB->Recv.Window );
if( FCB->Send.Window )
ExFreePool( FCB->Send.Window );
- if( FCB->AddressFrom )
+ if( FCB->AddressFrom )
ExFreePool( FCB->AddressFrom );
if( FCB->LocalAddress )
ExFreePool( FCB->LocalAddress );
-
+
ExFreePool(FCB->TdiDeviceName.Buffer);
-
+
ExFreePool(FCB);
AFD_DbgPrint(MIN_TRACE,("Deleted (%x)\n", FCB));
AFD_DbgPrint(MID_TRACE,
("AfdClose(DeviceObject %p Irp %p)\n", DeviceObject, Irp));
-
+
AFD_DbgPrint(MID_TRACE,("FCB %x\n", FCB));
FCB->PollState |= AFD_EVENT_CLOSE;
FileObject->FsContext = NULL;
DestroySocket( FCB );
-
+
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
}
NTSTATUS STDCALL
-AfdDisconnect(PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdDisconnect(PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp) {
PFILE_OBJECT FileObject = IrpSp->FileObject;
PAFD_FCB FCB = FileObject->FsContext;
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, FALSE );
- if( !(DisReq = LockRequest( Irp, IrpSp )) )
+ if( !(DisReq = LockRequest( Irp, IrpSp )) )
return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY,
Irp, 0, NULL, FALSE );
Status = TdiBuildNullConnectionInfo
( &ConnInfo, FCB->RemoteAddress->Address[0].AddressType );
- if( !NT_SUCCESS(Status) || !ConnInfo )
+ if( !NT_SUCCESS(Status) || !ConnInfo )
return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY,
Irp, 0, NULL, TRUE );
}
&DisReq->Timeout,
Flags,
&Iosb,
- NULL,
+ NULL,
NULL,
FCB->AddressFrom,
ConnInfo);
-
+
ExFreePool( ConnInfo );
return UnlockAndMaybeComplete( FCB, Status, Irp, 0, NULL, TRUE );
/* write data */
case IRP_MJ_WRITE:
return AfdConnectedSocketWriteData( DeviceObject, Irp, IrpSp, TRUE );
-
+
/* read data */
case IRP_MJ_READ:
return AfdConnectedSocketReadData( DeviceObject, Irp, IrpSp, TRUE );
-
+
case IRP_MJ_DEVICE_CONTROL:
{
switch( IrpSp->Parameters.DeviceIoControl.IoControlCode ) {
return AfdListenSocket( DeviceObject, Irp, IrpSp );
case IOCTL_AFD_RECV:
- return AfdConnectedSocketReadData( DeviceObject, Irp, IrpSp,
+ return AfdConnectedSocketReadData( DeviceObject, Irp, IrpSp,
FALSE );
case IOCTL_AFD_SELECT:
return AfdPacketSocketReadData( DeviceObject, Irp, IrpSp );
case IOCTL_AFD_SEND:
- return AfdConnectedSocketWriteData( DeviceObject, Irp, IrpSp,
+ return AfdConnectedSocketWriteData( DeviceObject, Irp, IrpSp,
FALSE );
case IOCTL_AFD_SEND_DATAGRAM:
}
break;
}
-
+
/* unsupported operations */
default:
{
Status = STATUS_NOT_IMPLEMENTED;
AFD_DbgPrint(MIN_TRACE,
- ("Irp: Unknown Major code was %x\n",
+ ("Irp: Unknown Major code was %x\n",
IrpSp->MajorFunction));
break;
}
}
-
+
AFD_DbgPrint(MID_TRACE, ("Returning %x\n", Status));
Irp->IoStatus.Status = Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return (Status);
}
{
}
-NTSTATUS STDCALL
+NTSTATUS STDCALL
DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
{
PDEVICE_OBJECT DeviceObject;
BOOLEAN CantReadMore( PAFD_FCB FCB ) {
UINT BytesAvailable = FCB->Recv.Content - FCB->Recv.BytesUsed;
-
- return !BytesAvailable &&
+
+ return !BytesAvailable &&
(FCB->PollState & (AFD_EVENT_CLOSE | AFD_EVENT_DISCONNECT));
}
PAFD_RECV_INFO RecvReq,
PUINT TotalBytesCopied ) {
UINT i, BytesToCopy = 0,
- BytesAvailable =
+ BytesAvailable =
FCB->Recv.Content - FCB->Recv.BytesUsed;
*TotalBytesCopied = 0;
PAFD_MAPBUF Map;
Map = (PAFD_MAPBUF)(RecvReq->BufferArray + RecvReq->BufferCount);
- AFD_DbgPrint(MID_TRACE,("Buffer Count: %d @ %x\n",
+ AFD_DbgPrint(MID_TRACE,("Buffer Count: %d @ %x\n",
RecvReq->BufferCount,
RecvReq->BufferArray));
- for( i = 0;
- RecvReq->BufferArray &&
- BytesAvailable &&
- i < RecvReq->BufferCount;
+ for( i = 0;
+ RecvReq->BufferArray &&
+ BytesAvailable &&
+ i < RecvReq->BufferCount;
i++ ) {
- BytesToCopy =
+ BytesToCopy =
MIN( RecvReq->BufferArray[i].len, BytesAvailable );
if( Map[i].Mdl ) {
Map[i].BufferAddress = MmMapLockedPages( Map[i].Mdl, KernelMode );
-
- AFD_DbgPrint(MID_TRACE,("Buffer %d: %x:%d\n",
- i,
+
+ AFD_DbgPrint(MID_TRACE,("Buffer %d: %x:%d\n",
+ i,
Map[i].BufferAddress,
BytesToCopy));
RtlCopyMemory( Map[i].BufferAddress,
FCB->Recv.Window + FCB->Recv.BytesUsed,
BytesToCopy );
-
+
MmUnmapLockedPages( Map[i].BufferAddress, Map[i].Mdl );
-
+
FCB->Recv.BytesUsed += BytesToCopy;
*TotalBytesCopied += BytesToCopy;
BytesAvailable -= BytesToCopy;
AFD_DbgPrint(MID_TRACE,("Replenishing buffer\n"));
SocketCalloutEnter( FCB );
-
+
Status = TdiReceive( &FCB->ReceiveIrp.InFlightRequest,
FCB->Connection.Object,
TDI_RECEIVE_NORMAL,
* with zero bytes if we haven't yet overread, then kill the others.
*/
while( !IsListEmpty( &FCB->PendingIrpList[FUNCTION_RECV] ) ) {
- NextIrpEntry =
+ NextIrpEntry =
RemoveHeadList(&FCB->PendingIrpList[FUNCTION_RECV]);
- NextIrp =
+ NextIrp =
CONTAINING_RECORD(NextIrpEntry, IRP, Tail.Overlay.ListEntry);
NextIrpSp = IoGetCurrentIrpStackLocation( NextIrp );
RecvReq = NextIrpSp->Parameters.DeviceIoControl.Type3InputBuffer;
-
+
AFD_DbgPrint(MID_TRACE,("Completing recv %x (%d)\n", NextIrp,
TotalBytesCopied));
- UnlockBuffers( RecvReq->BufferArray,
+ UnlockBuffers( RecvReq->BufferArray,
RecvReq->BufferCount, FALSE );
- Status = NextIrp->IoStatus.Status =
+ Status = NextIrp->IoStatus.Status =
FCB->Overread ? STATUS_END_OF_FILE : STATUS_SUCCESS;
NextIrp->IoStatus.Information = 0;
if( NextIrp == Irp ) RetStatus = Status;
/* Try to clear some requests */
while( !IsListEmpty( &FCB->PendingIrpList[FUNCTION_RECV] ) &&
NT_SUCCESS(Status) ) {
- NextIrpEntry =
+ NextIrpEntry =
RemoveHeadList(&FCB->PendingIrpList[FUNCTION_RECV]);
- NextIrp =
+ NextIrp =
CONTAINING_RECORD(NextIrpEntry, IRP, Tail.Overlay.ListEntry);
NextIrpSp = IoGetCurrentIrpStackLocation( NextIrp );
RecvReq = NextIrpSp->Parameters.DeviceIoControl.Type3InputBuffer;
} else {
AFD_DbgPrint(MID_TRACE,("Completing recv %x (%d)\n", NextIrp,
TotalBytesCopied));
- UnlockBuffers( RecvReq->BufferArray,
+ UnlockBuffers( RecvReq->BufferArray,
RecvReq->BufferCount, FALSE );
NextIrp->IoStatus.Status = Status;
NextIrp->IoStatus.Information = TotalBytesCopied;
} else
FCB->PollState &= ~AFD_EVENT_RECEIVE;
- PollReeval( FCB->DeviceExt, FCB->FileObject );
+ PollReeval( FCB->DeviceExt, FCB->FileObject );
AFD_DbgPrint(MID_TRACE,("RetStatus for irp %x is %x\n", Irp, RetStatus));
SocketStateUnlock( FCB );
return STATUS_UNSUCCESSFUL;
}
-
+
HandleEOFOnIrp( FCB, Irp->IoStatus.Status, Irp->IoStatus.Information );
ReceiveActivity( FCB, NULL );
-
+
PollReeval( FCB->DeviceExt, FCB->FileObject );
SocketStateUnlock( FCB );
}
NTSTATUS STDCALL
-AfdConnectedSocketReadData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdConnectedSocketReadData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp, BOOLEAN Short) {
NTSTATUS Status = STATUS_INVALID_PARAMETER;
PFILE_OBJECT FileObject = IrpSp->FileObject;
PAFD_FCB FCB = FileObject->FsContext;
PAFD_RECV_INFO RecvReq;
UINT TotalBytesCopied = 0;
-
+
AFD_DbgPrint(MID_TRACE,("Called on %x\n", FCB));
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, FALSE );
FCB->State != SOCKET_STATE_CONNECTING ) {
AFD_DbgPrint(MID_TRACE,("Called recv on wrong kind of socket (s%x)\n",
FCB->State));
- return UnlockAndMaybeComplete( FCB, STATUS_UNSUCCESSFUL,
+ return UnlockAndMaybeComplete( FCB, STATUS_UNSUCCESSFUL,
Irp, 0, NULL, FALSE );
}
if( FCB->Flags & AFD_ENDPOINT_CONNECTIONLESS )
{
AFD_DbgPrint(MID_TRACE,("Receive on connection-less sockets not implemented\n"));
- return UnlockAndMaybeComplete( FCB, STATUS_NOT_IMPLEMENTED,
+ return UnlockAndMaybeComplete( FCB, STATUS_NOT_IMPLEMENTED,
Irp, 0, NULL, FALSE );
}
FCB->EventsFired &= ~AFD_EVENT_RECEIVE;
PollReeval( FCB->DeviceExt, FCB->FileObject );
- if( !(RecvReq = LockRequest( Irp, IrpSp )) )
- return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY,
+ if( !(RecvReq = LockRequest( Irp, IrpSp )) )
+ return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY,
Irp, 0, NULL, FALSE );
AFD_DbgPrint(MID_TRACE,("Recv flags %x\n", RecvReq->AfdFlags));
- RecvReq->BufferArray = LockBuffers( RecvReq->BufferArray,
+ RecvReq->BufferArray = LockBuffers( RecvReq->BufferArray,
RecvReq->BufferCount,
NULL, NULL,
TRUE, FALSE );
Irp->IoStatus.Status = STATUS_PENDING;
Irp->IoStatus.Information = 0;
- InsertTailList( &FCB->PendingIrpList[FUNCTION_RECV],
+ InsertTailList( &FCB->PendingIrpList[FUNCTION_RECV],
&Irp->Tail.Overlay.ListEntry );
/************ From this point, the IRP is not ours ************/
Status = ReceiveActivity( FCB, Irp );
-
+
if( Status == STATUS_PENDING && RecvReq->AfdFlags & AFD_IMMEDIATE ) {
AFD_DbgPrint(MID_TRACE,("Nonblocking\n"));
Status = STATUS_CANT_WAIT;
TotalBytesCopied = 0;
RemoveEntryList( &Irp->Tail.Overlay.ListEntry );
UnlockBuffers( RecvReq->BufferArray, RecvReq->BufferCount, FALSE );
- return UnlockAndMaybeComplete( FCB, Status, Irp,
+ return UnlockAndMaybeComplete( FCB, Status, Irp,
TotalBytesCopied, NULL, TRUE );
} else if( Status == STATUS_PENDING ) {
AFD_DbgPrint(MID_TRACE,("Leaving read irp\n"));
NTSTATUS STDCALL
-SatisfyPacketRecvRequest( PAFD_FCB FCB, PIRP Irp,
+SatisfyPacketRecvRequest( PAFD_FCB FCB, PIRP Irp,
PAFD_STORED_DATAGRAM DatagramRecv,
PUINT TotalBytesCopied ) {
NTSTATUS Status = STATUS_SUCCESS;
PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation( Irp );
- PAFD_RECV_INFO RecvReq =
+ PAFD_RECV_INFO RecvReq =
IrpSp->Parameters.DeviceIoControl.Type3InputBuffer;
UINT BytesToCopy = 0, BytesAvailable = DatagramRecv->Len, AddrLen = 0;
PAFD_MAPBUF Map;
- Map = (PAFD_MAPBUF)(RecvReq->BufferArray +
- RecvReq->BufferCount +
+ Map = (PAFD_MAPBUF)(RecvReq->BufferArray +
+ RecvReq->BufferCount +
EXTRA_LOCK_BUFFERS);
- BytesToCopy =
+ BytesToCopy =
MIN( RecvReq->BufferArray[0].len, BytesAvailable );
-
+
AFD_DbgPrint(MID_TRACE,("BytesToCopy: %d len %d\n", BytesToCopy,
RecvReq->BufferArray[0].len));
-
+
if( Map[0].Mdl ) {
/* Copy the address */
if( Map[1].Mdl && Map[2].Mdl ) {
AddrLen );
MmUnmapLockedPages( Map[1].BufferAddress, Map[1].Mdl );
-
+
AFD_DbgPrint(MID_TRACE,("Copying address len\n"));
Map[2].BufferAddress = MmMapLockedPages( Map[2].Mdl, KernelMode );
AFD_DbgPrint(MID_TRACE,("Mapping data buffer pages\n"));
Map[0].BufferAddress = MmMapLockedPages( Map[0].Mdl, KernelMode );
-
- AFD_DbgPrint(MID_TRACE,("Buffer %d: %x:%d\n",
- 0,
+
+ AFD_DbgPrint(MID_TRACE,("Buffer %d: %x:%d\n",
+ 0,
Map[0].BufferAddress,
BytesToCopy));
RtlCopyMemory( Map[0].BufferAddress,
FCB->Recv.Window + FCB->Recv.BytesUsed,
BytesToCopy );
-
+
MmUnmapLockedPages( Map[0].BufferAddress, Map[0].Mdl );
FCB->Recv.BytesUsed = 0;
Irp->IoStatus.Information = BytesToCopy;
ExFreePool( DatagramRecv->Address );
ExFreePool( DatagramRecv );
-
+
AFD_DbgPrint(MID_TRACE,("Done\n"));
return Status;
DestroySocket( FCB );
return STATUS_SUCCESS;
}
-
+
DatagramRecv = ExAllocatePool( NonPagedPool, DGSize );
if( DatagramRecv ) {
DatagramRecv->Len = Irp->IoStatus.Information;
RtlCopyMemory( DatagramRecv->Buffer, FCB->Recv.Window,
DatagramRecv->Len );
- AFD_DbgPrint(MID_TRACE,("Received (A %x)\n",
+ AFD_DbgPrint(MID_TRACE,("Received (A %x)\n",
FCB->AddressFrom->RemoteAddress));
- DatagramRecv->Address =
+ DatagramRecv->Address =
TaCopyTransportAddress( FCB->AddressFrom->RemoteAddress );
-
+
InsertTailList( &FCB->DatagramList, &DatagramRecv->ListEntry );
} else Status = STATUS_NO_MEMORY;
/* Satisfy as many requests as we can */
- while( NT_SUCCESS(Status) &&
- !IsListEmpty( &FCB->DatagramList ) &&
+ while( NT_SUCCESS(Status) &&
+ !IsListEmpty( &FCB->DatagramList ) &&
!IsListEmpty( &FCB->PendingIrpList[FUNCTION_RECV] ) ) {
AFD_DbgPrint(MID_TRACE,("Looping trying to satisfy request\n"));
ListEntry = RemoveHeadList( &FCB->DatagramList );
AFD_DbgPrint(MID_TRACE,("RecvReq: %x, DatagramRecv: %x\n",
RecvReq, DatagramRecv));
- if( DatagramRecv->Len > RecvReq->BufferArray[0].len &&
+ if( DatagramRecv->Len > RecvReq->BufferArray[0].len &&
!(RecvReq->TdiFlags & TDI_RECEIVE_PARTIAL) ) {
InsertHeadList( &FCB->DatagramList,
&DatagramRecv->ListEntry );
} else {
AFD_DbgPrint(MID_TRACE,("Satisfying\n"));
Status = SatisfyPacketRecvRequest
- ( FCB, NextIrp, DatagramRecv,
+ ( FCB, NextIrp, DatagramRecv,
(PUINT)&NextIrp->IoStatus.Information );
AFD_DbgPrint(MID_TRACE,("Unlocking\n"));
UnlockBuffers( RecvReq->BufferArray, RecvReq->BufferCount, TRUE );
}
}
- if( !IsListEmpty( &FCB->DatagramList ) ) {
+ if( !IsListEmpty( &FCB->DatagramList ) ) {
AFD_DbgPrint(MID_TRACE,("Signalling\n"));
FCB->PollState |= AFD_EVENT_RECEIVE;
- } else
+ } else
FCB->PollState &= ~AFD_EVENT_RECEIVE;
PollReeval( FCB->DeviceExt, FCB->FileObject );
}
NTSTATUS STDCALL
-AfdPacketSocketReadData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdPacketSocketReadData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
NTSTATUS Status = STATUS_SUCCESS;
PFILE_OBJECT FileObject = IrpSp->FileObject;
FCB->EventsFired &= ~AFD_EVENT_RECEIVE;
/* Check that the socket is bound */
- if( FCB->State != SOCKET_STATE_BOUND )
+ if( FCB->State != SOCKET_STATE_BOUND )
return UnlockAndMaybeComplete
( FCB, STATUS_UNSUCCESSFUL, Irp, 0, NULL, FALSE );
- if( !(RecvReq = LockRequest( Irp, IrpSp )) )
+ if( !(RecvReq = LockRequest( Irp, IrpSp )) )
return UnlockAndMaybeComplete
( FCB, STATUS_NO_MEMORY, Irp, 0, NULL, FALSE );
-
+
AFD_DbgPrint(MID_TRACE,("Recv flags %x\n", RecvReq->AfdFlags));
- RecvReq->BufferArray = LockBuffers( RecvReq->BufferArray,
+ RecvReq->BufferArray = LockBuffers( RecvReq->BufferArray,
RecvReq->BufferCount,
RecvReq->Address,
RecvReq->AddressLength,
ListEntry = RemoveHeadList( &FCB->DatagramList );
DatagramRecv = CONTAINING_RECORD
( ListEntry, AFD_STORED_DATAGRAM, ListEntry );
- if( DatagramRecv->Len > RecvReq->BufferArray[0].len &&
+ if( DatagramRecv->Len > RecvReq->BufferArray[0].len &&
!(RecvReq->TdiFlags & TDI_RECEIVE_PARTIAL) ) {
InsertHeadList( &FCB->DatagramList,
&DatagramRecv->ListEntry );
FCB->PollState &= ~AFD_EVENT_RECEIVE;
else
FCB->PollState |= AFD_EVENT_RECEIVE;
-
+
PollReeval( FCB->DeviceExt, FCB->FileObject );
-
+
return UnlockAndMaybeComplete
( FCB, Status, Irp, RecvReq->BufferArray[0].len, NULL, TRUE );
} else {
Status = SatisfyPacketRecvRequest
- ( FCB, Irp, DatagramRecv,
+ ( FCB, Irp, DatagramRecv,
(PUINT)&Irp->IoStatus.Information );
if( IsListEmpty( &FCB->DatagramList ) )
VOID CopyBackStatus( PAFD_HANDLE HandleArray,
UINT HandleCount ) {
UINT i;
-
+
for( i = 0; i < HandleCount; i++ ) {
HandleArray[i].Events = HandleArray[i].Status;
HandleArray[i].Status = 0;
VOID ZeroEvents( PAFD_HANDLE HandleArray,
UINT HandleCount ) {
UINT i;
-
+
for( i = 0; i < HandleCount; i++ )
HandleArray[i].Status = 0;
}
AFD_DbgPrint(MID_TRACE,("Done\n"));
}
-VOID SignalSocket( PAFD_ACTIVE_POLL Poll, PAFD_POLL_INFO PollReq,
+VOID SignalSocket( PAFD_ACTIVE_POLL Poll, PAFD_POLL_INFO PollReq,
NTSTATUS Status ) {
int i;
PIRP Irp = Poll->Irp;
AFD_DbgPrint(MID_TRACE,("Timeout\n"));
}
-VOID KillSelectsForFCB( PAFD_DEVICE_EXTENSION DeviceExt,
+VOID KillSelectsForFCB( PAFD_DEVICE_EXTENSION DeviceExt,
PFILE_OBJECT FileObject,
BOOLEAN OnlyExclusive ) {
KIRQL OldIrql;
Poll = CONTAINING_RECORD(ListEntry, AFD_ACTIVE_POLL, ListEntry);
ListEntry = ListEntry->Flink;
Irp = Poll->Irp;
- PollReq = Irp->AssociatedIrp.SystemBuffer;
+ PollReq = Irp->AssociatedIrp.SystemBuffer;
HandleArray = AFD_HANDLES(PollReq);
for( i = 0; i < PollReq->HandleCount; i++ ) {
}
}
}
-
+
KeReleaseSpinLock( &DeviceExt->Lock, OldIrql );
-
+
AFD_DbgPrint(MID_TRACE,("Done\n"));
}
NTSTATUS STDCALL
-AfdSelect( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdSelect( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
NTSTATUS Status = STATUS_NO_MEMORY;
PAFD_FCB FCB;
PAFD_DEVICE_EXTENSION DeviceExt = DeviceObject->DeviceExtension;
PAFD_ACTIVE_POLL Poll = NULL;
UINT CopySize = IrpSp->Parameters.DeviceIoControl.InputBufferLength;
- UINT AllocSize =
+ UINT AllocSize =
CopySize + sizeof(AFD_ACTIVE_POLL) - sizeof(AFD_POLL_INFO);
KIRQL OldIrql;
UINT i, Signalled = 0;
ULONG Exclusive = PollReq->Exclusive;
- AFD_DbgPrint(MID_TRACE,("Called (HandleCount %d Timeout %d)\n",
+ AFD_DbgPrint(MID_TRACE,("Called (HandleCount %d Timeout %d)\n",
PollReq->HandleCount,
(INT)(PollReq->Timeout.QuadPart)));
for( i = 0; i < PollReq->HandleCount; i++ ) {
if( !AFD_HANDLES(PollReq)[i].Handle ) continue;
- KillSelectsForFCB( DeviceExt,
+ KillSelectsForFCB( DeviceExt,
(PFILE_OBJECT)AFD_HANDLES(PollReq)[i].Handle,
TRUE );
}
PollReq->HandleCount );
Poll = ExAllocatePool( NonPagedPool, AllocSize );
-
+
if( Poll ) {
Poll->Irp = Irp;
Poll->DeviceExt = DeviceExt;
KeInitializeTimerEx( &Poll->Timer, NotificationTimer );
KeSetTimer( &Poll->Timer, PollReq->Timeout, &Poll->TimeoutDpc );
- KeInitializeDpc( (PRKDPC)&Poll->TimeoutDpc,
+ KeInitializeDpc( (PRKDPC)&Poll->TimeoutDpc,
(PKDEFERRED_ROUTINE)SelectTimeout,
Poll );
-
+
KeAcquireSpinLock( &DeviceExt->Lock, &OldIrql );
InsertTailList( &DeviceExt->Polls, &Poll->ListEntry );
for( i = 0; i < PollReq->HandleCount; i++ ) {
if( !AFD_HANDLES(PollReq)[i].Handle ) continue;
-
+
FileObject = (PFILE_OBJECT)AFD_HANDLES(PollReq)[i].Handle;
FCB = FileObject->FsContext;
-
+
if( (FCB->PollState & AFD_EVENT_CLOSE) ||
(PollReq->Handles[i].Status & AFD_EVENT_CLOSE) ) {
AFD_HANDLES(PollReq)[i].Handle = 0;
DbgPrint("\n");
#endif
- PollReq->Handles[i].Status =
+ PollReq->Handles[i].Status =
PollReq->Handles[i].Events & FCB->PollState;
if( PollReq->Handles[i].Status ) {
- AFD_DbgPrint(MID_TRACE,("Signalling %x with %x\n",
+ AFD_DbgPrint(MID_TRACE,("Signalling %x with %x\n",
FCB, FCB->PollState));
Signalled++;
}
}
NTSTATUS STDCALL
-AfdEventSelect( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdEventSelect( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
PFILE_OBJECT FileObject = IrpSp->FileObject;
NTSTATUS Status = STATUS_NO_MEMORY;
- PAFD_EVENT_SELECT_INFO EventSelectInfo =
+ PAFD_EVENT_SELECT_INFO EventSelectInfo =
(PAFD_EVENT_SELECT_INFO)LockRequest( Irp, IrpSp );
PAFD_FCB FCB = FileObject->FsContext;
- AFD_DbgPrint(MID_TRACE,("Called (Event %x Triggers %x)\n",
+ AFD_DbgPrint(MID_TRACE,("Called (Event %x Triggers %x)\n",
EventSelectInfo->EventObject,
EventSelectInfo->Events));
-
+
if( !SocketAcquireStateLock( FCB ) ) {
UnlockRequest( Irp, IrpSp );
return LostSocket( Irp, FALSE );
KernelMode,
(PVOID *)&FCB->EventSelect,
NULL );
-
+
if( !NT_SUCCESS(Status) )
FCB->EventSelect = NULL;
else
FCB->EventSelectTriggers = EventSelectInfo->Events;
} else /* Work done, cancelling select */
Status = STATUS_SUCCESS;
-
+
AFD_DbgPrint(MID_TRACE,("Returning %x\n", Status));
return UnlockAndMaybeComplete( FCB, STATUS_SUCCESS, Irp,
}
NTSTATUS STDCALL
-AfdEnumEvents( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdEnumEvents( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
PFILE_OBJECT FileObject = IrpSp->FileObject;
- PAFD_ENUM_NETWORK_EVENTS_INFO EnumReq =
+ PAFD_ENUM_NETWORK_EVENTS_INFO EnumReq =
(PAFD_ENUM_NETWORK_EVENTS_INFO)LockRequest( Irp, IrpSp );
PAFD_FCB FCB = FileObject->FsContext;
AFD_DbgPrint(MID_TRACE,("Called (FCB %x)\n", FCB));
-
+
if( !SocketAcquireStateLock( FCB ) ) {
UnlockRequest( Irp, IrpSp );
return LostSocket( Irp, FALSE );
EnumReq->PollEvents = FCB->PollState;
RtlZeroMemory( EnumReq->EventStatus, sizeof(EnumReq->EventStatus) );
-
+
return UnlockAndMaybeComplete( FCB, STATUS_SUCCESS, Irp,
0, NULL, TRUE );
}
PollReq->Handles[i].Status = AFD_EVENT_CLOSE;
Signalled++;
} else {
- PollReq->Handles[i].Status =
+ PollReq->Handles[i].Status =
PollReq->Handles[i].Events & FCB->PollState;
if( PollReq->Handles[i].Status ) {
- AFD_DbgPrint(MID_TRACE,("Signalling %x with %x\n",
+ AFD_DbgPrint(MID_TRACE,("Signalling %x with %x\n",
FCB, FCB->PollState));
Signalled++;
}
PAFD_POLL_INFO PollReq;
PKEVENT EventSelect = NULL;
- AFD_DbgPrint(MID_TRACE,("Called: DeviceExt %x FileObject %x\n",
+ AFD_DbgPrint(MID_TRACE,("Called: DeviceExt %x FileObject %x\n",
DeviceExt, FileObject));
-
+
KeAcquireSpinLock( &DeviceExt->Lock, &OldIrql );
/* Take care of any event select signalling */
/* Not sure if i can do this at DISPATCH_LEVEL ... try it at passive */
AFD_DbgPrint(MID_TRACE,("Current State: %x, Events Fired: %x, "
"Select Triggers %x\n",
- FCB->PollState, FCB->EventsFired,
+ FCB->PollState, FCB->EventsFired,
FCB->EventSelectTriggers));
if( FCB->PollState & ~FCB->EventsFired & FCB->EventSelectTriggers ) {
FCB->EventsFired |= FCB->PollState;
ThePollEnt = ThePollEnt->Flink;
AFD_DbgPrint(MID_TRACE,("Signalling socket\n"));
SignalSocket( Poll, PollReq, STATUS_SUCCESS );
- } else
+ } else
ThePollEnt = ThePollEnt->Flink;
}
AFD_DbgPrint(MID_TRACE, ("Called\n"));
AFD_DbgPrint(MID_TRACE, ("Irp->UserEvent = %x\n", Irp->UserEvent));
-
+
Status = IoCallDriver(DeviceObject, Irp);
AFD_DbgPrint(MID_TRACE, ("IoCallDriver: %08x\n", Status));
NTSTATUS Status;
ULONG EaLength;
PTRANSPORT_ADDRESS Address;
-
+
AFD_DbgPrint(MAX_TRACE, ("Called. DeviceName (%wZ) Name (0x%X)\n",
DeviceName, Name));
-
+
/* EaName must be 0-terminated, even though TDI_TRANSPORT_ADDRESS_LENGTH does *not* include the 0 */
EaLength = sizeof(FILE_FULL_EA_INFORMATION) +
TDI_TRANSPORT_ADDRESS_LENGTH +
EaInfo = (PFILE_FULL_EA_INFORMATION)ExAllocatePool(NonPagedPool, EaLength);
if (!EaInfo)
return STATUS_INSUFFICIENT_RESOURCES;
-
+
RtlZeroMemory(EaInfo, EaLength);
EaInfo->EaNameLength = TDI_TRANSPORT_ADDRESS_LENGTH;
/* Don't copy the terminating 0; we have already zeroed it */
TdiTransportAddress,
TDI_TRANSPORT_ADDRESS_LENGTH);
EaInfo->EaValueLength = sizeof(TA_IP_ADDRESS);
- Address =
+ Address =
(PTRANSPORT_ADDRESS)(EaInfo->EaName + TDI_TRANSPORT_ADDRESS_LENGTH + 1); /* 0-terminated */
TaCopyTransportAddressInPlace( Address, Name );
EaLength = sizeof(FILE_FULL_EA_INFORMATION) +
TDI_CONNECTION_CONTEXT_LENGTH +
sizeof(PVOID) + 1;
-
+
EaInfo = (PFILE_FULL_EA_INFORMATION)ExAllocatePool(NonPagedPool, EaLength);
if (!EaInfo)
return STATUS_INSUFFICIENT_RESOURCES;
ExFreePool(*RequestConnectionInfo);
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
TdiBuildListen(*Irp, /* IRP */
DeviceObject, /* Device object */
ConnectionObject, /* File object */
*ReturnConnectionInfo); /* Return connection information */
Status = TdiCall(*Irp, DeviceObject, NULL /* Don't wait for completion */, Iosb);
-
+
return Status;
}
&Iosb);
if (!Irp)
return STATUS_INSUFFICIENT_RESOURCES;
-
+
Status = TdiCall(Irp, DeviceObject, &Event, &Iosb);
if (Return)
NULL,
QueryType,
MdlBuffer);
-
+
Status = TdiCall(Irp, DeviceObject, &Event, &Iosb);
return Status;
/* Does not block... The MDL is deleted in the receive completion
routine. */
- AFD_DbgPrint(MID_TRACE,("Status %x Information %d\n",
+ AFD_DbgPrint(MID_TRACE,("Status %x Information %d\n",
Status, Iosb->Information));
return Status;
return Buffer;
}
-VOID TaCopyTransportAddressInPlace( PTRANSPORT_ADDRESS Target,
+VOID TaCopyTransportAddressInPlace( PTRANSPORT_ADDRESS Target,
PTRANSPORT_ADDRESS Source ) {
UINT AddrLen = TaLengthOfTransportAddress( Source );
RtlCopyMemory( Target, Source, AddrLen );
PTRANSPORT_ADDRESS TaCopyTransportAddress( PTRANSPORT_ADDRESS OtherAddress ) {
UINT AddrLen;
PTRANSPORT_ADDRESS A;
-
+
ASSERT(OtherAddress->TAAddressCount == 1);
AddrLen = TaLengthOfTransportAddress( OtherAddress );
A = ExAllocatePool( NonPagedPool, AddrLen );
- if( A )
+ if( A )
TaCopyTransportAddressInPlace( A, OtherAddress );
-
+
return A;
}
NTSTATUS TdiBuildNullConnectionInfoInPlace
( PTDI_CONNECTION_INFORMATION ConnInfo,
- ULONG Type )
+ ULONG Type )
/*
* FUNCTION: Builds a NULL TDI connection information structure
* ARGUMENTS:
ConnInfo->OptionsLength = sizeof(ULONG);
ConnInfo->RemoteAddressLength = TdiAddressSize;
- ConnInfo->RemoteAddress = TransportAddress =
+ ConnInfo->RemoteAddress = TransportAddress =
(PTRANSPORT_ADDRESS)&ConnInfo[1];
TransportAddress->TAAddressCount = 1;
TransportAddress->Address[0].AddressType = Type;
/*
* FUNCTION: Builds a NULL TDI connection information structure
* ARGUMENTS:
- * ConnectionInfo = Address of buffer pointer to allocate connection
+ * ConnectionInfo = Address of buffer pointer to allocate connection
* information in
* Type = TDI style address type (TDI_ADDRESS_TYPE_XXX).
* RETURNS:
PTDI_CONNECTION_INFORMATION ConnInfo;
ULONG TdiAddressSize;
NTSTATUS Status;
-
+
TdiAddressSize = TdiAddressSizeFromType(Type);
ConnInfo = (PTDI_CONNECTION_INFORMATION)
Status = TdiBuildNullConnectionInfoInPlace( ConnInfo, Type );
- if (!NT_SUCCESS(Status))
+ if (!NT_SUCCESS(Status))
ExFreePool( ConnInfo );
else
*ConnectionInfo = ConnInfo;
NTSTATUS Status = STATUS_SUCCESS;
RtlCopyMemory( ConnectionInfo->RemoteAddress,
- Address,
+ Address,
ConnectionInfo->RemoteAddressLength );
-
+
return Status;
}
PTRANSPORT_ADDRESS Address ) {
NTSTATUS Status = TdiBuildNullConnectionInfo
( ConnectionInfo, Address->Address[0].AddressType );
-
+
if( NT_SUCCESS(Status) )
TdiBuildConnectionInfoInPlace( *ConnectionInfo, Address );
return Status;
}
-NTSTATUS
+NTSTATUS
TdiBuildConnectionInfoPair
( PTDI_CONNECTION_INFO_PAIR ConnectionInfo,
- PTRANSPORT_ADDRESS From, PTRANSPORT_ADDRESS To )
+ PTRANSPORT_ADDRESS From, PTRANSPORT_ADDRESS To )
/*
* FUNCTION: Fill a TDI_CONNECTION_INFO_PAIR struct will the two addresses
* given.
- * ARGUMENTS:
+ * ARGUMENTS:
* ConnectionInfo: The pair
* From: The from address
* To: The to address
RtlZeroMemory( LayoutFrame, 2 * SizeOfEntry );
- PTDI_CONNECTION_INFORMATION
- FromTdiConn = (PTDI_CONNECTION_INFORMATION)LayoutFrame,
+ PTDI_CONNECTION_INFORMATION
+ FromTdiConn = (PTDI_CONNECTION_INFORMATION)LayoutFrame,
ToTdiConn = (PTDI_CONNECTION_INFORMATION)LayoutFrame + SizeOfEntry;
-
+
if (From != NULL) {
TdiBuildConnectionInfoInPlace( FromTdiConn, From );
} else {
- TdiBuildNullConnectionInfoInPlace( FromTdiConn,
+ TdiBuildNullConnectionInfoInPlace( FromTdiConn,
From->Address[0].AddressType );
}
-
+
TdiBuildConnectionInfoInPlace( ToTdiConn, To );
return STATUS_SUCCESS;
}
-PTA_ADDRESS TdiGetRemoteAddress( PTDI_CONNECTION_INFORMATION TdiConn )
+PTA_ADDRESS TdiGetRemoteAddress( PTDI_CONNECTION_INFORMATION TdiConn )
/*
- * Convenience function that rounds out the abstraction of
+ * Convenience function that rounds out the abstraction of
* the TDI_CONNECTION_INFORMATION struct.
*/
{
if( !SocketAcquireStateLock( FCB ) ) return Status;
- FCB->SendIrp.InFlightRequest = NULL;
+ FCB->SendIrp.InFlightRequest = NULL;
/* Request is not in flight any longer */
if( FCB->State == SOCKET_STATE_CLOSED ) {
if( !NT_SUCCESS(Status) ) {
/* Complete all following send IRPs with error */
-
+
while( !IsListEmpty( &FCB->PendingIrpList[FUNCTION_SEND] ) ) {
- NextIrpEntry =
+ NextIrpEntry =
RemoveHeadList(&FCB->PendingIrpList[FUNCTION_SEND]);
- NextIrp =
+ NextIrp =
CONTAINING_RECORD(NextIrpEntry, IRP, Tail.Overlay.ListEntry);
NextIrpSp = IoGetCurrentIrpStackLocation( NextIrp );
SendReq = NextIrpSp->Parameters.DeviceIoControl.Type3InputBuffer;
IoCompleteRequest( NextIrp, IO_NETWORK_INCREMENT );
}
-
+
SocketStateUnlock( FCB );
return STATUS_SUCCESS;
if( !FCB->Send.BytesUsed &&
!IsListEmpty( &FCB->PendingIrpList[FUNCTION_SEND] ) &&
NT_SUCCESS(Status) ) {
- NextIrpEntry =
+ NextIrpEntry =
RemoveHeadList(&FCB->PendingIrpList[FUNCTION_RECV]);
- NextIrp =
+ NextIrp =
CONTAINING_RECORD(NextIrpEntry, IRP, Tail.Overlay.ListEntry);
NextIrpSp = IoGetCurrentIrpStackLocation( NextIrp );
SendReq = NextIrpSp->Parameters.DeviceIoControl.Type3InputBuffer;
Map = (PAFD_MAPBUF)(SendReq->BufferArray + SendReq->BufferCount);
AFD_DbgPrint(MID_TRACE,("SendReq @ %x\n", SendReq));
-
+
SpaceAvail = FCB->Send.Size - FCB->Send.BytesUsed;
-
- for( i = 0; FCB->Send.BytesUsed < FCB->Send.Content &&
+
+ for( i = 0; FCB->Send.BytesUsed < FCB->Send.Content &&
i < SendReq->BufferCount; i++ ) {
- Map[i].BufferAddress =
+ Map[i].BufferAddress =
MmMapLockedPages( Map[i].Mdl, KernelMode );
- CopySize = MIN( SpaceAvail,
+ CopySize = MIN( SpaceAvail,
SendReq->BufferArray[i].len );
RtlCopyMemory( FCB->Send.Window + FCB->Send.BytesUsed,
Map[i].BufferAddress,
CopySize );
-
+
MmUnmapLockedPages( Map[i].Mdl, KernelMode );
-
+
FCB->Send.BytesUsed += CopySize;
TotalBytesCopied += CopySize;
SpaceAvail -= CopySize;
}
}
-
+
/* Some data is still waiting */
if( FCB->Send.BytesUsed ) {
FCB->PollState &= ~AFD_EVENT_SEND;
Status = STATUS_SUCCESS;
AFD_DbgPrint(MID_TRACE,("Dismissing request: %x\n", Status));
-
- return UnlockAndMaybeComplete( FCB, Status, Irp, TotalBytesCopied,
+
+ return UnlockAndMaybeComplete( FCB, Status, Irp, TotalBytesCopied,
NULL, TRUE );
} else if( NextIrp ) {
AFD_DbgPrint(MID_TRACE,("Could not do any more with Irp %x\n",
}
SocketStateUnlock( FCB );
-
+
return STATUS_SUCCESS;
}
FCB->PollState |= AFD_EVENT_SEND;
PollReeval( FCB->DeviceExt, FCB->FileObject );
- FCB->SendIrp.InFlightRequest = NULL;
+ FCB->SendIrp.InFlightRequest = NULL;
/* Request is not in flight any longer */
if( FCB->State == SOCKET_STATE_CLOSED ) {
}
NTSTATUS STDCALL
-AfdConnectedSocketWriteData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdConnectedSocketWriteData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp, BOOLEAN Short) {
NTSTATUS Status = STATUS_SUCCESS;
PFILE_OBJECT FileObject = IrpSp->FileObject;
PAFD_FCB FCB = FileObject->FsContext;
PAFD_SEND_INFO SendReq;
- UINT TotalBytesCopied = 0, i, CopySize = 0,
+ UINT TotalBytesCopied = 0, i, CopySize = 0,
SpaceAvail = 0, TotalBytesEncountered = 0;
AFD_DbgPrint(MID_TRACE,("Called on %x\n", FCB));
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, FALSE );
-
+
FCB->EventsFired &= ~AFD_EVENT_SEND;
if( FCB->Flags & AFD_ENDPOINT_CONNECTIONLESS )
{
PAFD_SEND_INFO_UDP SendReq;
PTDI_CONNECTION_INFORMATION TargetAddress;
-
+
/* Check that the socket is bound */
- if( FCB->State != SOCKET_STATE_BOUND )
+ if( FCB->State != SOCKET_STATE_BOUND )
return UnlockAndMaybeComplete( FCB, STATUS_UNSUCCESSFUL, Irp,
0, NULL, FALSE );
- if( !(SendReq = LockRequest( Irp, IrpSp )) )
+ if( !(SendReq = LockRequest( Irp, IrpSp )) )
return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY, Irp, 0,
NULL, FALSE );
SendReq->BufferCount,
NULL, NULL,
FALSE, FALSE );
-
+
TdiBuildConnectionInfo( &TargetAddress, FCB->RemoteAddress );
SocketCalloutEnter( FCB );
&FCB->SendIrp.Iosb,
PacketSocketSendComplete,
FCB );
-
+
SocketCalloutLeave( FCB );
ExFreePool( TargetAddress );
if( Status == STATUS_PENDING ) Status = STATUS_SUCCESS;
AFD_DbgPrint(MID_TRACE,("Dismissing request: %x\n", Status));
-
+
return UnlockAndMaybeComplete( FCB, Status, Irp,
SendReq->BufferArray[0].len,
NULL, TRUE );
}
- if( !(SendReq = LockRequest( Irp, IrpSp )) )
+ if( !(SendReq = LockRequest( Irp, IrpSp )) )
return UnlockAndMaybeComplete
( FCB, STATUS_NO_MEMORY, Irp, TotalBytesCopied, NULL, FALSE );
}
}
- AFD_DbgPrint(MID_TRACE,("We already have %d bytes waiting.\n",
+ AFD_DbgPrint(MID_TRACE,("We already have %d bytes waiting.\n",
FCB->Send.BytesUsed));
SendReq->BufferArray = LockBuffers( SendReq->BufferArray,
NULL, NULL,
FALSE, FALSE );
- AFD_DbgPrint(MID_TRACE,("FCB->Send.BytesUsed = %d\n",
+ AFD_DbgPrint(MID_TRACE,("FCB->Send.BytesUsed = %d\n",
FCB->Send.BytesUsed));
if( !FCB->Send.BytesUsed ) {
AFD_DbgPrint(MID_TRACE,("We can accept %d bytes\n",
SpaceAvail));
-
- for( i = 0; FCB->Send.BytesUsed < FCB->Send.Size &&
+
+ for( i = 0; FCB->Send.BytesUsed < FCB->Send.Size &&
i < SendReq->BufferCount; i++ ) {
- CopySize = MIN( SpaceAvail,
+ CopySize = MIN( SpaceAvail,
SendReq->BufferArray[i].len );
TotalBytesEncountered += SendReq->BufferArray[i].len;
AFD_DbgPrint(MID_TRACE,("Copying Buffer %d, %x:%d to %x\n",
- i,
+ i,
SendReq->BufferArray[i].buf,
CopySize,
FCB->Send.Window + FCB->Send.BytesUsed));
-
+
RtlCopyMemory( FCB->Send.Window + FCB->Send.BytesUsed,
SendReq->BufferArray[i].buf,
CopySize );
-
+
FCB->Send.BytesUsed += CopySize;
TotalBytesCopied += CopySize;
SpaceAvail -= CopySize;
}
-
+
if( TotalBytesEncountered == 0 ) {
UnlockBuffers( SendReq->BufferArray, SendReq->BufferCount, FALSE );
-
+
AFD_DbgPrint(MID_TRACE,("Empty send\n"));
return UnlockAndMaybeComplete
( FCB, Status, Irp, TotalBytesCopied, NULL, TRUE );
}
-
+
AFD_DbgPrint(MID_TRACE,("Completed %d bytes\n", TotalBytesCopied));
-
+
if( TotalBytesCopied > 0 ) {
UnlockBuffers( SendReq->BufferArray, SendReq->BufferCount, FALSE );
&FCB->SendIrp.Iosb,
SendComplete,
FCB );
-
+
SocketCalloutLeave( FCB );
if( Status == STATUS_PENDING )
Status = STATUS_SUCCESS;
-
- AFD_DbgPrint(MID_TRACE,("Dismissing request: %x (%d)\n",
+
+ AFD_DbgPrint(MID_TRACE,("Dismissing request: %x (%d)\n",
Status, TotalBytesCopied));
-
+
return UnlockAndMaybeComplete
( FCB, Status, Irp, TotalBytesCopied, NULL, TRUE );
}
}
NTSTATUS STDCALL
-AfdPacketSocketWriteData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdPacketSocketWriteData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp) {
NTSTATUS Status = STATUS_SUCCESS;
PTDI_CONNECTION_INFORMATION TargetAddress;
PFILE_OBJECT FileObject = IrpSp->FileObject;
PAFD_FCB FCB = FileObject->FsContext;
PAFD_SEND_INFO_UDP SendReq;
-
+
AFD_DbgPrint(MID_TRACE,("Called on %x\n", FCB));
if( !SocketAcquireStateLock( FCB ) ) return LostSocket( Irp, FALSE );
FCB->PollState &= ~AFD_EVENT_SEND;
/* Check that the socket is bound */
- if( FCB->State != SOCKET_STATE_BOUND )
+ if( FCB->State != SOCKET_STATE_BOUND )
return UnlockAndMaybeComplete
( FCB, STATUS_UNSUCCESSFUL, Irp, 0, NULL, FALSE );
- if( !(SendReq = LockRequest( Irp, IrpSp )) )
+ if( !(SendReq = LockRequest( Irp, IrpSp )) )
return UnlockAndMaybeComplete
( FCB, STATUS_NO_MEMORY, Irp, 0, NULL, FALSE );
-
+
AFD_DbgPrint
- (MID_TRACE,("RemoteAddress #%d Type %d\n",
+ (MID_TRACE,("RemoteAddress #%d Type %d\n",
((PTRANSPORT_ADDRESS)SendReq->RemoteAddress)->
TAAddressCount,
((PTRANSPORT_ADDRESS)SendReq->RemoteAddress)->
&FCB->SendIrp.Iosb,
PacketSocketSendComplete,
FCB );
-
+
SocketCalloutLeave( FCB );
ExFreePool( TargetAddress );
if( Status == STATUS_PENDING ) Status = STATUS_SUCCESS;
AFD_DbgPrint(MID_TRACE,("Dismissing request: %x\n", Status));
-
+
return UnlockAndMaybeComplete
( FCB, Status, Irp, SendReq->BufferArray[0].len, NULL, TRUE );
}
#define SGID_CONNECTIONLESS 1 /* XXX Find this flag */
-/* XXX This is a hack we should clean up later
+/* XXX This is a hack we should clean up later
* We do this in order to get some storage for the locked handle table
* Maybe I'll use some tail item in the irp instead */
#define AFD_HANDLES(x) ((PAFD_HANDLE)(x)->Exclusive)
typedef struct _AFD_IN_FLIGHT_REQUEST {
PIRP InFlightRequest;
- IO_STATUS_BLOCK Iosb;
+ IO_STATUS_BLOCK Iosb;
PTDI_CONNECTION_INFORMATION ConnectionCallInfo;
PTDI_CONNECTION_INFORMATION ConnectionReturnInfo;
} AFD_IN_FLIGHT_REQUEST, *PAFD_IN_FLIGHT_REQUEST;
/* context.c */
NTSTATUS STDCALL
-AfdGetContext( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdGetContext( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp );
NTSTATUS STDCALL
-AfdSetContext( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdSetContext( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp );
/* info.c */
NTSTATUS STDCALL
-AfdGetInfo( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdGetInfo( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp );
NTSTATUS STDCALL
-AfdGetSockOrPeerName( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdGetSockOrPeerName( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp, BOOLEAN Local );
/* listen.c */
/* lock.c */
-PAFD_WSABUF LockBuffers( PAFD_WSABUF Buf, UINT Count,
+PAFD_WSABUF LockBuffers( PAFD_WSABUF Buf, UINT Count,
PVOID AddressBuf, PINT AddressLen,
BOOLEAN Write, BOOLEAN LockAddress );
VOID UnlockBuffers( PAFD_WSABUF Buf, UINT Count, BOOL Address );
UINT SocketAcquireStateLock( PAFD_FCB FCB );
NTSTATUS DDKAPI UnlockAndMaybeComplete
( PAFD_FCB FCB, NTSTATUS Status, PIRP Irp,
- UINT Information,
+ UINT Information,
PIO_COMPLETION_ROUTINE Completion,
BOOL ShouldUnlockIrp );
VOID SocketStateUnlock( PAFD_FCB FCB );
PVOID Context );
NTSTATUS STDCALL
-AfdConnectedSocketReadData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdConnectedSocketReadData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp, BOOLEAN Short);
NTSTATUS STDCALL
-AfdPacketSocketReadData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdPacketSocketReadData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp );
/* select.c */
NTSTATUS STDCALL
-AfdSelect( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdSelect( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp );
NTSTATUS STDCALL
-AfdEventSelect( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdEventSelect( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp );
NTSTATUS STDCALL
-AfdEnumEvents( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdEnumEvents( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp );
VOID PollReeval( PAFD_DEVICE_EXTENSION DeviceObject, PFILE_OBJECT FileObject );
VOID KillSelectsForFCB( PAFD_DEVICE_EXTENSION DeviceExt,
/* write.c */
NTSTATUS STDCALL
-AfdConnectedSocketWriteData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdConnectedSocketWriteData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp, BOOLEAN Short);
NTSTATUS STDCALL
-AfdPacketSocketWriteData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
+AfdPacketSocketWriteData(PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp);
#endif/*_AFD_H*/
UINT TaLengthOfTransportAddress( PTRANSPORT_ADDRESS Addr );
VOID TaCopyAddressInPlace( PTA_ADDRESS Target, PTA_ADDRESS Source );
PTA_ADDRESS TaCopyAddress( PTA_ADDRESS Source );
-VOID TaCopyTransportAddressInPlace( PTRANSPORT_ADDRESS Target,
+VOID TaCopyTransportAddressInPlace( PTRANSPORT_ADDRESS Target,
PTRANSPORT_ADDRESS Source );
UINT TdiAddressSizeFromType( UINT Type );
UINT TdiAddressSizeFromName( PTRANSPORT_ADDRESS Name );
NTSTATUS TdiBuildNullConnectionInfo
( PTDI_CONNECTION_INFORMATION *ConnectionInfo, ULONG Type );
NTSTATUS TdiBuildConnectionInfoPair
-( PTDI_CONNECTION_INFO_PAIR ConnectionInfo,
- PTRANSPORT_ADDRESS From,
+( PTDI_CONNECTION_INFO_PAIR ConnectionInfo,
+ PTRANSPORT_ADDRESS From,
PTRANSPORT_ADDRESS To );
PTA_ADDRESS TdiGetRemoteAddress( PTDI_CONNECTION_INFORMATION TdiConn );
* TRUE if NIC is believed to be present, FALSE if not
*/
{
- int i;
+ int i;
NDIS_DbgPrint(MAX_TRACE, ("Called\n"));
/* Select page 0 and stop NIC */
NdisRawWritePortUchar(Adapter->IOBase + PG0_CR, CR_STP | CR_RD2 | CR_PAGE0);
-
+
/* Initialize DCR - Data Configuration Register (byte mode/8 bytes FIFO) */
NdisRawWritePortUchar(Adapter->IOBase + PG0_DCR, DCR_LS | DCR_FT10);
/* Start transmitting */
NdisRawWritePortUchar(Adapter->IOBase + PG0_CR, CR_STA | CR_TXP | CR_RD2);
- NDIS_DbgPrint(MID_TRACE, ("Transmitting. FrameStart (%d) TXCurrent (%d) TXStart (%d) Length (%d).\n\n",
+ NDIS_DbgPrint(MID_TRACE, ("Transmitting. FrameStart (%d) TXCurrent (%d) TXStart (%d) Length (%d).\n\n",
FrameStart,
Adapter->TXCurrent,
Adapter->TXStart,
/* Select page 0, read and start the NIC */
NdisRawWritePortUchar(Adapter->IOBase + PG0_CR, CR_STA | CR_RD0 | CR_PAGE0);
-
+
if (Adapter->WordMode)
NdisRawReadPortBufferUshort(Adapter->IOBase + NIC_DATA, Target, Count >> 1);
else
/* Write and start the NIC */
NdisRawWritePortUchar(Adapter->IOBase + PG0_CR, CR_STA | CR_RD1 | CR_PAGE0);
-
+
if (Adapter->WordMode)
NdisRawWritePortBufferUshort(Adapter->IOBase + NIC_DATA, Source, Count >> 1);
else
/* Select page 0 and stop the NIC */
NdisRawWritePortUchar(Adapter->IOBase + PG0_CR, CR_STP | CR_RD2 | CR_PAGE0);
-
+
/* Clear RBCR0,RBCR1 - Remote Byte Count Registers */
NdisRawWritePortUchar(Adapter->IOBase + PG0_RBCR0, 0x00);
NdisRawWritePortUchar(Adapter->IOBase + PG0_RBCR1, 0x00);
Mask = (Mask << 1);
switch (Adapter->InterruptStatus & Mask) {
- case ISR_OVW:
+ case ISR_OVW:
NDIS_DbgPrint(MID_TRACE, ("Overflow interrupt.\n"));
/* Overflow. Handled almost the same way as a receive interrupt */
Adapter->BufferOverflow = TRUE;
NICUpdateCounters(Adapter);
Adapter->ReceiveError = TRUE;
-
+
case ISR_PRX:
NDIS_DbgPrint(MID_TRACE, ("Receive interrupt.\n"));
HandleReceive(Adapter);
else
NDIS_DbgPrint(MAX_TRACE,("No miniport adapter yet\n"));
-
+
Adapter->InterruptStatus &= ~(ISR_PRX | ISR_RXE);
- break;
+ break;
case ISR_TXE:
NDIS_DbgPrint(MID_TRACE, ("Transmit error interrupt.\n"));
break;
case OID_GEN_MAC_OPTIONS:
GenericULONG = NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA |
- NDIS_MAC_OPTION_RECEIVE_SERIALIZED |
+ NDIS_MAC_OPTION_RECEIVE_SERIALIZED |
NDIS_MAC_OPTION_TRANSFERS_NOT_PEND |
NDIS_MAC_OPTION_NO_LOOPBACK;
break;
Status = NDIS_STATUS_NOT_SUPPORTED;
break;
}
-
+
Adapter->PacketFilter = GenericULONG;
/* FIXME: Set filter on hardware */
NdisQueryBuffer(DstBuffer, (PVOID)&DstData, &DstSize);
SrcData = Adapter->PacketOffset + sizeof(DISCARD_HEADER) + ByteOffset;
- if (ByteOffset + sizeof(DISCARD_HEADER) + BytesToTransfer >
+ if (ByteOffset + sizeof(DISCARD_HEADER) + BytesToTransfer >
Adapter->PacketHeader.PacketLength)
- BytesToTransfer = Adapter->PacketHeader.PacketLength -
+ BytesToTransfer = Adapter->PacketHeader.PacketLength -
sizeof(DISCARD_HEADER) - ByteOffset;
/* Start copying the data */
DbgPrint("ne2000!MiniportInitialize: failed to set DwordTest: 0x%x\n", Status);
KeBugCheck(0);
}
-
+
DbgPrint("ne2000!MiniportInitialize: DwordTest successfully set\n");
-
+
NdisInitUnicodeString(&Keyword, L"StringTest");
ParameterValue.ParameterType = NdisParameterString;
NdisInitUnicodeString(&ParameterValue.ParameterData.StringData, L"Testing123");
DbgPrint("ne2000!MiniportInitialize: failed to set StringTest: 0x%x\n", Status);
KeBugCheck(0);
}
-
+
DbgPrint("ne2000!MiniportInitialize: StringTest successfully set\n");
}
IN NDIS_HANDLE MiniportAdapterContext)
/*
* FUNCTION: Handle an interrupt if told to by MiniportISR
- * ARGUMENTS:
+ * ARGUMENTS:
* MiniportAdapterContext: context specified to NdisMSetAttributes
* NOTES:
* - Called by NDIS at DISPATCH_LEVEL
NdisMEthIndicateReceiveComplete(Adapter->MiniportAdapterHandle);
RtlZeroMemory(Descriptor, sizeof(RECEIVE_DESCRIPTOR));
- Descriptor->RBADR =
+ Descriptor->RBADR =
(ULONG)(Adapter->ReceiveBufferPtrPhys + Adapter->CurrentReceiveDescriptorIndex * BUFFER_SIZE);
Descriptor->BCNT = (-BUFFER_SIZE) | 0xf000;
Descriptor->FLAGS |= RD_OWN;
NdisDprReleaseSpinLock(&Adapter->Lock);
}
-NDIS_STATUS
+NDIS_STATUS
MiQueryCard(
IN PADAPTER Adapter)
/*
/* set busmaster and io space enable bits */
buf32 = PCI_BMEN | PCI_IOEN;
- NdisWritePciSlotInformation(Adapter->MiniportAdapterHandle, 0, PCI_COMMAND, &buf32, 4);
+ NdisWritePciSlotInformation(Adapter->MiniportAdapterHandle, 0, PCI_COMMAND, &buf32, 4);
/* get IO base physical address */
buf32 = 0;
/* allocate the initialization block */
Adapter->InitializationBlockLength = sizeof(INITIALIZATION_BLOCK);
- NdisMAllocateSharedMemory(Adapter->MiniportAdapterHandle, Adapter->InitializationBlockLength,
+ NdisMAllocateSharedMemory(Adapter->MiniportAdapterHandle, Adapter->InitializationBlockLength,
FALSE, (PVOID *)&Adapter->InitializationBlockVirt, &PhysicalAddress);
if(!Adapter->InitializationBlockVirt)
{
/* allocate transmit buffers */
Adapter->TransmitBufferLength = BUFFER_SIZE * NUMBER_OF_BUFFERS;
- NdisMAllocateSharedMemory(Adapter->MiniportAdapterHandle, Adapter->TransmitBufferLength,
+ NdisMAllocateSharedMemory(Adapter->MiniportAdapterHandle, Adapter->TransmitBufferLength,
FALSE, (PVOID *)&Adapter->TransmitBufferPtrVirt, &PhysicalAddress);
if(!Adapter->TransmitBufferPtrVirt)
{
/* allocate receive buffers */
Adapter->ReceiveBufferLength = BUFFER_SIZE * NUMBER_OF_BUFFERS;
- NdisMAllocateSharedMemory(Adapter->MiniportAdapterHandle, Adapter->ReceiveBufferLength,
+ NdisMAllocateSharedMemory(Adapter->MiniportAdapterHandle, Adapter->ReceiveBufferLength,
FALSE, (PVOID *)&Adapter->ReceiveBufferPtrVirt, &PhysicalAddress);
if(!Adapter->ReceiveBufferPtrVirt)
{
if(Adapter->InitializationBlockVirt)
{
PhysicalAddress.u.LowPart = (ULONG)Adapter->InitializationBlockPhys;
- NdisMFreeSharedMemory(Adapter->MiniportAdapterHandle, Adapter->InitializationBlockLength,
+ NdisMFreeSharedMemory(Adapter->MiniportAdapterHandle, Adapter->InitializationBlockLength,
FALSE, Adapter->InitializationBlockVirt, PhysicalAddress);
}
if(Adapter->TransmitBufferPtrVirt)
{
PhysicalAddress.u.LowPart = (ULONG)Adapter->TransmitBufferPtrPhys;
- NdisMFreeSharedMemory(Adapter->MiniportAdapterHandle, Adapter->TransmitBufferLength,
+ NdisMFreeSharedMemory(Adapter->MiniportAdapterHandle, Adapter->TransmitBufferLength,
FALSE, Adapter->TransmitBufferPtrVirt, PhysicalAddress);
}
if(Adapter->ReceiveBufferPtrVirt)
{
PhysicalAddress.u.LowPart = (ULONG)Adapter->ReceiveBufferPtrPhys;
- NdisMFreeSharedMemory(Adapter->MiniportAdapterHandle, Adapter->ReceiveBufferLength,
+ NdisMFreeSharedMemory(Adapter->MiniportAdapterHandle, Adapter->ReceiveBufferLength,
FALSE, Adapter->ReceiveBufferPtrVirt, PhysicalAddress);
}
}
NdisRawWritePortUshort(Adapter->PortOffset + RDP, CSR0_STOP);
return TRUE;
}
-
+
VOID
STDCALL
MiniportHalt(
/* free the lock */
NdisFreeSpinLock(&Adapter->Lock);
-
+
/* free the adapter */
NdisFreeMemory(Adapter, 0, 0);
}
}
return FALSE;
}
-
+
VOID
STDCALL
MiniportMediaDetectionTimer(
MiSyncMediaDetection,
FunctionContext))
{
- NdisMIndicateStatus(Adapter->MiniportAdapterHandle,
+ NdisMIndicateStatus(Adapter->MiniportAdapterHandle,
Adapter->MediaState == NdisMediaStateConnected ?
NDIS_STATUS_MEDIA_CONNECT : NDIS_STATUS_MEDIA_DISCONNECT,
(PVOID)0, 0);
NdisMIndicateStatusComplete(Adapter->MiniportAdapterHandle);
}
}
-
+
VOID
MiInitChip(
PADAPTER Adapter)
NdisRawWritePortUshort(Adapter->PortOffset + RAP, BCR4);
NdisRawWritePortUshort(Adapter->PortOffset + BDP, BCR4_LNKSTE|BCR4_FDLSE);
Adapter->MediaState = MiGetMediaState(Adapter);
-
+
PCNET_DbgPrint(("card started\n"));
Adapter->Flags &= ~RESET_IN_PROGRESS;
}
/* register an IO port range */
- Status = NdisMRegisterIoPortRange(&Adapter->PortOffset, Adapter->MiniportAdapterHandle,
+ Status = NdisMRegisterIoPortRange(&Adapter->PortOffset, Adapter->MiniportAdapterHandle,
Adapter->IoBaseAddress, NUMBER_OF_PORTS);
if(Status != NDIS_STATUS_SUCCESS)
{
}
/* Allocate map registers */
- Status = NdisMAllocateMapRegisters(Adapter->MiniportAdapterHandle, 0,
+ Status = NdisMAllocateMapRegisters(Adapter->MiniportAdapterHandle, 0,
NDIS_DMA_32BITS, 8, BUFFER_SIZE);
if(Status != NDIS_STATUS_SUCCESS)
{
NdisRawWritePortUshort(Adapter->PortOffset + RDP, CSR0_IENA | CSR0_TDMD);
return TRUE;
}
-
+
NDIS_STATUS
STDCALL
MiniportSend(
SourceBuffer, SourceLength);
Position += SourceLength;
-
+
NdisGetNextBuffer(NdisBuffer, &NdisBuffer);
}
} ADAPTER_STATS, *PADAPTER_STATS;
/* adapter struct */
-typedef struct _ADAPTER
+typedef struct _ADAPTER
{
NDIS_SPIN_LOCK Lock;
-
+
NDIS_HANDLE MiniportAdapterHandle;
ULONG Flags;
ULONG InterruptVector;
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* PROGRAMMERS:
- * Vizzini (vizzini@plasmic.com),
- * borrowed very heavily from the ReactOS ne2000 driver by
+ * Vizzini (vizzini@plasmic.com),
+ * borrowed very heavily from the ReactOS ne2000 driver by
* Casper S. Hornstrup (chorns@users.sourceforge.net)
* REVISIONS:
* 14-Sep-2003 vizzini - Created
#include "pcnet.h"
/* List of supported OIDs */
-static ULONG MiniportOIDList[] =
+static ULONG MiniportOIDList[] =
{
OID_GEN_SUPPORTED_LIST,
OID_GEN_HARDWARE_STATUS,
CopyFrom = (PVOID)&GenericULONG;
CopySize = sizeof(ULONG);
- switch (Oid)
+ switch (Oid)
{
case OID_GEN_SUPPORTED_LIST:
{
}
case OID_GEN_LINK_SPEED:
- {
+ {
GenericULONG = 100000; /* 10Mbps */
break;
}
case OID_GEN_MAC_OPTIONS:
{
GenericULONG = NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA |
- NDIS_MAC_OPTION_RECEIVE_SERIALIZED |
+ NDIS_MAC_OPTION_RECEIVE_SERIALIZED |
NDIS_MAC_OPTION_TRANSFERS_NOT_PEND;
break;
}
break;
case OID_GEN_RCV_NO_BUFFER:
- GenericULONG = Adapter->Statistics.RcvBufferErrors +
+ GenericULONG = Adapter->Statistics.RcvBufferErrors +
Adapter->Statistics.RcvOverflowErrors;
break;
}
}
- if (Status == NDIS_STATUS_SUCCESS)
+ if (Status == NDIS_STATUS_SUCCESS)
{
- if (CopySize > InformationBufferLength)
+ if (CopySize > InformationBufferLength)
{
*BytesNeeded = (CopySize - InformationBufferLength);
*BytesWritten = 0;
Status = NDIS_STATUS_BUFFER_TOO_SHORT;
- }
- else
+ }
+ else
{
NdisMoveMemory(InformationBuffer, CopyFrom, CopySize);
*BytesWritten = CopySize;
NdisAcquireSpinLock(&Adapter->Lock);
- switch (Oid)
+ switch (Oid)
{
case OID_GEN_CURRENT_PACKET_FILTER:
{
/* Verify length */
- if (InformationBufferLength < sizeof(ULONG))
+ if (InformationBufferLength < sizeof(ULONG))
{
*BytesRead = 0;
*BytesNeeded = sizeof(ULONG) - InformationBufferLength;
NDIS_PACKET_TYPE_MAC_FRAME |
NDIS_PACKET_TYPE_SMT |
NDIS_PACKET_TYPE_SOURCE_ROUTING)
- )
+ )
{
*BytesRead = 4;
*BytesNeeded = 0;
Status = NDIS_STATUS_NOT_SUPPORTED;
break;
}
-
+
Adapter->CurrentPacketFilter = GenericULONG;
/* FIXME: Set filter on hardware */
case OID_GEN_CURRENT_LOOKAHEAD:
{
/* Verify length */
- if (InformationBufferLength < sizeof(ULONG))
+ if (InformationBufferLength < sizeof(ULONG))
{
*BytesRead = 0;
*BytesNeeded = sizeof(ULONG) - InformationBufferLength;
case OID_802_3_MULTICAST_LIST:
{
/* Verify length. Must be multiple of hardware address length */
- if ((InformationBufferLength % 6) != 0)
+ if ((InformationBufferLength % 6) != 0)
{
*BytesRead = 0;
*BytesNeeded = 0;
}
}
- if (Status == NDIS_STATUS_SUCCESS)
+ if (Status == NDIS_STATUS_SUCCESS)
{
*BytesRead = InformationBufferLength;
*BytesNeeded = 0;
LA_DbgPrint(DEBUG_DATALINK, ("Called.\n"));
KeAcquireSpinLock( &DeviceExt->Lock, &OldIrql );
-
+
if (Status == NDIS_STATUS_SUCCESS) {
PNDIS_BUFFER NdisBuffer;
&LPPacket.EthHeader,
&ContigSize,
&LPPacket.TotalSize);
-
+
LPPacket.TotalSize = BytesTransferred;
-
+
/* Determine which upper layer protocol that should receive
this packet and pass it to the correct receive handler */
("Ether Type = %x Total = %d Packet %x Payload %x\n",
PacketType, LPPacket.TotalSize, LPPacket.EthHeader,
LPPacket.EthHeader + 1));
-
+
NdisBuffer->Next = NULL;
for( ListEntry = DeviceExt->ProtocolListHead.Flink;
Proto = CONTAINING_RECORD(ListEntry, LAN_PROTOCOL, ListEntry);
LA_DbgPrint(MID_TRACE,("Examining protocol %x\n", Proto));
for( i = 0; i < Proto->NumEtherTypes; i++ ) {
- LA_DbgPrint(MID_TRACE,(".Accepts proto %x\n",
+ LA_DbgPrint(MID_TRACE,(".Accepts proto %x\n",
Proto->EtherType[i]));
if( Proto->EtherType[i] == PacketType &&
!IsListEmpty( &Proto->ReadIrpListHead ) ) {
if( Proto->Buffered ) {
LA_DbgPrint(MID_TRACE,("Buffered copy\n"));
RtlCopyMemory
- ( Header->Address +
+ ( Header->Address +
IEEE_802_ADDR_LENGTH,
LPPacket.EthHeader + 1,
- LPPacket.TotalSize -
+ LPPacket.TotalSize -
sizeof(*LPPacket.EthHeader) );
Header->Fixed.Mdl = NULL;
- } else
+ } else
Header->Fixed.Mdl = NdisBuffer;
-
+
ReadIrp->IoStatus.Status = 0;
- ReadIrp->IoStatus.Information =
- (Header->Address + IEEE_802_ADDR_LENGTH +
- LPPacket.TotalSize -
+ ReadIrp->IoStatus.Information =
+ (Header->Address + IEEE_802_ADDR_LENGTH +
+ LPPacket.TotalSize -
sizeof(*LPPacket.EthHeader)) -
(PCHAR)Header;
}
}
}
-
+
KeReleaseSpinLock( &DeviceExt->Lock, OldIrql );
-
+
FreeNdisPacket( Packet );
}
UINT Size, PayloadSize = OverallLength -
((ToWrite->Address + ToWrite->Fixed.AddressLen) - (PCHAR)ToWrite);
- NdisStatus = AllocatePacketWithBuffer( &NdisPacket, NULL,
+ NdisStatus = AllocatePacketWithBuffer( &NdisPacket, NULL,
PayloadSize + sizeof(ETH_HEADER) );
-
+
KeAcquireSpinLock( &DeviceExt->Lock, &OldIrql );
if( !NT_SUCCESS(NdisStatus) ) goto end;
GetDataPtr( NdisPacket, 0, (PCHAR *)&EthHeader, &Size );
if( !EthHeader ) goto end;
- LA_DbgPrint(MID_TRACE,("Writing %d bytes of Dst\n",
+ LA_DbgPrint(MID_TRACE,("Writing %d bytes of Dst\n",
ToWrite->Fixed.AddressLen));
/* Handle broadcast for other media types here */
if( ToWrite->Fixed.AddressLen )
- RtlCopyMemory( EthHeader->DstAddr,
- ToWrite->Address,
+ RtlCopyMemory( EthHeader->DstAddr,
+ ToWrite->Address,
ToWrite->Fixed.AddressLen );
else
memset( EthHeader->DstAddr, -1, sizeof(EthHeader->DstAddr) );
LA_DbgPrint(MID_TRACE,("Writing %d bytes of Src\n", Adapter->HWAddressLength));
- RtlCopyMemory( EthHeader->SrcAddr,
+ RtlCopyMemory( EthHeader->SrcAddr,
Adapter->HWAddress,
Adapter->HWAddressLength );
LA_DbgPrint(MID_TRACE,("Writing %d bytes of payload\n", PayloadSize));
EthHeader->EType = ToWrite->Fixed.PacketType;
- RtlCopyMemory( EthHeader + 1,
+ RtlCopyMemory( EthHeader + 1,
ToWrite->Address + ToWrite->Fixed.AddressLen,
PayloadSize );
- LANTransmit( Adapter, NdisPacket, ToWrite->Address,
+ LANTransmit( Adapter, NdisPacket, ToWrite->Address,
ToWrite->Fixed.PacketType );
end:
- KeReleaseSpinLock( &DeviceExt->Lock, OldIrql );
+ KeReleaseSpinLock( &DeviceExt->Lock, OldIrql );
return OverallLength;
}
Adapter->HeaderSize = sizeof(ETH_HEADER);
Adapter->MinFrameSize = 60;
AddressOID = OID_802_3_CURRENT_ADDRESS;
- Adapter->PacketFilter =
+ Adapter->PacketFilter =
NDIS_PACKET_TYPE_BROADCAST |
NDIS_PACKET_TYPE_DIRECTED |
NDIS_PACKET_TYPE_MULTICAST;
&Adapter->ListEntry,
&DeviceExt->Lock);
- Adapter->RegistryPath.Buffer =
+ Adapter->RegistryPath.Buffer =
ExAllocatePool( NonPagedPool, RegistryPath->MaximumLength );
if( !Adapter->RegistryPath.Buffer )
return NDIS_STATUS_RESOURCES;
-
+
RtlCopyUnicodeString( &Adapter->RegistryPath,
RegistryPath );
&Adapter->Lookahead,
sizeof(ULONG));
if (NdisStatus != NDIS_STATUS_SUCCESS) {
- LA_DbgPrint(MID_TRACE,
- ("Could not set lookahead buffer size (0x%X).\n",
+ LA_DbgPrint(MID_TRACE,
+ ("Could not set lookahead buffer size (0x%X).\n",
NdisStatus));
return NdisStatus;
}
&Adapter->PacketFilter,
sizeof(UINT));
if (NdisStatus != NDIS_STATUS_SUCCESS) {
- LA_DbgPrint(MID_TRACE, ("Could not set packet filter (0x%X).\n",
+ LA_DbgPrint(MID_TRACE, ("Could not set packet filter (0x%X).\n",
NdisStatus));
return NdisStatus;
}
*/
{
PLAN_DEVICE_EXT DeviceExt = LanDeviceObject->DeviceExtension;
-
+
LA_DbgPrint(DEBUG_DATALINK, ("Called.\n"));
NDIS_STATUS NdisStatus;
PLIST_ENTRY NextEntry;
PLAN_ADAPTER Current;
KIRQL OldIrql;
-
+
KeAcquireSpinLock(&DeviceExt->Lock, &OldIrql);
-
+
/* Search the list and remove every adapter we find */
CurrentEntry = DeviceExt->AdapterListHead.Flink;
while (CurrentEntry != &DeviceExt->AdapterListHead) {
LANUnregisterAdapter(Current);
CurrentEntry = NextEntry;
}
-
+
NdisDeregisterProtocol(&NdisStatus, DeviceExt->NdisProtocolHandle);
}
NTSTATUS STDCALL
-LanCreateProtocol( PDEVICE_OBJECT DeviceObject, PIRP Irp,
+LanCreateProtocol( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
PLAN_PROTOCOL Proto;
PFILE_FULL_EA_INFORMATION EaInfo;
- PLAN_DEVICE_EXT DeviceExt =
+ PLAN_DEVICE_EXT DeviceExt =
(PLAN_DEVICE_EXT)DeviceObject->DeviceExtension;
PFILE_OBJECT FileObject = IrpSp->FileObject;
PCHAR ProtoNumbersToMatch;
UINT Size = sizeof( *Proto );
NTSTATUS Status = STATUS_SUCCESS;
-
+
EaInfo = Irp->AssociatedIrp.SystemBuffer;
Size += EaInfo->EaValueLength;
Proto = ExAllocatePool( NonPagedPool, Size );
LA_DbgPrint(MID_TRACE,("NumEtherTypes: %d\n", Proto->NumEtherTypes));
- RtlCopyMemory( Proto->EtherType,
+ RtlCopyMemory( Proto->EtherType,
ProtoNumbersToMatch,
sizeof(USHORT) * Proto->NumEtherTypes );
NTSTATUS STDCALL
LanCloseProtocol( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
- PLAN_DEVICE_EXT DeviceExt =
+ PLAN_DEVICE_EXT DeviceExt =
(PLAN_DEVICE_EXT)DeviceObject->DeviceExtension;
PFILE_OBJECT FileObject = IrpSp->FileObject;
PLAN_PROTOCOL Proto = FileObject->FsContext;
while( !IsListEmpty( &Proto->ReadIrpListHead ) ) {
ReadIrpListEntry = RemoveHeadList( &Proto->ReadIrpListHead );
- ReadIrp = CONTAINING_RECORD( ReadIrpListEntry, IRP,
+ ReadIrp = CONTAINING_RECORD( ReadIrpListEntry, IRP,
Tail.Overlay.ListEntry );
ReadIrp->IoStatus.Information = 0;
ReadIrp->IoStatus.Status = STATUS_UNSUCCESSFUL;
ListEntry = ListEntry->Flink ) {
Current = CONTAINING_RECORD(ListEntry, LAN_ADAPTER, ListEntry);
if( Current->Index == Index ) {
- Target = Current;
+ Target = Current;
break;
}
}
PIO_STACK_LOCATION IrpSp ) {
PLAN_PACKET_HEADER ToWrite = Irp->AssociatedIrp.SystemBuffer;
NTSTATUS Status = STATUS_SUCCESS;
-
+
LA_DbgPrint(MID_TRACE,("Called\n"));
- Irp->IoStatus.Information =
+ Irp->IoStatus.Information =
LANTransmitInternal( ToWrite, IrpSp->Parameters.Write.Length );
Irp->IoStatus.Status = Status;
-
+
IoCompleteRequest( Irp, IO_NETWORK_INCREMENT );
return Status;
}
NTSTATUS STDCALL
LanReadData( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
- PLAN_DEVICE_EXT DeviceExt =
+ PLAN_DEVICE_EXT DeviceExt =
(PLAN_DEVICE_EXT)DeviceObject->DeviceExtension;
PFILE_OBJECT FileObject = IrpSp->FileObject;
PLAN_PROTOCOL Proto = FileObject->FsContext;
LanEnumAdapters( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
PLIST_ENTRY ListEntry;
- PLAN_DEVICE_EXT DeviceExt =
+ PLAN_DEVICE_EXT DeviceExt =
(PLAN_DEVICE_EXT)DeviceObject->DeviceExtension;
NTSTATUS Status = STATUS_SUCCESS;
PLAN_ADAPTER Adapter;
LA_DbgPrint(MID_TRACE,("Called\n"));
KeAcquireSpinLock( &DeviceExt->Lock, &OldIrql );
-
+
for( ListEntry = DeviceExt->AdapterListHead.Flink;
ListEntry != &DeviceExt->AdapterListHead;
ListEntry = ListEntry->Flink ) AdapterCount++;
LA_DbgPrint(MID_TRACE,("Ending\n"));
Irp->IoStatus.Status = Status;
- Irp->IoStatus.Information = (PCHAR)Output -
+ Irp->IoStatus.Information = (PCHAR)Output -
(PCHAR)Irp->AssociatedIrp.SystemBuffer;
IoCompleteRequest( Irp, IO_NO_INCREMENT );
NTSTATUS STDCALL
LanAdapterInfo( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
- PLAN_DEVICE_EXT DeviceExt =
+ PLAN_DEVICE_EXT DeviceExt =
(PLAN_DEVICE_EXT)DeviceObject->DeviceExtension;
PLAN_ADAPTER Adapter;
PLAN_ADDRESS_C Address;
KeAcquireSpinLock( &DeviceExt->Lock, &OldIrql );
- if( IrpSp->Parameters.DeviceIoControl.InputBufferLength <
+ if( IrpSp->Parameters.DeviceIoControl.InputBufferLength <
sizeof(*AdapterIndexPtr) )
Adapter = NULL;
else
Info->Media = Adapter->Media;
Info->Speed = Adapter->Speed;
/* Ethernet specific XXX */
- Info->AddressLen = IEEE_802_ADDR_LENGTH;
+ Info->AddressLen = IEEE_802_ADDR_LENGTH;
Info->Overhead = Adapter->HeaderSize;
Info->MTU = Adapter->MTU;
Info->RegKeySize = Adapter->RegistryPath.Length;
/* Write the address info */
Writing += Adapter->RegistryPath.Length;
-
+
for( ListEntry = Adapter->AddressList.Flink;
ListEntry != &Adapter->AddressList;
ListEntry = ListEntry->Flink ) {
- Address = CONTAINING_RECORD(ListEntry, LAN_ADDRESS_C,
+ Address = CONTAINING_RECORD(ListEntry, LAN_ADDRESS_C,
ListEntry);
AddrSize = LAN_ADDR_SIZE(Address->ClientPart.AddressLen,
Address->ClientPart.HWAddressLen);
for( ListEntry = Adapter->ForeignList.Flink;
ListEntry != &Adapter->ForeignList;
ListEntry = ListEntry->Flink ) {
- Address = CONTAINING_RECORD(ListEntry, LAN_ADDRESS_C,
+ Address = CONTAINING_RECORD(ListEntry, LAN_ADDRESS_C,
ListEntry);
AddrSize = LAN_ADDR_SIZE(Address->ClientPart.AddressLen,
Address->ClientPart.HWAddressLen);
ASSERT( BytesNeeded == Writing - Irp->AssociatedIrp.SystemBuffer );
} else Status = STATUS_BUFFER_TOO_SMALL;
} else Status = STATUS_NO_SUCH_DEVICE;
-
+
KeReleaseSpinLock( &DeviceExt->Lock, OldIrql );
LA_DbgPrint(MID_TRACE,("Ending (%d bytes)\n", BytesNeeded));
NTSTATUS STDCALL
LanSetBufferedMode( PDEVICE_OBJECT DeviceObject, PIRP Irp,
PIO_STACK_LOCATION IrpSp ) {
- PLAN_DEVICE_EXT DeviceExt =
+ PLAN_DEVICE_EXT DeviceExt =
(PLAN_DEVICE_EXT)DeviceObject->DeviceExtension;
PFILE_OBJECT FileObject = IrpSp->FileObject;
PLAN_PROTOCOL Proto = FileObject->FsContext;
LA_DbgPrint(MID_TRACE,("Called %x\n", Proto));
- KeAcquireSpinLock( &DeviceExt->Lock, &OldIrql );
+ KeAcquireSpinLock( &DeviceExt->Lock, &OldIrql );
- if( IrpSp->Parameters.DeviceIoControl.InputBufferLength >=
+ if( IrpSp->Parameters.DeviceIoControl.InputBufferLength >=
sizeof(Proto->Buffered) )
RtlCopyMemory( &Proto->Buffered, Irp->AssociatedIrp.SystemBuffer,
sizeof(Proto->Buffered) );
else
Status = STATUS_INVALID_PARAMETER;
-
+
KeReleaseSpinLock( &DeviceExt->Lock, OldIrql );
LA_DbgPrint(MID_TRACE,("Set buffered for %x to %d\n", Proto->Buffered));
/* write data */
case IRP_MJ_WRITE:
return LanWriteData( DeviceObject, Irp, IrpSp );
-
+
/* read data */
case IRP_MJ_READ:
return LanReadData( DeviceObject, Irp, IrpSp );
case IRP_MJ_DEVICE_CONTROL:
{
- LA_DbgPrint(MID_TRACE,("DeviceIoControl: %x\n",
+ LA_DbgPrint(MID_TRACE,("DeviceIoControl: %x\n",
IrpSp->Parameters.DeviceIoControl.
IoControlCode));
switch( IrpSp->Parameters.DeviceIoControl.IoControlCode ) {
{
Status = STATUS_NOT_IMPLEMENTED;
LA_DbgPrint(MIN_TRACE,
- ("Irp: Unknown Major code was %x\n",
+ ("Irp: Unknown Major code was %x\n",
IrpSp->MajorFunction));
break;
}
}
-
+
LA_DbgPrint(MID_TRACE, ("Returning %x\n", Status));
Irp->IoStatus.Status = Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return (Status);
}
CloseNdisPools();
}
-NTSTATUS STDCALL DriverEntry( PDRIVER_OBJECT DriverObject,
+NTSTATUS STDCALL DriverEntry( PDRIVER_OBJECT DriverObject,
PUNICODE_STRING RegsitryPath ) {
PDEVICE_OBJECT DeviceObject;
PLAN_DEVICE_EXT DeviceExt;
LANRegisterProtocol( &LanString );
DeviceObject->Flags |= DO_BUFFERED_IO;
-
+
LA_DbgPrint(MID_TRACE,("Device created: object %x ext %x\n",
DeviceObject, DeviceExt));
-
- return (Status);
+
+ return (Status);
}
/* EOF */
/* Last argument is extra space size */
NdisAllocatePacketPool( &NdisStatus, &GlobalPacketPool, 100, 0 );
if( !NT_SUCCESS(NdisStatus) ) return NdisStatus;
-
+
NdisAllocateBufferPool( &NdisStatus, &GlobalBufferPool, 100 );
if( !NT_SUCCESS(NdisStatus) )
NdisFreePacketPool(GlobalPacketPool);
}
void GetDataPtr( PNDIS_PACKET Packet,
- UINT Offset,
+ UINT Offset,
PCHAR *DataOut,
PUINT Size ) {
PNDIS_BUFFER Buffer;
PCHAR NewData;
NewData = ExAllocatePool( NonPagedPool, Len );
- if( !NewData ) return NDIS_STATUS_NOT_ACCEPTED; // XXX
+ if( !NewData ) return NDIS_STATUS_NOT_ACCEPTED; // XXX
TrackWithTag(EXALLOC_TAG, NewData, File, Line);
- if( Data )
+ if( Data )
RtlCopyMemory(NewData, Data, Len);
NdisAllocatePacket( &Status, &Packet, GlobalPacketPool );
#define GET_MINIPORT_DRIVER(Handle)((PMINIPORT_DRIVER)Handle)
/* Information about a logical adapter */
-typedef struct _LOGICAL_ADAPTER
+typedef struct _LOGICAL_ADAPTER
{
NDIS_MINIPORT_BLOCK NdisMiniportBlock; /* NDIS defined fields */
KDPC MiniportDpc; /* DPC routine for adapter */
PLOGICAL_ADAPTER Adapter,
PNDIS_REQUEST NdisRequest);
-BOOLEAN
+BOOLEAN
NdisFindDevice(
- UINT VendorID,
- UINT DeviceID,
- PUINT BusNumber,
+ UINT VendorID,
+ UINT DeviceID,
+ PUINT BusNumber,
PUINT SlotNumber);
VOID
/*
* FUNCTION: Copies data from a buffer to an NDIS buffer chain
* ARGUMENTS:
- * DstBuffer = Pointer to destination NDIS buffer
+ * DstBuffer = Pointer to destination NDIS buffer
* DstOffset = Destination start offset
* SrcData = Pointer to source buffer
* Length = Number of bytes to copy
PUCHAR SrcData;
NDIS_DbgPrint(MAX_TRACE, ("DstData 0x%X SrcBuffer 0x%X SrcOffset 0x%X Length %d\n",DstData,SrcBuffer, SrcOffset, Length));
-
+
/* Skip SrcOffset bytes in the source buffer chain */
if (SkipToOffset(SrcBuffer, SrcOffset, &SrcData, &SrcSize) == -1)
return 0;
{
if (MmGetMdlByteCount(Buffer) == 0)
return 1;
-
+
return ADDRESS_AND_SIZE_TO_SPAN_PAGES(
MmGetMdlVirtualAddress(Buffer),
MmGetMdlByteCount(Buffer));
NDIS_DbgPrint(MID_TRACE,("Free buffer -> %x\n", Temp));
Temp = Temp->Next;
}
-
+
NDIS_DbgPrint(MID_TRACE,("|:. <- End free buffers"));
#endif
MmInitializeMdl(&Temp->Mdl, VirtualAddress, Length);
Temp->Mdl.MdlFlags |= (MDL_SOURCE_IS_NONPAGED_POOL | MDL_ALLOCATED_FIXED_SIZE);
Temp->Mdl.MappedSystemVa = VirtualAddress;
-
+
Temp->BufferPool = Pool;
*Buffer = (PNDIS_BUFFER)Temp;
/*
* @unimplemented
*/
-NDIS_STATUS
+NDIS_STATUS
DDKAPI
NdisClModifyCallQoS(
IN NDIS_HANDLE NdisVcHandle,
/*
* @unimplemented
*/
-VOID
+VOID
EXPORT
NdisMCoSendComplete(
IN NDIS_STATUS Status,
* REVISIONS:
* Vizzini 07-28-2003 Created
* NOTES:
- * - Resource tracking has to be implemented here because of the design of the NDIS API.
+ * - Resource tracking has to be implemented here because of the design of the NDIS API.
* Whenever a read operation is performed, the NDIS library allocates space and returns
* it. A linked list is kept associated with every handle of the memory allocated to
* it. When the handle is closed, the resources are systematically released.
* pass this NDIS_HANDLE to things like ZwQueryValueKey(). I don't thknk they do (they
* certainly should not), but it should be kept in mind.
* UPDATE: I just found this in the NTDDK:
- * NdisOpenProtocolConfiguration returns a handle for the
- * HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\NICDriverInstance\Parameters\ProtocolName
+ * NdisOpenProtocolConfiguration returns a handle for the
+ * HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\NICDriverInstance\Parameters\ProtocolName
* registry key. XXX This is a problem. Following that, the DDK instructs programmers
* to use NdisReadConfiguration and NdisWriteConfiguration. No telling what the world's idiots
* have done with this.
* places that the DDK doesn't explicitly mention it, though.
* - There's a general reliance on the fact that UNICODE_STRING.Length doesn't include a trailing
* 0, which it shouldn't
- * - I added support for NdisParameterBinary. It's at the end of the struct. I wonder if
+ * - I added support for NdisParameterBinary. It's at the end of the struct. I wonder if
* it'll break things.
* - All the routines in this file are PASSIVE_LEVEL only, and all memory is PagedPool
*/
* ARGUMENTS:
* Status: Pointer to a caller-supplied NDIS_STATUS where we return status
* ConfigurationHandle: The Configuration Handle passed back from the call to one of the Open functions
- * Keyword: The registry value name to write
+ * Keyword: The registry value name to write
* ParameterValue: The value data to write
* RETURNS:
* NDIS_STATUS_SUCCESS - the operation completed successfully
break;
}
- *Status = ZwSetValueKey(((PMINIPORT_CONFIGURATION_CONTEXT)ConfigurationHandle)->Handle,
+ *Status = ZwSetValueKey(((PMINIPORT_CONFIGURATION_CONTEXT)ConfigurationHandle)->Handle,
Keyword, 0, ParameterType, Data, DataSize);
if(*Status != STATUS_SUCCESS)
*ParameterValue = NULL;
*Status = NDIS_STATUS_FAILURE;
-
+
if(ParameterType != NdisParameterInteger &&
ParameterType != NdisParameterHexInteger &&
ParameterType != NdisParameterString &&
MiniportResource->ResourceType = 0;
MiniportResource->Resource = *ParameterValue;
- NDIS_DbgPrint(MID_TRACE,("inserting 0x%x into the resource list\n",
+ NDIS_DbgPrint(MID_TRACE,("inserting 0x%x into the resource list\n",
MiniportResource->Resource));
- ExInterlockedInsertTailList(&ConfigurationContext->ResourceListHead,
+ ExInterlockedInsertTailList(&ConfigurationContext->ResourceListHead,
&MiniportResource->ListEntry, &ConfigurationContext->ResourceLock);
(*ParameterValue)->ParameterType = NdisParameterInteger;
MiniportResource->ResourceType = 0;
MiniportResource->Resource = *ParameterValue;
NDIS_DbgPrint(MID_TRACE,("inserting 0x%x into the resource list\n", MiniportResource->Resource));
- ExInterlockedInsertTailList(&ConfigurationContext->ResourceListHead,
+ ExInterlockedInsertTailList(&ConfigurationContext->ResourceListHead,
&MiniportResource->ListEntry, &ConfigurationContext->ResourceLock);
(*ParameterValue)->ParameterType = NdisParameterInteger;
MiniportResource->ResourceType = 0;
MiniportResource->Resource = *ParameterValue;
NDIS_DbgPrint(MID_TRACE,("inserting 0x%x into the resource list\n", MiniportResource->Resource));
- ExInterlockedInsertTailList(&ConfigurationContext->ResourceListHead,
+ ExInterlockedInsertTailList(&ConfigurationContext->ResourceListHead,
&MiniportResource->ListEntry, &ConfigurationContext->ResourceLock);
(*ParameterValue)->ParameterType = NdisParameterInteger;
}
/* grab the value */
- *Status = ZwQueryValueKey(ConfigurationContext->Handle, Keyword, KeyValuePartialInformation,
+ *Status = ZwQueryValueKey(ConfigurationContext->Handle, Keyword, KeyValuePartialInformation,
KeyInformation, KeyDataLength + sizeof(KEY_VALUE_PARTIAL_INFORMATION), &KeyDataLength);
if(*Status != STATUS_SUCCESS)
{
{
switch(chr)
{
- case L'0': return 0;
- case L'1': return 1;
- case L'2': return 2;
- case L'3': return 3;
- case L'4': return 4;
- case L'5': return 5;
+ case L'0': return 0;
+ case L'1': return 1;
+ case L'2': return 2;
+ case L'3': return 3;
+ case L'4': return 4;
+ case L'5': return 5;
case L'6': return 6;
case L'7': return 7;
case L'8': return 8;
case L'9': return 9;
- case L'A':
- case L'a':
+ case L'A':
+ case L'a':
return 10;
case L'B':
case L'b':
return;
}
- *Status = ZwEnumerateKey(ConfigurationHandle, Index, KeyBasicInformation, KeyInformation,
+ *Status = ZwEnumerateKey(ConfigurationHandle, Index, KeyBasicInformation, KeyInformation,
KeyInformationLength + sizeof(KEY_BASIC_INFORMATION), &KeyInformationLength);
if(*Status != STATUS_SUCCESS)
PETH_FILTER NewFilter;
NewFilter = ExAllocatePool(NonPagedPool, sizeof(ETH_FILTER));
- if (NewFilter != NULL)
+ if (NewFilter != NULL)
{
RtlZeroMemory(NewFilter, sizeof(ETH_FILTER));
NewFilter->MaxMulticastAddresses = MaximumMulticastAddresses;
{
CurrentEntry = Adapter->ProtocolListHead.Flink;
- while (CurrentEntry != &Adapter->ProtocolListHead)
+ while (CurrentEntry != &Adapter->ProtocolListHead)
{
AdapterBinding = CONTAINING_RECORD(CurrentEntry, ADAPTER_BINDING, AdapterListEntry);
/*
* @implemented
*/
-ULONG
+ULONG
EXPORT
NdisImmediateWritePciSlotInformation(
IN NDIS_HANDLE WrapperConfigurationContext,
* FUNCTION: returns a nic's hardware resources
* ARGUMENTS:
* Status: on return, contains the status of the operation
- * WrapperConfigurationContext: handle input to MiniportInitialize
+ * WrapperConfigurationContext: handle input to MiniportInitialize
* ResourceList: on return, contains the list of resources for the nic
* BufferSize: size of ResourceList
* NOTES:
return;
}
- ResourceListSize =
+ ResourceListSize =
FIELD_OFFSET(CM_PARTIAL_RESOURCE_LIST, PartialDescriptors) +
MiniportBlock->AllocatedResources->List[0].PartialResourceList.Count *
sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR);
KeAcquireSpinLockAtDpcLevel(&Adapter->NdisMiniportBlock.Lock);
{
- if ((!WasBusy) && (Adapter->WorkQueueHead))
+ if ((!WasBusy) && (Adapter->WorkQueueHead))
{
KeInsertQueueDpc(&Adapter->MiniportDpc, NULL, NULL);
- }
- else
+ }
+ else
{
Adapter->MiniportBusy = WasBusy;
}
&QueueMiniportHandleInterrupt,
Adapter->NdisMiniportBlock.MiniportAdapterContext);
- if (QueueMiniportHandleInterrupt)
+ if (QueueMiniportHandleInterrupt)
{
NDIS_DbgPrint(MAX_TRACE, ("Queueing DPC.\n"));
KeInsertQueueDpc(&Adapter->NdisMiniportBlock.Interrupt->InterruptDpc, NULL, NULL);
* Irp: Reserved; must be ignored
* MapRegisterBase: Map registers assigned for transfer
* Context: LOGICAL_ADAPTER object of the requesting miniport
- * NOTES:
+ * NOTES:
* - Called once per BaseMapRegister (see NdisMAllocateMapRegisters)
* - Called at IRQL = DISPATCH_LEVEL
*/
* RETURNS:
* NDIS_STATUS_SUCCESS on success
* NDIS_STATUS_RESOURCES on failure
- * NOTES:
+ * NOTES:
* - the win2k ddk and the nt4 ddk have conflicting prototypes for this.
* I'm implementing the 2k one.
* - do not confuse a "base map register" with a "map register" - they
* map registers that represent the transfer.
* - Because of the above sillyness, you can only specify a few base map
* registers at most. a 1514-byte packet is two map registers at 4k
- * page size.
+ * page size.
* - NDIS limits the total number of allocated map registers to 64,
* which (in the case of the above example) limits the number of base
* map registers to 32.
/*
* map registers correlate to physical pages. ndis documents a
- * maximum of 64 map registers that it will return.
+ * maximum of 64 map registers that it will return.
* at 4k pages, a 1514-byte buffer can span not more than 2 pages.
*
* the number of registers required for a given physical mapping
- * is (first register + last register + one per page size),
+ * is (first register + last register + one per page size),
* given that physical mapping is > 2.
*/
if(AvailableMapRegisters < MapRegistersPerBaseRegister)
{
- NDIS_DbgPrint(MIN_TRACE, ("Didn't get enough map registers from hal - requested 0x%x, got 0x%x\n",
+ NDIS_DbgPrint(MIN_TRACE, ("Didn't get enough map registers from hal - requested 0x%x, got 0x%x\n",
MapRegistersPerBaseRegister, AvailableMapRegisters));
return NDIS_STATUS_RESOURCES;
* FUNCTION: Sets up map registers for a bus-master DMA transfer
* ARGUMENTS:
* MiniportAdapterHandle: handle originally input to MiniportInitialize
- * Buffer: data to be transferred
+ * Buffer: data to be transferred
* PhysicalMapRegister: specifies the map register to set up
* WriteToDevice: if true, data is being written to the device; else it is being read
* PhysicalAddressArray: list of mapped ranges suitable for DMA with the device
* - The basic idea: call IoMapTransfer() in a loop as many times as it takes
* in order to map all of the virtual memory to physical memoroy readable
* by the device
- * - The caller supplies storage for the physical address array.
+ * - The caller supplies storage for the physical address array.
*/
{
PLOGICAL_ADAPTER Adapter = 0;
ULONG Length = TotalLength;
ReturnedAddress = Adapter->NdisMiniportBlock.SystemAdapterObject->DmaOperations->MapTransfer(
- Adapter->NdisMiniportBlock.SystemAdapterObject, Buffer,
- Adapter->NdisMiniportBlock.MapRegisters[PhysicalMapRegister].MapRegister,
+ Adapter->NdisMiniportBlock.SystemAdapterObject, Buffer,
+ Adapter->NdisMiniportBlock.MapRegisters[PhysicalMapRegister].MapRegister,
CurrentVa, &Length, WriteToDevice);
Adapter->NdisMiniportBlock.MapRegisters[PhysicalMapRegister].WriteToDevice = WriteToDevice;
Length = MmGetMdlByteCount(Buffer);
Adapter->NdisMiniportBlock.SystemAdapterObject->DmaOperations->FlushAdapterBuffers(
- Adapter->NdisMiniportBlock.SystemAdapterObject, Buffer,
+ Adapter->NdisMiniportBlock.SystemAdapterObject, Buffer,
Adapter->NdisMiniportBlock.MapRegisters[PhysicalMapRegister].MapRegister,
- CurrentVa, Length,
+ CurrentVa, Length,
Adapter->NdisMiniportBlock.MapRegisters[PhysicalMapRegister].WriteToDevice);
}
for(i = 0; i < Adapter->NdisMiniportBlock.BaseMapRegistersNeeded; i++)
{
AdapterObject->DmaOperations->FreeMapRegisters(
- Adapter->NdisMiniportBlock.SystemAdapterObject,
+ Adapter->NdisMiniportBlock.SystemAdapterObject,
Adapter->NdisMiniportBlock.MapRegisters[i].MapRegister,
MapRegistersPerBaseRegister);
}
if (AdapterObject == NULL)
return 0;
-
+
return AdapterObject->DmaOperations->ReadDmaCounter(AdapterObject);
}
if (AdapterObject == NULL)
return 0;
-
+
return AdapterObject->DmaOperations->GetDmaAlignment(AdapterObject);
}
if (NT_SUCCESS(Status))
return NDIS_STATUS_SUCCESS;
- if (Status == STATUS_INSUFFICIENT_RESOURCES)
+ if (Status == STATUS_INSUFFICIENT_RESOURCES)
{
/* FIXME: Log error */
NDIS_DbgPrint(MIN_TRACE, ("Resource conflict!\n"));
IN NDIS_HANDLE NdisAdapterHandle,
IN NDIS_ERROR_CODE ErrorCode,
IN ULONG NumberOfErrorValues,
- ...)
+ ...)
/*
* FUNCTION: Write a syslog error
* ARGUMENTS:
* ARGUMENTS:
* VirtualAddress = a pointer to the returned memory block
* Length = the number of requested bytes
- * Tag = 32-bit pool tag
- * RETURNS:
+ * Tag = 32-bit pool tag
+ * RETURNS:
* NDIS_STATUS_SUCCESS on success
* NDIS_STATUS_FAILURE on failure
*/
{
NDIS_DbgPrint(MAX_TRACE, ("Called.\n"));
- if (MemoryFlags & NDIS_MEMORY_NONCACHED)
+ if (MemoryFlags & NDIS_MEMORY_NONCACHED)
{
*VirtualAddress = MmAllocateNonCachedMemory(Length);
if(!*VirtualAddress)
return NDIS_STATUS_SUCCESS;
}
- if (MemoryFlags & NDIS_MEMORY_CONTIGUOUS)
+ if (MemoryFlags & NDIS_MEMORY_CONTIGUOUS)
{
*VirtualAddress = MmAllocateContiguousMemory(Length, HighestAcceptableAddress);
if(!*VirtualAddress)
{
NDIS_DbgPrint(MAX_TRACE, ("Called.\n"));
- if (MemoryFlags & NDIS_MEMORY_NONCACHED)
+ if (MemoryFlags & NDIS_MEMORY_NONCACHED)
{
MmFreeNonCachedMemory(VirtualAddress, Length);
return;
}
- if (MemoryFlags & NDIS_MEMORY_CONTIGUOUS)
+ if (MemoryFlags & NDIS_MEMORY_CONTIGUOUS)
{
MmFreeContiguousMemory(VirtualAddress);
return;
VOID
STDCALL
NdisMFreeSharedMemoryPassive(
- PVOID Context)
+ PVOID Context)
/*
* FUNCTION: Free a common buffer
* ARGUMENTS:
PMINIPORT_SHARED_MEMORY Memory;
NDIS_DbgPrint(MAX_TRACE,("Called.\n"));
-
+
ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
/* Must be NonpagedPool because by definition we're at DISPATCH_LEVEL */
Memory->PhysicalAddress = PhysicalAddress;
Memory->VirtualAddress = VirtualAddress;
Memory->Cached = Cached;
-
+
PsCreateSystemThread(&ThreadHandle, THREAD_ALL_ACCESS, 0, 0, 0, NdisMFreeSharedMemoryPassive, Memory);
ZwClose(ThreadHandle);
}
*/
#define BREAK_ON_MINIPORT_INIT 0
-/*
+/*
* This has to be big enough to hold the results of querying the Route value
* from the Linkage key. Please re-code me to determine this dynamically.
*/
/* Number of media we know */
#define MEDIA_ARRAY_SIZE 15
-static NDIS_MEDIUM MediaArray[MEDIA_ARRAY_SIZE] =
+static NDIS_MEDIUM MediaArray[MEDIA_ARRAY_SIZE] =
{
NdisMedium802_3,
NdisMedium802_5,
/* KIRQL OldIrql; */
PLIST_ENTRY CurrentEntry;
PADAPTER_BINDING AdapterBinding;
-
+
NDIS_DbgPrint(DEBUG_MINIPORT, ("Called. Adapter (0x%X) HeaderBuffer (0x%X) "
"HeaderBufferSize (0x%X) LookaheadBuffer (0x%X) LookaheadBufferSize (0x%X).\n",
Adapter, HeaderBuffer, HeaderBufferSize, LookaheadBuffer, LookaheadBufferSize));
CurrentEntry = Adapter->ProtocolListHead.Flink;
NDIS_DbgPrint(DEBUG_MINIPORT, ("CurrentEntry = %x\n", CurrentEntry));
- if (CurrentEntry == &Adapter->ProtocolListHead)
+ if (CurrentEntry == &Adapter->ProtocolListHead)
{
NDIS_DbgPrint(DEBUG_MINIPORT, ("WARNING: No upper protocol layer.\n"));
}
- while (CurrentEntry != &Adapter->ProtocolListHead)
+ while (CurrentEntry != &Adapter->ProtocolListHead)
{
AdapterBinding = CONTAINING_RECORD(CurrentEntry, ADAPTER_BINDING, AdapterListEntry);
NDIS_DbgPrint(DEBUG_MINIPORT, ("AdapterBinding = %x\n", AdapterBinding));
#endif
NDIS_DbgPrint
- (MID_TRACE,
+ (MID_TRACE,
("XXX (%x) %x %x %x %x %x %x %x XXX\n",
*AdapterBinding->ProtocolBinding->Chars.ReceiveHandler,
AdapterBinding->NdisOpenBlock.NdisCommonOpenBlock.ProtocolBindingContext,
NdisQueryPacket(Packet, NULL, NULL, &NdisBuffer, NULL);
- if (!NdisBuffer)
+ if (!NdisBuffer)
{
NDIS_DbgPrint(MID_TRACE, ("Packet contains no buffers.\n"));
return FALSE;
/* FIXME: Should handle fragmented packets */
- switch (Adapter->NdisMiniportBlock.MediaType)
+ switch (Adapter->NdisMiniportBlock.MediaType)
{
case NdisMedium802_3:
Length = ETH_LENGTH_OF_ADDRESS;
return FALSE;
}
- if (BufferLength < Length)
+ if (BufferLength < Length)
{
NDIS_DbgPrint(MID_TRACE, ("Buffer is too small.\n"));
return FALSE;
{
CurrentEntry = AdapterListHead.Flink;
- while (CurrentEntry != &AdapterListHead)
+ while (CurrentEntry != &AdapterListHead)
{
Adapter = CONTAINING_RECORD(CurrentEntry, LOGICAL_ADAPTER, ListEntry);
NDIS_DbgPrint(DEBUG_MINIPORT, ("AdapterName = %wZ\n", AdapterName));
NDIS_DbgPrint(DEBUG_MINIPORT, ("DeviceName = %wZ\n", &Adapter->NdisMiniportBlock.MiniportName));
- if (RtlCompareUnicodeString(AdapterName, &Adapter->NdisMiniportBlock.MiniportName, TRUE) == 0)
+ if (RtlCompareUnicodeString(AdapterName, &Adapter->NdisMiniportBlock.MiniportName, TRUE) == 0)
{
ReferenceObject(Adapter);
break;
if(Adapter)
{
- NDIS_DbgPrint(DEBUG_MINIPORT, ("Leaving. Adapter found at 0x%x\n", Adapter));
+ NDIS_DbgPrint(DEBUG_MINIPORT, ("Leaving. Adapter found at 0x%x\n", Adapter));
}
else
{
NDIS_DbgPrint(DEBUG_MINIPORT, ("Called.\n"));
- if (Adapter->QueryBufferLength == 0)
+ if (Adapter->QueryBufferLength == 0)
{
/* XXX is 32 the right number? */
Adapter->QueryBuffer = ExAllocatePool(NonPagedPool, (Size == 0)? 32 : Size);
- if (!Adapter->QueryBuffer)
+ if (!Adapter->QueryBuffer)
{
NDIS_DbgPrint(MIN_TRACE, ("Insufficient resources.\n"));
return NDIS_STATUS_RESOURCES;
&BytesNeeded);
/* XXX is status_pending part of success macro? */
- if ((NT_SUCCESS(NdisStatus)) || (NdisStatus == NDIS_STATUS_PENDING))
+ if ((NT_SUCCESS(NdisStatus)) || (NdisStatus == NDIS_STATUS_PENDING))
{
NDIS_DbgPrint(DEBUG_MINIPORT, ("Miniport returned status (0x%X).\n", NdisStatus));
return NdisStatus;
}
- if (NdisStatus == NDIS_STATUS_INVALID_LENGTH)
+ if (NdisStatus == NDIS_STATUS_INVALID_LENGTH)
{
ExFreePool(Adapter->QueryBuffer);
Adapter->QueryBufferLength += BytesNeeded;
Adapter->QueryBuffer = ExAllocatePool(NonPagedPool, Adapter->QueryBufferLength);
- if (!Adapter->QueryBuffer)
+ if (!Adapter->QueryBuffer)
{
NDIS_DbgPrint(MIN_TRACE, ("Insufficient resources.\n"));
return NDIS_STATUS_RESOURCES;
ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
#if 0
- if (Adapter->WorkQueueLevel < NDIS_MINIPORT_WORK_QUEUE_SIZE - 1)
+ if (Adapter->WorkQueueLevel < NDIS_MINIPORT_WORK_QUEUE_SIZE - 1)
{
Item = &Adapter->WorkQueue[Adapter->WorkQueueLevel];
Adapter->WorkQueueLevel++;
- }
- else
+ }
+ else
#endif
{
Item = ExAllocatePool(NonPagedPool, sizeof(NDIS_MINIPORT_WORK_ITEM));
- if (Item == NULL)
+ if (Item == NULL)
{
NDIS_DbgPrint(MIN_TRACE, ("Insufficient resources.\n"));
return NDIS_STATUS_RESOURCES;
/* safe due to adapter lock held */
Item->Link.Next = NULL;
- if (!Adapter->WorkQueueHead)
+ if (!Adapter->WorkQueueHead)
{
Adapter->WorkQueueHead = Item;
Adapter->WorkQueueTail = Item;
- }
- else
+ }
+ else
{
Adapter->WorkQueueTail->Link.Next = (PSINGLE_LIST_ENTRY)Item;
Adapter->WorkQueueTail = Item;
Item = Adapter->WorkQueueHead;
- if (Item)
+ if (Item)
{
/* safe due to adapter lock held */
Adapter->WorkQueueHead = (PNDIS_MINIPORT_WORK_ITEM)Item->Link.Next;
Adapter->NdisMiniportBlock.MediaRequest = NdisRequest;
- switch (NdisRequest->RequestType)
+ switch (NdisRequest->RequestType)
{
case NdisRequestQueryInformation:
return (*Adapter->Miniport->Chars.QueryInformationHandler)(
IN NDIS_HANDLE MiniportAdapterHandle,
IN NDIS_STATUS Status)
{
- PNDIS_MINIPORT_BLOCK MiniportBlock =
+ PNDIS_MINIPORT_BLOCK MiniportBlock =
(PNDIS_MINIPORT_BLOCK)MiniportAdapterHandle;
ASSERT(MiniportBlock);
if( MiniportBlock->QueryCompleteHandler )
NdisStatus = MiniDequeueWorkItem(Adapter, &WorkItemType, &WorkItemContext);
- if (NdisStatus == NDIS_STATUS_SUCCESS)
+ if (NdisStatus == NDIS_STATUS_SUCCESS)
{
- switch (WorkItemType)
+ switch (WorkItemType)
{
case NdisWorkItemSend:
/*
*/
(*Adapter->Miniport->Chars.SendPacketsHandler)(
Adapter->NdisMiniportBlock.MiniportAdapterContext, (PPNDIS_PACKET)&WorkItemContext, 1);
- NdisStatus =
+ NdisStatus =
NDIS_GET_PACKET_STATUS((PNDIS_PACKET)WorkItemContext);
NDIS_DbgPrint(MAX_TRACE, ("back from miniport's SendPackets handler\n"));
if (NdisStatus == NDIS_STATUS_PENDING)
break;
- switch (((PNDIS_REQUEST)WorkItemContext)->RequestType)
+ switch (((PNDIS_REQUEST)WorkItemContext)->RequestType)
{
case NdisRequestQueryInformation:
NdisMQueryInformationComplete((NDIS_HANDLE)Adapter, NdisStatus);
Miniport = ExAllocatePool(NonPagedPool, sizeof(MINIPORT_DRIVER));
- if (!Miniport)
+ if (!Miniport)
{
NDIS_DbgPrint(MIN_TRACE, ("Insufficient resources.\n"));
return;
if(sh)
sh(Context->DriverContext);
-}
+}
\f
/*
NDIS_DbgPrint(DEBUG_MINIPORT, ("Called.\n"));
- if(BugcheckContext)
+ if(BugcheckContext)
return;
BugcheckContext = ExAllocatePool(NonPagedPool, sizeof(MINIPORT_BUGCHECK_CONTEXT));
/* not sure if this needs to be initialized or not... oh well, it's a leak. */
BugcheckContext->CallbackRecord = ExAllocatePool(NonPagedPool, sizeof(KBUGCHECK_CALLBACK_RECORD));
- KeRegisterBugCheckCallback(BugcheckContext->CallbackRecord, NdisIBugcheckCallback,
+ KeRegisterBugCheckCallback(BugcheckContext->CallbackRecord, NdisIBugcheckCallback,
BugcheckContext, sizeof(BugcheckContext), (PUCHAR)"Ndis Miniport");
}
/* Get MAC options for adapter */
NdisStatus = MiniQueryInformation(Adapter, OID_GEN_MAC_OPTIONS, 0, &BytesWritten);
- if (NdisStatus != NDIS_STATUS_SUCCESS)
+ if (NdisStatus != NDIS_STATUS_SUCCESS)
{
NDIS_DbgPrint(MIN_TRACE, ("OID_GEN_MAC_OPTIONS failed. NdisStatus (0x%X).\n", NdisStatus));
return NdisStatus;
/* Get current hardware address of adapter */
NdisStatus = MiniQueryInformation(Adapter, AddressOID, 0, &BytesWritten);
- if (NdisStatus != NDIS_STATUS_SUCCESS)
+ if (NdisStatus != NDIS_STATUS_SUCCESS)
{
NDIS_DbgPrint(MIN_TRACE, ("Address OID (0x%X) failed. NdisStatus (0x%X).\n", AddressOID, NdisStatus));
return NdisStatus;
/* Get maximum lookahead buffer size of adapter */
NdisStatus = MiniQueryInformation(Adapter, OID_GEN_MAXIMUM_LOOKAHEAD, 0, &BytesWritten);
- if (NdisStatus != NDIS_STATUS_SUCCESS)
+ if (NdisStatus != NDIS_STATUS_SUCCESS)
{
NDIS_DbgPrint(MIN_TRACE, ("OID_GEN_MAXIMUM_LOOKAHEAD failed. NdisStatus (0x%X).\n", NdisStatus));
return NdisStatus;
/* Get current lookahead buffer size of adapter */
NdisStatus = MiniQueryInformation(Adapter, OID_GEN_CURRENT_LOOKAHEAD, 0, &BytesWritten);
- if (NdisStatus != NDIS_STATUS_SUCCESS)
+ if (NdisStatus != NDIS_STATUS_SUCCESS)
{
NDIS_DbgPrint(MIN_TRACE, ("OID_GEN_CURRENT_LOOKAHEAD failed. NdisStatus (0x%X).\n", NdisStatus));
return NdisStatus;
NDIS_DbgPrint(DEBUG_MINIPORT, ("CurLookaheadLength (0x%X).\n", Adapter->NdisMiniportBlock.CurrentLookahead));
- if (Adapter->NdisMiniportBlock.MaximumLookahead != 0)
+ if (Adapter->NdisMiniportBlock.MaximumLookahead != 0)
{
Adapter->LookaheadLength = Adapter->NdisMiniportBlock.MaximumLookahead + Adapter->MediumHeaderSize;
Adapter->LookaheadBuffer = ExAllocatePool(NonPagedPool, Adapter->LookaheadLength);
/*
* Prepare wrapper context used by HW and configuration routines.
*/
-
+
Status = IoOpenDeviceRegistryKey(
Adapter->NdisMiniportBlock.PhysicalDeviceObject, PLUGPLAY_REGKEY_DRIVER,
KEY_ALL_ACCESS, &WrapperContext.RegistryHandle);
{
ResourceCount = Stack->Parameters.StartDevice.AllocatedResources->List[0].
PartialResourceList.Count;
- ResourceListSize =
+ ResourceListSize =
FIELD_OFFSET(CM_RESOURCE_LIST, List[0].PartialResourceList.
PartialDescriptors[ResourceCount]);
RtlCopyMemory(Adapter->NdisMiniportBlock.AllocatedResources,
Stack->Parameters.StartDevice.AllocatedResources,
ResourceListSize);
-
+
RtlCopyMemory(Adapter->NdisMiniportBlock.AllocatedResourcesTranslated,
Stack->Parameters.StartDevice.AllocatedResourcesTranslated,
ResourceListSize);
* Store the Bus Type, Bus Number and Slot information. It's used by
* the hardware routines then.
*/
-
+
NdisOpenConfiguration(&NdisStatus, &ConfigHandle, (NDIS_HANDLE)&WrapperContext);
Size = sizeof(ULONG);
ZwClose(WrapperContext.RegistryHandle);
if (NdisStatus != NDIS_STATUS_SUCCESS ||
- SelectedMediumIndex >= MEDIA_ARRAY_SIZE)
+ SelectedMediumIndex >= MEDIA_ARRAY_SIZE)
{
NDIS_DbgPrint(MIN_TRACE, ("MiniportInitialize() failed for an adapter.\n"));
return (NTSTATUS)NdisStatus;
Adapter->NdisMiniportBlock.MediaType = MediaArray[SelectedMediumIndex];
- switch (Adapter->NdisMiniportBlock.MediaType)
+ switch (Adapter->NdisMiniportBlock.MediaType)
{
case NdisMedium802_3:
Adapter->MediumHeaderSize = 14; /* XXX figure out what to do about LLC */
return STATUS_UNSUCCESSFUL;
}
- if (!Success || NdisStatus != NDIS_STATUS_SUCCESS)
+ if (!Success || NdisStatus != NDIS_STATUS_SUCCESS)
{
NDIS_DbgPrint(MAX_TRACE, ("couldn't create filter (%x)\n", NdisStatus));
if (Adapter->LookaheadBuffer)
* gathered by IoGetDeviceProperty. I choosed the second because
* IoOpenDriverRegistryKey wasn't implemented at the time of writing.
*/
-
+
Status = IoGetDeviceProperty(PhysicalDeviceObject, DevicePropertyDriverKeyName,
0, NULL, &DriverKeyLength);
if (Status != STATUS_BUFFER_TOO_SMALL)
/*
* Create the device object.
*/
-
+
NDIS_DbgPrint(MAX_TRACE, ("creating device %wZ\n", &ExportName));
Status = IoCreateDevice(Miniport->DriverObject, sizeof(LOGICAL_ADAPTER),
&ExportName, FILE_DEVICE_PHYSICAL_NETCARD,
0, FALSE, &DeviceObject);
- if (!NT_SUCCESS(Status))
+ if (!NT_SUCCESS(Status))
{
NDIS_DbgPrint(MIN_TRACE, ("Could not create device object.\n"));
RtlFreeUnicodeString(&ExportName);
Adapter->NdisMiniportBlock.OldPnPDeviceState = 0;
Adapter->NdisMiniportBlock.PnPDeviceState = NdisPnPDeviceAdded;
-
+
KeInitializeDpc(&Adapter->MiniportDpc, MiniportDpc, (PVOID)Adapter);
DeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
-
+
return STATUS_SUCCESS;
}
* MiniportCharacteristics = Pointer to a buffer with miniport characteristics
* CharacteristicsLength = Number of bytes in characteristics buffer
* RETURNS:
- * Status of operation
+ * Status of operation
*/
{
UINT MinSize;
NDIS_DbgPrint(MAX_TRACE, ("Called.\n"));
- switch (MiniportCharacteristics->MajorNdisVersion)
+ switch (MiniportCharacteristics->MajorNdisVersion)
{
case 0x03:
MinSize = sizeof(NDIS30_MINIPORT_CHARACTERISTICS);
return NDIS_STATUS_BAD_VERSION;
}
- if (CharacteristicsLength < MinSize)
+ if (CharacteristicsLength < MinSize)
{
NDIS_DbgPrint(DEBUG_MINIPORT, ("Bad miniport characteristics.\n"));
return NDIS_STATUS_BAD_CHARACTERISTICS;
(!MiniportCharacteristics->InitializeHandler)||
(!MiniportCharacteristics->QueryInformationHandler) ||
(!MiniportCharacteristics->ResetHandler) ||
- (!MiniportCharacteristics->SetInformationHandler))
+ (!MiniportCharacteristics->SetInformationHandler))
{
NDIS_DbgPrint(DEBUG_MINIPORT, ("Bad miniport characteristics.\n"));
return NDIS_STATUS_BAD_CHARACTERISTICS;
}
- if (MiniportCharacteristics->MajorNdisVersion == 0x03)
+ if (MiniportCharacteristics->MajorNdisVersion == 0x03)
{
- if (!MiniportCharacteristics->SendHandler)
+ if (!MiniportCharacteristics->SendHandler)
{
NDIS_DbgPrint(DEBUG_MINIPORT, ("Bad miniport characteristics.\n"));
return NDIS_STATUS_BAD_CHARACTERISTICS;
}
- }
- else if (MiniportCharacteristics->MajorNdisVersion >= 0x04)
+ }
+ else if (MiniportCharacteristics->MajorNdisVersion >= 0x04)
{
/* NDIS 4.0+ */
if ((!MiniportCharacteristics->SendHandler) &&
- (!MiniportCharacteristics->SendPacketsHandler))
+ (!MiniportCharacteristics->SendPacketsHandler))
{
NDIS_DbgPrint(DEBUG_MINIPORT, ("Bad miniport characteristics.\n"));
return NDIS_STATUS_BAD_CHARACTERISTICS;
}
KeReleaseSpinLock(&Adapter->NdisMiniportBlock.Lock, OldIrql);
- if (BufferedLength > Adapter->MediumHeaderSize)
+ if (BufferedLength > Adapter->MediumHeaderSize)
{
/* XXX Change this to call SendPackets so we don't have to duplicate this wacky logic */
MiniIndicateData(Adapter, NULL, Adapter->LookaheadBuffer, Adapter->MediumHeaderSize,
&Adapter->LookaheadBuffer[Adapter->MediumHeaderSize], BufferedLength - Adapter->MediumHeaderSize,
PacketLength - Adapter->MediumHeaderSize);
- }
- else
+ }
+ else
{
MiniIndicateData(Adapter, NULL, Adapter->LookaheadBuffer, Adapter->MediumHeaderSize, NULL, 0, 0);
}
KIRQL OldIrql;
BOOLEAN QueueWorkItem = FALSE;
NDIS_STATUS NdisStatus;
- PADAPTER_BINDING AdapterBinding;
+ PADAPTER_BINDING AdapterBinding;
PLOGICAL_ADAPTER Adapter;
NDIS_DbgPrint(MAX_TRACE, ("Called.\n"));
}
/* MiniQueueWorkItem must be called at IRQL >= DISPATCH_LEVEL */
- if (QueueWorkItem)
+ if (QueueWorkItem)
{
MiniQueueWorkItem(Adapter, NdisWorkItemRequest, (PVOID)NdisRequest);
KeReleaseSpinLock(&Adapter->NdisMiniportBlock.Lock, OldIrql);
return NDIS_STATUS_PENDING;
- }
+ }
KeReleaseSpinLock(&Adapter->NdisMiniportBlock.Lock, OldIrql);
/*
* Test the packet to see if it is a MAC loopback.
*
- * We may have to loop this packet if miniport cannot.
+ * We may have to loop this packet if miniport cannot.
* If dest MAC address of packet == MAC address of adapter,
* this is a loopback frame.
*/
{
NDIS_DbgPrint(MIN_TRACE, ("Looping packet.\n"));
- if (QueueWorkItem)
+ if (QueueWorkItem)
{
MiniQueueWorkItem(Adapter, NdisWorkItemSendLoopback, (PVOID)Packet);
return NDIS_STATUS_PENDING;
KeRaiseIrql(DISPATCH_LEVEL, &RaiseOldIrql);
{
/*
- * atm this *only* handles loopback packets - it calls MiniIndicateData to
+ * atm this *only* handles loopback packets - it calls MiniIndicateData to
* send back to the protocol. FIXME: this will need to be adjusted a bit.
* Also, I'm not sure you really have to be at dispatch level for this. It
* might use a ReceivePackets handler, which can run <= DISPATCH_LEVEL.
NDIS_DbgPrint(MID_TRACE,("Not a loopback packet\n"));
/* This is a normal send packet, not a loopback packet. */
- if (QueueWorkItem)
+ if (QueueWorkItem)
{
MiniQueueWorkItem(Adapter, NdisWorkItemSend, (PVOID)Packet);
NDIS_DbgPrint(MAX_TRACE, ("Queued a work item and returning\n"));
ASSERT(Adapter->Miniport);
- /*
- * Call the appropriate send handler
+ /*
+ * Call the appropriate send handler
*
* If a miniport provides a SendPackets handler, we always call it. If not, we call the
* Send handler.
KeLowerIrql(RaiseOldIrql);
}
}
-
+
/* XXX why the hell do we do this? */
NDIS_DbgPrint(MAX_TRACE, ("acquiring miniport block lock\n"));
KeAcquireSpinLock(&Adapter->NdisMiniportBlock.Lock, &SpinOldIrql);
}
Adapter = MiniLocateDevice(AdapterName);
- if (!Adapter)
+ if (!Adapter)
{
NDIS_DbgPrint(MIN_TRACE, ("Adapter not found.\n"));
*Status = NDIS_STATUS_ADAPTER_NOT_FOUND;
/* Find the media type in the list provided by the protocol driver */
Found = FALSE;
- for (i = 0; i < MediumArraySize; i++)
+ for (i = 0; i < MediumArraySize; i++)
{
- if (Adapter->NdisMiniportBlock.MediaType == MediumArray[i])
+ if (Adapter->NdisMiniportBlock.MediaType == MediumArray[i])
{
*SelectedMediumIndex = i;
Found = TRUE;
}
}
- if (!Found)
+ if (!Found)
{
NDIS_DbgPrint(MIN_TRACE, ("Medium is not supported.\n"));
*Status = NDIS_STATUS_UNSUPPORTED_MEDIA;
/* Now that we have confirmed that the adapter can be opened, create a binding */
AdapterBinding = ExAllocatePool(NonPagedPool, sizeof(ADAPTER_BINDING));
- if (!AdapterBinding)
+ if (!AdapterBinding)
{
NDIS_DbgPrint(MIN_TRACE, ("Insufficient resources.\n"));
*Status = NDIS_STATUS_RESOURCES;
/* Set fields required by some NDIS macros */
AdapterBinding->NdisOpenBlock.NdisCommonOpenBlock.BindingHandle = (NDIS_HANDLE)AdapterBinding;
-
+
/* Set handlers (some NDIS macros require these) */
AdapterBinding->NdisOpenBlock.NdisCommonOpenBlock.RequestHandler = ProRequest;
* ProtocolCharacteristics = Pointer to NDIS_PROTOCOL_CHARACTERISTICS structure
* CharacteristicsLength = Size of structure which ProtocolCharacteristics targets
* NOTES:
- * - you *must* set NdisProtocolHandle before doing anything that could wind up
+ * - you *must* set NdisProtocolHandle before doing anything that could wind up
* getting BindAdapterHandler, as it will probably call OpenAdapter with this handle
* - the above implies that the initialization of the protocol block must be complete
* by then
NDIS_DbgPrint(MAX_TRACE, ("Called.\n"));
/* first validate the PROTOCOL_CHARACTERISTICS */
- switch (ProtocolCharacteristics->MajorNdisVersion)
+ switch (ProtocolCharacteristics->MajorNdisVersion)
{
- case 0x03:
+ case 0x03:
/* we don't really want to support ndis3 drivers - so we complain for now */
NDIS_DbgPrint(MID_TRACE, ("NDIS 3 protocol attempting to register\n"));
MinSize = sizeof(NDIS30_PROTOCOL_CHARACTERISTICS);
return;
}
- if (CharacteristicsLength < MinSize)
+ if (CharacteristicsLength < MinSize)
{
NDIS_DbgPrint(DEBUG_PROTOCOL, ("Bad protocol characteristics.\n"));
*Status = NDIS_STATUS_BAD_CHARACTERISTICS;
/* set up the protocol block */
Protocol = ExAllocatePool(NonPagedPool, sizeof(PROTOCOL_BINDING));
- if (!Protocol)
+ if (!Protocol)
{
NDIS_DbgPrint(MIN_TRACE, ("Insufficient resources.\n"));
*Status = NDIS_STATUS_RESOURCES;
RtlCopyMemory(&Protocol->Chars, ProtocolCharacteristics, MinSize);
NtStatus = RtlUpcaseUnicodeString(&Protocol->Chars.Name, &ProtocolCharacteristics->Name, TRUE);
- if (!NT_SUCCESS(NtStatus))
+ if (!NT_SUCCESS(NtStatus))
{
NDIS_DbgPrint(MIN_TRACE, ("Insufficient resources.\n"));
ExFreePool(Protocol);
InitializeListHead(&Protocol->AdapterListHead);
- /*
- * bind the protocol to all of its miniports
+ /*
+ * bind the protocol to all of its miniports
*
* open registry path
* get list of devices from Bind key
* \Registry\Machine\System\CurrentControlSet\Services\Nic1\Parameters\Tcpip
*
* This is constructed as follows:
- * SERVICES_KEY + extracted device name + Protocol name from characteristics
+ * SERVICES_KEY + extracted device name + Protocol name from characteristics
*/
PathLength = sizeof(SERVICES_KEY) + /* \Registry\Machine\System\CurrentControlSet\Services\ */
NDIS_DbgPrint(MAX_TRACE, ("Calling protocol's BindAdapter handler with DeviceName %wZ and RegistryPath %wZ\n",
&DeviceName, &RegistryPath));
-
+
/* XXX SD must do something with bind context */
*NdisProtocolHandle = Protocol;
NTSTATUS
EXPORT
NdisUpcaseUnicodeString(
- OUT PUNICODE_STRING DestinationString,
+ OUT PUNICODE_STRING DestinationString,
IN PUNICODE_STRING SourceString)
/*
* FUNCTION: Uppercase a UNICODE string
/*
* @implemented
*/
-PSINGLE_LIST_ENTRY
+PSINGLE_LIST_ENTRY
EXPORT
NdisInterlockedPopEntrySList(
IN PSLIST_HEADER ListHead,
/*
* @implemented
*/
-PSINGLE_LIST_ENTRY
+PSINGLE_LIST_ENTRY
EXPORT
NdisInterlockedPushEntrySList(
IN PSLIST_HEADER ListHead,
/*
* @unimplemented
*/
-NDIS_STATUS
+NDIS_STATUS
EXPORT
NdisIMCancelInitializeDeviceInstance(
IN NDIS_HANDLE DriverHandle,
/* the key is represented by the initial and final value */
/* of the bucket. At the moment bucket_lookup is able to */
/* manage values of 16, 32 bits. */
-uint32 bucket_lookup(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
+uint32 bucket_lookup(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
{
uint32 value;
uint32 i,j;
if ((data->key_len!=1)&& /*16 bit value*/
(data->key_len!=2)) /*32 bit value*/
return TME_ERROR;
-
+
/*32 bit values*/
blocks=data->filled_blocks-1;
block_size=data->block_size;
if (data->key_len==2)
{
value=SW_ULONG_AT(key,0);
-
+
if((value<SW_ULONG_AT(temp,0))||(value>SW_ULONG_AT(temp+block_size*(blocks-1),4)))
{
uint32 *key32=(uint32*) key;
data->last_found=NULL;
return TME_FALSE;
}
-
+
while(found==-1) /* search routine */
- {
+ {
i=(i==1)? 1:i>>1;
if (SW_ULONG_AT(temp+block_size*j,0)>value)
if (SW_ULONG_AT(temp+block_size*(j-1),4)<value)
else
j-=i;
else
- if (SW_ULONG_AT(temp+block_size*j,4)<value)
+ if (SW_ULONG_AT(temp+block_size*j,4)<value)
if (SW_ULONG_AT(temp+block_size*j,0)>value)
found=-2;
else
j+=i;
else found=j;
- }
+ }
if (found<0)
{
uint32 *key32=(uint32*) key;
key32[0]=key32[1]=0;
GET_TIME((struct timeval *)(data->shared_memory_base_address+8),time_ref);
-
+
data->last_found=NULL;
return TME_FALSE;
}
-
+
data->last_found=data->lut_base_address+found*sizeof(RECORD);
COPY_MEMORY(key,temp+block_size*found,8);
else
{
value=SW_USHORT_AT(key,0);
-
+
if((value<SW_USHORT_AT(temp,0))||(value>SW_USHORT_AT(temp+block_size*(blocks-1),2)))
{
uint16 *key16=(uint16*) key;
key16[0]=key16[1]=0;
-
+
GET_TIME((struct timeval *)(data->shared_memory_base_address+4),time_ref);
data->last_found=NULL;
return TME_FALSE;
}
-
+
while(found==-1) /* search routine */
- {
+ {
i=(i==1)? 1:i>>1;
if (SW_USHORT_AT(temp+block_size*j,0)>value)
if (SW_USHORT_AT(temp+block_size*(j-1),2)<value)
else
j-=i;
else
- if (SW_USHORT_AT(temp+block_size*j,2)<value)
+ if (SW_USHORT_AT(temp+block_size*j,2)<value)
if (SW_USHORT_AT(temp+block_size*j,0)>value)
found=-2;
else
j+=i;
else found=j;
- }
+ }
if (found<0)
{
data->last_found=NULL;
return TME_FALSE;
}
-
+
data->last_found=data->lut_base_address+found*sizeof(RECORD);
GET_TIME((struct timeval *)(temp+block_size*found+4),time_ref);
COPY_MEMORY(key,temp+block_size*found,4);
-
+
return TME_TRUE;
}
-
+
}
-uint32 bucket_lookup_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
-{
+uint32 bucket_lookup_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
+{
RECORD *records=(RECORD*)data->lut_base_address;
if ((data->key_len!=1)&& /*16 bit value*/
uint32 start,stop;
uint8 *tmp;
- start=SW_ULONG_AT(key,0);
+ start=SW_ULONG_AT(key,0);
stop=SW_ULONG_AT(key,4);
if (start>stop)
return TME_ERROR;
if (data->filled_entries>0)
{
- tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries-1].block,0);
+ tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries-1].block,0);
/*check if it is coherent with the previous block*/
if (SW_ULONG_AT(tmp,4)>=start)
return TME_ERROR;
}
-
+
if (data->filled_blocks==data->shared_memory_blocks)
return TME_ERROR;
if (data->filled_entries==data->lut_entries)
return TME_ERROR;
- tmp=data->shared_memory_base_address+data->block_size*data->filled_blocks;
-
+ tmp=data->shared_memory_base_address+data->block_size*data->filled_blocks;
+
COPY_MEMORY(tmp,key,8);
-
+
SW_ULONG_ASSIGN(&records[data->filled_entries].block,tmp-mem_ex->buffer);
SW_ULONG_ASSIGN(&records[data->filled_entries].exec_fcn,data->default_exec);
-
- GET_TIME((struct timeval *)(tmp+8),time_ref);
-
+
+ GET_TIME((struct timeval *)(tmp+8),time_ref);
+
data->filled_blocks++;
data->filled_entries++;
-
+
return TME_TRUE;
}
else
uint16 start,stop;
uint8 *tmp;
- start=SW_USHORT_AT(key,0);
+ start=SW_USHORT_AT(key,0);
stop=SW_USHORT_AT(key,2);
if (start>stop)
return TME_ERROR;
if (data->filled_entries>0)
{
- tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries-1].block,0);
+ tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries-1].block,0);
/*check if it is coherent with the previous block*/
if (SW_USHORT_AT(tmp,2)>=start)
return TME_ERROR;
}
-
+
if (data->filled_blocks==data->shared_memory_blocks)
return TME_ERROR;
if (data->filled_entries==data->lut_entries)
return TME_ERROR;
- tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries].block,0);
-
+ tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries].block,0);
+
COPY_MEMORY(tmp,key,4);
-
+
SW_ULONG_ASSIGN(&records[data->filled_entries].block,tmp-mem_ex->buffer);
SW_ULONG_ASSIGN(&records[data->filled_entries].exec_fcn,data->default_exec);
-
- GET_TIME((struct timeval *)(tmp+4),time_ref);
-
+
+ GET_TIME((struct timeval *)(tmp+4),time_ref);
+
data->filled_blocks++;
data->filled_entries++;
-
+
return TME_TRUE;
}
}
uint32 count_packets(uint8 *block, uint32 pkt_size, TME_DATA *data, MEM_TYPE *mem_ex, uint8 *mem_data)
{
-
+
c_p_data *counters=(c_p_data*)(block+data->key_len*4);
counters->bytes+=pkt_size;
counters->packets++;
-
+
return TME_SUCCESS;
}
PathPrefix = L"\\??\\";
PathLen = 8;
}
-
+
// Insert the correct path prefix.
FullFileNameLength = PathLen + fileName->MaximumLength;
-
+
#define NPF_TAG_FILENAME TAG('0', 'D', 'W', 'A')
- FullFileName.Buffer = ExAllocatePoolWithTag(NonPagedPool,
+ FullFileName.Buffer = ExAllocatePoolWithTag(NonPagedPool,
FullFileNameLength,
NPF_TAG_FILENAME);
-
+
if (FullFileName.Buffer == NULL) {
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
return ntStatus;
}
-
+
FullFileName.Length = PathLen;
FullFileName.MaximumLength = (USHORT)FullFileNameLength;
-
+
if(PathLen)
RtlMoveMemory (FullFileName.Buffer, PathPrefix, PathLen);
-
+
RtlAppendUnicodeStringToString (&FullFileName, fileName);
-
+
IF_LOUD(DbgPrint( "Packet: Attempting to open %wZ\n", &FullFileName);)
-
+
InitializeObjectAttributes ( &ObjectAttributes,
&FullFileName,
OBJ_CASE_INSENSITIVE,
NULL,
NULL );
-
+
// Create the dump file
ntStatus = ZwCreateFile( &Open->DumpFileHandle,
SYNCHRONIZE | FILE_WRITE_DATA,
if ( !NT_SUCCESS( ntStatus ) )
{
IF_LOUD(DbgPrint("NPF: Error opening file %x\n", ntStatus);)
-
+
ExFreePool(FullFileName.Buffer);
Open->DumpFileHandle=NULL;
ntStatus = STATUS_NO_SUCH_FILE;
return ntStatus;
}
-
+
ExFreePool(FullFileName.Buffer);
-
+
ntStatus = ObReferenceObjectByHandle(Open->DumpFileHandle,
FILE_WRITE_ACCESS,
#ifndef __GNUC__
KernelMode,
(PVOID)&Open->DumpFileObject,
0);
-
+
if ( !NT_SUCCESS( ntStatus ) )
{
IF_LOUD(DbgPrint("NPF: Error creating file, status=%x\n", ntStatus);)
-
+
ZwClose( Open->DumpFileHandle );
Open->DumpFileHandle=NULL;
-
+
ntStatus = STATUS_NO_SUCH_FILE;
return ntStatus;
}
-
+
fsdDevice = IoGetRelatedDeviceObject(Open->DumpFileObject);
IF_LOUD(DbgPrint("NPF: Dump: write file created succesfully, status=%d \n",ntStatus);)
return ntStatus;
-}
+}
//-------------------------------------------------------------------
// Detect the medium type
switch (Open->Medium){
-
+
case NdisMediumWan:
hdr.linktype = DLT_EN10MB;
break;
-
+
case NdisMedium802_3:
hdr.linktype = DLT_EN10MB;
break;
-
+
case NdisMediumFddi:
hdr.linktype = DLT_FDDI;
break;
-
- case NdisMedium802_5:
- hdr.linktype = DLT_IEEE802;
+
+ case NdisMedium802_5:
+ hdr.linktype = DLT_IEEE802;
break;
-
+
case NdisMediumArcnet878_2:
hdr.linktype = DLT_ARCNET;
break;
-
+
case NdisMediumAtm:
hdr.linktype = DLT_ATM_RFC1483;
break;
-
+
default:
hdr.linktype = DLT_EN10MB;
}
NULL,
NULL );
-
+
if ( !NT_SUCCESS( ntStatus ) )
{
IF_LOUD(DbgPrint("NPF: Error dumping file %x\n", ntStatus);)
-
+
ZwClose( Open->DumpFileHandle );
Open->DumpFileHandle=NULL;
-
+
ntStatus = STATUS_NO_SUCH_FILE;
return ntStatus;
}
Open->DumpOffset.QuadPart=24;
-
+
ntStatus = PsCreateSystemThread(&Open->DumpThreadHandle,
THREAD_ALL_ACCESS,
(ACCESS_MASK)0L,
0,
(PKSTART_ROUTINE)NPF_DumpThread,
Open);
-
+
if ( !NT_SUCCESS( ntStatus ) )
{
IF_LOUD(DbgPrint("NPF: Error creating dump thread, status=%x\n", ntStatus);)
-
+
ZwClose( Open->DumpFileHandle );
Open->DumpFileHandle=NULL;
return ntStatus;
- }
+ }
ntStatus = ObReferenceObjectByHandle(Open->DumpThreadHandle,
THREAD_ALL_ACCESS,
NULL,
if ( !NT_SUCCESS( ntStatus ) )
{
IF_LOUD(DbgPrint("NPF: Error creating dump thread, status=%x\n", ntStatus);)
-
+
ObDereferenceObject(Open->DumpFileObject);
ZwClose( Open->DumpFileHandle );
Open->DumpFileHandle=NULL;
return ntStatus;
- }
-
+ }
+
return ntStatus;
-
+
}
//-------------------------------------------------------------------
while(TRUE){
// Wait until some packets arrive or the timeout expires
- NdisWaitEvent(&Open->DumpEvent, 5000);
+ NdisWaitEvent(&Open->DumpEvent, 5000);
IF_LOUD(DbgPrint("NPF: Worker Thread - event signalled\n");)
-
+
if(Open->DumpLimitReached ||
Open->BufSize==0){ // BufSize=0 means that this instance was closed, or that the buffer is too
// small for any capture. In both cases it is better to end the dump
PsTerminateSystemThread(STATUS_SUCCESS);
return;
}
-
+
NdisResetEvent(&Open->DumpEvent);
// Write the content of the buffer to the file
PsTerminateSystemThread(STATUS_SUCCESS);
return;
}
-
+
}
-
+
}
//-------------------------------------------------------------------
PMDL lMdl;
UINT SizeToDump;
-
+
Thead=Open->Bhead;
Ttail=Open->Btail;
TLastByte=Open->BLastByte;
-
+
IF_LOUD(DbgPrint("NPF: NPF_SaveCurrentBuffer.\n");)
// Get the address of the buffer
{
// Size limit reached
UINT PktLen;
-
+
SizeToDump = 0;
-
+
// Scan the buffer to detect the exact amount of data to save
while(TRUE){
PktLen = ((struct sf_pkthdr*)(CurrBuff + Thead + SizeToDump))->caplen + sizeof(struct sf_pkthdr);
-
+
if((UINT)Open->DumpOffset.QuadPart + SizeToDump + PktLen > Open->MaxDumpBytes)
break;
-
+
SizeToDump += PktLen;
}
-
+
}
else
SizeToDump = TLastByte-Thead;
-
+
lMdl=IoAllocateMdl(CurrBuff+Thead, SizeToDump, FALSE, FALSE, NULL);
if (lMdl == NULL)
{
IF_LOUD(DbgPrint("NPF: dump thread: Failed to allocate Mdl\n");)
return STATUS_UNSUCCESSFUL;
}
-
+
MmBuildMdlForNonPagedPool(lMdl);
-
+
// Write to disk
NPF_WriteDumpFile(Open->DumpFileObject,
&Open->DumpOffset,
SizeToDump,
lMdl,
&IoStatus);
-
+
IoFreeMdl(lMdl);
-
+
if(!NT_SUCCESS(IoStatus.Status)){
// Error
return STATUS_UNSUCCESSFUL;
}
-
+
if(SizeToDump != TLastByte-Thead){
// Size limit reached.
Open->DumpLimitReached = TRUE;
-
+
// Awake the application
KeSetEvent(Open->ReadEvent,0,FALSE);
return STATUS_UNSUCCESSFUL;
}
-
+
// Update the packet buffer
Open->DumpOffset.QuadPart+=(TLastByte-Thead);
Open->BLastByte=Ttail;
}
if( Ttail > Thead ){
-
+
if(Open->MaxDumpBytes &&
(UINT)Open->DumpOffset.QuadPart + GetBuffOccupation(Open) > Open->MaxDumpBytes)
{
// Size limit reached
UINT PktLen;
-
+
SizeToDump = 0;
-
+
// Scan the buffer to detect the exact amount of data to save
while(Thead + SizeToDump < Ttail){
PktLen = ((struct sf_pkthdr*)(CurrBuff + Thead + SizeToDump))->caplen + sizeof(struct sf_pkthdr);
-
+
if((UINT)Open->DumpOffset.QuadPart + SizeToDump + PktLen > Open->MaxDumpBytes)
break;
-
+
SizeToDump += PktLen;
}
-
+
}
else
SizeToDump = Ttail-Thead;
-
+
lMdl=IoAllocateMdl(CurrBuff+Thead, SizeToDump, FALSE, FALSE, NULL);
if (lMdl == NULL)
{
IF_LOUD(DbgPrint("NPF: dump thread: Failed to allocate Mdl\n");)
return STATUS_UNSUCCESSFUL;
}
-
+
MmBuildMdlForNonPagedPool(lMdl);
-
+
// Write to disk
NPF_WriteDumpFile(Open->DumpFileObject,
&Open->DumpOffset,
SizeToDump,
lMdl,
&IoStatus);
-
+
IoFreeMdl(lMdl);
-
+
if(!NT_SUCCESS(IoStatus.Status)){
// Error
return STATUS_UNSUCCESSFUL;
}
-
+
if(SizeToDump != Ttail-Thead){
// Size limit reached.
Open->DumpLimitReached = TRUE;
// Awake the application
KeSetEvent(Open->ReadEvent,0,FALSE);
-
+
return STATUS_UNSUCCESSFUL;
}
-
+
// Update the packet buffer
- Open->DumpOffset.QuadPart+=(Ttail-Thead);
+ Open->DumpOffset.QuadPart+=(Ttail-Thead);
Open->Bhead=Ttail;
-
+
}
return STATUS_SUCCESS;
NPF_OpenDumpFile(Open,&Open->DumpFileName, TRUE);
- // Flush the buffer to file
+ // Flush the buffer to file
NPF_SaveCurrentBuffer(Open);
// Close The file
ObDereferenceObject(Open->DumpFileObject);
ZwClose( Open->DumpFileHandle );
-
+
Open->DumpFileHandle = NULL;
ObDereferenceObject(Open->DumpFileObject);
//-------------------------------------------------------------------
#ifndef __GNUC__
-static NTSTATUS
+static NTSTATUS
#else
NTSTATUS STDCALL
#endif
// Copy the status information back into the "user" IOSB
*Irp->UserIosb = Irp->IoStatus;
-
+
// Wake up the mainline code
KeSetEvent(Irp->UserEvent, 0, FALSE);
-
+
return STATUS_MORE_PROCESSING_REQUIRED;
}
KEVENT event;
PIO_STACK_LOCATION ioStackLocation;
PDEVICE_OBJECT fsdDevice = IoGetRelatedDeviceObject(FileObject);
-
+
// Set up the event we'll use
KeInitializeEvent(&event, SynchronizationEvent, FALSE);
-
+
// Allocate and build the IRP we'll be sending to the FSD
irp = IoAllocateIrp(fsdDevice->StackSize, FALSE);
case BUCKET_LOOKUP_INSERT:
return (lut_fcn) bucket_lookup_insert;
-
+
default:
return NULL;
}
-
+
return NULL;
}
{
case COUNT_PACKETS:
return (exec_fcn) count_packets;
-
+
case TCP_SESSION:
return (exec_fcn) tcp_session;
default:
return NULL;
}
-
+
return NULL;
}
//
void emit_code(binary_stream *stream, ULONG value, UINT len)
{
-
+
switch (len){
case 1:
break;
default:;
-
+
}
return;
#else
stream.refs=(UINT *)malloc((nins + 1)*sizeof(UINT));
#endif
- if(stream.refs==NULL)
+ if(stream.refs==NULL)
{
return NULL;
}
stream.cur_ip=0;
stream.bpf_pc=0;
- // the first pass will emit the lengths of the instructions
+ // the first pass will emit the lengths of the instructions
// to create the reference table
emitm=emit_lenght;
-
+
for(pass=0;;){
ins = prog;
MOVodd(EBX, EBP, 8)
for(i=0;i<nins;i++){
-
+
stream.bpf_pc++;
-
+
switch (ins->code) {
-
+
default:
-
+
return NULL;
-
+
case BPF_RET|BPF_K:
-
+
MOVid(EAX,ins->k)
POP(EDI)
POP(ESI)
POP(EBX)
POP(EBP)
RET()
-
+
break;
-
+
case BPF_RET|BPF_A:
-
+
POP(EDI)
POP(ESI)
POP(EDX)
POP(EBX)
POP(EBP)
RET()
-
+
break;
-
+
case BPF_LD|BPF_W|BPF_ABS:
-
+
MOVid(ECX,ins->k)
MOVrd(ESI,ECX)
ADDib(ECX,sizeof(INT))
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
- MOVid(EAX,0)
+ MOVid(EAX,0)
MOVobw(AX, EBX, ESI)
SWAP_AX()
break;
-
+
case BPF_LD|BPF_B|BPF_ABS:
-
+
MOVid(ECX,ins->k)
CMPodd(ECX, EBP, 0x10)
JLEb(12)
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
- MOVid(EAX,0)
+ MOVid(EAX,0)
MOVobb(AL,EBX,ECX)
break;
MOVodd(EDX, EBP, 0xc)
break;
-
+
case BPF_LD|BPF_W|BPF_IND:
-
+
MOVid(ECX,ins->k)
ADDrd(ECX,EDX)
MOVrd(ESI,ECX)
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
MOVobd(EAX, EBX, ESI)
BSWAP(EAX)
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
- MOVid(EAX,0)
+ MOVid(EAX,0)
MOVobw(AX, EBX, ESI)
SWAP_AX()
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
- MOVid(EAX,0)
+ MOVid(EAX,0)
MOVobb(AL,EBX,ECX)
break;
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
MOVid(EDX,0)
MOVobb(DL,EBX,ECX)
ANDib(DL, 0xf)
SHLib(EDX, 2)
-
+
break;
case BPF_LD|BPF_IMM:
break;
case BPF_LDX|BPF_IMM:
-
+
MOVid(EDX,ins->k)
break;
CMPid(EAX, ins->k)
JG(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5) // 5 is the size of the following JMP
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
case BPF_JMP|BPF_JGE|BPF_K:
CMPid(EAX, ins->k)
JGE(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
case BPF_JMP|BPF_JEQ|BPF_K:
CMPid(EAX, ins->k)
- JE(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JE(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
MOVrd(ECX,EAX)
ANDid(ECX,ins->k)
JE(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc])
break;
CMPrd(EAX, EDX)
JA(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
case BPF_JMP|BPF_JGE|BPF_X:
CMPrd(EAX, EDX)
JAE(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
CMPrd(EAX, EDX)
JE(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
MOVrd(ECX,EAX)
ANDrd(ECX,EDX)
JE(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc])
-
+ JMP(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc])
+
break;
case BPF_ALU|BPF_ADD|BPF_X:
ADDrd(EAX,EDX)
-
+
break;
case BPF_ALU|BPF_SUB|BPF_X:
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
MOVrd(ECX,EDX)
- MOVid(EDX,0)
+ MOVid(EDX,0)
DIVrd(ECX)
MOVrd(EDX,ECX)
case BPF_ALU|BPF_AND|BPF_X:
ANDrd(EAX,EDX)
-
+
break;
case BPF_ALU|BPF_OR|BPF_X:
case BPF_ALU|BPF_SUB|BPF_K:
SUB_EAXi(ins->k)
-
+
break;
case BPF_ALU|BPF_MUL|BPF_K:
MOVrd(ECX,EDX)
- MOVid(EDX,ins->k)
+ MOVid(EDX,ins->k)
MULrd(EDX)
MOVrd(EDX,ECX)
case BPF_ALU|BPF_DIV|BPF_K:
MOVrd(ECX,EDX)
- MOVid(EDX,0)
+ MOVid(EDX,0)
MOVid(ESI,ins->k)
DIVrd(ESI)
MOVrd(EDX,ECX)
case BPF_ALU|BPF_OR|BPF_K:
ORid(EAX, ins->k)
-
+
break;
case BPF_ALU|BPF_LSH|BPF_K:
}
-
- ins++;
+
+ ins++;
}
pass++;
if(pass == 2) break;
-
+
#ifdef NTKERNEL
#define NPF_TAG_STREAMBUF TAG('1', 'J', 'W', 'A')
stream.ibuf=(CHAR*)ExAllocatePoolWithTag(NonPagedPool, stream.cur_ip, NPF_TAG_STREAMBUF);
#else
stream.ibuf=(CHAR*)malloc(stream.cur_ip);
#endif
- if(stream.ibuf==NULL)
+ if(stream.ibuf==NULL)
{
#ifdef NTKERNEL
ExFreePool(stream.refs);
#endif
return NULL;
}
-
+
// modify the reference table to contain the offsets and not the lengths of the instructions
for(i=1; i< nins + 1; i++)
stream.refs[i]+=stream.refs[i-1];
//////////////////////////////////////////////////////////////
void BPF_Destroy_JIT_Filter(JIT_BPF_Filter *Filter){
-
+
#ifdef NTKERNEL
ExFreePool(Filter->mem);
ExFreePool(Filter->Function);
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
-/** @ingroup NPF
+/** @ingroup NPF
* @{
*/
-/** @defgroup NPF_include NPF structures and definitions
+/** @defgroup NPF_include NPF structures and definitions
* @{
*/
}binary_stream;
-/*! \brief Prototype of a filtering function created by the jitter.
+/*! \brief Prototype of a filtering function created by the jitter.
The syntax and the meaning of the parameters is analogous to the one of bpf_filter(). Notice that the filter
is not among the parameters, because it is hardwired in the function.
emitm(&stream, 0x0f, 1);\
emitm(&stream, 0x87, 1);\
emitm(&stream, off32, 4);
-
+
/// jae off32
#define JAE(off32) \
emitm(&stream, 0x0f, 1);\
/* Prototypes */
/**************************/
-/** @ingroup NPF
+/** @ingroup NPF
* @{
*/
-/** @defgroup NPF_code NPF functions
+/** @defgroup NPF_code NPF functions
* @{
*/
BPF_jitter allocates the buffers for the new native filter and then translates the program pointed by fp
calling BPFtoX86().
-*/
+*/
JIT_BPF_Filter* BPF_jitter(struct bpf_insn *fp, INT nins);
/*!
\param mem Memory used by the x86 function to emulate the RAM of the BPF pseudo processor.
\return The x86 filtering function.
- This function does the hard work for the JIT compilation. It takes a group of BPF pseudo instructions and
+ This function does the hard work for the JIT compilation. It takes a group of BPF pseudo instructions and
through the instruction macros defined in jitter.h it is able to create an function directly executable
by NPF.
-*/
+*/
BPF_filter_function BPFtoX86(struct bpf_insn *ins, UINT nins, INT *mem);
/*!
\brief Deletes a filtering function that was previously created by BPF_jitter().
\param Filter The filter to destroy.
This function frees the variuos buffers (code, memory, etc.) associated with a filtering function.
-*/
+*/
void BPF_Destroy_JIT_Filter(JIT_BPF_Filter *Filter);
/**
(dest)=ExAllocatePool(NonPagedPool,sizeof(type)*(amount)); \
if ((dest)!=NULL) \
RtlZeroMemory((dest),sizeof(type)*(amount)); \
- }
+ }
#define FREE_MEMORY(dest) ExFreePool(dest);
#define ZERO_MEMORY(dest,amount) RtlZeroMemory(dest,amount);
#endif /*WIN_NT_DRIVER*/
-#endif
+#endif
/* if not found, inserts an element */
/* returns TME_TRUE if the entry is found or created, */
/* returns TME_FALSE if no more blocks are available */
-uint32 normal_lut_w_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
+uint32 normal_lut_w_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
{
uint32 i;
uint32 tocs=0;
RECORD *records=(RECORD*)data->lut_base_address;
uint8 *offset;
uint32 key_len=data->key_len;
- /*the key is shrinked into a 32-bit value */
- for (i=0; i<key_len;i++)
+ /*the key is shrinked into a 32-bit value */
+ for (i=0; i<key_len;i++)
shrinked_key^=key32[i];
/*the first index in the table is calculated*/
index=shrinked_key % data->lut_entries;
while (tocs<=data->filled_entries)
- {
+ {
if (records[index].block==0)
{ /*creation of a new entry*/
{
/*no more free blocks*/
GET_TIME((struct timeval *)(data->shared_memory_base_address+4*key_len),time_ref);
- data->last_found=NULL;
+ data->last_found=NULL;
return TME_FALSE;
}
/*with the newly created entry*/
offset=data->shared_memory_base_address+
data->block_size*data->filled_blocks;
-
+
/*copy the key in the block*/
COPY_MEMORY(offset,key32,key_len*4);
GET_TIME((struct timeval *)(offset+4*key_len),time_ref);
SW_ULONG_ASSIGN(&records[index].block,offset-mem_ex->buffer);
data->filled_blocks++;
-
+
/*assign the exec function ID to the entry, in NBO*/
SW_ULONG_ASSIGN(&records[index].exec_fcn,data->default_exec);
data->filled_entries++;
data->last_found=(uint8*)&records[index];
-
- return TME_TRUE;
+
+ return TME_TRUE;
}
/*offset contains the absolute pointer to the block*/
/*associated with the current entry */
- offset=mem_ex->buffer+SW_ULONG_AT(&records[index].block,0);
+ offset=mem_ex->buffer+SW_ULONG_AT(&records[index].block,0);
for (i=0; (i<key_len) && (key32[i]==ULONG_AT(offset,i*4)); i++);
-
+
if (i==key_len)
{
/*key in the block matches the one provided, right entry*/
data->last_found=(uint8*)&records[index];
return TME_TRUE;
}
- else
+ else
{
/* wrong entry, rehashing */
if (IS_DELETABLE(offset+key_len*4,data))
SW_ULONG_ASSIGN(&records[index].exec_fcn,data->default_exec);
GET_TIME((struct timeval*)(offset+key_len*4),time_ref);
data->last_found=(uint8*)&records[index];
- return TME_TRUE;
+ return TME_TRUE;
}
else
{
/* if not found, returns out of count entry index */
/* returns TME_TRUE if the entry is found */
/* returns TME_FALSE if the entry is not found */
-uint32 normal_lut_wo_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
+uint32 normal_lut_wo_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
{
uint32 i;
uint32 tocs=0;
RECORD *records=(RECORD*)data->lut_base_address;
uint8 *offset;
uint32 key_len=data->key_len;
- /*the key is shrinked into a 32-bit value */
- for (i=0; i<key_len;i++)
+ /*the key is shrinked into a 32-bit value */
+ for (i=0; i<key_len;i++)
shrinked_key^=key32[i];
/*the first index in the table is calculated*/
index=shrinked_key % data->lut_entries;
while (tocs<=data->filled_entries)
- {
+ {
if (records[index].block==0)
{ /*out of table, insertion is not allowed*/
GET_TIME((struct timeval *)(data->shared_memory_base_address+4*key_len),time_ref);
- data->last_found=NULL;
+ data->last_found=NULL;
return TME_FALSE;
}
/*offset contains the absolute pointer to the block*/
/*associated with the current entry */
-
- offset=mem_ex->buffer+SW_ULONG_AT(&records[index].block,0);
+
+ offset=mem_ex->buffer+SW_ULONG_AT(&records[index].block,0);
for (i=0; (i<key_len) && (key32[i]==ULONG_AT(offset,i*4)); i++);
-
+
if (i==key_len)
{
/*key in the block matches the one provided, right entry*/
data->last_found=(uint8*)&records[index];
return TME_TRUE;
}
- else
+ else
{
/*wrong entry, rehashing*/
index=(index+data->rehashing_value) % data->lut_entries;
#endif
#define NORMAL_LUT_W_INSERT 0x00000000
-uint32 normal_lut_w_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref);
+uint32 normal_lut_w_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref);
#define NORMAL_LUT_WO_INSERT 0x00000001
-uint32 normal_lut_wo_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref);
+uint32 normal_lut_wo_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref);
#define DUMMY_INSERT 1234
#endif
/// Global start time. Used as an absolute reference for timestamp conversion.
struct time_conv G_Start_Time = {
- 0,
- {0, 0},
+ 0,
+ {0, 0},
};
UINT n_Opened_Instances = 0;
// Save or open here
IrpSp->FileObject->FsContext=Open;
-
+
Open->DeviceExtension=DeviceExtension;
-
-
+
+
// Save the Irp here for the completeion routine to retrieve
Open->OpenCloseIrp=Irp;
-
+
// Allocate a packet pool for our xmit and receive packets
NdisAllocatePacketPool(
&Status,
&Open->PacketPool,
TRANSMIT_PACKETS,
sizeof(PACKET_RESERVED));
-
-
+
+
if (Status != NDIS_STATUS_SUCCESS) {
-
+
IF_LOUD(DbgPrint("NPF: Failed to allocate packet pool\n");)
-
+
ExFreePool(Open);
ExFreePool(EvName);
Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
PacketItoa(NamedEventsCounter,(PUCHAR)(Open->ReadEventName.Buffer+21));
InterlockedIncrement((PLONG)&NamedEventsCounter);
-
+
IF_LOUD(DbgPrint("\nCreated the named event for the read; name=%ws, counter=%d\n", Open->ReadEventName.Buffer,NamedEventsCounter-1);)
//allocate the event objects
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
KeInitializeEvent(Open->ReadEvent, NotificationEvent, FALSE);
KeClearEvent(Open->ReadEvent);
NdisInitializeEvent(&Open->WriteEvent);
// list to hold irp's want to reset the adapter
InitializeListHead(&Open->ResetIrpList);
-
-
+
+
// Initialize the request list
KeInitializeSpinLock(&Open->RequestSpinLock);
InitializeListHead(&Open->RequestList);
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
Open->mem_ex.size = DEFAULT_MEM_EX_SIZE;
RtlZeroMemory(Open->mem_ex.buffer, DEFAULT_MEM_EX_SIZE);
-
+
//
// Initialize the open instance
//
//allocate the spinlock for the buffer pointers
NdisAllocateSpinLock(&Open->BufLock);
-
+
//
// link up the request stored in our open block
//
&Open->RequestList,
&Open->Requests[i].ListElement,
&Open->RequestSpinLock);
-
+
}
-
+
IoMarkIrpPending(Irp);
-
+
//
// Try to open the MAC
//
{
NPF_OpenAdapterComplete(Open,Status,NDIS_STATUS_SUCCESS);
}
-
+
return(STATUS_PENDING);
}
NdisAcquireSpinLock(&Opened_Instances_Lock);
n_Opened_Instances++;
NdisReleaseSpinLock(&Opened_Instances_Lock);
-
+
IF_LOUD(DbgPrint("Opened Instances:%d", n_Opened_Instances);)
// Get the absolute value of the system boot time.
MaxSizeReq->Irp = Irp;
MaxSizeReq->Internal = TRUE;
-
+
MaxSizeReq->Request.RequestType = NdisRequestQueryInformation;
MaxSizeReq->Request.DATA.QUERY_INFORMATION.Oid = OID_GEN_MAXIMUM_TOTAL_SIZE;
-
+
MaxSizeReq->Request.DATA.QUERY_INFORMATION.InformationBuffer = &Open->MaxFrameSize;
MaxSizeReq->Request.DATA.QUERY_INFORMATION.InformationBufferLength = 4;
//free the buffer
Open->BufSize=0;
if(Open->Buffer != NULL)ExFreePool(Open->Buffer);
-
+
//free mem_ex
Open->mem_ex.size = 0;
if(Open->mem_ex.buffer != NULL)ExFreePool(Open->mem_ex.buffer);
-
+
NdisFreePacketPool(Open->PacketPool);
// Free the string with the name of the dump file
if(Open->DumpFileName.Buffer!=NULL)
ExFreePool(Open->DumpFileName.Buffer);
-
+
ExFreePool(Open->ReadEventName.Buffer);
ExFreePool(Open);
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return(STATUS_SUCCESS);
}
Open->OpenCloseIrp = Irp;
IoMarkIrpPending(Irp);
-
+
// If this instance is in dump mode, complete the dump and close the file
if((Open->mode & MODE_DUMP) && Open->DumpFileHandle != NULL){
NTSTATUS wres;
);
if (Status != NDIS_STATUS_PENDING) {
-
+
NPF_CloseAdapterComplete(
Open,
Status
);
return STATUS_SUCCESS;
-
+
}
-
+
return(STATUS_PENDING);
}
// free the allocated structures only if the instance is still bound to the adapter
if(Open->Bound == TRUE){
-
+
// Free the filter if it's present
if(Open->bpfprogram != NULL)
ExFreePool(Open->bpfprogram);
// Free the jitted filter if it's present
if(Open->Filter != NULL)
BPF_Destroy_JIT_Filter(Open->Filter);
-
+
//free the buffer
Open->BufSize = 0;
if(Open->Buffer!=NULL)ExFreePool(Open->Buffer);
-
+
//free mem_ex
Open->mem_ex.size = 0;
if(Open->mem_ex.buffer != NULL)ExFreePool(Open->mem_ex.buffer);
-
+
NdisFreePacketPool(Open->PacketPool);
-
+
Irp=Open->OpenCloseIrp;
-
+
// Free the string with the name of the dump file
if(Open->DumpFileName.Buffer!=NULL)
ExFreePool(Open->DumpFileName.Buffer);
ExFreePool(Open->ReadEventName.Buffer);
ExFreePool(Open);
-
+
// Complete the request only if the instance is still bound to the adapter
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
WCHAR* bindT;
PKEY_VALUE_PARTIAL_INFORMATION tcpBindingsP;
UNICODE_STRING macName;
-
+
// This driver at the moment works only on single processor machines
if(NdisSystemProcessorCount() != 1){
return STATUS_IMAGE_MP_UP_MISMATCH;
return Status;
}
-
+
NdisAllocateSpinLock(&Opened_Instances_Lock);
// Set up the device driver entry points.
if (Status != STATUS_SUCCESS) {
- IF_LOUD(DbgPrint("Trying dynamic binding\n");)
+ IF_LOUD(DbgPrint("Trying dynamic binding\n");)
*/
bindP = getAdaptersList();
IF_LOUD(DbgPrint("Adapters not found in the registry, try to copy the bindings of TCP-IP.\n");)
tcpBindingsP = getTcpBindings();
-
+
if (tcpBindingsP == NULL){
IF_LOUD(DbgPrint("TCP-IP not found, quitting.\n");)
goto RegistryError;
}
-
+
bindP = (WCHAR*)tcpBindingsP;
bindT = (WCHAR*)(tcpBindingsP->Data);
} else {
NTSTATUS status;
HANDLE keyHandle;
UINT BufPos=0;
-
+
#define NPF_TAG_DEVICENAME TAG('0', 'P', 'W', 'A')
PWCHAR DeviceNames = (PWCHAR) ExAllocatePoolWithTag(PagedPool, 4096, NPF_TAG_DEVICENAME);
-
+
if (DeviceNames == NULL) {
IF_LOUD(DbgPrint("Unable the allocate the buffer for the list of the network adapters\n");)
return NULL;
}
-
+
InitializeObjectAttributes(&objAttrs, &AdapterListKey,
OBJ_CASE_INSENSITIVE, NULL, NULL);
status = ZwOpenKey(&keyHandle, KEY_READ, &objAttrs);
ULONG resultLength;
CHAR AdapInfo[1024];
UINT i=0;
-
+
IF_LOUD(DbgPrint("getAdaptersList: scanning the list of the adapters in the registry, DeviceNames=%x\n",DeviceNames);)
-
+
// Scan the list of the devices
while((status=ZwEnumerateKey(keyHandle,i,KeyBasicInformation,AdapInfo,sizeof(AdapInfo),&resultLength))==STATUS_SUCCESS) {
WCHAR ExportKeyName [512];
HANDLE ExportKeyHandle;
KEY_VALUE_PARTIAL_INFORMATION valueInfo;
ULONG resultLength;
-
+
RtlCopyMemory(ExportKeyName,
ExportKeyPrefix,
ExportKeyPrefixSize);
-
+
RtlCopyMemory((PCHAR)ExportKeyName+ExportKeyPrefixSize,
tInfo->Name,
tInfo->NameLength+2);
-
+
RtlCopyMemory((PCHAR)ExportKeyName+ExportKeyPrefixSize+tInfo->NameLength,
LinkageKeyPrefix,
LinkageKeyPrefixSize);
-
+
IF_LOUD(DbgPrint("Key name=%ws\n", ExportKeyName);)
-
+
RtlInitUnicodeString(&AdapterKeyName, ExportKeyName);
-
+
InitializeObjectAttributes(&objAttrs, &AdapterKeyName,
OBJ_CASE_INSENSITIVE, NULL, NULL);
-
+
status=ZwOpenKey(&ExportKeyHandle,KEY_READ,&objAttrs);
-
+
if (!NT_SUCCESS(status)) {
DbgPrint("OpenKey Failed, %d!\n",status);
i++;
continue;
}
-
+
status = ZwQueryValueKey(ExportKeyHandle, &FinalExportKey,
KeyValuePartialInformation, &valueInfo,
sizeof(valueInfo), &resultLength);
-
+
if (!NT_SUCCESS(status) && (status != STATUS_BUFFER_OVERFLOW)) {
IF_LOUD(DbgPrint("\n\nStatus of %x querying key value for size\n", status);)
} else { // We know how big it needs to be.
valueInfoP->DataLength);
BufPos+=valueInfoP->DataLength-2;
}
-
+
ExFreePool(valueInfoP);
} else {
IF_LOUD(DbgPrint("Error Allocating the buffer for the device name\n");)
}
-
+
}
-
+
// terminate the buffer
DeviceNames[BufPos/2]=0;
DeviceNames[BufPos/2+1]=0;
-
+
ZwClose (ExportKeyHandle);
i++;
-
+
}
-
+
ZwClose (keyHandle);
-
+
}
if(BufPos==0){
ExFreePool(DeviceNames);
#define NPF_TAG_KEYVALUE2 TAG('2', 'P', 'W', 'A')
PKEY_VALUE_PARTIAL_INFORMATION valueInfoP =
(PKEY_VALUE_PARTIAL_INFORMATION)ExAllocatePoolWithTag(PagedPool, valueInfoLength, NPF_TAG_KEYVALUE2);
-
+
if (valueInfoP != NULL) {
status = ZwQueryValueKey(keyHandle, &bindValueName,
KeyValuePartialInformation,
valueInfoP,
valueInfoLength, &resultLength);
-
+
if (!NT_SUCCESS(status)) {
IF_LOUD(DbgPrint("\n\nStatus of %x querying key value\n", status);)
}
deviceName.MaximumLength = (USHORT)(amacNameP->Length + NPF_Prefix.Length + sizeof(UNICODE_NULL));
#define NPF_TAG_DEVICENAMEBUF TAG('3', 'P', 'W', 'A')
deviceName.Buffer = ExAllocatePoolWithTag(PagedPool, deviceName.MaximumLength, NPF_TAG_DEVICENAMEBUF);
-
+
if (deviceName.Buffer == NULL)
return FALSE;
deviceSymLink.Length = 0;
- deviceSymLink.MaximumLength =(USHORT)(amacNameP->Length-devicePrefix.Length
- + symbolicLinkPrefix.Length
- + NPF_Prefix.Length
+ deviceSymLink.MaximumLength =(USHORT)(amacNameP->Length-devicePrefix.Length
+ + symbolicLinkPrefix.Length
+ + NPF_Prefix.Length
+ sizeof(UNICODE_NULL));
#define NPF_TAG_SYMLINKBUF TAG('3', 'P', 'W', 'A')
RtlAppendUnicodeStringToString(&deviceName, &NPF_Prefix);
RtlAppendUnicodeToString(&deviceName, amacNameP->Buffer +
devicePrefix.Length / sizeof(WCHAR));
-
+
RtlAppendUnicodeStringToString(&deviceSymLink, &symbolicLinkPrefix);
RtlAppendUnicodeStringToString(&deviceSymLink, &NPF_Prefix);
RtlAppendUnicodeToString(&deviceSymLink, amacNameP->Buffer +
devicePrefix.Length / sizeof(WCHAR));
IF_LOUD(DbgPrint("Creating device name: %ws\n", deviceName.Buffer);)
-
- status = IoCreateDevice(adriverObjectP,
+
+ status = IoCreateDevice(adriverObjectP,
sizeof(PDEVICE_EXTENSION),
- &deviceName,
+ &deviceName,
FILE_DEVICE_TRANSPORT,
0,
FALSE,
return TRUE;
}
-
- else
+
+ else
{
IF_LOUD(DbgPrint("\n\nIoCreateDevice status = %x\n", status););
ExFreePool(deviceName.Buffer);
ExFreePool(deviceSymLink.Buffer);
-
+
return FALSE;
}
}
PDEVICE_OBJECT DeviceObject;
PDEVICE_OBJECT OldDeviceObject;
PDEVICE_EXTENSION DeviceExtension;
-
+
NDIS_HANDLE NdisProtocolHandle;
NDIS_STATUS Status;
-
+
NDIS_STRING SymLink;
IF_LOUD(DbgPrint("NPF: Unload\n"););
while (DeviceObject != NULL) {
OldDeviceObject=DeviceObject;
-
+
DeviceObject=DeviceObject->NextDevice;
DeviceExtension = OldDeviceObject->DeviceExtension;
if (DeviceExtension->ExportString)
{
RtlInitUnicodeString(&SymLink , DeviceExtension->ExportString);
-
+
IF_LOUD(DbgPrint("Deleting SymLink at %p\n", SymLink.Buffer););
IoDeleteSymbolicLink(&SymLink);
BOOLEAN IsExtendedFilter=FALSE;
IF_LOUD(DbgPrint("NPF: IoControl\n");)
-
+
IrpSp = IoGetCurrentIrpStackLocation(Irp);
FunctionCode=IrpSp->Parameters.DeviceIoControl.IoControlCode;
Open=IrpSp->FileObject->FsContext;
Irp->IoStatus.Status = STATUS_SUCCESS;
IF_LOUD(DbgPrint("NPF: Function code is %08lx buff size=%08lx %08lx\n",FunctionCode,IrpSp->Parameters.DeviceIoControl.InputBufferLength,IrpSp->Parameters.DeviceIoControl.OutputBufferLength);)
-
+
switch (FunctionCode){
-
+
case BIOCGSTATS: //function to get the capture stats
-
- if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength < 4*sizeof(INT)){
+
+ if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength < 4*sizeof(INT)){
EXIT_FAILURE(0);
}
*(((PUINT)Irp->UserBuffer)) = Open->Received;
*(((PUINT)Irp->UserBuffer)+1) = Open->Dropped;
*(((PUINT)Irp->UserBuffer)+2) = 0; // Not yet supported
-
+
EXIT_SUCCESS(4*sizeof(INT));
-
+
break;
-
+
case BIOCGEVNAME: //function to get the name of the event associated with the current instance
- if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength<26){
+ if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength<26){
EXIT_FAILURE(0);
}
{
EXIT_SUCCESS(WriteRes);
}
-
+
EXIT_FAILURE(WriteRes);
break;
- case BIOCSETF:
-
+ case BIOCSETF:
+
// Free the previous buffer if it was present
if(Open->bpfprogram!=NULL){
TmpBPFProgram=Open->bpfprogram;
Open->bpfprogram = NULL;
ExFreePool(TmpBPFProgram);
}
-
+
if (Open->Filter!=NULL)
{
JIT_BPF_Filter *OldFilter=Open->Filter;
Open->Filter=NULL;
BPF_Destroy_JIT_Filter(OldFilter);
}
-
+
// Get the pointer to the new program
prog=(PUCHAR)Irp->AssociatedIrp.SystemBuffer;
-
+
if(prog==NULL){
IF_LOUD(DbgPrint("0001");)
-
+
EXIT_FAILURE(0);
}
-
+
insns=(IrpSp->Parameters.DeviceIoControl.InputBufferLength)/sizeof(struct bpf_insn);
-
+
//count the number of operative instructions
for (cnt=0;(cnt<insns) &&(((struct bpf_insn*)prog)[cnt].code!=BPF_SEPARATION); cnt++);
-
+
IF_LOUD(DbgPrint("Operative instructions=%u\n",cnt);)
- if (((struct bpf_insn*)prog)[cnt].code==BPF_SEPARATION && (insns-cnt-1)!=0)
+ if (((struct bpf_insn*)prog)[cnt].code==BPF_SEPARATION && (insns-cnt-1)!=0)
{
IF_LOUD(DbgPrint("Initialization instructions=%u\n",insns-cnt-1);)
-
+
IsExtendedFilter=TRUE;
initprogram=&((struct bpf_insn*)prog)[cnt+1];
-
+
if(bpf_filter_init(initprogram,&(Open->mem_ex),&(Open->tme), &G_Start_Time)!=INIT_OK)
{
-
+
IF_LOUD(DbgPrint("Error initializing NPF machine (bpf_filter_init)\n");)
-
+
EXIT_FAILURE(0);
}
}
//the NPF processor has been initialized, we have to validate the operative instructions
insns=cnt;
-
+
if(bpf_validate((struct bpf_insn*)prog,cnt,Open->mem_ex.size)==0)
{
IF_LOUD(DbgPrint("Error validating program");)
- //FIXME: the machine has been initialized(?), but the operative code is wrong.
+ //FIXME: the machine has been initialized(?), but the operative code is wrong.
//we have to reset the machine!
//something like: reallocate the mem_ex, and reset the tme_core
EXIT_FAILURE(0);
}
-
+
// Allocate the memory to contain the new filter program
// We could need the original BPF binary if we are forced to use bpf_filter_with_2_buffers()
#define NPF_TAG_BPFPROG TAG('4', 'P', 'W', 'A')
// no memory
EXIT_FAILURE(0);
}
-
+
//copy the program in the new buffer
RtlCopyMemory(TmpBPFProgram,prog,cnt*sizeof(struct bpf_insn));
Open->bpfprogram=TmpBPFProgram;
-
+
// Create the new JIT filter function
if(!IsExtendedFilter)
if((Open->Filter=BPF_jitter((struct bpf_insn*)Open->bpfprogram,cnt)) == NULL) {
Open->Bhead = 0;
Open->Btail = 0;
Open->BLastByte = (UINT) -1;
- Open->Received = 0;
+ Open->Received = 0;
Open->Dropped = 0;
Open->Accepted = 0;
EXIT_SUCCESS(IrpSp->Parameters.DeviceIoControl.InputBufferLength);
-
- break;
-
+
+ break;
+
case BIOCSMODE: //set the capture mode
-
+
mode=*((PULONG)Irp->AssociatedIrp.SystemBuffer);
-
+
if(mode == MODE_CAPT){
Open->mode=MODE_CAPT;
-
+
EXIT_SUCCESS(0);
}
else if (mode==MODE_MON){
Open->mode=MODE_MON;
EXIT_SUCCESS(0);
- }
+ }
else{
if(mode & MODE_STAT){
Open->mode = MODE_STAT;
Open->Nbytes.QuadPart=0;
Open->Npackets.QuadPart=0;
-
+
if(Open->TimeOut.QuadPart==0)Open->TimeOut.QuadPart=-10000000;
-
+
}
-
+
if(mode & MODE_DUMP){
-
+
Open->mode |= MODE_DUMP;
Open->MinToCopy=(Open->BufSize<2000000)?Open->BufSize/2:1000000;
-
- }
+
+ }
EXIT_SUCCESS(0);
}
-
+
EXIT_FAILURE(0);
-
+
break;
case BIOCSETDUMPFILENAME:
if(Open->mode & MODE_DUMP)
{
-
+
// Close current dump file
if(Open->DumpFileHandle != NULL){
NPF_CloseDumpFile(Open);
Open->DumpFileHandle = NULL;
}
-
+
if(IrpSp->Parameters.DeviceIoControl.InputBufferLength == 0){
EXIT_FAILURE(0);
}
-
+
// Allocate the buffer that will contain the string
#define NPF_TAG_DUMPNAMEBUF TAG('5', 'P', 'W', 'A')
DumpNameBuff=ExAllocatePoolWithTag(NonPagedPool, IrpSp->Parameters.DeviceIoControl.InputBufferLength, NPF_TAG_DUMPNAMEBUF);
IF_LOUD(DbgPrint("NPF: unable to allocate the dump filename: not enough memory or name already set\n");)
EXIT_FAILURE(0);
}
-
+
// Copy the buffer
- RtlCopyBytes((PVOID)DumpNameBuff,
- Irp->AssociatedIrp.SystemBuffer,
+ RtlCopyBytes((PVOID)DumpNameBuff,
+ Irp->AssociatedIrp.SystemBuffer,
IrpSp->Parameters.DeviceIoControl.InputBufferLength);
-
- // Force a \0 at the end of the filename to avoid that malformed strings cause RtlInitUnicodeString to crash the system
+
+ // Force a \0 at the end of the filename to avoid that malformed strings cause RtlInitUnicodeString to crash the system
((SHORT*)DumpNameBuff)[IrpSp->Parameters.DeviceIoControl.InputBufferLength/2-1]=0;
-
+
// Create the unicode string
RtlInitUnicodeString(&Open->DumpFileName, DumpNameBuff);
-
+
IF_LOUD(DbgPrint("NPF: dump file name set to %ws, len=%d\n",
Open->DumpFileName.Buffer,
IrpSp->Parameters.DeviceIoControl.InputBufferLength);)
-
+
// Try to create the file
if ( NT_SUCCESS( NPF_OpenDumpFile(Open,&Open->DumpFileName,FALSE)) &&
NT_SUCCESS( NPF_StartDump(Open))){
-
+
EXIT_SUCCESS(0);
}
}
-
+
EXIT_FAILURE(0);
-
+
break;
-
+
case BIOCSETDUMPLIMITS:
Open->MaxDumpBytes = *(PULONG)Irp->AssociatedIrp.SystemBuffer;
break;
case BIOCISDUMPENDED:
- if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength < 4){
+ if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength < 4){
EXIT_FAILURE(0);
}
break;
case BIOCSETBUFFERSIZE:
-
+
// Get the number of bytes to allocate
dim = *((PULONG)Irp->AssociatedIrp.SystemBuffer);
Open->Bhead = 0;
Open->Btail = 0;
Open->BLastByte = (UINT) -1;
-
+
Open->BufSize = (UINT)dim;
EXIT_SUCCESS(dim);
-
+
break;
-
+
case BIOCSRTIMEOUT: //set the timeout on the read calls
-
+
timeout = *((PULONG)Irp->AssociatedIrp.SystemBuffer);
if((int)timeout==-1)
Open->TimeOut.QuadPart=(LONGLONG)IMMEDIATE;
//IF_LOUD(DbgPrint("NPF: read timeout set to %d:%d\n",Open->TimeOut.HighPart,Open->TimeOut.LowPart);)
EXIT_SUCCESS(timeout);
-
+
break;
-
+
case BIOCSWRITEREP: //set the writes repetition number
-
+
Open->Nwrites = *((PULONG)Irp->AssociatedIrp.SystemBuffer);
-
+
EXIT_SUCCESS(Open->Nwrites);
-
+
break;
case BIOCSMINTOCOPY: //set the minimum buffer's size to copy to the application
Open->MinToCopy = *((PULONG)Irp->AssociatedIrp.SystemBuffer);
-
+
EXIT_SUCCESS(Open->MinToCopy);
-
+
break;
-
+
case IOCTL_PROTOCOL_RESET:
-
+
IF_LOUD(DbgPrint("NPF: IoControl - Reset request\n");)
IoMarkIrpPending(Irp);
IF_LOUD(DbgPrint("NPF: IoControl - ResetComplete being called\n");)
NPF_ResetComplete(Open,Status);
}
-
+
break;
-
-
+
+
case BIOCSETOID:
case BIOCQUERYOID:
-
+
// Extract a request from the list of free ones
RequestListEntry=ExInterlockedRemoveHeadList(&Open->RequestList,&Open->RequestSpinLock);
if (RequestListEntry == NULL)
pRequest->Irp=Irp;
pRequest->Internal = FALSE;
-
+
//
// See if it is an Ndis request
//
OidData=Irp->AssociatedIrp.SystemBuffer;
-
+
if (((FunctionCode == BIOCSETOID) || (FunctionCode == BIOCQUERYOID))
&&
(IrpSp->Parameters.DeviceIoControl.InputBufferLength == IrpSp->Parameters.DeviceIoControl.OutputBufferLength)
(IrpSp->Parameters.DeviceIoControl.InputBufferLength >= sizeof(PACKET_OID_DATA))
&&
(IrpSp->Parameters.DeviceIoControl.InputBufferLength >= sizeof(PACKET_OID_DATA)-1+OidData->Length)) {
-
+
IF_LOUD(DbgPrint("NPF: IoControl: Request: Oid=%08lx, Length=%08lx\n",OidData->Oid,OidData->Length);)
-
+
//
// The buffer is valid
//
if (FunctionCode == BIOCSETOID){
-
+
pRequest->Request.RequestType=NdisRequestSetInformation;
pRequest->Request.DATA.SET_INFORMATION.Oid=OidData->Oid;
-
+
pRequest->Request.DATA.SET_INFORMATION.InformationBuffer=OidData->Data;
pRequest->Request.DATA.SET_INFORMATION.InformationBufferLength=OidData->Length;
} else{
pRequest->Request.RequestType=NdisRequestQueryInformation;
pRequest->Request.DATA.QUERY_INFORMATION.Oid=OidData->Oid;
-
+
pRequest->Request.DATA.QUERY_INFORMATION.InformationBuffer=OidData->Data;
pRequest->Request.DATA.QUERY_INFORMATION.InformationBufferLength=OidData->Length;
-
+
}
NdisResetEvent(&Open->IOEvent);
Open->AdapterHandle,
&pRequest->Request
);
-
+
} else {
//
// buffer too small
Status=NDIS_STATUS_FAILURE;
pRequest->Request.DATA.SET_INFORMATION.BytesRead=0;
pRequest->Request.DATA.QUERY_INFORMATION.BytesWritten=0;
-
+
}
-
+
if (Status != NDIS_STATUS_PENDING) {
IF_LOUD(DbgPrint("NPF: Calling RequestCompleteHandler\n");)
-
+
NPF_RequestComplete(Open, &pRequest->Request, Status);
return Status;
-
+
}
NdisWaitEvent(&Open->IOEvent, 5000);
return(Open->IOStatus);
-
+
break;
-
-
+
+
default:
-
+
EXIT_FAILURE(0);
}
-
+
return Status;
}
// Put the request in the list of the free ones
ExInterlockedInsertTailList(&Open->RequestList, &pRequest->ListElement, &Open->RequestSpinLock);
-
+
if(Status != NDIS_STATUS_SUCCESS)
Open->MaxFrameSize = 1514; // Assume Ethernet
*MacDriverName = ExAllocatePool(PagedPool, 50 * sizeof(WCHAR));
//memcpy(*MacDriverName, L"\\Device\\ne2000", 15 * sizeof(WCHAR));
memcpy(*MacDriverName, L"\\Device\\ne2000", 15 * sizeof(WCHAR));
-
+
*PacketDriverName = ExAllocatePool(PagedPool, 50 * sizeof(WCHAR));
memcpy(*PacketDriverName, L"\\Device\\NPF_ne2000", 19 * sizeof(WCHAR));
Status = STATUS_SUCCESS;
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
-/** @ingroup NPF
+/** @ingroup NPF
* @{
*/
-/** @defgroup NPF_include NPF structures and definitions
+/** @defgroup NPF_include NPF structures and definitions
* @{
*/
#ifndef __PACKET_INCLUDE______
#define __PACKET_INCLUDE______
-#define NTKERNEL ///< Forces the compilation of the jitter with kernel calls
+#define NTKERNEL ///< Forces the compilation of the jitter with kernel calls
#ifdef __GNUC__
#undef EXIT_SUCCESS
#define MAX_REQUESTS 32 ///< Maximum number of simultaneous IOCTL requests.
#define Packet_ALIGNMENT sizeof(int) ///< Alignment macro. Defines the alignment size.
-#define Packet_WORDALIGN(x) (((x)+(Packet_ALIGNMENT-1))&~(Packet_ALIGNMENT-1)) ///< Alignment macro. Rounds up to the next
- ///< even multiple of Packet_ALIGNMENT.
+#define Packet_WORDALIGN(x) (((x)+(Packet_ALIGNMENT-1))&~(Packet_ALIGNMENT-1)) ///< Alignment macro. Rounds up to the next
+ ///< even multiple of Packet_ALIGNMENT.
/***************************/
\brief IOCTL code: set kernel buffer size.
This IOCTL is used to set a new size of the circular buffer associated with an instance of NPF.
- When a BIOCSETBUFFERSIZE command is received, the driver frees the old buffer, allocates the new one
- and resets all the parameters associated with the buffer in the OPEN_INSTANCE structure. The currently
+ When a BIOCSETBUFFERSIZE command is received, the driver frees the old buffer, allocates the new one
+ and resets all the parameters associated with the buffer in the OPEN_INSTANCE structure. The currently
buffered packets are lost.
*/
#define BIOCSETBUFFERSIZE 9592
/*!
\brief IOCTL code: set packet filtering program.
- This IOCTL sets a new packet filter in the driver. Before allocating any memory for the new filter, the
- bpf_validate() function is called to check the correctness of the filter. If this function returns TRUE,
- the filter is copied to the driver's memory, its address is stored in the bpfprogram field of the
- OPEN_INSTANCE structure associated with current instance of the driver, and the filter will be applied to
- every incoming packet. This command also empties the circular buffer used by current instance
+ This IOCTL sets a new packet filter in the driver. Before allocating any memory for the new filter, the
+ bpf_validate() function is called to check the correctness of the filter. If this function returns TRUE,
+ the filter is copied to the driver's memory, its address is stored in the bpfprogram field of the
+ OPEN_INSTANCE structure associated with current instance of the driver, and the filter will be applied to
+ every incoming packet. This command also empties the circular buffer used by current instance
to store packets. This is done to avoid the presence in the buffer of packets that do not match the filter.
*/
#define BIOCSETF 9030
/*!
\brief IOCTL code: get the capture stats
- This command returns to the application the number of packets received and the number of packets dropped by
+ This command returns to the application the number of packets received and the number of packets dropped by
an instance of the driver.
*/
#define BIOCGSTATS 9031
/*!
\brief IOCTL code: set number of physical repetions of every packet written by the app
- Sets the number of times a single write call must be repeated. This command sets the OPEN_INSTANCE::Nwrites
+ Sets the number of times a single write call must be repeated. This command sets the OPEN_INSTANCE::Nwrites
member, and is used to implement the 'multiple write' feature of the driver.
*/
#define BIOCSWRITEREP 7413
/*!
\brief IOCTL code: set an OID value
- This IOCTL is used to perform an OID set operation on the NIC driver.
+ This IOCTL is used to perform an OID set operation on the NIC driver.
*/
#define BIOCSETOID 2147483648UL
/*!
\brief IOCTL code: get an OID value
- This IOCTL is used to perform an OID get operation on the NIC driver.
+ This IOCTL is used to perform an OID get operation on the NIC driver.
*/
#define BIOCQUERYOID 2147483652UL
\brief IOCTL code: Send a buffer containing multiple packets to the network, ignoring the timestamps.
Command used to send a buffer of packets in a single system call. Every packet in the buffer is preceded by
- a sf_pkthdr structure. The timestamps of the packets are ignored, i.e. the packets are sent as fast as
+ a sf_pkthdr structure. The timestamps of the packets are ignored, i.e. the packets are sent as fast as
possible. The NPF_BufferedWrite() function is invoked to send the packets.
*/
#define BIOCSENDPACKETSNOSYNC 9032
\brief IOCTL code: Send a buffer containing multiple packets to the network, considering the timestamps.
Command used to send a buffer of packets in a single system call. Every packet in the buffer is preceded by
- a sf_pkthdr structure. The timestamps of the packets are used to synchronize the write, i.e. the packets
+ a sf_pkthdr structure. The timestamps of the packets are used to synchronize the write, i.e. the packets
are sent to the network respecting the intervals specified in the sf_pkthdr structure assiciated with each
- packet. NPF_BufferedWrite() function is invoked to send the packets.
+ packet. NPF_BufferedWrite() function is invoked to send the packets.
*/
#define BIOCSENDPACKETSSYNC 9033
#define IMMEDIATE 1 ///< Immediate timeout. Forces a read call to return immediately.
-// The following definitions are used to provide compatibility
+// The following definitions are used to provide compatibility
// of the dump files with the ones of libpcap
#define TCPDUMP_MAGIC 0xa1b2c3d4 ///< Libpcap magic number. Used by programs like tcpdump to recognize a driver's generated dump file.
#define PCAP_VERSION_MAJOR 2 ///< Major libpcap version of the dump file. Used by programs like tcpdump to recognize a driver's generated dump file.
Used when a driver instance is set in dump mode to create a libpcap-compatible file.
*/
-struct packet_file_header
+struct packet_file_header
{
UINT magic; ///< Libpcap magic number
USHORT version_major; ///< Libpcap major version
*/
struct sf_pkthdr {
struct timeval ts; ///< time stamp
- UINT caplen; ///< Length of captured portion. The captured portion can be different from
- ///< the original packet, because it is possible (with a proper filter) to
- ///< instruct the driver to capture only a portion of the packets.
+ UINT caplen; ///< Length of captured portion. The captured portion can be different from
+ ///< the original packet, because it is possible (with a proper filter) to
+ ///< instruct the driver to capture only a portion of the packets.
UINT len; ///< Length of the original packet (off wire).
};
/*!
\brief Stores an OID request.
-
- This structure is used by the driver to perform OID query or set operations on the underlying NIC driver.
- The OID operations be performed usually only by network drivers, but NPF exports this mechanism to user-level
+
+ This structure is used by the driver to perform OID query or set operations on the underlying NIC driver.
+ The OID operations be performed usually only by network drivers, but NPF exports this mechanism to user-level
applications through an IOCTL interface. The driver uses this structure to wrap a NDIS_REQUEST structure.
This allows to handle correctly the callback structure of NdisRequest(), handling multiple requests and
maintaining information about the IRPs to complete.
/*!
\brief Contains a NDIS packet.
-
+
The driver uses this structure to wrap a NDIS_PACKET structure.
This allows to handle correctly the callback structure of NdisTransferData(), handling multiple requests and
maintaining information about the IRPs to complete.
LIST_ENTRY ListElement; ///< Used to handle lists of packets.
PIRP Irp; ///< Irp that performed the request
PMDL pMdl; ///< MDL mapping the buffer of the packet.
- BOOLEAN FreeBufAfterWrite; ///< True if the memory buffer associated with the packet must be freed
+ BOOLEAN FreeBufAfterWrite; ///< True if the memory buffer associated with the packet must be freed
///< after a call to NdisSend().
} PACKET_RESERVED, *PPACKET_RESERVED;
/*!
\brief Port device extension.
-
+
Structure containing some data relative to every adapter on which NPF is bound.
*/
typedef struct _DEVICE_EXTENSION {
NDIS_HANDLE NdisProtocolHandle; ///< NDIS handle of NPF.
NDIS_STRING AdapterName; ///< Name of the adapter.
- PWSTR ExportString; ///< Name of the exported device, i.e. name that the applications will use
+ PWSTR ExportString; ///< Name of the exported device, i.e. name that the applications will use
///< to open this adapter through WinPcap.
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;
/*!
\brief Contains the state of a running instance of the NPF driver.
-
+
This is the most important structure of NPF: it is used by almost all the functions of the driver. An
_OPEN_INSTANCE structure is associated with every user-level session, allowing concurrent access
to the driver.
UINT Medium; ///< Type of physical medium the underlying NDIS driver uses. See the
///< documentation of NdisOpenAdapter in the MS DDK for details.
NDIS_HANDLE PacketPool; ///< Pool of NDIS_PACKET structures used to transfer the packets from and to the NIC driver.
- PIRP OpenCloseIrp; ///< Pointer used to store the open/close IRP requests and provide them to the
+ PIRP OpenCloseIrp; ///< Pointer used to store the open/close IRP requests and provide them to the
///< callbacks of NDIS.
KSPIN_LOCK RequestSpinLock; ///< SpinLock used to synchronize the OID requests.
LIST_ENTRY RequestList; ///< List of pending OID requests.
PKEVENT ReadEvent; ///< Pointer to the event on which the read calls on this instance must wait.
HANDLE ReadEventHandle; ///< Handle of the event on which the read calls on this instance must wait.
UNICODE_STRING ReadEventName; ///< Name of the event on which the read calls on this instance must wait.
- ///< The event is created with a name, so it can be used at user level to know when it
- ///< is possible to access the driver without being blocked. This fiels stores the name
+ ///< The event is created with a name, so it can be used at user level to know when it
+ ///< is possible to access the driver without being blocked. This fiels stores the name
///< that and is used by the BIOCGEVNAME IOCTL call.
- INT Received; ///< Number of packets received by current instance from its opening, i.e. number of
- ///< packet received by the network adapter since the beginning of the
+ INT Received; ///< Number of packets received by current instance from its opening, i.e. number of
+ ///< packet received by the network adapter since the beginning of the
///< capture/monitoring/dump session.
- INT Dropped; ///< Number of packet that current instance had to drop, from its opening. A packet
- ///< is dropped if there is no more space to store it in the circular buffer that the
+ INT Dropped; ///< Number of packet that current instance had to drop, from its opening. A packet
+ ///< is dropped if there is no more space to store it in the circular buffer that the
///< driver associates to current instance.
- INT Accepted; ///< Number of packet that current capture instance acepted, from its opening. A packet
+ INT Accepted; ///< Number of packet that current capture instance acepted, from its opening. A packet
///< is accepted if it passes the filter and fits in the buffer. Accepted packets are the
///< ones that reach the application.
PUCHAR bpfprogram; ///< Pointer to the filtering pseudo-code associated with current instance of the driver.
///< This code is used only in particular situations (for example when the packet received
///< from the NIC driver is stored in two non-consecutive buffers. In normal situations
- ///< the filtering routine created by the JIT compiler and pointed by the next field
+ ///< the filtering routine created by the JIT compiler and pointed by the next field
///< is used. See \ref NPF for details on the filtering process.
- JIT_BPF_Filter *Filter; ///< Pointer to the native filtering function created by the jitter.
+ JIT_BPF_Filter *Filter; ///< Pointer to the native filtering function created by the jitter.
///< See BPF_jitter() for details.
- PUCHAR Buffer; ///< Pointer to the circular buffer associated with every driver instance. It contains the
+ PUCHAR Buffer; ///< Pointer to the circular buffer associated with every driver instance. It contains the
///< data that will be passed to the application. See \ref NPF for details.
UINT Bhead; ///< Head of the circular buffer.
UINT Btail; ///< Tail of the circular buffer.
UINT BufSize; ///< Size of the circular buffer.
UINT BLastByte; ///< Position of the last valid byte in the circular buffer.
- PMDL TransferMdl; ///< MDL used to map the portion of the buffer that will contain an incoming packet.
+ PMDL TransferMdl; ///< MDL used to map the portion of the buffer that will contain an incoming packet.
///< Used by NdisTransferData().
NDIS_SPIN_LOCK BufLock; ///< SpinLock that protects the access tho the circular buffer variables.
UINT MinToCopy; ///< Minimum amount of data in the circular buffer that unlocks a read. Set with the
///< BIOCSMINTOCOPY IOCTL.
- LARGE_INTEGER TimeOut; ///< Timeout after which a read is released, also if the amount of data in the buffer is
+ LARGE_INTEGER TimeOut; ///< Timeout after which a read is released, also if the amount of data in the buffer is
///< less than MinToCopy. Set with the BIOCSRTIMEOUT IOCTL.
-
+
int mode; ///< Working mode of the driver. See PacketSetMode() for details.
LARGE_INTEGER Nbytes; ///< Amount of bytes accepted by the filter when this instance is in statistical mode.
LARGE_INTEGER Npackets; ///< Number of packets accepted by the filter when this instance is in statistical mode.
NDIS_SPIN_LOCK CountersLock; ///< SpinLock that protects the statistical mode counters.
- UINT Nwrites; ///< Number of times a single write must be physically repeated. See \ref NPF for an
+ UINT Nwrites; ///< Number of times a single write must be physically repeated. See \ref NPF for an
///< explanation
UINT Multiple_Write_Counter; ///< Counts the number of times a single write has already physically repeated.
NDIS_EVENT WriteEvent; ///< Event used to synchronize the multiple write process.
NDIS_EVENT DumpEvent; ///< Event used to synchronize the dump thread with the tap when the instance is in dump mode.
LARGE_INTEGER DumpOffset; ///< Current offset in the dump file.
UNICODE_STRING DumpFileName; ///< String containing the name of the dump file.
- UINT MaxDumpBytes; ///< Maximum dimension in bytes of the dump file. If the dump file reaches this size it
+ UINT MaxDumpBytes; ///< Maximum dimension in bytes of the dump file. If the dump file reaches this size it
///< will be closed. A value of 0 means unlimited size.
- UINT MaxDumpPacks; ///< Maximum number of packets that will be saved in the dump file. If this number of
- ///< packets is reached the dump will be closed. A value of 0 means unlimited number of
+ UINT MaxDumpPacks; ///< Maximum number of packets that will be saved in the dump file. If this number of
+ ///< packets is reached the dump will be closed. A value of 0 means unlimited number of
///< packets.
- BOOLEAN DumpLimitReached; ///< TRUE if the maximum dimension of the dump file (MaxDumpBytes or MaxDumpPacks) is
+ BOOLEAN DumpLimitReached; ///< TRUE if the maximum dimension of the dump file (MaxDumpBytes or MaxDumpPacks) is
///< reached.
MEM_TYPE mem_ex; ///< Memory used by the TME virtual co-processor
TME_CORE tme; ///< Data structure containing the virtualization of the TME co-processor
NDIS_SPIN_LOCK machine_lock; ///< SpinLock that protects the mem_ex buffer
- UINT MaxFrameSize; ///< Maximum frame size that the underlying MAC acceptes. Used to perform a check on the
+ UINT MaxFrameSize; ///< Maximum frame size that the underlying MAC acceptes. Used to perform a check on the
///< size of the frames sent with NPF_Write() or NPF_BufferedWrite().
} OPEN_INSTANCE, *POPEN_INSTANCE;
/* Prototypes */
/***************************/
-/** @defgroup NPF_code NPF functions
+/** @defgroup NPF_code NPF functions
* @{
*/
\return A string containing a list of network adapters.
DriverEntry is a mandatory function in a device driver. Like the main() of a user level program, it is called
- by the system when the driver is loaded in memory and started. Its purpose is to initialize the driver,
+ by the system when the driver is loaded in memory and started. Its purpose is to initialize the driver,
performing all the allocations and the setup. In particular, DriverEntry registers all the driver's I/O
callbacks, creates the devices, defines NPF as a protocol inside NDIS.
-*/
+*/
//NTSTATUS
//DriverEntry(
// IN PDRIVER_OBJECT DriverObject,
\brief Returns the list of the MACs available on the system.
\return A string containing a list of network adapters.
- The list of adapters is retrieved from the
- SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318} registry key.
+ The list of adapters is retrieved from the
+ SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318} registry key.
NPF tries to create its bindings from this list. In this way it is possible to be loaded
and unloaded dynamically without passing from the control panel.
*/
\param Irp Pointer to the IRP containing the user request.
\return The status of the operation. See ntstatus.h in the DDK.
- This function is called by the OS when a new instance of the driver is opened, i.e. when a user application
+ This function is called by the OS when a new instance of the driver is opened, i.e. when a user application
performs a CreateFile on a device created by NPF. NPF_Open allocates and initializes variables, objects
- and buffers needed by the new instance, fills the OPEN_INSTANCE structure associated with it and opens the
+ and buffers needed by the new instance, fills the OPEN_INSTANCE structure associated with it and opens the
adapter with a call to NdisOpenAdapter.
*/
NTSTATUS STDCALL
\param Status Status of the opening operation performed by NDIS.
\param OpenErrorStatus not used by NPF.
- Callback function associated with the NdisOpenAdapter() NDIS function. It is invoked by NDIS when the NIC
+ Callback function associated with the NdisOpenAdapter() NDIS function. It is invoked by NDIS when the NIC
driver has finished an open operation that was previously started by NPF_Open().
*/
VOID STDCALL
\param Irp Pointer to the IRP containing the user request.
\return The status of the operation. See ntstatus.h in the DDK.
- This function is called when a running instance of the driver is closed by the user with a CloseHandle().
- It stops the capture/monitoring/dump process, deallocates the memory and the objects associated with the
- instance and closing the files. The network adapter is then closed with a call to NdisCloseAdapter.
+ This function is called when a running instance of the driver is closed by the user with a CloseHandle().
+ It stops the capture/monitoring/dump process, deallocates the memory and the objects associated with the
+ instance and closing the files. The network adapter is then closed with a call to NdisCloseAdapter.
*/
NTSTATUS STDCALL
NPF_Close(
\param ProtocolBindingContext Context of the function. Contains a pointer to the OPEN_INSTANCE structure associated with the current instance.
\param Status Status of the close operation performed by NDIS.
- Callback function associated with the NdisCloseAdapter() NDIS function. It is invoked by NDIS when the NIC
+ Callback function associated with the NdisCloseAdapter() NDIS function. It is invoked by NDIS when the NIC
driver has finished a close operation that was previously started by NPF_Close().
*/
VOID STDCALL
/*!
\brief Callback invoked by NDIS when a packet arrives from the network.
- \param ProtocolBindingContext Context of the function. Points to a OPEN_INSTANCE structure that identifies
+ \param ProtocolBindingContext Context of the function. Points to a OPEN_INSTANCE structure that identifies
the NPF instance to which the packets are destined.
- \param MacReceiveContext Handle that identifies the underlying NIC driver that generated the request.
+ \param MacReceiveContext Handle that identifies the underlying NIC driver that generated the request.
This value must be used when the packet is transferred from the NIC driver with NdisTransferData().
\param HeaderBuffer Pointer to the buffer in the NIC driver memory that contains the header of the packet.
\param HeaderBufferSize Size in bytes of the header.
- \param LookAheadBuffer Pointer to the buffer in the NIC driver's memory that contains the incoming packet's
+ \param LookAheadBuffer Pointer to the buffer in the NIC driver's memory that contains the incoming packet's
data <b>available to NPF</b>. This value does not necessarily coincide with the actual size of the packet,
since only a portion can be available at this time. The remaining portion can be obtained with the
NdisTransferData() NDIS function.
\param PacketSize Total size of the incoming packet, excluded the header.
\return The status of the operation. See ntstatus.h in the DDK.
- NPF_tap() is called by the underlying NIC for every incoming packet. It is the most important and one of
- the most complex functions of NPF: it executes the filter, runs the statistical engine (if the instance is in
+ NPF_tap() is called by the underlying NIC for every incoming packet. It is the most important and one of
+ the most complex functions of NPF: it executes the filter, runs the statistical engine (if the instance is in
statistical mode), gathers the timestamp, moves the packet in the buffer. NPF_tap() is the only function,
- along with the filtering ones, that is executed for every incoming packet, therefore it is carefully
+ along with the filtering ones, that is executed for every incoming packet, therefore it is carefully
optimized.
*/
NDIS_STATUS STDCALL
\param Status Status of the transfer operation.
\param BytesTransferred Amount of bytes transferred.
- Callback function associated with the NdisTransferData() NDIS function. It is invoked by NDIS when the NIC
+ Callback function associated with the NdisTransferData() NDIS function. It is invoked by NDIS when the NIC
driver has finished the transfer of a packet from the NIC driver memory to the NPF circular buffer.
*/
VOID STDCALL
Once the packet capture driver is opened it can be configured from user-level applications with IOCTL commands
using the DeviceIoControl() system call. NPF_IoControl receives and serves all the IOCTL calls directed to NPF.
- The following commands are recognized:
- - #BIOCSETBUFFERSIZE
- - #BIOCSETF
- - #BIOCGSTATS
+ The following commands are recognized:
+ - #BIOCSETBUFFERSIZE
+ - #BIOCSETF
+ - #BIOCGSTATS
- #BIOCSRTIMEOUT
- - #BIOCSMODE
- - #BIOCSWRITEREP
- - #BIOCSMINTOCOPY
- - #BIOCSETOID
- - #BIOCQUERYOID
+ - #BIOCSMODE
+ - #BIOCSWRITEREP
+ - #BIOCSMINTOCOPY
+ - #BIOCSETOID
+ - #BIOCQUERYOID
- #BIOCSETDUMPFILENAME
- #BIOCGEVNAME
- #BIOCSENDPACKETSSYNC
/*!
\brief Ends an OID request.
\param ProtocolBindingContext Context of the function. Contains a pointer to the OPEN_INSTANCE structure associated with the current instance.
- \param pRequest Pointer to the completed OID request.
+ \param pRequest Pointer to the completed OID request.
\param Status Status of the operation.
- Callback function associated with the NdisRequest() NDIS function. It is invoked by NDIS when the NIC
+ Callback function associated with the NdisRequest() NDIS function. It is invoked by NDIS when the NIC
driver has finished an OID request operation that was previously started by NPF_IoControl().
*/
VOID STDCALL
This function is called by the OS in consequence of user WriteFile() call, with the data of the packet that must
be sent on the net. The data is contained in the buffer associated with Irp, NPF_Write takes it and
- delivers it to the NIC driver via the NdisSend() function. The Nwrites field of the OPEN_INSTANCE structure
+ delivers it to the NIC driver via the NdisSend() function. The Nwrites field of the OPEN_INSTANCE structure
associated with Irp indicates the number of copies of the packet that will be sent: more than one copy of the
packet can be sent for performance reasons.
*/
The buffer received as input parameter contains an arbitrary number of packets, each of which preceded by a
sf_pkthdr structure. NPF_BufferedWrite() scans the buffer and sends every packet via the NdisSend() function.
When Sync is set to TRUE, the packets are synchronized with the KeQueryPerformanceCounter() function.
- This requires a remarkable amount of CPU, but allows to respect the timestamps associated with packets with a precision
+ This requires a remarkable amount of CPU, but allows to respect the timestamps associated with packets with a precision
of some microseconds (depending on the precision of the performance counter of the machine).
If Sync is false, the timestamps are ignored and the packets are sent as fat as possible.
*/
-INT NPF_BufferedWrite(IN PIRP Irp,
- IN PCHAR UserBuff,
+INT NPF_BufferedWrite(IN PIRP Irp,
+ IN PCHAR UserBuff,
IN ULONG UserBuffSize,
BOOLEAN sync);
/*!
\brief Ends a send operation.
\param ProtocolBindingContext Context of the function. Contains a pointer to the OPEN_INSTANCE structure associated with the current instance.
- \param pRequest Pointer to the NDIS PACKET structure used by NPF_Write() to send the packet.
+ \param pRequest Pointer to the NDIS PACKET structure used by NPF_Write() to send the packet.
\param Status Status of the operation.
- Callback function associated with the NdisSend() NDIS function. It is invoked by NDIS when the NIC
+ Callback function associated with the NdisSend() NDIS function. It is invoked by NDIS when the NIC
driver has finished an OID request operation that was previously started by NPF_Write().
*/
VOID STDCALL
\param ProtocolBindingContext Context of the function. Contains a pointer to the OPEN_INSTANCE structure associated with the current instance.
\param Status Status of the operation.
- Callback function associated with the NdisReset() NDIS function. It is invoked by NDIS when the NIC
- driver has finished an OID request operation that was previously started by NPF_IoControl(), in an IOCTL_PROTOCOL_RESET
+ Callback function associated with the NdisReset() NDIS function. It is invoked by NDIS when the NIC
+ driver has finished an OID request operation that was previously started by NPF_IoControl(), in an IOCTL_PROTOCOL_RESET
command.
*/
VOID STDCALL
This function is called by the OS in consequence of user ReadFile() call. It moves the data present in the
kernel buffer to the user buffer associated with Irp.
- First of all, NPF_Read checks the amount of data in kernel buffer associated with current NPF instance.
+ First of all, NPF_Read checks the amount of data in kernel buffer associated with current NPF instance.
- If the instance is in capture mode and the buffer contains more than OPEN_INSTANCE::MinToCopy bytes,
NPF_Read moves the data in the user buffer and returns immediatly. In this way, the read performed by the
user is not blocking.
- - If the buffer contains less than MinToCopy bytes, the application's request isn't
- satisfied immediately, but it's blocked until at least MinToCopy bytes arrive from the net
+ - If the buffer contains less than MinToCopy bytes, the application's request isn't
+ satisfied immediately, but it's blocked until at least MinToCopy bytes arrive from the net
or the timeout on this read expires. The timeout is kept in the OPEN_INSTANCE::TimeOut field.
- - If the instance is in statistical mode or in dump mode, the application's request is blocked until the
+ - If the instance is in statistical mode or in dump mode, the application's request is blocked until the
timeout kept in OPEN_INSTANCE::TimeOut expires.
*/
NTSTATUS STDCALL
);
/*!
- \brief Function used by NPF_ReadRegistry() to quesry the registry keys associated woth NPF if the driver
+ \brief Function used by NPF_ReadRegistry() to quesry the registry keys associated woth NPF if the driver
is manually installed via the control panel.
Normally not used in recent versions of NPF.
/*!
\brief Callback for NDIS BindAdapterHandler. Not used by NPF.
-
+
Function called by NDIS when a new adapter is installed on the machine With Plug and Play.
*/
VOID NPF_BindAdapter(
\param Status out variable filled by NPF_UnbindAdapter with the status of the unbind operation.
\param ProtocolBindingContext Context of the function. Contains a pointer to the OPEN_INSTANCE structure associated with current instance.
\param UnbindContext Specifies a handle, supplied by NDIS, that NPF can use to complete the opration.
-
+
Function called by NDIS when a new adapter is removed from the machine without shutting it down.
NPF_UnbindAdapter closes the adapter calling NdisCloseAdapter() and frees the memory and the structures
associated with it. It also releases the waiting user-level app and closes the dump thread if the instance
\param len Its length, in pseudo instructions.
\param mem_ex_size The length of the extended memory, used to validate LD/ST to that memory
\return true if f is a valid filter program..
-
- The kernel needs to be able to verify an application's filter code. Otherwise, a bogus program could easily
+
+ The kernel needs to be able to verify an application's filter code. Otherwise, a bogus program could easily
crash the system.
- This function returns true if f is a valid filter program. The constraints are that each jump be forward and
- to a valid code. The code must terminate with either an accept or reject.
+ This function returns true if f is a valid filter program. The constraints are that each jump be forward and
+ to a valid code. The code must terminate with either an accept or reject.
*/
int bpf_validate(struct bpf_insn *f,int len, uint32 mem_ex_size);
\param time_ref Data structure needed by the TME co-processor to timestamp data
\return The portion of the packet to keep, in bytes. 0 means that the packet must be rejected, -1 means that
the whole packet must be kept.
-
+
\note this function is not used in normal situations, because the jitter creates a native filtering function
that is faster than the interpreter.
*/
struct time_conv *time_ref);
/*!
- \brief The filtering pseudo-machine interpreter with two buffers. This function is slower than bpf_filter(),
+ \brief The filtering pseudo-machine interpreter with two buffers. This function is slower than bpf_filter(),
but works correctly also if the MAC header and the data of the packet are in two different buffers.
\param pc The filter.
\param p Pointer to a memory buffer containing the MAC header of the packet.
\param time_ref Data structure needed by the TME co-processor to timestamp data
\return The portion of the packet to keep, in bytes. 0 means that the packet must be rejected, -1 means that
the whole packet must be kept.
-
+
This function is used when NDIS passes the packet to NPF_tap() in two buffers instaed than in a single one.
*/
UINT bpf_filter_with_2_buffers(register struct bpf_insn *pc,
\brief The dump thread.
\param Open The NPF instance that creates the thread.
- This function moves the content of the NPF kernel buffer to file. It runs in the user context, so at lower
+ This function moves the content of the NPF kernel buffer to file. It runs in the user context, so at lower
priority than the TAP.
*/
VOID NPF_DumpThread(POPEN_INSTANCE Open);
/*!
\brief Called by NDIS to notify us of a PNP event. The most significant one for us is power state change.
- \param ProtocolBindingContext Pointer to open context structure. This is NULL for global reconfig
+ \param ProtocolBindingContext Pointer to open context structure. This is NULL for global reconfig
events.
\param pNetPnPEvent Pointer to the PnP event
UINT Occupation;
NdisAcquireSpinLock( &Open->BufLock );
-
+
if(Open->Btail >= Open->Bhead) Occupation = Open->Btail-Open->Bhead;
else Occupation = Open->BLastByte-Open->Bhead+Open->Btail;
NBlocks=WordLength>>8;
ULSrc = (PULONG) Source;
- ULDest = (PULONG) Destination;
+ ULDest = (PULONG) Destination;
for(n=0;n<NBlocks;n++){
for(i=0;i<256;i++){
*ULDest++ = *ULSrc++;
}
*Bhead+=n<<2;
- UCDest = (PUCHAR) ULDest;
- UCSrc = (PUCHAR) ULSrc;
+ UCDest = (PUCHAR) ULDest;
+ UCSrc = (PUCHAR) ULSrc;
n=Length-(WordLength<<2);
for(i=0;i<n;i++){
*UCDest++ = *UCSrc++;
UINT PktLen;
IF_LOUD(DbgPrint("NPF: Read\n");)
-
+
IrpSp = IoGetCurrentIrpStackLocation(Irp);
Open=IrpSp->FileObject->FsContext;
-
+
if( Open->Bound == FALSE ){
// The Network adapter was removed.
EXIT_FAILURE(0);
}
-
- if( Open->mode & MODE_DUMP && Open->DumpFileHandle == NULL ){
+
+ if( Open->mode & MODE_DUMP && Open->DumpFileHandle == NULL ){
// this instance is in dump mode, but the dump file has still not been opened
EXIT_FAILURE(0);
}
//See if the buffer is full enough to be copied
if( GetBuffOccupation(Open) <= Open->MinToCopy || Open->mode & MODE_DUMP )
{
- //wait until some packets arrive or the timeout expires
+ //wait until some packets arrive or the timeout expires
if(Open->TimeOut.QuadPart != (LONGLONG)IMMEDIATE)
KeWaitForSingleObject(Open->ReadEvent,
UserRequest,
(Open->TimeOut.QuadPart == (LONGLONG)0)? NULL: &(Open->TimeOut));
KeClearEvent(Open->ReadEvent);
-
+
if(Open->mode & MODE_STAT){ //this capture instance is in statistics mode
CurrBuff=(PUCHAR)MmGetSystemAddressForMdl(Irp->MdlAddress);
-
+
//fill the bpf header for this packet
header=(struct bpf_hdr*)CurrBuff;
GET_TIME(&header->bh_tstamp,&G_Start_Time);
*(LONGLONG*)(CurrBuff+sizeof(struct bpf_hdr))=Open->Npackets.QuadPart;
*(LONGLONG*)(CurrBuff+sizeof(struct bpf_hdr)+8)=Open->Nbytes.QuadPart;
-
+
//reset the countetrs
NdisAcquireSpinLock( &Open->CountersLock );
Open->Npackets.QuadPart=0;
Open->Nbytes.QuadPart=0;
NdisReleaseSpinLock( &Open->CountersLock );
-
+
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return STATUS_SUCCESS;
}
-
+
if(Open->mode==MODE_MON) //this capture instance is in monitor mode
- {
+ {
PTME_DATA data;
ULONG cnt;
ULONG block_size;
PUCHAR tmp;
UserPointer=MmGetSystemAddressForMdl(Irp->MdlAddress);
-
+
if ((!IS_VALIDATED(Open->tme.validated_blocks,Open->tme.active_read))||(IrpSp->Parameters.Read.Length<sizeof(struct bpf_hdr)))
- {
+ {
EXIT_FAILURE(0);
}
-
+
header=(struct bpf_hdr*)UserPointer;
-
+
GET_TIME(&header->bh_tstamp,&G_Start_Time);
-
+
header->bh_hdrlen=sizeof(struct bpf_hdr);
-
+
//moves user memory pointer
UserPointer+=sizeof(struct bpf_hdr);
-
+
//calculus of data to be copied
//if the user buffer is smaller than data to be copied,
//only some data will be copied
if (data->last_read.tv_sec!=0)
data->last_read=header->bh_tstamp;
-
+
bytecopy=data->block_size*data->filled_blocks;
-
+
if ((IrpSp->Parameters.Read.Length-sizeof(struct bpf_hdr))<bytecopy)
bytecopy=(IrpSp->Parameters.Read.Length-sizeof(struct bpf_hdr))/ data->block_size;
- else
+ else
bytecopy=data->filled_blocks;
tmp=data->shared_memory_base_address;
block_size=data->block_size;
-
+
for (cnt=0;cnt<bytecopy;cnt++)
{
NdisAcquireSpinLock(&Open->machine_lock);
tmp+=block_size;
UserPointer+=block_size;
}
-
+
bytecopy*=block_size;
header->bh_caplen=bytecopy;
{
EXIT_SUCCESS(0);
}
-
+
}
//
// The buffer if full enough to be copied,
//
NdisAcquireSpinLock( &Open->BufLock );
-
+
Thead = Open->Bhead;
Ttail = Open->Btail;
TLastByte = Open->BLastByte;
//get the address of the buffer
CurrBuff=Open->Buffer;
-
+
NdisReleaseSpinLock( &Open->BufLock );
-
+
Input_Buffer_Length=IrpSp->Parameters.Read.Length;
packp=(PUCHAR)MmGetSystemAddressForMdl(Irp->MdlAddress);
-
+
//
//fill the application buffer
PacketMoveMem(packp, CurrBuff+Thead, TLastByte - Thead, &(Open->Bhead));
NdisAcquireSpinLock( &Open->BufLock );
-
+
Open->BLastByte = Open->Btail;
Open->Bhead = 0;
NdisReleaseSpinLock( &Open->BufLock );
-
+
EXIT_SUCCESS(TLastByte-Thead);
}
-
+
//the buffer must be scannned to determine the number of bytes to copy
SizeToCopy = 0;
while(TRUE){
// Reset the buffer
NdisAcquireSpinLock( &Open->BufLock );
Open->BLastByte = (UINT) -1;
- Open->Bhead = 0;
+ Open->Bhead = 0;
NdisReleaseSpinLock( &Open->BufLock );
EXIT_SUCCESS(SizeToCopy);
if(SizeToCopy + PktLen > Input_Buffer_Length)
break;
-
+
SizeToCopy += PktLen;
}
BOOLEAN ResetBuff = FALSE;
IF_VERY_LOUD(DbgPrint("NPF: tap\n");)
- IF_VERY_LOUD(DbgPrint("HeaderBufferSize=%d, LookAheadBuffer=%d, LookaheadBufferSize=%d, PacketSize=%d\n",
+ IF_VERY_LOUD(DbgPrint("HeaderBufferSize=%d, LookAheadBuffer=%d, LookaheadBufferSize=%d, PacketSize=%d\n",
HeaderBufferSize,
LookAheadBuffer,
LookaheadBufferSize,
}
NdisAcquireSpinLock(&Open->machine_lock);
-
+
//
//Check if the lookahead buffer follows the mac header.
//If the data follow the header (i.e. there is only a buffer) a normal bpf_filter() is
&Open->mem_ex,
&Open->tme,
&G_Start_Time);
-
-
- else
+
+
+ else
if(Open->Filter != NULL)
{
if (Open->bpfprogram != NULL)
fres=Open->Filter->Function(HeaderBuffer,
PacketSize+HeaderBufferSize,
LookaheadBufferSize+HeaderBufferSize);
-
- // Restore the stack.
+
+ // Restore the stack.
// I ignore the reason, but this instruction is needed only at kernel level
#ifndef __GNUC__
- _asm add esp,12
+ _asm add esp,12
#else
asm("add $0x12,%esp;");
#endif
&G_Start_Time);
NdisReleaseSpinLock(&Open->machine_lock);
-
+
if(Open->mode==MODE_MON)
// we are in monitor mode
{
- if (fres==1)
+ if (fres==1)
KeSetEvent(Open->ReadEvent,0,FALSE);
return NDIS_STATUS_NOT_ACCEPTED;
return NDIS_STATUS_NOT_ACCEPTED;
//if the filter returns -1 the whole packet must be accepted
- if(fres==-1 || fres > PacketSize+HeaderBufferSize)fres=PacketSize+HeaderBufferSize;
+ if(fres==-1 || fres > PacketSize+HeaderBufferSize)fres=PacketSize+HeaderBufferSize;
if(Open->mode & MODE_STAT){
// we are in statistics mode
NdisAcquireSpinLock( &Open->CountersLock );
Open->Npackets.QuadPart++;
-
+
if(PacketSize+HeaderBufferSize<60)
Open->Nbytes.QuadPart+=60;
else
Open->Nbytes.QuadPart+=12;
NdisReleaseSpinLock( &Open->CountersLock );
-
+
if(!(Open->mode & MODE_DUMP)){
return NDIS_STATUS_NOT_ACCEPTED;
}
}
if(Open->BufSize==0)return NDIS_STATUS_NOT_ACCEPTED;
-
+
if(Open->mode & MODE_DUMP && Open->MaxDumpPacks && (UINT)Open->Accepted > Open->MaxDumpPacks){
// Reached the max number of packets to save in the dump file. Discard the packet and stop the dump thread.
Open->DumpLimitReached = TRUE; // This stops the thread
// Calculate the correct size for the header associated with the packet
NPFHdrSize=(Open->mode==MODE_CAPT)? sizeof(struct bpf_hdr): sizeof(struct sf_pkthdr);
-
+
NdisAcquireSpinLock( &Open->BufLock );
Thead=Open->Bhead;
TLastByte = Open->BLastByte;
NdisReleaseSpinLock( &Open->BufLock );
-
+
maxbufspace=Packet_WORDALIGN(fres+NPFHdrSize);
if(Ttail+maxbufspace >= Open->BufSize){
ResetBuff = TRUE;
}
}
-
+
if (Thead > Ttail && (Thead-Ttail) <= maxbufspace)
{
Open->Dropped++;
return NDIS_STATUS_NOT_ACCEPTED;
}
-
+
CurrBuff=Open->Buffer+Ttail;
if(LookaheadBufferSize != PacketSize || (UINT)LookAheadBuffer-(UINT)HeaderBuffer != HeaderBufferSize)
return NDIS_STATUS_NOT_ACCEPTED;
}
MmBuildMdlForNonPagedPool(pMdl);
-
+
//allocate the packet from NDIS
NdisAllocatePacket(&Status, &pPacketb, Open->PacketPool);
if (Status != NDIS_STATUS_SUCCESS)
}
//link the buffer to the packet
NdisChainBufferAtFront(pPacketb,pMdl);
-
+
BufferLength=fres-HeaderBufferSize;
//Find out how much to transfer
SizeToTransfer = (PacketSize < BufferLength) ? PacketSize : BufferLength;
-
+
//copy the ethernet header into buffer
NdisMoveMappedMemory((CurrBuff)+NPFHdrSize,HeaderBuffer,HeaderBufferSize);
-
+
//Copy the look ahead buffer
if(LookaheadBufferSize)
{
NdisMoveMappedMemory((CurrBuff) + NPFHdrSize + HeaderBufferSize,
- LookAheadBuffer,
+ LookAheadBuffer,
(SizeToTransfer < LookaheadBufferSize)? SizeToTransfer : LookaheadBufferSize );
-
+
SizeToTransfer = (SizeToTransfer > LookaheadBufferSize)?
SizeToTransfer - LookaheadBufferSize : 0;
}
-
+
Open->TransferMdl=pMdl;
-
+
if(SizeToTransfer)
{
//Call the Mac to transfer the packet
else{
BytesTransfered = 0;
}
-
+
}
else
{
if( fres > (BytesTransfered+HeaderBufferSize+LookaheadBufferSize) )
fres = BytesTransfered+HeaderBufferSize+LookaheadBufferSize;
-
+
//
// Build the header
//
}
else
Ttail+=fres+NPFHdrSize;
-
- //update the buffer
+
+ //update the buffer
NdisAcquireSpinLock( &Open->BufLock );
-
+
if(ResetBuff){
Open->BLastByte = Open->Btail;
}
Open->Btail=Ttail;
-
+
NdisReleaseSpinLock( &Open->BufLock );
}
NdisSetEvent(&Open->DumpEvent);
}
else
- KeSetEvent(Open->ReadEvent,0,FALSE);
+ KeSetEvent(Open->ReadEvent,0,FALSE);
}
-
+
}
}
-
+
return NDIS_STATUS_SUCCESS;
-
+
}
//-------------------------------------------------------------------
POPEN_INSTANCE Open;
IF_LOUD(DbgPrint("NPF: TransferDataComplete\n");)
-
+
Open= (POPEN_INSTANCE)ProtocolBindingContext;
IoFreeMdl(Open->TransferMdl);
NdisSetEvent(&Open->DumpEvent);
}
else
- KeSetEvent(Open->ReadEvent,0,FALSE);
+ KeSetEvent(Open->ReadEvent,0,FALSE);
}
return;
}
//
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
{
- uint32 next_status;
+ uint32 next_status;
uint32 direction=ULONG_AT(mem_data,12);
uint8 flags=mem_ex->buffer[25];
tcp_data *session=(tcp_data*)(block+data->key_len*4);
-
+
session->last_timestamp=session->timestamp_block;
session->timestamp_block.tv_sec=0x7fffffff;
-
+
if (direction==session->direction)
{
session->pkts_cln_to_srv++;
}
/* we use only thes four flags, we don't need PSH or URG */
flags&=(ACK|FIN|SYN|RST);
-
+
switch (session->status)
{
case ERROR_TCP:
next_status=ERROR_TCP;
break;
-
+
case UNKNOWN:
if (flags==SYN)
{
session->seq_n_0_cln=SW_ULONG_AT(mem_ex->buffer,16);
break;
}
-
+
if ((flags==(SYN|ACK))&&(direction!=session->direction))
- {
+ {
if (SW_ULONG_AT(mem_ex->buffer,20)!=session->seq_n_0_cln+1)
{
next_status=ERROR_TCP;
break;
}
next_status=SYN_ACK_RCV;
-
+
session->syn_ack_timestamp=session->last_timestamp;
session->seq_n_0_srv=SW_ULONG_AT(mem_ex->buffer,16);
session->ack_srv=SW_ULONG_AT(mem_ex->buffer,20);
break;
}
-
+
if ((flags==ACK)&&(!(flags&(SYN|FIN|RST)))&&(direction==session->direction))
{
if (SW_ULONG_AT(mem_ex->buffer,20)!=session->seq_n_0_srv+1)
next_status=ERROR_TCP;
break;
-
+
case ESTABLISHED:
if (flags&SYN)
{
next_status=ESTABLISHED;
break;
}
-
+
if ((!(flags&ACK))&&
(direction==session->direction)&&
(SW_ULONG_AT(mem_ex->buffer,16)==session->seq_n_0_cln)&&
next_status=ESTABLISHED;
break;
}
-
+
next_status=ERROR_TCP;
break;
}
}
next_status=ESTABLISHED;
break;
-
+
case CLOSED_RST:
next_status=CLOSED_RST;
break;
-
- case FIN_SRV_RCV:
+
+ case FIN_SRV_RCV:
if (flags&SYN)
{
next_status=ERROR_TCP;
break;
}
-
+
next_status=FIN_SRV_RCV;
-
+
if (flags&ACK)
{
uint32 new_ack=SW_ULONG_AT(mem_ex->buffer,20);
if ((new_ack-session->ack_cln)<MAX_WINDOW)
session->ack_cln=new_ack;
}
-
+
if (flags&RST)
next_status=CLOSED_RST;
else
next_status=ERROR_TCP;
break;
}
-
+
next_status=FIN_CLN_RCV;
-
+
if (flags&ACK)
{
uint32 new_ack=SW_ULONG_AT(mem_ex->buffer,20);
if (new_ack-session->ack_srv<MAX_WINDOW)
session->ack_srv=new_ack;
}
-
+
if (flags&RST)
next_status=CLOSED_RST;
else
}
session->status=next_status;
-
+
if ((next_status==CLOSED_FIN)||(next_status==UNKNOWN)||(next_status==CLOSED_RST)||(next_status==ERROR_TCP))
session->timestamp_block=session->last_timestamp;
-
+
return TME_SUCCESS;
}
if (data->reference!=0)
return;
-
- // get the absolute value of the system boot time.
+
+ // get the absolute value of the system boot time.
PTime=KeQueryPerformanceCounter(&TimeFreq);
KeQuerySystemTime(&SystemTime);
#ifndef __GNUC__
if (data->reference!=0)
return;
-
+
KeInitializeEvent(&event,NotificationEvent,FALSE);
i.QuadPart=-3500000;
KeRaiseIrql(HIGH_LEVEL,&old);
}
reference=delta*(start_freq.QuadPart)/delta2;
data->reference=reference/1000;
- if (reference%1000>500)
+ if (reference%1000>500)
data->reference++;
data->reference*=1000;
reference=data->reference;
/*!
\brief A microsecond precise timestamp.
- included in the sf_pkthdr or the bpf_hdr that NPF associates with every packet.
+ included in the sf_pkthdr or the bpf_hdr that NPF associates with every packet.
*/
struct timeval {
if (data->reference!=0)
return;
-
- // get the absolute value of the system boot time.
+
+ // get the absolute value of the system boot time.
PTime=KeQueryPerformanceCounter(&TimeFreq);
KeQuerySystemTime(&SystemTime);
tmp.tv_sec=(LONG)(SystemTime.QuadPart/10000000-11644473600);
if (data->reference!=0)
return;
-
+
KeInitializeEvent(&event,NotificationEvent,FALSE);
i.QuadPart=-3500000;
KeRaiseIrql(HIGH_LEVEL,&old);
}
reference=delta*(start_freq.QuadPart)/delta2;
data->reference=reference/1000;
- if (reference%1000>500)
+ if (reference%1000>500)
data->reference++;
data->reference*=1000;
reference=data->reference;
#include <net/tme/tme.h>
#endif
-/* resizes extended memory */
+/* resizes extended memory */
uint32 init_extended_memory(uint32 size, MEM_TYPE *mem_ex)
{
uint8 *tmp;
-
+
if ((mem_ex==NULL)||(mem_ex->buffer==NULL)||(size==0))
return TME_ERROR; /* awfully never reached!!!! */
ALLOCATE_MEMORY(tmp,uint8,size);
if (tmp==NULL)
return TME_ERROR; /* no memory */
-
+
mem_ex->size=size;
mem_ex->buffer=tmp;
return TME_SUCCESS;
}
/* activates a block of the TME */
-uint32 set_active_tme_block(TME_CORE *tme, uint32 block)
+uint32 set_active_tme_block(TME_CORE *tme, uint32 block)
{
if ((block>=MAX_TME_DATA_BLOCKS)||(!IS_VALIDATED(tme->validated_blocks,block)))
/* it will be useful to store them in the registry */
uint32 init_tme_block(TME_CORE *tme, uint32 block)
{
-
+
TME_DATA *data;
if (block>=MAX_TME_DATA_BLOCKS)
return TME_ERROR;
data->default_exec=TME_DEFAULT_EXEC_DEFAULT;
/* extra segment size */
data->extra_segment_size=TME_EXTRA_SEGMENT_SIZE_DEFAULT;
-
+
data->enable_deletion=FALSE;
data->last_read.tv_sec=0;
uint32 required_memory;
uint8 *base=mem_ex_offset+mem_ex->buffer;
TME_DATA *data;
-
+
/* FIXME soluzione un po' posticcia... */
if (mem_ex_offset==0)
return TME_ERROR;
if (block>=MAX_TME_DATA_BLOCKS)
return TME_ERROR;
data=&tme->block_data[block];
-
+
if (data->lut_entries==0)
return TME_ERROR;
/* the TME block can be initialized */
ZERO_MEMORY(base,required_memory);
-
+
data->lut_base_address=base;
-
+
data->shared_memory_base_address=
data->lut_base_address+
data->lut_entries*sizeof(RECORD);
tme->working=block;
return TME_SUCCESS;
}
-
+
/* I/F between the bpf machine and the callbacks, just some checks */
uint32 lookup_frontend(MEM_TYPE *mem_ex, TME_CORE *tme,uint32 mem_ex_offset, struct time_conv *time_ref)
{
if (tme->active==TME_NONE_ACTIVE)
return TME_FALSE;
-
+
return (tme->block_data[tme->active].lookup_code)(mem_ex_offset+mem_ex->buffer,&tme->block_data[tme->active],mem_ex, time_ref);
}
/* I/F between the bpf machine and the callbacks, just some checks */
uint32 execute_frontend(MEM_TYPE *mem_ex, TME_CORE *tme, uint32 pkt_size, uint32 offset)
{
-
+
exec_fcn tmp;
TME_DATA *data;
uint8 *block;
return TME_ERROR;
data=&tme->block_data[tme->active];
-
+
if (data->last_found==NULL)
{ /*out lut exec */
tmp=exec_fcn_mapper(data->out_lut_exec);
return TME_ERROR;
}
}
-
+
if (offset>=mem_ex->size)
return TME_ERROR;
-
+
mem_data=mem_ex->buffer+offset;
-
+
return tmp(block,pkt_size,data,mem_ex,mem_data);
}
{
if (tme==NULL)
return TME_ERROR;
- ZERO_MEMORY(tme, sizeof(TME_CORE));
+ ZERO_MEMORY(tme, sizeof(TME_CORE));
return TME_SUCCESS;
}
-
+
/* returns a register value of the active TME block */
/* FIXME last found in maniera elegante e veloce ?!?! */
uint32 get_tme_block_register(TME_DATA *data,MEM_TYPE *mem_ex,uint32 rgstr,uint32 *rval)
case TME_REHASHING_VALUE:
data->rehashing_value=value;
return TME_SUCCESS;
- case TME_FILLED_ENTRIES:
+ case TME_FILLED_ENTRIES:
data->filled_entries=value;
return TME_SUCCESS;
- case TME_FILLED_BLOCKS:
+ case TME_FILLED_BLOCKS:
if (value<=data->shared_memory_blocks)
{
data->filled_blocks=value;
}
else
return TME_ERROR;
- case TME_DEFAULT_EXEC:
+ case TME_DEFAULT_EXEC:
data->default_exec=value;
return TME_SUCCESS;
case TME_OUT_LUT_EXEC:
switch (rgstr)
{
- case TME_LUT_ENTRIES:
+ case TME_LUT_ENTRIES:
data->lut_entries=value;
return TME_SUCCESS;
- case TME_KEY_LEN:
+ case TME_KEY_LEN:
data->key_len=value;
return TME_SUCCESS;
- case TME_SHARED_MEMORY_BLOCKS:
+ case TME_SHARED_MEMORY_BLOCKS:
data->shared_memory_blocks=value;
return TME_SUCCESS;
- case TME_BLOCK_SIZE:
+ case TME_BLOCK_SIZE:
data->block_size=value;
return TME_SUCCESS;
- case TME_EXTRA_SEGMENT_SIZE:
+ case TME_EXTRA_SEGMENT_SIZE:
data->extra_segment_size=value;
return TME_SUCCESS;
default:
}
/* chooses the TME block for read */
-uint32 set_active_read_tme_block(TME_CORE *tme, uint32 block)
+uint32 set_active_read_tme_block(TME_CORE *tme, uint32 block)
{
if ((block>=MAX_TME_DATA_BLOCKS)||(!IS_VALIDATED(tme->validated_blocks,block)))
#endif
/* error codes */
-#define TME_ERROR 0
+#define TME_ERROR 0
#define TME_SUCCESS 1
#define TME_TRUE 2
#define TME_FALSE 3
#define TME_NONE_ACTIVE 0xffffffff
#define DELTA_READ 2 /* secs */
-#define TME_LUT_ENTRIES 0x00000000
+#define TME_LUT_ENTRIES 0x00000000
#define TME_MAX_FILL_STATE 0x00000001 /*potrebbe servire per un thread a passive level!?!?! */
-#define TME_REHASHING_VALUE 0x00000002
+#define TME_REHASHING_VALUE 0x00000002
#define TME_KEY_LEN 0x00000003
#define TME_SHARED_MEMORY_BLOCKS 0x00000004
#define TME_FILLED_ENTRIES 0x00000005
uint32 validated_blocks;
TME_DATA block_data[MAX_TME_DATA_BLOCKS];
uint32 active_read;
-
+
} TME_CORE, *PTME_CORE;
static __inline int32 IS_DELETABLE(void *timestamp, TME_DATA *data)
*
* This code is derived from the Stanford/CMU enet packet filter,
* (net/enet.c) distributed as part of 4.3BSD, and code contributed
- * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
+ * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
* Berkeley Laboratory.
*
* Redistribution and use in source and binary forms, with or without
u_int bf_len;
struct bpf_insn *bf_insns;
};
-
+
/*
* Struct returned by BIOCGSTATS.
*/
};
/*
- * Struct return by BIOCVERSION. This represents the version number of
+ * Struct return by BIOCVERSION. This represents the version number of
* the filter language described by the instruction encodings below.
* bpf understands a program iff kernel_major == filter_major &&
* kernel_minor >= filter_minor, that is, if the value returned by the
/* TME instructions */
#define BPF_TME 0x08
-#define BPF_LOOKUP 0x90
+#define BPF_LOOKUP 0x90
#define BPF_EXECUTE 0xa0
#define BPF_INIT 0xb0
#define BPF_VALIDATE 0xc0
*
* This code is derived from the Stanford/CMU enet packet filter,
* (net/enet.c) distributed as part of 4.3BSD, and code contributed
- * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
+ * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
* Berkeley Laboratory.
*
* Redistribution and use in source and binary forms, with or without
* 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.
-
+
@(#)bpf.c 7.5 (Berkeley) 7/15/91
*/
register int k;
u_int32 j,tmp;
u_short tmp2;
-
+
int32 mem[BPF_MEMWORDS];
if (pc == 0)
switch (pc->code) {
default:
-
+
return 0;
case BPF_RET|BPF_K:
case BPF_LD|BPF_MEM:
A = mem[pc->k];
continue;
-
+
case BPF_LDX|BPF_MEM:
X = mem[pc->k];
continue;
case BPF_LDX|BPF_MEM_EX_IMM|BPF_W:
X = EXTRACT_LONG(&mem_ex->buffer[pc->k]);
continue;
-
+
case BPF_LD|BPF_MEM_EX_IND|BPF_B:
k = X + pc->k;
if ((int32)k>= (int32)mem_ex->size) {
case BPF_ALU|BPF_ADD|BPF_X:
A += X;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_X:
A -= X;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_X:
A *= X;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_X:
if (X == 0)
return 0;
A /= X;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_X:
A &= X;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_X:
A |= X;
continue;
case BPF_ALU|BPF_ADD|BPF_K:
A += pc->k;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_K:
A -= pc->k;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_K:
A *= pc->k;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_K:
A /= pc->k;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_K:
A &= pc->k;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_K:
A |= pc->k;
continue;
case BPF_MISC|BPF_TME|BPF_LOOKUP:
j=lookup_frontend(mem_ex,tme,pc->k,time_ref);
if (j==TME_ERROR)
- return 0;
+ return 0;
pc += (j == TME_TRUE) ? pc->jt : pc->jf;
continue;
register struct bpf_insn *pc;
register u_char *p;
register u_char *pd;
- register int headersize;
+ register int headersize;
u_int wirelen;
register u_int buflen;
PMEM_TYPE mem_ex;
switch (pc->code) {
default:
-
+
return 0;
case BPF_RET|BPF_K:
if (k + sizeof(int32) > buflen) {
return 0;
}
-
+
if(k + (int)sizeof(int32) < headersize) A = EXTRACT_LONG(&p[k]);
else if(k + 2 == headersize){
A=(u_int32)*((u_char *)p+k)<<24|
(u_int32)*((u_char *)pd+k-headersize+3);
}
A = EXTRACT_LONG(&pd[k-headersize]);
-
+
continue;
-
+
case BPF_LD|BPF_H|BPF_ABS:
k = pc->k;
if (k + sizeof(short) > buflen) {
return 0;
}
-
+
if(k + (int)sizeof(short) < headersize) A = EXTRACT_SHORT(&p[k]);
else if(k == headersize){
A=(u_short)*((u_char *)p+k)<<8|
(u_short)*((u_char *)pd+k-headersize);
}
A = EXTRACT_SHORT(&pd[k-headersize]);
-
+
continue;
case BPF_LD|BPF_B|BPF_ABS:
(u_int32)*((u_char *)pd+k-headersize+3);
}
A = EXTRACT_LONG(&pd[k-headersize]);
-
+
continue;
-
+
case BPF_LD|BPF_H|BPF_IND:
k = X + pc->k;
if (k + sizeof(short) > buflen) {
return 0;
}
-
+
if(k + (int)sizeof(short) < headersize) A = EXTRACT_SHORT(&p[k]);
else if(k == headersize){
A=(u_short)*((u_char *)p+k)<<8|
if ((int)k >= (int)buflen) {
return 0;
}
-
+
if((pc->k)<headersize) X = (p[pc->k] & 0xf) << 2;
else X = (pd[(pc->k)-headersize] & 0xf) << 2;
case BPF_LD|BPF_MEM:
A = mem[pc->k];
continue;
-
+
case BPF_LDX|BPF_MEM:
X = mem[pc->k];
continue;
case BPF_LDX|BPF_MEM_EX_IMM|BPF_W:
X = EXTRACT_LONG(&mem_ex->buffer[pc->k]);
continue;
-
+
case BPF_LD|BPF_MEM_EX_IND|BPF_B:
k = X + pc->k;
if ((int32)k>= (int32)mem_ex->size) {
A=EXTRACT_LONG((uint32*)&mem_ex->buffer[k]);
continue;
/* END LD NO PACKET INSTRUCTIONS */
-
+
case BPF_ST:
mem[pc->k] = A;
continue;
*(uint16*)&mem_ex->buffer[pc->k+X]=EXTRACT_SHORT(&tmp2);
continue;
/* END STORE INSTRUCTIONS */
-
-
-
+
+
+
case BPF_JMP|BPF_JA:
pc += pc->k;
continue;
case BPF_ALU|BPF_ADD|BPF_X:
A += X;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_X:
A -= X;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_X:
A *= X;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_X:
if (X == 0)
return 0;
A /= X;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_X:
A &= X;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_X:
A |= X;
continue;
case BPF_ALU|BPF_ADD|BPF_K:
A += pc->k;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_K:
A -= pc->k;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_K:
A *= pc->k;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_K:
A /= pc->k;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_K:
A &= pc->k;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_K:
A |= pc->k;
continue;
case BPF_MISC|BPF_TME|BPF_LOOKUP:
j=lookup_frontend(mem_ex,tme,pc->k,time_ref);
if (j==TME_ERROR)
- return 0;
+ return 0;
pc += (j == TME_TRUE) ? pc->jt : pc->jf;
continue;
bpf_validate(f, len,mem_ex_size)
struct bpf_insn *f;
int32 len;
- uint32 mem_ex_size;
+ uint32 mem_ex_size;
{
register int32 i,j;
register struct bpf_insn *p;
int32 flag;
-
+
for (i = 0; i < len; ++i) {
/*
- * Check that that jumps are forward, and within
+ * Check that that jumps are forward, and within
* the code block.
*/
-
+
p = &f[i];
IF_LOUD(DbgPrint("Validating program");)
-
+
flag=0;
for(j=0;j<VALID_INSTRUCTIONS_LEN;j++)
if (p->code==valid_instructions[j])
return 0;
IF_LOUD(DbgPrint("Validating program: no unknown instructions");)
-
+
if (BPF_CLASS(p->code) == BPF_JMP) {
register int32 from = i + 1;
}
IF_LOUD(DbgPrint("Validating program: no wrong JUMPS");)
-
+
/*
* Check that memory operations use valid addresses.
*/
if (((BPF_CLASS(p->code) == BPF_ST && ((p->code &BPF_MEM_EX_IMM)!=BPF_MEM_EX_IMM && (p->code &BPF_MEM_EX_IND)!=BPF_MEM_EX_IND)) ||
- (BPF_CLASS(p->code) == BPF_LD &&
+ (BPF_CLASS(p->code) == BPF_LD &&
(p->code & 0xe0) == BPF_MEM)) &&
(p->k >= BPF_MEMWORDS || p->k < 0))
return 0;
-
+
IF_LOUD(DbgPrint("Validating program: no wrong ST/LD memory locations");)
-
+
/*
- * Check if key stores use valid addresses
- */
+ * Check if key stores use valid addresses
+ */
if (BPF_CLASS(p->code) == BPF_ST && (p->code &BPF_MEM_EX_IMM)==BPF_MEM_EX_IMM)
switch (BPF_SIZE(p->code))
{
*
* This code is derived from the Stanford/CMU enet packet filter,
* (net/enet.c) distributed as part of 4.3BSD, and code contributed
- * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
+ * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
* Berkeley Laboratory.
*
* Redistribution and use in source and binary forms, with or without
case BPF_LD|BPF_MEM:
A = mem[pc->k];
continue;
-
+
case BPF_LDX|BPF_MEM:
X = mem[pc->k];
continue;
:"=a"(X),"=c"(tmp): );
#endif
continue;
-
+
case BPF_LD|BPF_MEM_EX_IND|BPF_B:
k = X + pc->k;
if ((int32)k>= (int32)mem_ex->size) {
case BPF_ALU|BPF_ADD|BPF_X:
A += X;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_X:
A -= X;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_X:
A *= X;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_X:
if (X == 0)
return 0;
A /= X;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_X:
A &= X;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_X:
A |= X;
continue;
case BPF_ALU|BPF_ADD|BPF_K:
A += pc->k;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_K:
A -= pc->k;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_K:
A *= pc->k;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_K:
A /= pc->k;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_K:
A &= pc->k;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_K:
A |= pc->k;
continue;
case BPF_MISC|BPF_TME|BPF_LOOKUP:
j=lookup_frontend(mem_ex,tme,pc->k,time_ref);
if (j==TME_ERROR)
- return 0;
+ return 0;
pc += (j == TME_TRUE) ? pc->jt : pc->jf;
continue;
if (init_tme_block(tme,pc->k)==TME_ERROR)
return 0;
continue;
-
+
case BPF_MISC|BPF_TME|BPF_VALIDATE:
if (validate_tme_block(mem_ex,tme,A,pc->k)==TME_ERROR)
return 0;
case BPF_MISC|BPF_TME|BPF_SET_AUTODELETION:
set_autodeletion(&tme->block_data[tme->working],pc->k);
continue;
-
+
/* END TME INSTRUCTIONS */
}
for(i=0;i<Open->Nwrites;i++){
-
+
// Try to get a packet from our list of free ones
NdisAllocatePacket(
&Status,
&pPacket,
Open->PacketPool
);
-
+
if (Status != NDIS_STATUS_SUCCESS) {
-
+
// No free packets
Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
IoCompleteRequest (Irp, IO_NO_INCREMENT);
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
// The packet has a buffer that needs not to be freed after every single write
RESERVED(pPacket)->FreeBufAfterWrite = FALSE;
// Save the IRP associated with the packet
RESERVED(pPacket)->Irp=Irp;
-
+
// Attach the writes buffer to the packet
NdisChainBufferAtFront(pPacket,Irp->MdlAddress);
-
+
// Call the MAC
NdisSend(
&Status,
pPacket,
Status
);
-
+
}
-
+
if(i%100==99){
- NdisWaitEvent(&Open->WriteEvent,1000);
+ NdisWaitEvent(&Open->WriteEvent,1000);
NdisResetEvent(&Open->WriteEvent);
}
}
-
+
return(STATUS_PENDING);
}
INT
NPF_BufferedWrite(
- IN PIRP Irp,
- IN PCHAR UserBuff,
- IN ULONG UserBuffSize,
+ IN PIRP Irp,
+ IN PCHAR UserBuff,
+ IN ULONG UserBuffSize,
BOOLEAN Sync)
{
POPEN_INSTANCE Open;
struct sf_pkthdr *winpcap_hdr;
PMDL TmpMdl;
PCHAR EndOfUserBuff = UserBuff + UserBuffSize;
-
+
IF_LOUD(DbgPrint("NPF: BufferedWrite, UserBuff=%x, Size=%u\n", UserBuff, UserBuffSize);)
-
+
IrpSp = IoGetCurrentIrpStackLocation(Irp);
-
+
Open=IrpSp->FileObject->FsContext;
-
+
// Security check on the length of the user buffer
if(UserBuff==0)
{
return 0;
}
-
+
// Check that the MaxFrameSize is correctly initialized
if(Open->MaxFrameSize == 0)
{
return 0;
}
-
+
// Start from the first packet
winpcap_hdr = (struct sf_pkthdr*)UserBuff;
-
+
// Retrieve the time references
StartTicks = KeQueryPerformanceCounter(&TimeFreq);
BufStartTime.tv_sec = winpcap_hdr->ts.tv_sec;
BufStartTime.tv_usec = winpcap_hdr->ts.tv_usec;
-
+
// Chech the consistency of the user buffer
if( (PCHAR)winpcap_hdr + winpcap_hdr->caplen + sizeof(struct sf_pkthdr) > EndOfUserBuff )
{
return -1;
}
-
+
// Save the current time stamp counter
CurTicks = KeQueryPerformanceCounter(NULL);
-
+
// Main loop: send the buffer to the wire
while( TRUE ){
-
+
if(winpcap_hdr->caplen ==0 || winpcap_hdr->caplen > Open->MaxFrameSize)
{
// Malformed header
IF_LOUD(DbgPrint("NPF_BufferedWrite: malformed or bogus user buffer, aborting write.\n");)
-
+
return -1;
}
-
+
// Allocate an MDL to map the packet data
TmpMdl=IoAllocateMdl((PCHAR)winpcap_hdr + sizeof(struct sf_pkthdr),
winpcap_hdr->caplen,
FALSE,
FALSE,
NULL);
-
+
if (TmpMdl == NULL)
{
// Unable to map the memory: packet lost
return -1;
}
-
+
MmBuildMdlForNonPagedPool(TmpMdl); // XXX can this line be removed?
-
+
// Allocate a packet from our free list
NdisAllocatePacket( &Status, &pPacket, Open->PacketPool);
-
+
if (Status != NDIS_STATUS_SUCCESS) {
// No free packets
IF_LOUD(DbgPrint("NPF_BufferedWrite: no more free packets, returning.\n");)
return (PCHAR)winpcap_hdr - UserBuff;
}
-
+
// The packet has a buffer that needs to be freed after every single write
RESERVED(pPacket)->FreeBufAfterWrite = TRUE;
-
+
// Attach the MDL to the packet
NdisChainBufferAtFront(pPacket,TmpMdl);
-
+
// Call the MAC
NdisSend( &Status, Open->AdapterHandle, pPacket);
-
+
if (Status != NDIS_STATUS_PENDING) {
// The send didn't pend so call the completion handler now
NPF_SendComplete(
Open,
pPacket,
Status
- );
+ );
}
-
+
// Step to the next packet in the buffer
winpcap_hdr = (struct sf_pkthdr *)((PCHAR)winpcap_hdr + winpcap_hdr->caplen + sizeof(struct sf_pkthdr));
-
+
// Check if the end of the user buffer has been reached
if( (PCHAR)winpcap_hdr >= EndOfUserBuff )
{
return (PCHAR)winpcap_hdr - UserBuff;
}
-
+
if( Sync ){
// Release the application if it has been blocked for approximately more than 1 seconds
if( winpcap_hdr->ts.tv_sec - BufStartTime.tv_sec > 1 )
{
IF_LOUD(DbgPrint("NPF_BufferedWrite: timestamp elapsed, returning.\n");)
-
+
return (PCHAR)winpcap_hdr - UserBuff;
}
-
+
#ifndef __GNUC__
// Calculate the time interval to wait before sending the next packet
TargetTicks.QuadPart = StartTicks.QuadPart +
#else
#endif
}
-
+
}
-
+
return (PCHAR)winpcap_hdr - UserBuff;
-
+
}
IN PNDIS_PACKET pPacket,
IN NDIS_STATUS Status
)
-
+
{
PIRP Irp;
PIO_STACK_LOCATION irpSp;
POPEN_INSTANCE Open;
PMDL TmpMdl;
-
+
IF_LOUD(DbgPrint("NPF: SendComplete, BindingContext=%d\n",ProtocolBindingContext);)
-
+
Open= (POPEN_INSTANCE)ProtocolBindingContext;
-
+
if( RESERVED(pPacket)->FreeBufAfterWrite ){
// Free the MDL associated with the packet
NdisUnchainBufferAtFront(pPacket, &TmpMdl);
else{
if((Open->Nwrites - Open->Multiple_Write_Counter) %100 == 99)
NdisSetEvent(&Open->WriteEvent);
-
+
Open->Multiple_Write_Counter--;
}
-
+
// recyle the packet
NdisReinitializePacket(pPacket);
-
+
// Put the packet back on the free list
NdisFreePacket(pPacket);
-
+
if( !(RESERVED(pPacket)->FreeBufAfterWrite) ){
if(Open->Multiple_Write_Counter==0){
// Release the buffer and awake the application
NdisUnchainBufferAtFront(pPacket, &TmpMdl);
-
+
Irp=RESERVED(pPacket)->Irp;
irpSp = IoGetCurrentIrpStackLocation(Irp);
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = irpSp->Parameters.Write.Length;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
}
}
/* the key is represented by the initial and final value */
/* of the bucket. At the moment bucket_lookup is able to */
/* manage values of 16, 32 bits. */
-uint32 bucket_lookup(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
+uint32 bucket_lookup(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
{
uint32 value;
uint32 i,j;
if ((data->key_len!=1)&& /*16 bit value*/
(data->key_len!=2)) /*32 bit value*/
return TME_ERROR;
-
+
/*32 bit values*/
blocks=data->filled_blocks-1;
block_size=data->block_size;
if (data->key_len==2)
{
value=SW_ULONG_AT(key,0);
-
+
if((value<SW_ULONG_AT(temp,0))||(value>SW_ULONG_AT(temp+block_size*(blocks-1),4)))
{
uint32 *key32=(uint32*) key;
data->last_found=NULL;
return TME_FALSE;
}
-
+
while(found==-1) /* search routine */
- {
+ {
i=(i==1)? 1:i>>1;
if (SW_ULONG_AT(temp+block_size*j,0)>value)
if (SW_ULONG_AT(temp+block_size*(j-1),4)<value)
else
j-=i;
else
- if (SW_ULONG_AT(temp+block_size*j,4)<value)
+ if (SW_ULONG_AT(temp+block_size*j,4)<value)
if (SW_ULONG_AT(temp+block_size*j,0)>value)
found=-2;
else
j+=i;
else found=j;
- }
+ }
if (found<0)
{
uint32 *key32=(uint32*) key;
key32[0]=key32[1]=0;
GET_TIME((struct timeval *)(data->shared_memory_base_address+8),time_ref);
-
+
data->last_found=NULL;
return TME_FALSE;
}
-
+
data->last_found=data->lut_base_address+found*sizeof(RECORD);
COPY_MEMORY(key,temp+block_size*found,8);
else
{
value=SW_USHORT_AT(key,0);
-
+
if((value<SW_USHORT_AT(temp,0))||(value>SW_USHORT_AT(temp+block_size*(blocks-1),2)))
{
uint16 *key16=(uint16*) key;
key16[0]=key16[1]=0;
-
+
GET_TIME((struct timeval *)(data->shared_memory_base_address+4),time_ref);
data->last_found=NULL;
return TME_FALSE;
}
-
+
while(found==-1) /* search routine */
- {
+ {
i=(i==1)? 1:i>>1;
if (SW_USHORT_AT(temp+block_size*j,0)>value)
if (SW_USHORT_AT(temp+block_size*(j-1),2)<value)
else
j-=i;
else
- if (SW_USHORT_AT(temp+block_size*j,2)<value)
+ if (SW_USHORT_AT(temp+block_size*j,2)<value)
if (SW_USHORT_AT(temp+block_size*j,0)>value)
found=-2;
else
j+=i;
else found=j;
- }
+ }
if (found<0)
{
data->last_found=NULL;
return TME_FALSE;
}
-
+
data->last_found=data->lut_base_address+found*sizeof(RECORD);
GET_TIME((struct timeval *)(temp+block_size*found+4),time_ref);
COPY_MEMORY(key,temp+block_size*found,4);
-
+
return TME_TRUE;
}
-
+
}
-uint32 bucket_lookup_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
-{
+uint32 bucket_lookup_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
+{
RECORD *records=(RECORD*)data->lut_base_address;
if ((data->key_len!=1)&& /*16 bit value*/
uint32 start,stop;
uint8 *tmp;
- start=SW_ULONG_AT(key,0);
+ start=SW_ULONG_AT(key,0);
stop=SW_ULONG_AT(key,4);
if (start>stop)
return TME_ERROR;
if (data->filled_entries>0)
{
- tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries-1].block,0);
+ tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries-1].block,0);
/*check if it is coherent with the previous block*/
if (SW_ULONG_AT(tmp,4)>=start)
return TME_ERROR;
}
-
+
if (data->filled_blocks==data->shared_memory_blocks)
return TME_ERROR;
if (data->filled_entries==data->lut_entries)
return TME_ERROR;
- tmp=data->shared_memory_base_address+data->block_size*data->filled_blocks;
-
+ tmp=data->shared_memory_base_address+data->block_size*data->filled_blocks;
+
COPY_MEMORY(tmp,key,8);
-
+
SW_ULONG_ASSIGN(&records[data->filled_entries].block,tmp-mem_ex->buffer);
SW_ULONG_ASSIGN(&records[data->filled_entries].exec_fcn,data->default_exec);
-
- GET_TIME((struct timeval *)(tmp+8),time_ref);
-
+
+ GET_TIME((struct timeval *)(tmp+8),time_ref);
+
data->filled_blocks++;
data->filled_entries++;
-
+
return TME_TRUE;
}
else
uint16 start,stop;
uint8 *tmp;
- start=SW_USHORT_AT(key,0);
+ start=SW_USHORT_AT(key,0);
stop=SW_USHORT_AT(key,2);
if (start>stop)
return TME_ERROR;
if (data->filled_entries>0)
{
- tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries-1].block,0);
+ tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries-1].block,0);
/*check if it is coherent with the previous block*/
if (SW_USHORT_AT(tmp,2)>=start)
return TME_ERROR;
}
-
+
if (data->filled_blocks==data->shared_memory_blocks)
return TME_ERROR;
if (data->filled_entries==data->lut_entries)
return TME_ERROR;
- tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries].block,0);
-
+ tmp=mem_ex->buffer+SW_ULONG_AT(&records[data->filled_entries].block,0);
+
COPY_MEMORY(tmp,key,4);
-
+
SW_ULONG_ASSIGN(&records[data->filled_entries].block,tmp-mem_ex->buffer);
SW_ULONG_ASSIGN(&records[data->filled_entries].exec_fcn,data->default_exec);
-
- GET_TIME((struct timeval *)(tmp+4),time_ref);
-
+
+ GET_TIME((struct timeval *)(tmp+4),time_ref);
+
data->filled_blocks++;
data->filled_entries++;
-
+
return TME_TRUE;
}
}
uint32 count_packets(uint8 *block, uint32 pkt_size, TME_DATA *data, MEM_TYPE *mem_ex, uint8 *mem_data)
{
-
+
c_p_data *counters=(c_p_data*)(block+data->key_len*4);
counters->bytes+=pkt_size;
counters->packets++;
-
+
return TME_SUCCESS;
}
PDEVICE_OBJECT fsdDevice;
FILE_STANDARD_INFORMATION StandardInfo;
-
+
IF_LOUD(DbgPrint("NPF: OpenDumpFile.\n");)
if(fileName->Buffer[0] == L'\\' &&
PathPrefix = L"\\??\\";
PathLen = 8;
}
-
+
// Insert the correct path prefix.
FullFileNameLength = PathLen + fileName->MaximumLength;
-
+
#define NPF_TAG_FILENAME TAG('0', 'D', 'W', 'A')
- FullFileName.Buffer = ExAllocatePoolWithTag(NonPagedPool,
+ FullFileName.Buffer = ExAllocatePoolWithTag(NonPagedPool,
FullFileNameLength,
NPF_TAG_FILENAME);
-
+
if (FullFileName.Buffer == NULL) {
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
return ntStatus;
}
-
+
FullFileName.Length = PathLen;
FullFileName.MaximumLength = (USHORT)FullFileNameLength;
-
+
if(PathLen)
RtlMoveMemory (FullFileName.Buffer, PathPrefix, PathLen);
-
+
RtlAppendUnicodeStringToString (&FullFileName, fileName);
-
+
IF_LOUD(DbgPrint( "Packet: Attempting to open %wZ\n", &FullFileName);)
-
+
InitializeObjectAttributes ( &ObjectAttributes,
&FullFileName,
OBJ_CASE_INSENSITIVE,
NULL,
NULL );
-
+
// Create the dump file
ntStatus = ZwCreateFile( &Open->DumpFileHandle,
SYNCHRONIZE | FILE_WRITE_DATA,
if ( !NT_SUCCESS( ntStatus ) )
{
IF_LOUD(DbgPrint("NPF: Error opening file %x\n", ntStatus);)
-
+
ExFreePool(FullFileName.Buffer);
Open->DumpFileHandle=NULL;
ntStatus = STATUS_NO_SUCH_FILE;
return ntStatus;
}
-
+
ExFreePool(FullFileName.Buffer);
-
+
ntStatus = ObReferenceObjectByHandle(Open->DumpFileHandle,
FILE_WRITE_ACCESS,
#ifndef __GNUC__
KernelMode,
(PVOID)&Open->DumpFileObject,
0);
-
+
if ( !NT_SUCCESS( ntStatus ) )
{
IF_LOUD(DbgPrint("NPF: Error creating file, status=%x\n", ntStatus);)
-
+
ZwClose( Open->DumpFileHandle );
Open->DumpFileHandle=NULL;
-
+
ntStatus = STATUS_NO_SUCH_FILE;
return ntStatus;
}
-
+
fsdDevice = IoGetRelatedDeviceObject(Open->DumpFileObject);
IF_LOUD(DbgPrint("NPF: Dump: write file created succesfully, status=%d \n",ntStatus);)
return ntStatus;
-}
+}
//-------------------------------------------------------------------
// Detect the medium type
switch (Open->Medium){
-
+
case NdisMediumWan:
hdr.linktype = DLT_EN10MB;
break;
-
+
case NdisMedium802_3:
hdr.linktype = DLT_EN10MB;
break;
-
+
case NdisMediumFddi:
hdr.linktype = DLT_FDDI;
break;
-
- case NdisMedium802_5:
- hdr.linktype = DLT_IEEE802;
+
+ case NdisMedium802_5:
+ hdr.linktype = DLT_IEEE802;
break;
-
+
case NdisMediumArcnet878_2:
hdr.linktype = DLT_ARCNET;
break;
-
+
case NdisMediumAtm:
hdr.linktype = DLT_ATM_RFC1483;
break;
-
+
default:
hdr.linktype = DLT_EN10MB;
}
NULL,
NULL );
-
+
if ( !NT_SUCCESS( ntStatus ) )
{
IF_LOUD(DbgPrint("NPF: Error dumping file %x\n", ntStatus);)
-
+
ZwClose( Open->DumpFileHandle );
Open->DumpFileHandle=NULL;
-
+
ntStatus = STATUS_NO_SUCH_FILE;
return ntStatus;
}
Open->DumpOffset.QuadPart=24;
-
+
ntStatus = PsCreateSystemThread(&Open->DumpThreadHandle,
THREAD_ALL_ACCESS,
(ACCESS_MASK)0L,
0,
(PKSTART_ROUTINE)NPF_DumpThread,
Open);
-
+
if ( !NT_SUCCESS( ntStatus ) )
{
IF_LOUD(DbgPrint("NPF: Error creating dump thread, status=%x\n", ntStatus);)
-
+
ZwClose( Open->DumpFileHandle );
Open->DumpFileHandle=NULL;
return ntStatus;
- }
+ }
ntStatus = ObReferenceObjectByHandle(Open->DumpThreadHandle,
THREAD_ALL_ACCESS,
NULL,
if ( !NT_SUCCESS( ntStatus ) )
{
IF_LOUD(DbgPrint("NPF: Error creating dump thread, status=%x\n", ntStatus);)
-
+
ObDereferenceObject(Open->DumpFileObject);
ZwClose( Open->DumpFileHandle );
Open->DumpFileHandle=NULL;
return ntStatus;
- }
-
+ }
+
return ntStatus;
-
+
}
//-------------------------------------------------------------------
while(TRUE){
// Wait until some packets arrive or the timeout expires
- NdisWaitEvent(&Open->DumpEvent, 5000);
+ NdisWaitEvent(&Open->DumpEvent, 5000);
IF_LOUD(DbgPrint("NPF: Worker Thread - event signalled\n");)
-
+
if(Open->DumpLimitReached ||
Open->BufSize==0){ // BufSize=0 means that this instance was closed, or that the buffer is too
// small for any capture. In both cases it is better to end the dump
PsTerminateSystemThread(STATUS_SUCCESS);
return;
}
-
+
NdisResetEvent(&Open->DumpEvent);
// Write the content of the buffer to the file
PsTerminateSystemThread(STATUS_SUCCESS);
return;
}
-
+
}
-
+
}
//-------------------------------------------------------------------
PMDL lMdl;
UINT SizeToDump;
-
+
Thead=Open->Bhead;
Ttail=Open->Btail;
TLastByte=Open->BLastByte;
-
+
IF_LOUD(DbgPrint("NPF: NPF_SaveCurrentBuffer.\n");)
// Get the address of the buffer
{
// Size limit reached
UINT PktLen;
-
+
SizeToDump = 0;
-
+
// Scan the buffer to detect the exact amount of data to save
while(TRUE){
PktLen = ((struct sf_pkthdr*)(CurrBuff + Thead + SizeToDump))->caplen + sizeof(struct sf_pkthdr);
-
+
if((UINT)Open->DumpOffset.QuadPart + SizeToDump + PktLen > Open->MaxDumpBytes)
break;
-
+
SizeToDump += PktLen;
}
-
+
}
else
SizeToDump = TLastByte-Thead;
-
+
lMdl=IoAllocateMdl(CurrBuff+Thead, SizeToDump, FALSE, FALSE, NULL);
if (lMdl == NULL)
{
IF_LOUD(DbgPrint("NPF: dump thread: Failed to allocate Mdl\n");)
return STATUS_UNSUCCESSFUL;
}
-
+
MmBuildMdlForNonPagedPool(lMdl);
-
+
// Write to disk
NPF_WriteDumpFile(Open->DumpFileObject,
&Open->DumpOffset,
SizeToDump,
lMdl,
&IoStatus);
-
+
IoFreeMdl(lMdl);
-
+
if(!NT_SUCCESS(IoStatus.Status)){
// Error
return STATUS_UNSUCCESSFUL;
}
-
+
if(SizeToDump != TLastByte-Thead){
// Size limit reached.
Open->DumpLimitReached = TRUE;
-
+
// Awake the application
KeSetEvent(Open->ReadEvent,0,FALSE);
return STATUS_UNSUCCESSFUL;
}
-
+
// Update the packet buffer
Open->DumpOffset.QuadPart+=(TLastByte-Thead);
Open->BLastByte=Ttail;
}
if( Ttail > Thead ){
-
+
if(Open->MaxDumpBytes &&
(UINT)Open->DumpOffset.QuadPart + GetBuffOccupation(Open) > Open->MaxDumpBytes)
{
// Size limit reached
UINT PktLen;
-
+
SizeToDump = 0;
-
+
// Scan the buffer to detect the exact amount of data to save
while(Thead + SizeToDump < Ttail){
PktLen = ((struct sf_pkthdr*)(CurrBuff + Thead + SizeToDump))->caplen + sizeof(struct sf_pkthdr);
-
+
if((UINT)Open->DumpOffset.QuadPart + SizeToDump + PktLen > Open->MaxDumpBytes)
break;
-
+
SizeToDump += PktLen;
}
-
+
}
else
SizeToDump = Ttail-Thead;
-
+
lMdl=IoAllocateMdl(CurrBuff+Thead, SizeToDump, FALSE, FALSE, NULL);
if (lMdl == NULL)
{
IF_LOUD(DbgPrint("NPF: dump thread: Failed to allocate Mdl\n");)
return STATUS_UNSUCCESSFUL;
}
-
+
MmBuildMdlForNonPagedPool(lMdl);
-
+
// Write to disk
NPF_WriteDumpFile(Open->DumpFileObject,
&Open->DumpOffset,
SizeToDump,
lMdl,
&IoStatus);
-
+
IoFreeMdl(lMdl);
-
+
if(!NT_SUCCESS(IoStatus.Status)){
// Error
return STATUS_UNSUCCESSFUL;
}
-
+
if(SizeToDump != Ttail-Thead){
// Size limit reached.
Open->DumpLimitReached = TRUE;
// Awake the application
KeSetEvent(Open->ReadEvent,0,FALSE);
-
+
return STATUS_UNSUCCESSFUL;
}
-
+
// Update the packet buffer
- Open->DumpOffset.QuadPart+=(Ttail-Thead);
+ Open->DumpOffset.QuadPart+=(Ttail-Thead);
Open->Bhead=Ttail;
-
+
}
return STATUS_SUCCESS;
NPF_OpenDumpFile(Open,&Open->DumpFileName, TRUE);
- // Flush the buffer to file
+ // Flush the buffer to file
NPF_SaveCurrentBuffer(Open);
// Close The file
ObDereferenceObject(Open->DumpFileObject);
ZwClose( Open->DumpFileHandle );
-
+
Open->DumpFileHandle = NULL;
ObDereferenceObject(Open->DumpFileObject);
//-------------------------------------------------------------------
#ifndef __GNUC__
-static NTSTATUS
+static NTSTATUS
#else
NTSTATUS STDCALL
#endif
// Copy the status information back into the "user" IOSB
*Irp->UserIosb = Irp->IoStatus;
-
+
// Wake up the mainline code
KeSetEvent(Irp->UserEvent, 0, FALSE);
-
+
return STATUS_MORE_PROCESSING_REQUIRED;
}
PIO_STACK_LOCATION ioStackLocation;
PDEVICE_OBJECT fsdDevice = IoGetRelatedDeviceObject(FileObject);
NTSTATUS Status;
-
+
// Set up the event we'll use
KeInitializeEvent(&event, SynchronizationEvent, FALSE);
-
+
// Allocate and build the IRP we'll be sending to the FSD
irp = IoAllocateIrp(fsdDevice->StackSize, FALSE);
case BUCKET_LOOKUP_INSERT:
return (lut_fcn) bucket_lookup_insert;
-
+
default:
return NULL;
}
-
+
return NULL;
}
{
case COUNT_PACKETS:
return (exec_fcn) count_packets;
-
+
case TCP_SESSION:
return (exec_fcn) tcp_session;
default:
return NULL;
}
-
+
return NULL;
}
//
void emit_code(binary_stream *stream, ULONG value, UINT len)
{
-
+
switch (len){
case 1:
break;
default:;
-
+
}
return;
#else
stream.refs=(UINT *)malloc((nins + 1)*sizeof(UINT));
#endif
- if(stream.refs==NULL)
+ if(stream.refs==NULL)
{
return NULL;
}
stream.cur_ip=0;
stream.bpf_pc=0;
- // the first pass will emit the lengths of the instructions
+ // the first pass will emit the lengths of the instructions
// to create the reference table
emitm=emit_lenght;
-
+
for(pass=0;;){
ins = prog;
MOVodd(EBX, EBP, 8)
for(i=0;i<nins;i++){
-
+
stream.bpf_pc++;
-
+
switch (ins->code) {
-
+
default:
-
+
return NULL;
-
+
case BPF_RET|BPF_K:
-
+
MOVid(EAX,ins->k)
POP(EDI)
POP(ESI)
POP(EBX)
POP(EBP)
RET()
-
+
break;
-
+
case BPF_RET|BPF_A:
-
+
POP(EDI)
POP(ESI)
POP(EDX)
POP(EBX)
POP(EBP)
RET()
-
+
break;
-
+
case BPF_LD|BPF_W|BPF_ABS:
-
+
MOVid(ECX,ins->k)
MOVrd(ESI,ECX)
ADDib(ECX,sizeof(INT))
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
- MOVid(EAX,0)
+ MOVid(EAX,0)
MOVobw(AX, EBX, ESI)
SWAP_AX()
break;
-
+
case BPF_LD|BPF_B|BPF_ABS:
-
+
MOVid(ECX,ins->k)
CMPodd(ECX, EBP, 0x10)
JLEb(12)
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
- MOVid(EAX,0)
+ MOVid(EAX,0)
MOVobb(AL,EBX,ECX)
break;
MOVodd(EDX, EBP, 0xc)
break;
-
+
case BPF_LD|BPF_W|BPF_IND:
-
+
MOVid(ECX,ins->k)
ADDrd(ECX,EDX)
MOVrd(ESI,ECX)
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
MOVobd(EAX, EBX, ESI)
BSWAP(EAX)
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
- MOVid(EAX,0)
+ MOVid(EAX,0)
MOVobw(AX, EBX, ESI)
SWAP_AX()
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
- MOVid(EAX,0)
+ MOVid(EAX,0)
MOVobb(AL,EBX,ECX)
break;
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
MOVid(EDX,0)
MOVobb(DL,EBX,ECX)
ANDib(DL, 0xf)
SHLib(EDX, 2)
-
+
break;
case BPF_LD|BPF_IMM:
break;
case BPF_LDX|BPF_IMM:
-
+
MOVid(EDX,ins->k)
break;
CMPid(EAX, ins->k)
JG(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5) // 5 is the size of the following JMP
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
case BPF_JMP|BPF_JGE|BPF_K:
CMPid(EAX, ins->k)
JGE(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
case BPF_JMP|BPF_JEQ|BPF_K:
CMPid(EAX, ins->k)
- JE(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JE(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
MOVrd(ECX,EAX)
ANDid(ECX,ins->k)
JE(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc])
break;
CMPrd(EAX, EDX)
JA(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
case BPF_JMP|BPF_JGE|BPF_X:
CMPrd(EAX, EDX)
JAE(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
CMPrd(EAX, EDX)
JE(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
+ JMP(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc])
break;
MOVrd(ECX,EAX)
ANDrd(ECX,EDX)
JE(stream.refs[stream.bpf_pc+ins->jf]-stream.refs[stream.bpf_pc]+5)
- JMP(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc])
-
+ JMP(stream.refs[stream.bpf_pc+ins->jt]-stream.refs[stream.bpf_pc])
+
break;
case BPF_ALU|BPF_ADD|BPF_X:
ADDrd(EAX,EDX)
-
+
break;
case BPF_ALU|BPF_SUB|BPF_X:
POP(ECX)
POP(EBX)
POP(EBP)
- MOVid(EAX,0)
+ MOVid(EAX,0)
RET()
MOVrd(ECX,EDX)
- MOVid(EDX,0)
+ MOVid(EDX,0)
DIVrd(ECX)
MOVrd(EDX,ECX)
case BPF_ALU|BPF_AND|BPF_X:
ANDrd(EAX,EDX)
-
+
break;
case BPF_ALU|BPF_OR|BPF_X:
case BPF_ALU|BPF_SUB|BPF_K:
SUB_EAXi(ins->k)
-
+
break;
case BPF_ALU|BPF_MUL|BPF_K:
MOVrd(ECX,EDX)
- MOVid(EDX,ins->k)
+ MOVid(EDX,ins->k)
MULrd(EDX)
MOVrd(EDX,ECX)
case BPF_ALU|BPF_DIV|BPF_K:
MOVrd(ECX,EDX)
- MOVid(EDX,0)
+ MOVid(EDX,0)
MOVid(ESI,ins->k)
DIVrd(ESI)
MOVrd(EDX,ECX)
case BPF_ALU|BPF_OR|BPF_K:
ORid(EAX, ins->k)
-
+
break;
case BPF_ALU|BPF_LSH|BPF_K:
}
-
- ins++;
+
+ ins++;
}
pass++;
if(pass == 2) break;
-
+
#ifdef NTKERNEL
#define NPF_TAG_STREAMBUF TAG('1', 'J', 'W', 'A')
stream.ibuf=(CHAR*)ExAllocatePoolWithTag(NonPagedPool, stream.cur_ip, NPF_TAG_STREAMBUF);
#else
stream.ibuf=(CHAR*)malloc(stream.cur_ip);
#endif
- if(stream.ibuf==NULL)
+ if(stream.ibuf==NULL)
{
#ifdef NTKERNEL
ExFreePool(stream.refs);
#endif
return NULL;
}
-
+
// modify the reference table to contain the offsets and not the lengths of the instructions
for(i=1; i< nins + 1; i++)
stream.refs[i]+=stream.refs[i-1];
//////////////////////////////////////////////////////////////
void BPF_Destroy_JIT_Filter(JIT_BPF_Filter *Filter){
-
+
#ifdef NTKERNEL
ExFreePool(Filter->mem);
ExFreePool(Filter->Function);
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
-/** @ingroup NPF
+/** @ingroup NPF
* @{
*/
-/** @defgroup NPF_include NPF structures and definitions
+/** @defgroup NPF_include NPF structures and definitions
* @{
*/
}binary_stream;
-/*! \brief Prototype of a filtering function created by the jitter.
+/*! \brief Prototype of a filtering function created by the jitter.
The syntax and the meaning of the parameters is analogous to the one of bpf_filter(). Notice that the filter
is not among the parameters, because it is hardwired in the function.
emitm(&stream, 0x0f, 1);\
emitm(&stream, 0x87, 1);\
emitm(&stream, off32, 4);
-
+
/// jae off32
#define JAE(off32) \
emitm(&stream, 0x0f, 1);\
/* Prototypes */
/**************************/
-/** @ingroup NPF
+/** @ingroup NPF
* @{
*/
-/** @defgroup NPF_code NPF functions
+/** @defgroup NPF_code NPF functions
* @{
*/
BPF_jitter allocates the buffers for the new native filter and then translates the program pointed by fp
calling BPFtoX86().
-*/
+*/
JIT_BPF_Filter* BPF_jitter(struct bpf_insn *fp, INT nins);
/*!
\param mem Memory used by the x86 function to emulate the RAM of the BPF pseudo processor.
\return The x86 filtering function.
- This function does the hard work for the JIT compilation. It takes a group of BPF pseudo instructions and
+ This function does the hard work for the JIT compilation. It takes a group of BPF pseudo instructions and
through the instruction macros defined in jitter.h it is able to create an function directly executable
by NPF.
-*/
+*/
BPF_filter_function BPFtoX86(struct bpf_insn *ins, UINT nins, INT *mem);
/*!
\brief Deletes a filtering function that was previously created by BPF_jitter().
\param Filter The filter to destroy.
This function frees the variuos buffers (code, memory, etc.) associated with a filtering function.
-*/
+*/
void BPF_Destroy_JIT_Filter(JIT_BPF_Filter *Filter);
/**
(dest)=ExAllocatePool(NonPagedPool,sizeof(type)*(amount)); \
if ((dest)!=NULL) \
RtlZeroMemory((dest),sizeof(type)*(amount)); \
- }
+ }
#define FREE_MEMORY(dest) ExFreePool(dest);
#define ZERO_MEMORY(dest,amount) RtlZeroMemory(dest,amount);
#endif /*WIN_NT_DRIVER*/
-#endif
+#endif
/* if not found, inserts an element */
/* returns TME_TRUE if the entry is found or created, */
/* returns TME_FALSE if no more blocks are available */
-uint32 normal_lut_w_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
+uint32 normal_lut_w_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
{
uint32 i;
uint32 tocs=0;
RECORD *records=(RECORD*)data->lut_base_address;
uint8 *offset;
uint32 key_len=data->key_len;
- /*the key is shrinked into a 32-bit value */
- for (i=0; i<key_len;i++)
+ /*the key is shrinked into a 32-bit value */
+ for (i=0; i<key_len;i++)
shrinked_key^=key32[i];
/*the first index in the table is calculated*/
index=shrinked_key % data->lut_entries;
while (tocs<=data->filled_entries)
- {
+ {
if (records[index].block==0)
{ /*creation of a new entry*/
{
/*no more free blocks*/
GET_TIME((struct timeval *)(data->shared_memory_base_address+4*key_len),time_ref);
- data->last_found=NULL;
+ data->last_found=NULL;
return TME_FALSE;
}
/*with the newly created entry*/
offset=data->shared_memory_base_address+
data->block_size*data->filled_blocks;
-
+
/*copy the key in the block*/
COPY_MEMORY(offset,key32,key_len*4);
GET_TIME((struct timeval *)(offset+4*key_len),time_ref);
SW_ULONG_ASSIGN(&records[index].block,offset-mem_ex->buffer);
data->filled_blocks++;
-
+
/*assign the exec function ID to the entry, in NBO*/
SW_ULONG_ASSIGN(&records[index].exec_fcn,data->default_exec);
data->filled_entries++;
data->last_found=(uint8*)&records[index];
-
- return TME_TRUE;
+
+ return TME_TRUE;
}
/*offset contains the absolute pointer to the block*/
/*associated with the current entry */
- offset=mem_ex->buffer+SW_ULONG_AT(&records[index].block,0);
+ offset=mem_ex->buffer+SW_ULONG_AT(&records[index].block,0);
for (i=0; (i<key_len) && (key32[i]==ULONG_AT(offset,i*4)); i++);
-
+
if (i==key_len)
{
/*key in the block matches the one provided, right entry*/
data->last_found=(uint8*)&records[index];
return TME_TRUE;
}
- else
+ else
{
/* wrong entry, rehashing */
if (IS_DELETABLE(offset+key_len*4,data))
SW_ULONG_ASSIGN(&records[index].exec_fcn,data->default_exec);
GET_TIME((struct timeval*)(offset+key_len*4),time_ref);
data->last_found=(uint8*)&records[index];
- return TME_TRUE;
+ return TME_TRUE;
}
else
{
/* if not found, returns out of count entry index */
/* returns TME_TRUE if the entry is found */
/* returns TME_FALSE if the entry is not found */
-uint32 normal_lut_wo_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
+uint32 normal_lut_wo_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref)
{
uint32 i;
uint32 tocs=0;
RECORD *records=(RECORD*)data->lut_base_address;
uint8 *offset;
uint32 key_len=data->key_len;
- /*the key is shrinked into a 32-bit value */
- for (i=0; i<key_len;i++)
+ /*the key is shrinked into a 32-bit value */
+ for (i=0; i<key_len;i++)
shrinked_key^=key32[i];
/*the first index in the table is calculated*/
index=shrinked_key % data->lut_entries;
while (tocs<=data->filled_entries)
- {
+ {
if (records[index].block==0)
{ /*out of table, insertion is not allowed*/
GET_TIME((struct timeval *)(data->shared_memory_base_address+4*key_len),time_ref);
- data->last_found=NULL;
+ data->last_found=NULL;
return TME_FALSE;
}
/*offset contains the absolute pointer to the block*/
/*associated with the current entry */
-
- offset=mem_ex->buffer+SW_ULONG_AT(&records[index].block,0);
+
+ offset=mem_ex->buffer+SW_ULONG_AT(&records[index].block,0);
for (i=0; (i<key_len) && (key32[i]==ULONG_AT(offset,i*4)); i++);
-
+
if (i==key_len)
{
/*key in the block matches the one provided, right entry*/
data->last_found=(uint8*)&records[index];
return TME_TRUE;
}
- else
+ else
{
/*wrong entry, rehashing*/
index=(index+data->rehashing_value) % data->lut_entries;
#endif
#define NORMAL_LUT_W_INSERT 0x00000000
-uint32 normal_lut_w_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref);
+uint32 normal_lut_w_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref);
#define NORMAL_LUT_WO_INSERT 0x00000001
-uint32 normal_lut_wo_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref);
+uint32 normal_lut_wo_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref);
#define DUMMY_INSERT 1234
#endif
/// Global start time. Used as an absolute reference for timestamp conversion.
struct time_conv G_Start_Time = {
- 0,
- {0, 0},
+ 0,
+ {0, 0},
};
UINT n_Opened_Instances = 0;
// Save or open here
IrpSp->FileObject->FsContext=Open;
-
+
Open->DeviceExtension=DeviceExtension;
-
-
+
+
// Save the Irp here for the completeion routine to retrieve
Open->OpenCloseIrp=Irp;
-
+
// Allocate a packet pool for our xmit and receive packets
NdisAllocatePacketPool(
&Status,
&Open->PacketPool,
TRANSMIT_PACKETS,
sizeof(PACKET_RESERVED));
-
-
+
+
if (Status != NDIS_STATUS_SUCCESS) {
-
+
IF_LOUD(DbgPrint("NPF: Failed to allocate packet pool\n");)
-
+
ExFreePool(Open);
ExFreePool(EvName);
Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
PacketItoa(NamedEventsCounter,(PUCHAR)(Open->ReadEventName.Buffer+21));
InterlockedIncrement(&NamedEventsCounter);
-
+
IF_LOUD(DbgPrint("\nCreated the named event for the read; name=%ws, counter=%d\n", Open->ReadEventName.Buffer,NamedEventsCounter-1);)
//allocate the event objects
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
KeInitializeEvent(Open->ReadEvent, NotificationEvent, FALSE);
KeClearEvent(Open->ReadEvent);
NdisInitializeEvent(&Open->WriteEvent);
// list to hold irp's want to reset the adapter
InitializeListHead(&Open->ResetIrpList);
-
-
+
+
// Initialize the request list
KeInitializeSpinLock(&Open->RequestSpinLock);
InitializeListHead(&Open->RequestList);
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
Open->mem_ex.size = DEFAULT_MEM_EX_SIZE;
RtlZeroMemory(Open->mem_ex.buffer, DEFAULT_MEM_EX_SIZE);
-
+
//
// Initialize the open instance
//
//allocate the spinlock for the buffer pointers
NdisAllocateSpinLock(&Open->BufLock);
-
+
//
// link up the request stored in our open block
//
&Open->RequestList,
&Open->Requests[i].ListElement,
&Open->RequestSpinLock);
-
+
}
-
+
IoMarkIrpPending(Irp);
-
+
//
// Try to open the MAC
//
{
NPF_OpenAdapterComplete(Open,Status,NDIS_STATUS_SUCCESS);
}
-
+
return(STATUS_PENDING);
}
NdisAcquireSpinLock(&Opened_Instances_Lock);
n_Opened_Instances++;
NdisReleaseSpinLock(&Opened_Instances_Lock);
-
+
IF_LOUD(DbgPrint("Opened Instances:%d", n_Opened_Instances);)
// Get the absolute value of the system boot time.
MaxSizeReq->Irp = Irp;
MaxSizeReq->Internal = TRUE;
-
+
MaxSizeReq->Request.RequestType = NdisRequestQueryInformation;
MaxSizeReq->Request.DATA.QUERY_INFORMATION.Oid = OID_GEN_MAXIMUM_TOTAL_SIZE;
-
+
MaxSizeReq->Request.DATA.QUERY_INFORMATION.InformationBuffer = &Open->MaxFrameSize;
MaxSizeReq->Request.DATA.QUERY_INFORMATION.InformationBufferLength = 4;
//free the buffer
Open->BufSize=0;
if(Open->Buffer != NULL)ExFreePool(Open->Buffer);
-
+
//free mem_ex
Open->mem_ex.size = 0;
if(Open->mem_ex.buffer != NULL)ExFreePool(Open->mem_ex.buffer);
-
+
NdisFreePacketPool(Open->PacketPool);
// Free the string with the name of the dump file
if(Open->DumpFileName.Buffer!=NULL)
ExFreePool(Open->DumpFileName.Buffer);
-
+
ExFreePool(Open->ReadEventName.Buffer);
ExFreePool(Open);
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return(STATUS_SUCCESS);
}
Open->OpenCloseIrp = Irp;
IoMarkIrpPending(Irp);
-
+
// If this instance is in dump mode, complete the dump and close the file
if((Open->mode & MODE_DUMP) && Open->DumpFileHandle != NULL){
NTSTATUS wres;
);
if (Status != NDIS_STATUS_PENDING) {
-
+
NPF_CloseAdapterComplete(
Open,
Status
);
return STATUS_SUCCESS;
-
+
}
-
+
return(STATUS_PENDING);
}
// free the allocated structures only if the instance is still bound to the adapter
if(Open->Bound == TRUE){
-
+
// Free the filter if it's present
if(Open->bpfprogram != NULL)
ExFreePool(Open->bpfprogram);
// Free the jitted filter if it's present
if(Open->Filter != NULL)
BPF_Destroy_JIT_Filter(Open->Filter);
-
+
//free the buffer
Open->BufSize = 0;
if(Open->Buffer!=NULL)ExFreePool(Open->Buffer);
-
+
//free mem_ex
Open->mem_ex.size = 0;
if(Open->mem_ex.buffer != NULL)ExFreePool(Open->mem_ex.buffer);
-
+
NdisFreePacketPool(Open->PacketPool);
-
+
Irp=Open->OpenCloseIrp;
-
+
// Free the string with the name of the dump file
if(Open->DumpFileName.Buffer!=NULL)
ExFreePool(Open->DumpFileName.Buffer);
ExFreePool(Open->ReadEventName.Buffer);
ExFreePool(Open);
-
+
// Complete the request only if the instance is still bound to the adapter
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
WCHAR* bindT;
PKEY_VALUE_PARTIAL_INFORMATION tcpBindingsP;
UNICODE_STRING macName;
-
+
// This driver at the moment works only on single processor machines
if(NdisSystemProcessorCount() != 1){
return STATUS_IMAGE_MP_UP_MISMATCH;
return Status;
}
-
+
NdisAllocateSpinLock(&Opened_Instances_Lock);
// Set up the device driver entry points.
if (Status != STATUS_SUCCESS) {
- IF_LOUD(DbgPrint("Trying dynamic binding\n");)
+ IF_LOUD(DbgPrint("Trying dynamic binding\n");)
*/
bindP = getAdaptersList();
IF_LOUD(DbgPrint("Adapters not found in the registry, try to copy the bindings of TCP-IP.\n");)
tcpBindingsP = getTcpBindings();
-
+
if (tcpBindingsP == NULL){
IF_LOUD(DbgPrint("TCP-IP not found, quitting.\n");)
goto RegistryError;
}
-
+
bindP = (WCHAR*)tcpBindingsP;
bindT = (WCHAR*)(tcpBindingsP->Data);
} else {
NTSTATUS status;
HANDLE keyHandle;
UINT BufPos=0;
-
+
#define NPF_TAG_DEVICENAME TAG('0', 'P', 'W', 'A')
PWCHAR DeviceNames = (PWCHAR) ExAllocatePoolWithTag(PagedPool, 4096, NPF_TAG_DEVICENAME);
-
+
if (DeviceNames == NULL) {
IF_LOUD(DbgPrint("Unable the allocate the buffer for the list of the network adapters\n");)
return NULL;
}
-
+
InitializeObjectAttributes(&objAttrs, &AdapterListKey,
OBJ_CASE_INSENSITIVE, NULL, NULL);
status = ZwOpenKey(&keyHandle, KEY_READ, &objAttrs);
KEY_VALUE_PARTIAL_INFORMATION valueInfo;
CHAR AdapInfo[1024];
UINT i=0;
-
+
IF_LOUD(DbgPrint("getAdaptersList: scanning the list of the adapters in the registry, DeviceNames=%x\n",DeviceNames);)
-
+
// Scan the list of the devices
while((status=ZwEnumerateKey(keyHandle,i,KeyBasicInformation,AdapInfo,sizeof(AdapInfo),&resultLength))==STATUS_SUCCESS) {
WCHAR ExportKeyName [512];
HANDLE ExportKeyHandle;
KEY_VALUE_PARTIAL_INFORMATION valueInfo;
ULONG resultLength;
-
+
RtlCopyMemory(ExportKeyName,
ExportKeyPrefix,
ExportKeyPrefixSize);
-
+
RtlCopyMemory((PCHAR)ExportKeyName+ExportKeyPrefixSize,
tInfo->Name,
tInfo->NameLength+2);
-
+
RtlCopyMemory((PCHAR)ExportKeyName+ExportKeyPrefixSize+tInfo->NameLength,
LinkageKeyPrefix,
LinkageKeyPrefixSize);
-
+
IF_LOUD(DbgPrint("Key name=%ws\n", ExportKeyName);)
-
+
RtlInitUnicodeString(&AdapterKeyName, ExportKeyName);
-
+
InitializeObjectAttributes(&objAttrs, &AdapterKeyName,
OBJ_CASE_INSENSITIVE, NULL, NULL);
-
+
status=ZwOpenKey(&ExportKeyHandle,KEY_READ,&objAttrs);
-
+
if (!NT_SUCCESS(status)) {
DbgPrint("OpenKey Failed, %d!\n",status);
i++;
continue;
}
-
+
status = ZwQueryValueKey(ExportKeyHandle, &FinalExportKey,
KeyValuePartialInformation, &valueInfo,
sizeof(valueInfo), &resultLength);
-
+
if (!NT_SUCCESS(status) && (status != STATUS_BUFFER_OVERFLOW)) {
IF_LOUD(DbgPrint("\n\nStatus of %x querying key value for size\n", status);)
} else { // We know how big it needs to be.
valueInfoP->DataLength);
BufPos+=valueInfoP->DataLength-2;
}
-
+
ExFreePool(valueInfoP);
} else {
IF_LOUD(DbgPrint("Error Allocating the buffer for the device name\n");)
}
-
+
}
-
+
// terminate the buffer
DeviceNames[BufPos/2]=0;
DeviceNames[BufPos/2+1]=0;
-
+
ZwClose (ExportKeyHandle);
i++;
-
+
}
-
+
ZwClose (keyHandle);
-
+
}
if(BufPos==0){
ExFreePool(DeviceNames);
#define NPF_TAG_KEYVALUE2 TAG('2', 'P', 'W', 'A')
PKEY_VALUE_PARTIAL_INFORMATION valueInfoP =
(PKEY_VALUE_PARTIAL_INFORMATION)ExAllocatePoolWithTag(PagedPool, valueInfoLength, NPF_TAG_KEYVALUE2);
-
+
if (valueInfoP != NULL) {
status = ZwQueryValueKey(keyHandle, &bindValueName,
KeyValuePartialInformation,
valueInfoP,
valueInfoLength, &resultLength);
-
+
if (!NT_SUCCESS(status)) {
IF_LOUD(DbgPrint("\n\nStatus of %x querying key value\n", status);)
}
deviceName.MaximumLength = (USHORT)(amacNameP->Length + NPF_Prefix.Length + sizeof(UNICODE_NULL));
#define NPF_TAG_DEVICENAMEBUF TAG('3', 'P', 'W', 'A')
deviceName.Buffer = ExAllocatePoolWithTag(PagedPool, deviceName.MaximumLength, NPF_TAG_DEVICENAMEBUF);
-
+
if (deviceName.Buffer == NULL)
return FALSE;
deviceSymLink.Length = 0;
- deviceSymLink.MaximumLength =(USHORT)(amacNameP->Length-devicePrefix.Length
- + symbolicLinkPrefix.Length
- + NPF_Prefix.Length
+ deviceSymLink.MaximumLength =(USHORT)(amacNameP->Length-devicePrefix.Length
+ + symbolicLinkPrefix.Length
+ + NPF_Prefix.Length
+ sizeof(UNICODE_NULL));
#define NPF_TAG_SYMLINKBUF TAG('3', 'P', 'W', 'A')
RtlAppendUnicodeStringToString(&deviceName, &NPF_Prefix);
RtlAppendUnicodeToString(&deviceName, amacNameP->Buffer +
devicePrefix.Length / sizeof(WCHAR));
-
+
RtlAppendUnicodeStringToString(&deviceSymLink, &symbolicLinkPrefix);
RtlAppendUnicodeStringToString(&deviceSymLink, &NPF_Prefix);
RtlAppendUnicodeToString(&deviceSymLink, amacNameP->Buffer +
devicePrefix.Length / sizeof(WCHAR));
IF_LOUD(DbgPrint("Creating device name: %ws\n", deviceName.Buffer);)
-
- status = IoCreateDevice(adriverObjectP,
+
+ status = IoCreateDevice(adriverObjectP,
sizeof(PDEVICE_EXTENSION),
- &deviceName,
+ &deviceName,
FILE_DEVICE_TRANSPORT,
0,
FALSE,
return TRUE;
}
-
- else
+
+ else
{
IF_LOUD(DbgPrint("\n\nIoCreateDevice status = %x\n", status););
ExFreePool(deviceName.Buffer);
ExFreePool(deviceSymLink.Buffer);
-
+
return FALSE;
}
}
PDEVICE_OBJECT DeviceObject;
PDEVICE_OBJECT OldDeviceObject;
PDEVICE_EXTENSION DeviceExtension;
-
+
NDIS_HANDLE NdisProtocolHandle;
NDIS_STATUS Status;
-
+
NDIS_STRING SymLink;
IF_LOUD(DbgPrint("NPF: Unload\n"););
while (DeviceObject != NULL) {
OldDeviceObject=DeviceObject;
-
+
DeviceObject=DeviceObject->NextDevice;
DeviceExtension = OldDeviceObject->DeviceExtension;
if (DeviceExtension->ExportString)
{
RtlInitUnicodeString(&SymLink , DeviceExtension->ExportString);
-
+
IF_LOUD(DbgPrint("Deleting SymLink at %p\n", SymLink.Buffer););
IoDeleteSymbolicLink(&SymLink);
BOOLEAN IsExtendedFilter=FALSE;
IF_LOUD(DbgPrint("NPF: IoControl\n");)
-
+
IrpSp = IoGetCurrentIrpStackLocation(Irp);
FunctionCode=IrpSp->Parameters.DeviceIoControl.IoControlCode;
Open=IrpSp->FileObject->FsContext;
Irp->IoStatus.Status = STATUS_SUCCESS;
IF_LOUD(DbgPrint("NPF: Function code is %08lx buff size=%08lx %08lx\n",FunctionCode,IrpSp->Parameters.DeviceIoControl.InputBufferLength,IrpSp->Parameters.DeviceIoControl.OutputBufferLength);)
-
+
switch (FunctionCode){
-
+
case BIOCGSTATS: //function to get the capture stats
-
- if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength < 4*sizeof(INT)){
+
+ if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength < 4*sizeof(INT)){
EXIT_FAILURE(0);
}
*(((PUINT)Irp->UserBuffer)) = Open->Received;
*(((PUINT)Irp->UserBuffer)+1) = Open->Dropped;
*(((PUINT)Irp->UserBuffer)+2) = 0; // Not yet supported
-
+
EXIT_SUCCESS(4*sizeof(INT));
-
+
break;
-
+
case BIOCGEVNAME: //function to get the name of the event associated with the current instance
- if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength<26){
+ if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength<26){
EXIT_FAILURE(0);
}
{
EXIT_SUCCESS(WriteRes);
}
-
+
EXIT_FAILURE(WriteRes);
break;
- case BIOCSETF:
-
+ case BIOCSETF:
+
// Free the previous buffer if it was present
if(Open->bpfprogram!=NULL){
TmpBPFProgram=Open->bpfprogram;
Open->bpfprogram = NULL;
ExFreePool(TmpBPFProgram);
}
-
+
if (Open->Filter!=NULL)
{
JIT_BPF_Filter *OldFilter=Open->Filter;
Open->Filter=NULL;
BPF_Destroy_JIT_Filter(OldFilter);
}
-
+
// Get the pointer to the new program
prog=(PUCHAR)Irp->AssociatedIrp.SystemBuffer;
-
+
if(prog==NULL){
IF_LOUD(DbgPrint("0001");)
-
+
EXIT_FAILURE(0);
}
-
+
insns=(IrpSp->Parameters.DeviceIoControl.InputBufferLength)/sizeof(struct bpf_insn);
-
+
//count the number of operative instructions
for (cnt=0;(cnt<insns) &&(((struct bpf_insn*)prog)[cnt].code!=BPF_SEPARATION); cnt++);
-
+
IF_LOUD(DbgPrint("Operative instructions=%u\n",cnt);)
- if (((struct bpf_insn*)prog)[cnt].code==BPF_SEPARATION && (insns-cnt-1)!=0)
+ if (((struct bpf_insn*)prog)[cnt].code==BPF_SEPARATION && (insns-cnt-1)!=0)
{
IF_LOUD(DbgPrint("Initialization instructions=%u\n",insns-cnt-1);)
-
+
IsExtendedFilter=TRUE;
initprogram=&((struct bpf_insn*)prog)[cnt+1];
-
+
if(bpf_filter_init(initprogram,&(Open->mem_ex),&(Open->tme), &G_Start_Time)!=INIT_OK)
{
-
+
IF_LOUD(DbgPrint("Error initializing NPF machine (bpf_filter_init)\n");)
-
+
EXIT_FAILURE(0);
}
}
//the NPF processor has been initialized, we have to validate the operative instructions
insns=cnt;
-
+
if(bpf_validate((struct bpf_insn*)prog,cnt,Open->mem_ex.size)==0)
{
IF_LOUD(DbgPrint("Error validating program");)
- //FIXME: the machine has been initialized(?), but the operative code is wrong.
+ //FIXME: the machine has been initialized(?), but the operative code is wrong.
//we have to reset the machine!
//something like: reallocate the mem_ex, and reset the tme_core
EXIT_FAILURE(0);
}
-
+
// Allocate the memory to contain the new filter program
// We could need the original BPF binary if we are forced to use bpf_filter_with_2_buffers()
#define NPF_TAG_BPFPROG TAG('4', 'P', 'W', 'A')
// no memory
EXIT_FAILURE(0);
}
-
+
//copy the program in the new buffer
RtlCopyMemory(TmpBPFProgram,prog,cnt*sizeof(struct bpf_insn));
Open->bpfprogram=TmpBPFProgram;
-
+
// Create the new JIT filter function
if(!IsExtendedFilter)
if((Open->Filter=BPF_jitter((struct bpf_insn*)Open->bpfprogram,cnt)) == NULL) {
Open->Bhead = 0;
Open->Btail = 0;
(INT)Open->BLastByte = -1;
- Open->Received = 0;
+ Open->Received = 0;
Open->Dropped = 0;
Open->Accepted = 0;
EXIT_SUCCESS(IrpSp->Parameters.DeviceIoControl.InputBufferLength);
-
- break;
-
+
+ break;
+
case BIOCSMODE: //set the capture mode
-
+
mode=*((PULONG)Irp->AssociatedIrp.SystemBuffer);
-
+
if(mode == MODE_CAPT){
Open->mode=MODE_CAPT;
-
+
EXIT_SUCCESS(0);
}
else if (mode==MODE_MON){
Open->mode=MODE_MON;
EXIT_SUCCESS(0);
- }
+ }
else{
if(mode & MODE_STAT){
Open->mode = MODE_STAT;
Open->Nbytes.QuadPart=0;
Open->Npackets.QuadPart=0;
-
+
if(Open->TimeOut.QuadPart==0)Open->TimeOut.QuadPart=-10000000;
-
+
}
-
+
if(mode & MODE_DUMP){
-
+
Open->mode |= MODE_DUMP;
Open->MinToCopy=(Open->BufSize<2000000)?Open->BufSize/2:1000000;
-
- }
+
+ }
EXIT_SUCCESS(0);
}
-
+
EXIT_FAILURE(0);
-
+
break;
case BIOCSETDUMPFILENAME:
if(Open->mode & MODE_DUMP)
{
-
+
// Close current dump file
if(Open->DumpFileHandle != NULL){
NPF_CloseDumpFile(Open);
Open->DumpFileHandle = NULL;
}
-
+
if(IrpSp->Parameters.DeviceIoControl.InputBufferLength == 0){
EXIT_FAILURE(0);
}
-
+
// Allocate the buffer that will contain the string
#define NPF_TAG_DUMPNAMEBUF TAG('5', 'P', 'W', 'A')
DumpNameBuff=ExAllocatePoolWithTag(NonPagedPool, IrpSp->Parameters.DeviceIoControl.InputBufferLength, NPF_TAG_DUMPNAMEBUF);
IF_LOUD(DbgPrint("NPF: unable to allocate the dump filename: not enough memory or name already set\n");)
EXIT_FAILURE(0);
}
-
+
// Copy the buffer
- RtlCopyBytes((PVOID)DumpNameBuff,
- Irp->AssociatedIrp.SystemBuffer,
+ RtlCopyBytes((PVOID)DumpNameBuff,
+ Irp->AssociatedIrp.SystemBuffer,
IrpSp->Parameters.DeviceIoControl.InputBufferLength);
-
- // Force a \0 at the end of the filename to avoid that malformed strings cause RtlInitUnicodeString to crash the system
+
+ // Force a \0 at the end of the filename to avoid that malformed strings cause RtlInitUnicodeString to crash the system
((SHORT*)DumpNameBuff)[IrpSp->Parameters.DeviceIoControl.InputBufferLength/2-1]=0;
-
+
// Create the unicode string
RtlInitUnicodeString(&Open->DumpFileName, DumpNameBuff);
-
+
IF_LOUD(DbgPrint("NPF: dump file name set to %ws, len=%d\n",
Open->DumpFileName.Buffer,
IrpSp->Parameters.DeviceIoControl.InputBufferLength);)
-
+
// Try to create the file
if ( NT_SUCCESS( NPF_OpenDumpFile(Open,&Open->DumpFileName,FALSE)) &&
NT_SUCCESS( NPF_StartDump(Open))){
-
+
EXIT_SUCCESS(0);
}
}
-
+
EXIT_FAILURE(0);
-
+
break;
-
+
case BIOCSETDUMPLIMITS:
Open->MaxDumpBytes = *(PULONG)Irp->AssociatedIrp.SystemBuffer;
break;
case BIOCISDUMPENDED:
- if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength < 4){
+ if(IrpSp->Parameters.DeviceIoControl.OutputBufferLength < 4){
EXIT_FAILURE(0);
}
break;
case BIOCSETBUFFERSIZE:
-
+
// Get the number of bytes to allocate
dim = *((PULONG)Irp->AssociatedIrp.SystemBuffer);
Open->Bhead = 0;
Open->Btail = 0;
(INT)Open->BLastByte = -1;
-
+
Open->BufSize = (UINT)dim;
EXIT_SUCCESS(dim);
-
+
break;
-
+
case BIOCSRTIMEOUT: //set the timeout on the read calls
-
+
timeout = *((PULONG)Irp->AssociatedIrp.SystemBuffer);
if((int)timeout==-1)
Open->TimeOut.QuadPart=(LONGLONG)IMMEDIATE;
//IF_LOUD(DbgPrint("NPF: read timeout set to %d:%d\n",Open->TimeOut.HighPart,Open->TimeOut.LowPart);)
EXIT_SUCCESS(timeout);
-
+
break;
-
+
case BIOCSWRITEREP: //set the writes repetition number
-
+
Open->Nwrites = *((PULONG)Irp->AssociatedIrp.SystemBuffer);
-
+
EXIT_SUCCESS(Open->Nwrites);
-
+
break;
case BIOCSMINTOCOPY: //set the minimum buffer's size to copy to the application
Open->MinToCopy = *((PULONG)Irp->AssociatedIrp.SystemBuffer);
-
+
EXIT_SUCCESS(Open->MinToCopy);
-
+
break;
-
+
case IOCTL_PROTOCOL_RESET:
-
+
IF_LOUD(DbgPrint("NPF: IoControl - Reset request\n");)
IoMarkIrpPending(Irp);
IF_LOUD(DbgPrint("NPF: IoControl - ResetComplete being called\n");)
NPF_ResetComplete(Open,Status);
}
-
+
break;
-
-
+
+
case BIOCSETOID:
case BIOCQUERYOID:
-
+
// Extract a request from the list of free ones
RequestListEntry=ExInterlockedRemoveHeadList(&Open->RequestList,&Open->RequestSpinLock);
if (RequestListEntry == NULL)
pRequest->Irp=Irp;
pRequest->Internal = FALSE;
-
+
//
// See if it is an Ndis request
//
OidData=Irp->AssociatedIrp.SystemBuffer;
-
+
if (((FunctionCode == BIOCSETOID) || (FunctionCode == BIOCQUERYOID))
&&
(IrpSp->Parameters.DeviceIoControl.InputBufferLength == IrpSp->Parameters.DeviceIoControl.OutputBufferLength)
(IrpSp->Parameters.DeviceIoControl.InputBufferLength >= sizeof(PACKET_OID_DATA))
&&
(IrpSp->Parameters.DeviceIoControl.InputBufferLength >= sizeof(PACKET_OID_DATA)-1+OidData->Length)) {
-
+
IF_LOUD(DbgPrint("NPF: IoControl: Request: Oid=%08lx, Length=%08lx\n",OidData->Oid,OidData->Length);)
-
+
//
// The buffer is valid
//
if (FunctionCode == BIOCSETOID){
-
+
pRequest->Request.RequestType=NdisRequestSetInformation;
pRequest->Request.DATA.SET_INFORMATION.Oid=OidData->Oid;
-
+
pRequest->Request.DATA.SET_INFORMATION.InformationBuffer=OidData->Data;
pRequest->Request.DATA.SET_INFORMATION.InformationBufferLength=OidData->Length;
} else{
pRequest->Request.RequestType=NdisRequestQueryInformation;
pRequest->Request.DATA.QUERY_INFORMATION.Oid=OidData->Oid;
-
+
pRequest->Request.DATA.QUERY_INFORMATION.InformationBuffer=OidData->Data;
pRequest->Request.DATA.QUERY_INFORMATION.InformationBufferLength=OidData->Length;
-
+
}
NdisResetEvent(&Open->IOEvent);
Open->AdapterHandle,
&pRequest->Request
);
-
+
} else {
//
// buffer too small
Status=NDIS_STATUS_FAILURE;
pRequest->Request.DATA.SET_INFORMATION.BytesRead=0;
pRequest->Request.DATA.QUERY_INFORMATION.BytesWritten=0;
-
+
}
-
+
if (Status != NDIS_STATUS_PENDING) {
IF_LOUD(DbgPrint("NPF: Calling RequestCompleteHandler\n");)
-
+
NPF_RequestComplete(Open, &pRequest->Request, Status);
return Status;
-
+
}
NdisWaitEvent(&Open->IOEvent, 5000);
return(Open->IOStatus);
-
+
break;
-
-
+
+
default:
-
+
EXIT_FAILURE(0);
}
-
+
return Status;
}
// Put the request in the list of the free ones
ExInterlockedInsertTailList(&Open->RequestList, &pRequest->ListElement, &Open->RequestSpinLock);
-
+
if(Status != NDIS_STATUS_SUCCESS)
Open->MaxFrameSize = 1514; // Assume Ethernet
*MacDriverName = ExAllocatePool(PagedPool, 50 * sizeof(WCHAR));
//memcpy(*MacDriverName, L"\\Device\\ne2000", 15 * sizeof(WCHAR));
memcpy(*MacDriverName, L"\\Device\\ne2000", 15 * sizeof(WCHAR));
-
+
*PacketDriverName = ExAllocatePool(PagedPool, 50 * sizeof(WCHAR));
memcpy(*PacketDriverName, L"\\Device\\NPF_ne2000", 19 * sizeof(WCHAR));
Status = STATUS_SUCCESS;
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
-/** @ingroup NPF
+/** @ingroup NPF
* @{
*/
-/** @defgroup NPF_include NPF structures and definitions
+/** @defgroup NPF_include NPF structures and definitions
* @{
*/
#ifndef __PACKET_INCLUDE______
#define __PACKET_INCLUDE______
-#define NTKERNEL ///< Forces the compilation of the jitter with kernel calls
+#define NTKERNEL ///< Forces the compilation of the jitter with kernel calls
#ifdef __GNUC__
#undef EXIT_SUCCESS
#define MAX_REQUESTS 32 ///< Maximum number of simultaneous IOCTL requests.
#define Packet_ALIGNMENT sizeof(int) ///< Alignment macro. Defines the alignment size.
-#define Packet_WORDALIGN(x) (((x)+(Packet_ALIGNMENT-1))&~(Packet_ALIGNMENT-1)) ///< Alignment macro. Rounds up to the next
- ///< even multiple of Packet_ALIGNMENT.
+#define Packet_WORDALIGN(x) (((x)+(Packet_ALIGNMENT-1))&~(Packet_ALIGNMENT-1)) ///< Alignment macro. Rounds up to the next
+ ///< even multiple of Packet_ALIGNMENT.
/***************************/
\brief IOCTL code: set kernel buffer size.
This IOCTL is used to set a new size of the circular buffer associated with an instance of NPF.
- When a BIOCSETBUFFERSIZE command is received, the driver frees the old buffer, allocates the new one
- and resets all the parameters associated with the buffer in the OPEN_INSTANCE structure. The currently
+ When a BIOCSETBUFFERSIZE command is received, the driver frees the old buffer, allocates the new one
+ and resets all the parameters associated with the buffer in the OPEN_INSTANCE structure. The currently
buffered packets are lost.
*/
#define BIOCSETBUFFERSIZE 9592
/*!
\brief IOCTL code: set packet filtering program.
- This IOCTL sets a new packet filter in the driver. Before allocating any memory for the new filter, the
- bpf_validate() function is called to check the correctness of the filter. If this function returns TRUE,
- the filter is copied to the driver's memory, its address is stored in the bpfprogram field of the
- OPEN_INSTANCE structure associated with current instance of the driver, and the filter will be applied to
- every incoming packet. This command also empties the circular buffer used by current instance
+ This IOCTL sets a new packet filter in the driver. Before allocating any memory for the new filter, the
+ bpf_validate() function is called to check the correctness of the filter. If this function returns TRUE,
+ the filter is copied to the driver's memory, its address is stored in the bpfprogram field of the
+ OPEN_INSTANCE structure associated with current instance of the driver, and the filter will be applied to
+ every incoming packet. This command also empties the circular buffer used by current instance
to store packets. This is done to avoid the presence in the buffer of packets that do not match the filter.
*/
#define BIOCSETF 9030
/*!
\brief IOCTL code: get the capture stats
- This command returns to the application the number of packets received and the number of packets dropped by
+ This command returns to the application the number of packets received and the number of packets dropped by
an instance of the driver.
*/
#define BIOCGSTATS 9031
/*!
\brief IOCTL code: set number of physical repetions of every packet written by the app
- Sets the number of times a single write call must be repeated. This command sets the OPEN_INSTANCE::Nwrites
+ Sets the number of times a single write call must be repeated. This command sets the OPEN_INSTANCE::Nwrites
member, and is used to implement the 'multiple write' feature of the driver.
*/
#define BIOCSWRITEREP 7413
/*!
\brief IOCTL code: set an OID value
- This IOCTL is used to perform an OID set operation on the NIC driver.
+ This IOCTL is used to perform an OID set operation on the NIC driver.
*/
#define BIOCSETOID 2147483648U
/*!
\brief IOCTL code: get an OID value
- This IOCTL is used to perform an OID get operation on the NIC driver.
+ This IOCTL is used to perform an OID get operation on the NIC driver.
*/
#define BIOCQUERYOID 2147483652U
\brief IOCTL code: Send a buffer containing multiple packets to the network, ignoring the timestamps.
Command used to send a buffer of packets in a single system call. Every packet in the buffer is preceded by
- a sf_pkthdr structure. The timestamps of the packets are ignored, i.e. the packets are sent as fast as
+ a sf_pkthdr structure. The timestamps of the packets are ignored, i.e. the packets are sent as fast as
possible. The NPF_BufferedWrite() function is invoked to send the packets.
*/
#define BIOCSENDPACKETSNOSYNC 9032
\brief IOCTL code: Send a buffer containing multiple packets to the network, considering the timestamps.
Command used to send a buffer of packets in a single system call. Every packet in the buffer is preceded by
- a sf_pkthdr structure. The timestamps of the packets are used to synchronize the write, i.e. the packets
+ a sf_pkthdr structure. The timestamps of the packets are used to synchronize the write, i.e. the packets
are sent to the network respecting the intervals specified in the sf_pkthdr structure assiciated with each
- packet. NPF_BufferedWrite() function is invoked to send the packets.
+ packet. NPF_BufferedWrite() function is invoked to send the packets.
*/
#define BIOCSENDPACKETSSYNC 9033
#define IMMEDIATE 1 ///< Immediate timeout. Forces a read call to return immediately.
-// The following definitions are used to provide compatibility
+// The following definitions are used to provide compatibility
// of the dump files with the ones of libpcap
#define TCPDUMP_MAGIC 0xa1b2c3d4 ///< Libpcap magic number. Used by programs like tcpdump to recognize a driver's generated dump file.
#define PCAP_VERSION_MAJOR 2 ///< Major libpcap version of the dump file. Used by programs like tcpdump to recognize a driver's generated dump file.
Used when a driver instance is set in dump mode to create a libpcap-compatible file.
*/
-struct packet_file_header
+struct packet_file_header
{
UINT magic; ///< Libpcap magic number
USHORT version_major; ///< Libpcap major version
*/
struct sf_pkthdr {
struct timeval ts; ///< time stamp
- UINT caplen; ///< Length of captured portion. The captured portion can be different from
- ///< the original packet, because it is possible (with a proper filter) to
- ///< instruct the driver to capture only a portion of the packets.
+ UINT caplen; ///< Length of captured portion. The captured portion can be different from
+ ///< the original packet, because it is possible (with a proper filter) to
+ ///< instruct the driver to capture only a portion of the packets.
UINT len; ///< Length of the original packet (off wire).
};
/*!
\brief Stores an OID request.
-
- This structure is used by the driver to perform OID query or set operations on the underlying NIC driver.
- The OID operations be performed usually only by network drivers, but NPF exports this mechanism to user-level
+
+ This structure is used by the driver to perform OID query or set operations on the underlying NIC driver.
+ The OID operations be performed usually only by network drivers, but NPF exports this mechanism to user-level
applications through an IOCTL interface. The driver uses this structure to wrap a NDIS_REQUEST structure.
This allows to handle correctly the callback structure of NdisRequest(), handling multiple requests and
maintaining information about the IRPs to complete.
/*!
\brief Contains a NDIS packet.
-
+
The driver uses this structure to wrap a NDIS_PACKET structure.
This allows to handle correctly the callback structure of NdisTransferData(), handling multiple requests and
maintaining information about the IRPs to complete.
LIST_ENTRY ListElement; ///< Used to handle lists of packets.
PIRP Irp; ///< Irp that performed the request
PMDL pMdl; ///< MDL mapping the buffer of the packet.
- BOOLEAN FreeBufAfterWrite; ///< True if the memory buffer associated with the packet must be freed
+ BOOLEAN FreeBufAfterWrite; ///< True if the memory buffer associated with the packet must be freed
///< after a call to NdisSend().
} PACKET_RESERVED, *PPACKET_RESERVED;
/*!
\brief Port device extension.
-
+
Structure containing some data relative to every adapter on which NPF is bound.
*/
typedef struct _DEVICE_EXTENSION {
NDIS_HANDLE NdisProtocolHandle; ///< NDIS handle of NPF.
NDIS_STRING AdapterName; ///< Name of the adapter.
- PWSTR ExportString; ///< Name of the exported device, i.e. name that the applications will use
+ PWSTR ExportString; ///< Name of the exported device, i.e. name that the applications will use
///< to open this adapter through WinPcap.
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;
/*!
\brief Contains the state of a running instance of the NPF driver.
-
+
This is the most important structure of NPF: it is used by almost all the functions of the driver. An
_OPEN_INSTANCE structure is associated with every user-level session, allowing concurrent access
to the driver.
UINT Medium; ///< Type of physical medium the underlying NDIS driver uses. See the
///< documentation of NdisOpenAdapter in the MS DDK for details.
NDIS_HANDLE PacketPool; ///< Pool of NDIS_PACKET structures used to transfer the packets from and to the NIC driver.
- PIRP OpenCloseIrp; ///< Pointer used to store the open/close IRP requests and provide them to the
+ PIRP OpenCloseIrp; ///< Pointer used to store the open/close IRP requests and provide them to the
///< callbacks of NDIS.
KSPIN_LOCK RequestSpinLock; ///< SpinLock used to synchronize the OID requests.
LIST_ENTRY RequestList; ///< List of pending OID requests.
PKEVENT ReadEvent; ///< Pointer to the event on which the read calls on this instance must wait.
HANDLE ReadEventHandle; ///< Handle of the event on which the read calls on this instance must wait.
UNICODE_STRING ReadEventName; ///< Name of the event on which the read calls on this instance must wait.
- ///< The event is created with a name, so it can be used at user level to know when it
- ///< is possible to access the driver without being blocked. This fiels stores the name
+ ///< The event is created with a name, so it can be used at user level to know when it
+ ///< is possible to access the driver without being blocked. This fiels stores the name
///< that and is used by the BIOCGEVNAME IOCTL call.
- INT Received; ///< Number of packets received by current instance from its opening, i.e. number of
- ///< packet received by the network adapter since the beginning of the
+ INT Received; ///< Number of packets received by current instance from its opening, i.e. number of
+ ///< packet received by the network adapter since the beginning of the
///< capture/monitoring/dump session.
- INT Dropped; ///< Number of packet that current instance had to drop, from its opening. A packet
- ///< is dropped if there is no more space to store it in the circular buffer that the
+ INT Dropped; ///< Number of packet that current instance had to drop, from its opening. A packet
+ ///< is dropped if there is no more space to store it in the circular buffer that the
///< driver associates to current instance.
- INT Accepted; ///< Number of packet that current capture instance acepted, from its opening. A packet
+ INT Accepted; ///< Number of packet that current capture instance acepted, from its opening. A packet
///< is accepted if it passes the filter and fits in the buffer. Accepted packets are the
///< ones that reach the application.
PUCHAR bpfprogram; ///< Pointer to the filtering pseudo-code associated with current instance of the driver.
///< This code is used only in particular situations (for example when the packet received
///< from the NIC driver is stored in two non-consecutive buffers. In normal situations
- ///< the filtering routine created by the JIT compiler and pointed by the next field
+ ///< the filtering routine created by the JIT compiler and pointed by the next field
///< is used. See \ref NPF for details on the filtering process.
- JIT_BPF_Filter *Filter; ///< Pointer to the native filtering function created by the jitter.
+ JIT_BPF_Filter *Filter; ///< Pointer to the native filtering function created by the jitter.
///< See BPF_jitter() for details.
- PUCHAR Buffer; ///< Pointer to the circular buffer associated with every driver instance. It contains the
+ PUCHAR Buffer; ///< Pointer to the circular buffer associated with every driver instance. It contains the
///< data that will be passed to the application. See \ref NPF for details.
UINT Bhead; ///< Head of the circular buffer.
UINT Btail; ///< Tail of the circular buffer.
UINT BufSize; ///< Size of the circular buffer.
UINT BLastByte; ///< Position of the last valid byte in the circular buffer.
- PMDL TransferMdl; ///< MDL used to map the portion of the buffer that will contain an incoming packet.
+ PMDL TransferMdl; ///< MDL used to map the portion of the buffer that will contain an incoming packet.
///< Used by NdisTransferData().
NDIS_SPIN_LOCK BufLock; ///< SpinLock that protects the access tho the circular buffer variables.
UINT MinToCopy; ///< Minimum amount of data in the circular buffer that unlocks a read. Set with the
///< BIOCSMINTOCOPY IOCTL.
- LARGE_INTEGER TimeOut; ///< Timeout after which a read is released, also if the amount of data in the buffer is
+ LARGE_INTEGER TimeOut; ///< Timeout after which a read is released, also if the amount of data in the buffer is
///< less than MinToCopy. Set with the BIOCSRTIMEOUT IOCTL.
-
+
int mode; ///< Working mode of the driver. See PacketSetMode() for details.
LARGE_INTEGER Nbytes; ///< Amount of bytes accepted by the filter when this instance is in statistical mode.
LARGE_INTEGER Npackets; ///< Number of packets accepted by the filter when this instance is in statistical mode.
NDIS_SPIN_LOCK CountersLock; ///< SpinLock that protects the statistical mode counters.
- UINT Nwrites; ///< Number of times a single write must be physically repeated. See \ref NPF for an
+ UINT Nwrites; ///< Number of times a single write must be physically repeated. See \ref NPF for an
///< explanation
UINT Multiple_Write_Counter; ///< Counts the number of times a single write has already physically repeated.
NDIS_EVENT WriteEvent; ///< Event used to synchronize the multiple write process.
NDIS_EVENT DumpEvent; ///< Event used to synchronize the dump thread with the tap when the instance is in dump mode.
LARGE_INTEGER DumpOffset; ///< Current offset in the dump file.
UNICODE_STRING DumpFileName; ///< String containing the name of the dump file.
- UINT MaxDumpBytes; ///< Maximum dimension in bytes of the dump file. If the dump file reaches this size it
+ UINT MaxDumpBytes; ///< Maximum dimension in bytes of the dump file. If the dump file reaches this size it
///< will be closed. A value of 0 means unlimited size.
- UINT MaxDumpPacks; ///< Maximum number of packets that will be saved in the dump file. If this number of
- ///< packets is reached the dump will be closed. A value of 0 means unlimited number of
+ UINT MaxDumpPacks; ///< Maximum number of packets that will be saved in the dump file. If this number of
+ ///< packets is reached the dump will be closed. A value of 0 means unlimited number of
///< packets.
- BOOLEAN DumpLimitReached; ///< TRUE if the maximum dimension of the dump file (MaxDumpBytes or MaxDumpPacks) is
+ BOOLEAN DumpLimitReached; ///< TRUE if the maximum dimension of the dump file (MaxDumpBytes or MaxDumpPacks) is
///< reached.
MEM_TYPE mem_ex; ///< Memory used by the TME virtual co-processor
TME_CORE tme; ///< Data structure containing the virtualization of the TME co-processor
NDIS_SPIN_LOCK machine_lock; ///< SpinLock that protects the mem_ex buffer
- UINT MaxFrameSize; ///< Maximum frame size that the underlying MAC acceptes. Used to perform a check on the
+ UINT MaxFrameSize; ///< Maximum frame size that the underlying MAC acceptes. Used to perform a check on the
///< size of the frames sent with NPF_Write() or NPF_BufferedWrite().
} OPEN_INSTANCE, *POPEN_INSTANCE;
/* Prototypes */
/***************************/
-/** @defgroup NPF_code NPF functions
+/** @defgroup NPF_code NPF functions
* @{
*/
\return A string containing a list of network adapters.
DriverEntry is a mandatory function in a device driver. Like the main() of a user level program, it is called
- by the system when the driver is loaded in memory and started. Its purpose is to initialize the driver,
+ by the system when the driver is loaded in memory and started. Its purpose is to initialize the driver,
performing all the allocations and the setup. In particular, DriverEntry registers all the driver's I/O
callbacks, creates the devices, defines NPF as a protocol inside NDIS.
-*/
+*/
//NTSTATUS
//DriverEntry(
// IN PDRIVER_OBJECT DriverObject,
\brief Returns the list of the MACs available on the system.
\return A string containing a list of network adapters.
- The list of adapters is retrieved from the
- SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318} registry key.
+ The list of adapters is retrieved from the
+ SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318} registry key.
NPF tries to create its bindings from this list. In this way it is possible to be loaded
and unloaded dynamically without passing from the control panel.
*/
\param Irp Pointer to the IRP containing the user request.
\return The status of the operation. See ntstatus.h in the DDK.
- This function is called by the OS when a new instance of the driver is opened, i.e. when a user application
+ This function is called by the OS when a new instance of the driver is opened, i.e. when a user application
performs a CreateFile on a device created by NPF. NPF_Open allocates and initializes variables, objects
- and buffers needed by the new instance, fills the OPEN_INSTANCE structure associated with it and opens the
+ and buffers needed by the new instance, fills the OPEN_INSTANCE structure associated with it and opens the
adapter with a call to NdisOpenAdapter.
*/
NTSTATUS
\param Status Status of the opening operation performed by NDIS.
\param OpenErrorStatus not used by NPF.
- Callback function associated with the NdisOpenAdapter() NDIS function. It is invoked by NDIS when the NIC
+ Callback function associated with the NdisOpenAdapter() NDIS function. It is invoked by NDIS when the NIC
driver has finished an open operation that was previously started by NPF_Open().
*/
VOID
\param Irp Pointer to the IRP containing the user request.
\return The status of the operation. See ntstatus.h in the DDK.
- This function is called when a running instance of the driver is closed by the user with a CloseHandle().
- It stops the capture/monitoring/dump process, deallocates the memory and the objects associated with the
- instance and closing the files. The network adapter is then closed with a call to NdisCloseAdapter.
+ This function is called when a running instance of the driver is closed by the user with a CloseHandle().
+ It stops the capture/monitoring/dump process, deallocates the memory and the objects associated with the
+ instance and closing the files. The network adapter is then closed with a call to NdisCloseAdapter.
*/
NTSTATUS
NPF_Close(
\param ProtocolBindingContext Context of the function. Contains a pointer to the OPEN_INSTANCE structure associated with the current instance.
\param Status Status of the close operation performed by NDIS.
- Callback function associated with the NdisCloseAdapter() NDIS function. It is invoked by NDIS when the NIC
+ Callback function associated with the NdisCloseAdapter() NDIS function. It is invoked by NDIS when the NIC
driver has finished a close operation that was previously started by NPF_Close().
*/
VOID
/*!
\brief Callback invoked by NDIS when a packet arrives from the network.
- \param ProtocolBindingContext Context of the function. Points to a OPEN_INSTANCE structure that identifies
+ \param ProtocolBindingContext Context of the function. Points to a OPEN_INSTANCE structure that identifies
the NPF instance to which the packets are destined.
- \param MacReceiveContext Handle that identifies the underlying NIC driver that generated the request.
+ \param MacReceiveContext Handle that identifies the underlying NIC driver that generated the request.
This value must be used when the packet is transferred from the NIC driver with NdisTransferData().
\param HeaderBuffer Pointer to the buffer in the NIC driver memory that contains the header of the packet.
\param HeaderBufferSize Size in bytes of the header.
- \param LookAheadBuffer Pointer to the buffer in the NIC driver's memory that contains the incoming packet's
+ \param LookAheadBuffer Pointer to the buffer in the NIC driver's memory that contains the incoming packet's
data <b>available to NPF</b>. This value does not necessarily coincide with the actual size of the packet,
since only a portion can be available at this time. The remaining portion can be obtained with the
NdisTransferData() NDIS function.
\param PacketSize Total size of the incoming packet, excluded the header.
\return The status of the operation. See ntstatus.h in the DDK.
- NPF_tap() is called by the underlying NIC for every incoming packet. It is the most important and one of
- the most complex functions of NPF: it executes the filter, runs the statistical engine (if the instance is in
+ NPF_tap() is called by the underlying NIC for every incoming packet. It is the most important and one of
+ the most complex functions of NPF: it executes the filter, runs the statistical engine (if the instance is in
statistical mode), gathers the timestamp, moves the packet in the buffer. NPF_tap() is the only function,
- along with the filtering ones, that is executed for every incoming packet, therefore it is carefully
+ along with the filtering ones, that is executed for every incoming packet, therefore it is carefully
optimized.
*/
NDIS_STATUS
\param Status Status of the transfer operation.
\param BytesTransferred Amount of bytes transferred.
- Callback function associated with the NdisTransferData() NDIS function. It is invoked by NDIS when the NIC
+ Callback function associated with the NdisTransferData() NDIS function. It is invoked by NDIS when the NIC
driver has finished the transfer of a packet from the NIC driver memory to the NPF circular buffer.
*/
VOID
Once the packet capture driver is opened it can be configured from user-level applications with IOCTL commands
using the DeviceIoControl() system call. NPF_IoControl receives and serves all the IOCTL calls directed to NPF.
- The following commands are recognized:
- - #BIOCSETBUFFERSIZE
- - #BIOCSETF
- - #BIOCGSTATS
+ The following commands are recognized:
+ - #BIOCSETBUFFERSIZE
+ - #BIOCSETF
+ - #BIOCGSTATS
- #BIOCSRTIMEOUT
- - #BIOCSMODE
- - #BIOCSWRITEREP
- - #BIOCSMINTOCOPY
- - #BIOCSETOID
- - #BIOCQUERYOID
+ - #BIOCSMODE
+ - #BIOCSWRITEREP
+ - #BIOCSMINTOCOPY
+ - #BIOCSETOID
+ - #BIOCQUERYOID
- #BIOCSETDUMPFILENAME
- #BIOCGEVNAME
- #BIOCSENDPACKETSSYNC
/*!
\brief Ends an OID request.
\param ProtocolBindingContext Context of the function. Contains a pointer to the OPEN_INSTANCE structure associated with the current instance.
- \param pRequest Pointer to the completed OID request.
+ \param pRequest Pointer to the completed OID request.
\param Status Status of the operation.
- Callback function associated with the NdisRequest() NDIS function. It is invoked by NDIS when the NIC
+ Callback function associated with the NdisRequest() NDIS function. It is invoked by NDIS when the NIC
driver has finished an OID request operation that was previously started by NPF_IoControl().
*/
VOID
This function is called by the OS in consequence of user WriteFile() call, with the data of the packet that must
be sent on the net. The data is contained in the buffer associated with Irp, NPF_Write takes it and
- delivers it to the NIC driver via the NdisSend() function. The Nwrites field of the OPEN_INSTANCE structure
+ delivers it to the NIC driver via the NdisSend() function. The Nwrites field of the OPEN_INSTANCE structure
associated with Irp indicates the number of copies of the packet that will be sent: more than one copy of the
packet can be sent for performance reasons.
*/
The buffer received as input parameter contains an arbitrary number of packets, each of which preceded by a
sf_pkthdr structure. NPF_BufferedWrite() scans the buffer and sends every packet via the NdisSend() function.
When Sync is set to TRUE, the packets are synchronized with the KeQueryPerformanceCounter() function.
- This requires a remarkable amount of CPU, but allows to respect the timestamps associated with packets with a precision
+ This requires a remarkable amount of CPU, but allows to respect the timestamps associated with packets with a precision
of some microseconds (depending on the precision of the performance counter of the machine).
If Sync is false, the timestamps are ignored and the packets are sent as fat as possible.
*/
-INT NPF_BufferedWrite(IN PIRP Irp,
- IN PCHAR UserBuff,
+INT NPF_BufferedWrite(IN PIRP Irp,
+ IN PCHAR UserBuff,
IN ULONG UserBuffSize,
BOOLEAN sync);
/*!
\brief Ends a send operation.
\param ProtocolBindingContext Context of the function. Contains a pointer to the OPEN_INSTANCE structure associated with the current instance.
- \param pRequest Pointer to the NDIS PACKET structure used by NPF_Write() to send the packet.
+ \param pRequest Pointer to the NDIS PACKET structure used by NPF_Write() to send the packet.
\param Status Status of the operation.
- Callback function associated with the NdisSend() NDIS function. It is invoked by NDIS when the NIC
+ Callback function associated with the NdisSend() NDIS function. It is invoked by NDIS when the NIC
driver has finished an OID request operation that was previously started by NPF_Write().
*/
VOID
\param ProtocolBindingContext Context of the function. Contains a pointer to the OPEN_INSTANCE structure associated with the current instance.
\param Status Status of the operation.
- Callback function associated with the NdisReset() NDIS function. It is invoked by NDIS when the NIC
- driver has finished an OID request operation that was previously started by NPF_IoControl(), in an IOCTL_PROTOCOL_RESET
+ Callback function associated with the NdisReset() NDIS function. It is invoked by NDIS when the NIC
+ driver has finished an OID request operation that was previously started by NPF_IoControl(), in an IOCTL_PROTOCOL_RESET
command.
*/
VOID
This function is called by the OS in consequence of user ReadFile() call. It moves the data present in the
kernel buffer to the user buffer associated with Irp.
- First of all, NPF_Read checks the amount of data in kernel buffer associated with current NPF instance.
+ First of all, NPF_Read checks the amount of data in kernel buffer associated with current NPF instance.
- If the instance is in capture mode and the buffer contains more than OPEN_INSTANCE::MinToCopy bytes,
NPF_Read moves the data in the user buffer and returns immediatly. In this way, the read performed by the
user is not blocking.
- - If the buffer contains less than MinToCopy bytes, the application's request isn't
- satisfied immediately, but it's blocked until at least MinToCopy bytes arrive from the net
+ - If the buffer contains less than MinToCopy bytes, the application's request isn't
+ satisfied immediately, but it's blocked until at least MinToCopy bytes arrive from the net
or the timeout on this read expires. The timeout is kept in the OPEN_INSTANCE::TimeOut field.
- - If the instance is in statistical mode or in dump mode, the application's request is blocked until the
+ - If the instance is in statistical mode or in dump mode, the application's request is blocked until the
timeout kept in OPEN_INSTANCE::TimeOut expires.
*/
NTSTATUS
);
/*!
- \brief Function used by NPF_ReadRegistry() to quesry the registry keys associated woth NPF if the driver
+ \brief Function used by NPF_ReadRegistry() to quesry the registry keys associated woth NPF if the driver
is manually installed via the control panel.
Normally not used in recent versions of NPF.
/*!
\brief Callback for NDIS BindAdapterHandler. Not used by NPF.
-
+
Function called by NDIS when a new adapter is installed on the machine With Plug and Play.
*/
VOID NPF_BindAdapter(
\param Status out variable filled by NPF_UnbindAdapter with the status of the unbind operation.
\param ProtocolBindingContext Context of the function. Contains a pointer to the OPEN_INSTANCE structure associated with current instance.
\param UnbindContext Specifies a handle, supplied by NDIS, that NPF can use to complete the opration.
-
+
Function called by NDIS when a new adapter is removed from the machine without shutting it down.
NPF_UnbindAdapter closes the adapter calling NdisCloseAdapter() and frees the memory and the structures
associated with it. It also releases the waiting user-level app and closes the dump thread if the instance
\param len Its length, in pseudo instructions.
\param mem_ex_size The length of the extended memory, used to validate LD/ST to that memory
\return true if f is a valid filter program..
-
- The kernel needs to be able to verify an application's filter code. Otherwise, a bogus program could easily
+
+ The kernel needs to be able to verify an application's filter code. Otherwise, a bogus program could easily
crash the system.
- This function returns true if f is a valid filter program. The constraints are that each jump be forward and
- to a valid code. The code must terminate with either an accept or reject.
+ This function returns true if f is a valid filter program. The constraints are that each jump be forward and
+ to a valid code. The code must terminate with either an accept or reject.
*/
int bpf_validate(struct bpf_insn *f,int len, uint32 mem_ex_size);
\param time_ref Data structure needed by the TME co-processor to timestamp data
\return The portion of the packet to keep, in bytes. 0 means that the packet must be rejected, -1 means that
the whole packet must be kept.
-
+
\note this function is not used in normal situations, because the jitter creates a native filtering function
that is faster than the interpreter.
*/
struct time_conv *time_ref);
/*!
- \brief The filtering pseudo-machine interpreter with two buffers. This function is slower than bpf_filter(),
+ \brief The filtering pseudo-machine interpreter with two buffers. This function is slower than bpf_filter(),
but works correctly also if the MAC header and the data of the packet are in two different buffers.
\param pc The filter.
\param p Pointer to a memory buffer containing the MAC header of the packet.
\param time_ref Data structure needed by the TME co-processor to timestamp data
\return The portion of the packet to keep, in bytes. 0 means that the packet must be rejected, -1 means that
the whole packet must be kept.
-
+
This function is used when NDIS passes the packet to NPF_tap() in two buffers instaed than in a single one.
*/
UINT bpf_filter_with_2_buffers(register struct bpf_insn *pc,
\brief The dump thread.
\param Open The NPF instance that creates the thread.
- This function moves the content of the NPF kernel buffer to file. It runs in the user context, so at lower
+ This function moves the content of the NPF kernel buffer to file. It runs in the user context, so at lower
priority than the TAP.
*/
VOID NPF_DumpThread(POPEN_INSTANCE Open);
/*!
\brief Called by NDIS to notify us of a PNP event. The most significant one for us is power state change.
- \param ProtocolBindingContext Pointer to open context structure. This is NULL for global reconfig
+ \param ProtocolBindingContext Pointer to open context structure. This is NULL for global reconfig
events.
\param pNetPnPEvent Pointer to the PnP event
UINT Occupation;
NdisAcquireSpinLock( &Open->BufLock );
-
+
if(Open->Btail >= Open->Bhead) Occupation = Open->Btail-Open->Bhead;
else Occupation = Open->BLastByte-Open->Bhead+Open->Btail;
WordLength=Length>>2;
NBlocks=WordLength>>8;
-
+
for(n=0;n<NBlocks;n++){
for(i=0;i<256;i++){
*((PULONG)Destination)++=*((PULONG)Source)++;
*((PULONG)Destination)++=*((PULONG)Source)++;
}
*Bhead+=n<<2;
-
+
n=Length-(WordLength<<2);
for(i=0;i<n;i++){
*((PUCHAR)Destination)++=*((PUCHAR)Source)++;
UINT PktLen;
IF_LOUD(DbgPrint("NPF: Read\n");)
-
+
IrpSp = IoGetCurrentIrpStackLocation(Irp);
Open=IrpSp->FileObject->FsContext;
-
+
if( Open->Bound == FALSE ){
// The Network adapter was removed.
EXIT_FAILURE(0);
}
-
- if( Open->mode & MODE_DUMP && Open->DumpFileHandle == NULL ){
+
+ if( Open->mode & MODE_DUMP && Open->DumpFileHandle == NULL ){
// this instance is in dump mode, but the dump file has still not been opened
EXIT_FAILURE(0);
}
//See if the buffer is full enough to be copied
if( GetBuffOccupation(Open) <= Open->MinToCopy || Open->mode & MODE_DUMP )
{
- //wait until some packets arrive or the timeout expires
+ //wait until some packets arrive or the timeout expires
if(Open->TimeOut.QuadPart != (LONGLONG)IMMEDIATE)
KeWaitForSingleObject(Open->ReadEvent,
UserRequest,
(Open->TimeOut.QuadPart == (LONGLONG)0)? NULL: &(Open->TimeOut));
KeClearEvent(Open->ReadEvent);
-
+
if(Open->mode & MODE_STAT){ //this capture instance is in statistics mode
CurrBuff=(PUCHAR)MmGetSystemAddressForMdl(Irp->MdlAddress);
-
+
//fill the bpf header for this packet
header=(struct bpf_hdr*)CurrBuff;
GET_TIME(&header->bh_tstamp,&G_Start_Time);
*(LONGLONG*)(CurrBuff+sizeof(struct bpf_hdr))=Open->Npackets.QuadPart;
*(LONGLONG*)(CurrBuff+sizeof(struct bpf_hdr)+8)=Open->Nbytes.QuadPart;
-
+
//reset the countetrs
NdisAcquireSpinLock( &Open->CountersLock );
Open->Npackets.QuadPart=0;
Open->Nbytes.QuadPart=0;
NdisReleaseSpinLock( &Open->CountersLock );
-
+
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
return STATUS_SUCCESS;
}
-
+
if(Open->mode==MODE_MON) //this capture instance is in monitor mode
- {
+ {
PTME_DATA data;
ULONG cnt;
ULONG block_size;
PUCHAR tmp;
UserPointer=MmGetSystemAddressForMdl(Irp->MdlAddress);
-
+
if ((!IS_VALIDATED(Open->tme.validated_blocks,Open->tme.active_read))||(IrpSp->Parameters.Read.Length<sizeof(struct bpf_hdr)))
- {
+ {
EXIT_FAILURE(0);
}
-
+
header=(struct bpf_hdr*)UserPointer;
-
+
GET_TIME(&header->bh_tstamp,&G_Start_Time);
-
+
header->bh_hdrlen=sizeof(struct bpf_hdr);
-
+
//moves user memory pointer
UserPointer+=sizeof(struct bpf_hdr);
-
+
//calculus of data to be copied
//if the user buffer is smaller than data to be copied,
//only some data will be copied
if (data->last_read.tv_sec!=0)
data->last_read=header->bh_tstamp;
-
+
bytecopy=data->block_size*data->filled_blocks;
-
+
if ((IrpSp->Parameters.Read.Length-sizeof(struct bpf_hdr))<bytecopy)
bytecopy=(IrpSp->Parameters.Read.Length-sizeof(struct bpf_hdr))/ data->block_size;
- else
+ else
bytecopy=data->filled_blocks;
tmp=data->shared_memory_base_address;
block_size=data->block_size;
-
+
for (cnt=0;cnt<bytecopy;cnt++)
{
NdisAcquireSpinLock(&Open->machine_lock);
tmp+=block_size;
UserPointer+=block_size;
}
-
+
bytecopy*=block_size;
header->bh_caplen=bytecopy;
{
EXIT_SUCCESS(0);
}
-
+
}
//
// The buffer if full enough to be copied,
//
NdisAcquireSpinLock( &Open->BufLock );
-
+
Thead = Open->Bhead;
Ttail = Open->Btail;
TLastByte = Open->BLastByte;
//get the address of the buffer
CurrBuff=Open->Buffer;
-
+
NdisReleaseSpinLock( &Open->BufLock );
-
+
Input_Buffer_Length=IrpSp->Parameters.Read.Length;
packp=(PUCHAR)MmGetSystemAddressForMdl(Irp->MdlAddress);
-
+
//
//fill the application buffer
PacketMoveMem(packp, CurrBuff+Thead, TLastByte - Thead, &(Open->Bhead));
NdisAcquireSpinLock( &Open->BufLock );
-
+
Open->BLastByte = Open->Btail;
Open->Bhead = 0;
NdisReleaseSpinLock( &Open->BufLock );
-
+
EXIT_SUCCESS(TLastByte-Thead);
}
-
+
//the buffer must be scannned to determine the number of bytes to copy
SizeToCopy = 0;
while(TRUE){
// Reset the buffer
NdisAcquireSpinLock( &Open->BufLock );
(INT)Open->BLastByte = -1;
- Open->Bhead = 0;
+ Open->Bhead = 0;
NdisReleaseSpinLock( &Open->BufLock );
EXIT_SUCCESS(SizeToCopy);
if(SizeToCopy + PktLen > Input_Buffer_Length)
break;
-
+
SizeToCopy += PktLen;
}
BOOLEAN ResetBuff = FALSE;
IF_VERY_LOUD(DbgPrint("NPF: tap\n");)
- IF_VERY_LOUD(DbgPrint("HeaderBufferSize=%d, LookAheadBuffer=%d, LookaheadBufferSize=%d, PacketSize=%d\n",
+ IF_VERY_LOUD(DbgPrint("HeaderBufferSize=%d, LookAheadBuffer=%d, LookaheadBufferSize=%d, PacketSize=%d\n",
HeaderBufferSize,
LookAheadBuffer,
LookaheadBufferSize,
}
NdisAcquireSpinLock(&Open->machine_lock);
-
+
//
//Check if the lookahead buffer follows the mac header.
//If the data follow the header (i.e. there is only a buffer) a normal bpf_filter() is
&Open->mem_ex,
&Open->tme,
&G_Start_Time);
-
-
- else
+
+
+ else
if(Open->Filter != NULL)
{
if (Open->bpfprogram != NULL)
fres=Open->Filter->Function(HeaderBuffer,
PacketSize+HeaderBufferSize,
LookaheadBufferSize+HeaderBufferSize);
-
- // Restore the stack.
+
+ // Restore the stack.
// I ignore the reason, but this instruction is needed only at kernel level
#ifndef __GNUC__
- _asm add esp,12
+ _asm add esp,12
#else
asm("add $0x12,%esp;");
#endif
&G_Start_Time);
NdisReleaseSpinLock(&Open->machine_lock);
-
+
if(Open->mode==MODE_MON)
// we are in monitor mode
{
- if (fres==1)
+ if (fres==1)
KeSetEvent(Open->ReadEvent,0,FALSE);
return NDIS_STATUS_NOT_ACCEPTED;
return NDIS_STATUS_NOT_ACCEPTED;
//if the filter returns -1 the whole packet must be accepted
- if(fres==-1 || fres > PacketSize+HeaderBufferSize)fres=PacketSize+HeaderBufferSize;
+ if(fres==-1 || fres > PacketSize+HeaderBufferSize)fres=PacketSize+HeaderBufferSize;
if(Open->mode & MODE_STAT){
// we are in statistics mode
NdisAcquireSpinLock( &Open->CountersLock );
Open->Npackets.QuadPart++;
-
+
if(PacketSize+HeaderBufferSize<60)
Open->Nbytes.QuadPart+=60;
else
Open->Nbytes.QuadPart+=12;
NdisReleaseSpinLock( &Open->CountersLock );
-
+
if(!(Open->mode & MODE_DUMP)){
return NDIS_STATUS_NOT_ACCEPTED;
}
}
if(Open->BufSize==0)return NDIS_STATUS_NOT_ACCEPTED;
-
+
if(Open->mode & MODE_DUMP && Open->MaxDumpPacks && (UINT)Open->Accepted > Open->MaxDumpPacks){
// Reached the max number of packets to save in the dump file. Discard the packet and stop the dump thread.
Open->DumpLimitReached = TRUE; // This stops the thread
// Calculate the correct size for the header associated with the packet
NPFHdrSize=(Open->mode==MODE_CAPT)? sizeof(struct bpf_hdr): sizeof(struct sf_pkthdr);
-
+
NdisAcquireSpinLock( &Open->BufLock );
Thead=Open->Bhead;
TLastByte = Open->BLastByte;
NdisReleaseSpinLock( &Open->BufLock );
-
+
maxbufspace=Packet_WORDALIGN(fres+NPFHdrSize);
if(Ttail+maxbufspace >= Open->BufSize){
ResetBuff = TRUE;
}
}
-
+
if (Thead > Ttail && (Thead-Ttail) <= maxbufspace)
{
Open->Dropped++;
return NDIS_STATUS_NOT_ACCEPTED;
}
-
+
CurrBuff=Open->Buffer+Ttail;
if(LookaheadBufferSize != PacketSize || (UINT)LookAheadBuffer-(UINT)HeaderBuffer != HeaderBufferSize)
return NDIS_STATUS_NOT_ACCEPTED;
}
MmBuildMdlForNonPagedPool(pMdl);
-
+
//allocate the packet from NDIS
NdisAllocatePacket(&Status, &pPacketb, Open->PacketPool);
if (Status != NDIS_STATUS_SUCCESS)
}
//link the buffer to the packet
NdisChainBufferAtFront(pPacketb,pMdl);
-
+
BufferLength=fres-HeaderBufferSize;
//Find out how much to transfer
SizeToTransfer = (PacketSize < BufferLength) ? PacketSize : BufferLength;
-
+
//copy the ethernet header into buffer
NdisMoveMappedMemory((CurrBuff)+NPFHdrSize,HeaderBuffer,HeaderBufferSize);
-
+
//Copy the look ahead buffer
if(LookaheadBufferSize)
{
NdisMoveMappedMemory((CurrBuff) + NPFHdrSize + HeaderBufferSize,
- LookAheadBuffer,
+ LookAheadBuffer,
(SizeToTransfer < LookaheadBufferSize)? SizeToTransfer : LookaheadBufferSize );
-
+
SizeToTransfer = (SizeToTransfer > LookaheadBufferSize)?
SizeToTransfer - LookaheadBufferSize : 0;
}
-
+
Open->TransferMdl=pMdl;
-
+
if(SizeToTransfer)
{
//Call the Mac to transfer the packet
else{
BytesTransfered = 0;
}
-
+
}
else
{
if( fres > (BytesTransfered+HeaderBufferSize+LookaheadBufferSize) )
fres = BytesTransfered+HeaderBufferSize+LookaheadBufferSize;
-
+
//
// Build the header
//
}
else
Ttail+=fres+NPFHdrSize;
-
- //update the buffer
+
+ //update the buffer
NdisAcquireSpinLock( &Open->BufLock );
-
+
if(ResetBuff){
Open->BLastByte = Open->Btail;
}
Open->Btail=Ttail;
-
+
NdisReleaseSpinLock( &Open->BufLock );
}
NdisSetEvent(&Open->DumpEvent);
}
else
- KeSetEvent(Open->ReadEvent,0,FALSE);
+ KeSetEvent(Open->ReadEvent,0,FALSE);
}
-
+
}
}
-
+
return NDIS_STATUS_SUCCESS;
-
+
}
//-------------------------------------------------------------------
POPEN_INSTANCE Open;
IF_LOUD(DbgPrint("NPF: TransferDataComplete\n");)
-
+
Open= (POPEN_INSTANCE)ProtocolBindingContext;
IoFreeMdl(Open->TransferMdl);
NdisSetEvent(&Open->DumpEvent);
}
else
- KeSetEvent(Open->ReadEvent,0,FALSE);
+ KeSetEvent(Open->ReadEvent,0,FALSE);
}
return;
}
//
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
{
- uint32 next_status;
+ uint32 next_status;
uint32 direction=ULONG_AT(mem_data,12);
uint8 flags=mem_ex->buffer[25];
tcp_data *session=(tcp_data*)(block+data->key_len*4);
-
+
session->last_timestamp=session->timestamp_block;
session->timestamp_block.tv_sec=0x7fffffff;
-
+
if (direction==session->direction)
{
session->pkts_cln_to_srv++;
}
/* we use only thes four flags, we don't need PSH or URG */
flags&=(ACK|FIN|SYN|RST);
-
+
switch (session->status)
{
case ERROR_TCP:
next_status=ERROR_TCP;
break;
-
+
case UNKNOWN:
if (flags==SYN)
{
session->seq_n_0_cln=SW_ULONG_AT(mem_ex->buffer,16);
break;
}
-
+
if ((flags==(SYN|ACK))&&(direction!=session->direction))
- {
+ {
if (SW_ULONG_AT(mem_ex->buffer,20)!=session->seq_n_0_cln+1)
{
next_status=ERROR_TCP;
break;
}
next_status=SYN_ACK_RCV;
-
+
session->syn_ack_timestamp=session->last_timestamp;
session->seq_n_0_srv=SW_ULONG_AT(mem_ex->buffer,16);
session->ack_srv=SW_ULONG_AT(mem_ex->buffer,20);
break;
}
-
+
if ((flags==ACK)&&(!(flags&(SYN|FIN|RST)))&&(direction==session->direction))
{
if (SW_ULONG_AT(mem_ex->buffer,20)!=session->seq_n_0_srv+1)
next_status=ERROR_TCP;
break;
-
+
case ESTABLISHED:
if (flags&SYN)
{
next_status=ESTABLISHED;
break;
}
-
+
if ((!(flags&ACK))&&
(direction==session->direction)&&
(SW_ULONG_AT(mem_ex->buffer,16)==session->seq_n_0_cln)&&
next_status=ESTABLISHED;
break;
}
-
+
next_status=ERROR_TCP;
break;
}
}
next_status=ESTABLISHED;
break;
-
+
case CLOSED_RST:
next_status=CLOSED_RST;
break;
-
- case FIN_SRV_RCV:
+
+ case FIN_SRV_RCV:
if (flags&SYN)
{
next_status=ERROR_TCP;
break;
}
-
+
next_status=FIN_SRV_RCV;
-
+
if (flags&ACK)
{
uint32 new_ack=SW_ULONG_AT(mem_ex->buffer,20);
if ((new_ack-session->ack_cln)<MAX_WINDOW)
session->ack_cln=new_ack;
}
-
+
if (flags&RST)
next_status=CLOSED_RST;
else
next_status=ERROR_TCP;
break;
}
-
+
next_status=FIN_CLN_RCV;
-
+
if (flags&ACK)
{
uint32 new_ack=SW_ULONG_AT(mem_ex->buffer,20);
if (new_ack-session->ack_srv<MAX_WINDOW)
session->ack_srv=new_ack;
}
-
+
if (flags&RST)
next_status=CLOSED_RST;
else
}
session->status=next_status;
-
+
if ((next_status==CLOSED_FIN)||(next_status==UNKNOWN)||(next_status==CLOSED_RST)||(next_status==ERROR_TCP))
session->timestamp_block=session->last_timestamp;
-
+
return TME_SUCCESS;
}
if (data->reference!=0)
return;
-
- // get the absolute value of the system boot time.
+
+ // get the absolute value of the system boot time.
PTime=KeQueryPerformanceCounter(&TimeFreq);
KeQuerySystemTime(&SystemTime);
#ifndef __GNUC__
if (data->reference!=0)
return;
-
+
KeInitializeEvent(&event,NotificationEvent,FALSE);
i.QuadPart=-3500000;
KeRaiseIrql(HIGH_LEVEL,&old);
}
reference=delta*(start_freq.QuadPart)/delta2;
data->reference=reference/1000;
- if (reference%1000>500)
+ if (reference%1000>500)
data->reference++;
data->reference*=1000;
reference=data->reference;
/*!
\brief A microsecond precise timestamp.
- included in the sf_pkthdr or the bpf_hdr that NPF associates with every packet.
+ included in the sf_pkthdr or the bpf_hdr that NPF associates with every packet.
*/
struct timeval {
if (data->reference!=0)
return;
-
- // get the absolute value of the system boot time.
+
+ // get the absolute value of the system boot time.
PTime=KeQueryPerformanceCounter(&TimeFreq);
KeQuerySystemTime(&SystemTime);
tmp.tv_sec=(LONG)(SystemTime.QuadPart/10000000-11644473600);
if (data->reference!=0)
return;
-
+
KeInitializeEvent(&event,NotificationEvent,FALSE);
i.QuadPart=-3500000;
KeRaiseIrql(HIGH_LEVEL,&old);
}
reference=delta*(start_freq.QuadPart)/delta2;
data->reference=reference/1000;
- if (reference%1000>500)
+ if (reference%1000>500)
data->reference++;
data->reference*=1000;
reference=data->reference;
#include <net/tme/tme.h>
#endif
-/* resizes extended memory */
+/* resizes extended memory */
uint32 init_extended_memory(uint32 size, MEM_TYPE *mem_ex)
{
uint8 *tmp;
-
+
if ((mem_ex==NULL)||(mem_ex->buffer==NULL)||(size==0))
return TME_ERROR; /* awfully never reached!!!! */
ALLOCATE_MEMORY(tmp,uint8,size);
if (tmp==NULL)
return TME_ERROR; /* no memory */
-
+
mem_ex->size=size;
mem_ex->buffer=tmp;
return TME_SUCCESS;
}
/* activates a block of the TME */
-uint32 set_active_tme_block(TME_CORE *tme, uint32 block)
+uint32 set_active_tme_block(TME_CORE *tme, uint32 block)
{
if ((block>=MAX_TME_DATA_BLOCKS)||(!IS_VALIDATED(tme->validated_blocks,block)))
/* it will be useful to store them in the registry */
uint32 init_tme_block(TME_CORE *tme, uint32 block)
{
-
+
TME_DATA *data;
if (block>=MAX_TME_DATA_BLOCKS)
return TME_ERROR;
data->default_exec=TME_DEFAULT_EXEC_DEFAULT;
/* extra segment size */
data->extra_segment_size=TME_EXTRA_SEGMENT_SIZE_DEFAULT;
-
+
data->enable_deletion=FALSE;
data->last_read.tv_sec=0;
uint32 required_memory;
uint8 *base=mem_ex_offset+mem_ex->buffer;
TME_DATA *data;
-
+
/* FIXME soluzione un po' posticcia... */
if (mem_ex_offset==0)
return TME_ERROR;
if (block>=MAX_TME_DATA_BLOCKS)
return TME_ERROR;
data=&tme->block_data[block];
-
+
if (data->lut_entries==0)
return TME_ERROR;
/* the TME block can be initialized */
ZERO_MEMORY(base,required_memory);
-
+
data->lut_base_address=base;
-
+
data->shared_memory_base_address=
data->lut_base_address+
data->lut_entries*sizeof(RECORD);
tme->working=block;
return TME_SUCCESS;
}
-
+
/* I/F between the bpf machine and the callbacks, just some checks */
uint32 lookup_frontend(MEM_TYPE *mem_ex, TME_CORE *tme,uint32 mem_ex_offset, struct time_conv *time_ref)
{
if (tme->active==TME_NONE_ACTIVE)
return TME_FALSE;
-
+
return (tme->block_data[tme->active].lookup_code)(mem_ex_offset+mem_ex->buffer,&tme->block_data[tme->active],mem_ex, time_ref);
}
/* I/F between the bpf machine and the callbacks, just some checks */
uint32 execute_frontend(MEM_TYPE *mem_ex, TME_CORE *tme, uint32 pkt_size, uint32 offset)
{
-
+
exec_fcn tmp;
TME_DATA *data;
uint8 *block;
return TME_ERROR;
data=&tme->block_data[tme->active];
-
+
if (data->last_found==NULL)
{ /*out lut exec */
tmp=exec_fcn_mapper(data->out_lut_exec);
return TME_ERROR;
}
}
-
+
if (offset>=mem_ex->size)
return TME_ERROR;
-
+
mem_data=mem_ex->buffer+offset;
-
+
return tmp(block,pkt_size,data,mem_ex,mem_data);
}
{
if (tme==NULL)
return TME_ERROR;
- ZERO_MEMORY(tme, sizeof(TME_CORE));
+ ZERO_MEMORY(tme, sizeof(TME_CORE));
return TME_SUCCESS;
}
-
+
/* returns a register value of the active TME block */
/* FIXME last found in maniera elegante e veloce ?!?! */
uint32 get_tme_block_register(TME_DATA *data,MEM_TYPE *mem_ex,uint32 rgstr,uint32 *rval)
case TME_REHASHING_VALUE:
data->rehashing_value=value;
return TME_SUCCESS;
- case TME_FILLED_ENTRIES:
+ case TME_FILLED_ENTRIES:
data->filled_entries=value;
return TME_SUCCESS;
- case TME_FILLED_BLOCKS:
+ case TME_FILLED_BLOCKS:
if (value<=data->shared_memory_blocks)
{
data->filled_blocks=value;
}
else
return TME_ERROR;
- case TME_DEFAULT_EXEC:
+ case TME_DEFAULT_EXEC:
data->default_exec=value;
return TME_SUCCESS;
case TME_OUT_LUT_EXEC:
switch (rgstr)
{
- case TME_LUT_ENTRIES:
+ case TME_LUT_ENTRIES:
data->lut_entries=value;
return TME_SUCCESS;
- case TME_KEY_LEN:
+ case TME_KEY_LEN:
data->key_len=value;
return TME_SUCCESS;
- case TME_SHARED_MEMORY_BLOCKS:
+ case TME_SHARED_MEMORY_BLOCKS:
data->shared_memory_blocks=value;
return TME_SUCCESS;
- case TME_BLOCK_SIZE:
+ case TME_BLOCK_SIZE:
data->block_size=value;
return TME_SUCCESS;
- case TME_EXTRA_SEGMENT_SIZE:
+ case TME_EXTRA_SEGMENT_SIZE:
data->extra_segment_size=value;
return TME_SUCCESS;
default:
}
/* chooses the TME block for read */
-uint32 set_active_read_tme_block(TME_CORE *tme, uint32 block)
+uint32 set_active_read_tme_block(TME_CORE *tme, uint32 block)
{
if ((block>=MAX_TME_DATA_BLOCKS)||(!IS_VALIDATED(tme->validated_blocks,block)))
#endif
/* error codes */
-#define TME_ERROR 0
+#define TME_ERROR 0
#define TME_SUCCESS 1
#define TME_TRUE 2
#define TME_FALSE 3
#define TME_NONE_ACTIVE 0xffffffff
#define DELTA_READ 2 /* secs */
-#define TME_LUT_ENTRIES 0x00000000
+#define TME_LUT_ENTRIES 0x00000000
#define TME_MAX_FILL_STATE 0x00000001 /*potrebbe servire per un thread a passive level!?!?! */
-#define TME_REHASHING_VALUE 0x00000002
+#define TME_REHASHING_VALUE 0x00000002
#define TME_KEY_LEN 0x00000003
#define TME_SHARED_MEMORY_BLOCKS 0x00000004
#define TME_FILLED_ENTRIES 0x00000005
uint32 validated_blocks;
TME_DATA block_data[MAX_TME_DATA_BLOCKS];
uint32 active_read;
-
+
} TME_CORE, *PTME_CORE;
static __inline int32 IS_DELETABLE(void *timestamp, TME_DATA *data)
*
* This code is derived from the Stanford/CMU enet packet filter,
* (net/enet.c) distributed as part of 4.3BSD, and code contributed
- * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
+ * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
* Berkeley Laboratory.
*
* Redistribution and use in source and binary forms, with or without
u_int bf_len;
struct bpf_insn *bf_insns;
};
-
+
/*
* Struct returned by BIOCGSTATS.
*/
};
/*
- * Struct return by BIOCVERSION. This represents the version number of
+ * Struct return by BIOCVERSION. This represents the version number of
* the filter language described by the instruction encodings below.
* bpf understands a program iff kernel_major == filter_major &&
* kernel_minor >= filter_minor, that is, if the value returned by the
/* TME instructions */
#define BPF_TME 0x08
-#define BPF_LOOKUP 0x90
+#define BPF_LOOKUP 0x90
#define BPF_EXECUTE 0xa0
#define BPF_INIT 0xb0
#define BPF_VALIDATE 0xc0
*
* This code is derived from the Stanford/CMU enet packet filter,
* (net/enet.c) distributed as part of 4.3BSD, and code contributed
- * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
+ * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
* Berkeley Laboratory.
*
* Redistribution and use in source and binary forms, with or without
* 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.
-
+
@(#)bpf.c 7.5 (Berkeley) 7/15/91
*/
register int k;
u_int32 j,tmp;
u_short tmp2;
-
+
int32 mem[BPF_MEMWORDS];
if (pc == 0)
switch (pc->code) {
default:
-
+
return 0;
case BPF_RET|BPF_K:
case BPF_LD|BPF_MEM:
A = mem[pc->k];
continue;
-
+
case BPF_LDX|BPF_MEM:
X = mem[pc->k];
continue;
case BPF_LDX|BPF_MEM_EX_IMM|BPF_W:
X = EXTRACT_LONG(&mem_ex->buffer[pc->k]);
continue;
-
+
case BPF_LD|BPF_MEM_EX_IND|BPF_B:
k = X + pc->k;
if ((int32)k>= (int32)mem_ex->size) {
case BPF_ALU|BPF_ADD|BPF_X:
A += X;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_X:
A -= X;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_X:
A *= X;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_X:
if (X == 0)
return 0;
A /= X;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_X:
A &= X;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_X:
A |= X;
continue;
case BPF_ALU|BPF_ADD|BPF_K:
A += pc->k;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_K:
A -= pc->k;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_K:
A *= pc->k;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_K:
A /= pc->k;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_K:
A &= pc->k;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_K:
A |= pc->k;
continue;
case BPF_MISC|BPF_TME|BPF_LOOKUP:
j=lookup_frontend(mem_ex,tme,pc->k,time_ref);
if (j==TME_ERROR)
- return 0;
+ return 0;
pc += (j == TME_TRUE) ? pc->jt : pc->jf;
continue;
register struct bpf_insn *pc;
register u_char *p;
register u_char *pd;
- register int headersize;
+ register int headersize;
u_int wirelen;
register u_int buflen;
PMEM_TYPE mem_ex;
switch (pc->code) {
default:
-
+
return 0;
case BPF_RET|BPF_K:
if (k + sizeof(int32) > buflen) {
return 0;
}
-
+
if(k + (int)sizeof(int32) < headersize) A = EXTRACT_LONG(&p[k]);
else if(k + 2 == headersize){
A=(u_int32)*((u_char *)p+k)<<24|
(u_int32)*((u_char *)pd+k-headersize+3);
}
A = EXTRACT_LONG(&pd[k-headersize]);
-
+
continue;
-
+
case BPF_LD|BPF_H|BPF_ABS:
k = pc->k;
if (k + sizeof(short) > buflen) {
return 0;
}
-
+
if(k + (int)sizeof(short) < headersize) A = EXTRACT_SHORT(&p[k]);
else if(k == headersize){
A=(u_short)*((u_char *)p+k)<<8|
(u_short)*((u_char *)pd+k-headersize);
}
A = EXTRACT_SHORT(&pd[k-headersize]);
-
+
continue;
case BPF_LD|BPF_B|BPF_ABS:
(u_int32)*((u_char *)pd+k-headersize+3);
}
A = EXTRACT_LONG(&pd[k-headersize]);
-
+
continue;
-
+
case BPF_LD|BPF_H|BPF_IND:
k = X + pc->k;
if (k + sizeof(short) > buflen) {
return 0;
}
-
+
if(k + (int)sizeof(short) < headersize) A = EXTRACT_SHORT(&p[k]);
else if(k == headersize){
A=(u_short)*((u_char *)p+k)<<8|
if ((int)k >= (int)buflen) {
return 0;
}
-
+
if((pc->k)<headersize) X = (p[pc->k] & 0xf) << 2;
else X = (pd[(pc->k)-headersize] & 0xf) << 2;
case BPF_LD|BPF_MEM:
A = mem[pc->k];
continue;
-
+
case BPF_LDX|BPF_MEM:
X = mem[pc->k];
continue;
case BPF_LDX|BPF_MEM_EX_IMM|BPF_W:
X = EXTRACT_LONG(&mem_ex->buffer[pc->k]);
continue;
-
+
case BPF_LD|BPF_MEM_EX_IND|BPF_B:
k = X + pc->k;
if ((int32)k>= (int32)mem_ex->size) {
A=EXTRACT_LONG((uint32*)&mem_ex->buffer[k]);
continue;
/* END LD NO PACKET INSTRUCTIONS */
-
+
case BPF_ST:
mem[pc->k] = A;
continue;
*(uint16*)&mem_ex->buffer[pc->k+X]=EXTRACT_SHORT(&tmp2);
continue;
/* END STORE INSTRUCTIONS */
-
-
-
+
+
+
case BPF_JMP|BPF_JA:
pc += pc->k;
continue;
case BPF_ALU|BPF_ADD|BPF_X:
A += X;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_X:
A -= X;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_X:
A *= X;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_X:
if (X == 0)
return 0;
A /= X;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_X:
A &= X;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_X:
A |= X;
continue;
case BPF_ALU|BPF_ADD|BPF_K:
A += pc->k;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_K:
A -= pc->k;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_K:
A *= pc->k;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_K:
A /= pc->k;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_K:
A &= pc->k;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_K:
A |= pc->k;
continue;
case BPF_MISC|BPF_TME|BPF_LOOKUP:
j=lookup_frontend(mem_ex,tme,pc->k,time_ref);
if (j==TME_ERROR)
- return 0;
+ return 0;
pc += (j == TME_TRUE) ? pc->jt : pc->jf;
continue;
bpf_validate(f, len,mem_ex_size)
struct bpf_insn *f;
int32 len;
- uint32 mem_ex_size;
+ uint32 mem_ex_size;
{
register int32 i,j;
register struct bpf_insn *p;
int32 flag;
-
+
for (i = 0; i < len; ++i) {
/*
- * Check that that jumps are forward, and within
+ * Check that that jumps are forward, and within
* the code block.
*/
-
+
p = &f[i];
IF_LOUD(DbgPrint("Validating program");)
-
+
flag=0;
for(j=0;j<VALID_INSTRUCTIONS_LEN;j++)
if (p->code==valid_instructions[j])
return 0;
IF_LOUD(DbgPrint("Validating program: no unknown instructions");)
-
+
if (BPF_CLASS(p->code) == BPF_JMP) {
register int32 from = i + 1;
}
IF_LOUD(DbgPrint("Validating program: no wrong JUMPS");)
-
+
/*
* Check that memory operations use valid addresses.
*/
if (((BPF_CLASS(p->code) == BPF_ST && ((p->code &BPF_MEM_EX_IMM)!=BPF_MEM_EX_IMM && (p->code &BPF_MEM_EX_IND)!=BPF_MEM_EX_IND)) ||
- (BPF_CLASS(p->code) == BPF_LD &&
+ (BPF_CLASS(p->code) == BPF_LD &&
(p->code & 0xe0) == BPF_MEM)) &&
(p->k >= BPF_MEMWORDS || p->k < 0))
return 0;
-
+
IF_LOUD(DbgPrint("Validating program: no wrong ST/LD memory locations");)
-
+
/*
- * Check if key stores use valid addresses
- */
+ * Check if key stores use valid addresses
+ */
if (BPF_CLASS(p->code) == BPF_ST && (p->code &BPF_MEM_EX_IMM)==BPF_MEM_EX_IMM)
switch (BPF_SIZE(p->code))
{
*
* This code is derived from the Stanford/CMU enet packet filter,
* (net/enet.c) distributed as part of 4.3BSD, and code contributed
- * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
+ * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
* Berkeley Laboratory.
*
* Redistribution and use in source and binary forms, with or without
case BPF_LD|BPF_MEM:
A = mem[pc->k];
continue;
-
+
case BPF_LDX|BPF_MEM:
X = mem[pc->k];
continue;
:"=a"(X),"=c"(tmp): );
#endif
continue;
-
+
case BPF_LD|BPF_MEM_EX_IND|BPF_B:
k = X + pc->k;
if ((int32)k>= (int32)mem_ex->size) {
case BPF_ALU|BPF_ADD|BPF_X:
A += X;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_X:
A -= X;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_X:
A *= X;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_X:
if (X == 0)
return 0;
A /= X;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_X:
A &= X;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_X:
A |= X;
continue;
case BPF_ALU|BPF_ADD|BPF_K:
A += pc->k;
continue;
-
+
case BPF_ALU|BPF_SUB|BPF_K:
A -= pc->k;
continue;
-
+
case BPF_ALU|BPF_MUL|BPF_K:
A *= pc->k;
continue;
-
+
case BPF_ALU|BPF_DIV|BPF_K:
A /= pc->k;
continue;
-
+
case BPF_ALU|BPF_AND|BPF_K:
A &= pc->k;
continue;
-
+
case BPF_ALU|BPF_OR|BPF_K:
A |= pc->k;
continue;
case BPF_MISC|BPF_TME|BPF_LOOKUP:
j=lookup_frontend(mem_ex,tme,pc->k,time_ref);
if (j==TME_ERROR)
- return 0;
+ return 0;
pc += (j == TME_TRUE) ? pc->jt : pc->jf;
continue;
if (init_tme_block(tme,pc->k)==TME_ERROR)
return 0;
continue;
-
+
case BPF_MISC|BPF_TME|BPF_VALIDATE:
if (validate_tme_block(mem_ex,tme,A,pc->k)==TME_ERROR)
return 0;
case BPF_MISC|BPF_TME|BPF_SET_AUTODELETION:
set_autodeletion(&tme->block_data[tme->working],pc->k);
continue;
-
+
/* END TME INSTRUCTIONS */
}
for(i=0;i<Open->Nwrites;i++){
-
+
// Try to get a packet from our list of free ones
NdisAllocatePacket(
&Status,
&pPacket,
Open->PacketPool
);
-
+
if (Status != NDIS_STATUS_SUCCESS) {
-
+
// No free packets
Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
IoCompleteRequest (Irp, IO_NO_INCREMENT);
return STATUS_INSUFFICIENT_RESOURCES;
}
-
+
// The packet has a buffer that needs not to be freed after every single write
RESERVED(pPacket)->FreeBufAfterWrite = FALSE;
// Save the IRP associated with the packet
RESERVED(pPacket)->Irp=Irp;
-
+
// Attach the writes buffer to the packet
NdisChainBufferAtFront(pPacket,Irp->MdlAddress);
-
+
// Call the MAC
NdisSend(
&Status,
pPacket,
Status
);
-
+
}
-
+
if(i%100==99){
- NdisWaitEvent(&Open->WriteEvent,1000);
+ NdisWaitEvent(&Open->WriteEvent,1000);
NdisResetEvent(&Open->WriteEvent);
}
}
-
+
return(STATUS_PENDING);
}
INT
NPF_BufferedWrite(
- IN PIRP Irp,
- IN PCHAR UserBuff,
- IN ULONG UserBuffSize,
+ IN PIRP Irp,
+ IN PCHAR UserBuff,
+ IN ULONG UserBuffSize,
BOOLEAN Sync)
{
POPEN_INSTANCE Open;
PMDL TmpMdl;
PCHAR CurPos;
PCHAR EndOfUserBuff = UserBuff + UserBuffSize;
-
+
IF_LOUD(DbgPrint("NPF: BufferedWrite, UserBuff=%x, Size=%u\n", UserBuff, UserBuffSize);)
-
+
IrpSp = IoGetCurrentIrpStackLocation(Irp);
-
+
Open=IrpSp->FileObject->FsContext;
-
+
// Security check on the length of the user buffer
if(UserBuff==0)
{
return 0;
}
-
+
// Check that the MaxFrameSize is correctly initialized
if(Open->MaxFrameSize == 0)
{
return 0;
}
-
+
// Start from the first packet
winpcap_hdr = (struct sf_pkthdr*)UserBuff;
-
+
// Retrieve the time references
StartTicks = KeQueryPerformanceCounter(&TimeFreq);
BufStartTime.tv_sec = winpcap_hdr->ts.tv_sec;
BufStartTime.tv_usec = winpcap_hdr->ts.tv_usec;
-
+
// Chech the consistency of the user buffer
if( (PCHAR)winpcap_hdr + winpcap_hdr->caplen + sizeof(struct sf_pkthdr) > EndOfUserBuff )
{
return -1;
}
-
+
// Save the current time stamp counter
CurTicks = KeQueryPerformanceCounter(NULL);
-
+
// Main loop: send the buffer to the wire
while( TRUE ){
-
+
if(winpcap_hdr->caplen ==0 || winpcap_hdr->caplen > Open->MaxFrameSize)
{
// Malformed header
IF_LOUD(DbgPrint("NPF_BufferedWrite: malformed or bogus user buffer, aborting write.\n");)
-
+
return -1;
}
-
+
// Allocate an MDL to map the packet data
TmpMdl=IoAllocateMdl((PCHAR)winpcap_hdr + sizeof(struct sf_pkthdr),
winpcap_hdr->caplen,
FALSE,
FALSE,
NULL);
-
+
if (TmpMdl == NULL)
{
// Unable to map the memory: packet lost
return -1;
}
-
+
MmBuildMdlForNonPagedPool(TmpMdl); // XXX can this line be removed?
-
+
// Allocate a packet from our free list
NdisAllocatePacket( &Status, &pPacket, Open->PacketPool);
-
+
if (Status != NDIS_STATUS_SUCCESS) {
// No free packets
IF_LOUD(DbgPrint("NPF_BufferedWrite: no more free packets, returning.\n");)
return (PCHAR)winpcap_hdr - UserBuff;
}
-
+
// The packet has a buffer that needs to be freed after every single write
RESERVED(pPacket)->FreeBufAfterWrite = TRUE;
-
+
// Attach the MDL to the packet
NdisChainBufferAtFront(pPacket,TmpMdl);
-
+
// Call the MAC
NdisSend( &Status, Open->AdapterHandle, pPacket);
-
+
if (Status != NDIS_STATUS_PENDING) {
// The send didn't pend so call the completion handler now
NPF_SendComplete(
Open,
pPacket,
Status
- );
+ );
}
-
+
// Step to the next packet in the buffer
(PCHAR)winpcap_hdr += winpcap_hdr->caplen + sizeof(struct sf_pkthdr);
-
+
// Check if the end of the user buffer has been reached
if( (PCHAR)winpcap_hdr >= EndOfUserBuff )
{
return (PCHAR)winpcap_hdr - UserBuff;
}
-
+
if( Sync ){
// Release the application if it has been blocked for approximately more than 1 seconds
if( winpcap_hdr->ts.tv_sec - BufStartTime.tv_sec > 1 )
{
IF_LOUD(DbgPrint("NPF_BufferedWrite: timestamp elapsed, returning.\n");)
-
+
return (PCHAR)winpcap_hdr - UserBuff;
}
-
+
#ifndef __GNUC__
// Calculate the time interval to wait before sending the next packet
TargetTicks.QuadPart = StartTicks.QuadPart +
#else
#endif
}
-
+
}
-
+
return (PCHAR)winpcap_hdr - UserBuff;
-
+
}
IN PNDIS_PACKET pPacket,
IN NDIS_STATUS Status
)
-
+
{
PIRP Irp;
PIO_STACK_LOCATION irpSp;
POPEN_INSTANCE Open;
PMDL TmpMdl;
-
+
IF_LOUD(DbgPrint("NPF: SendComplete, BindingContext=%d\n",ProtocolBindingContext);)
-
+
Open= (POPEN_INSTANCE)ProtocolBindingContext;
-
+
if( RESERVED(pPacket)->FreeBufAfterWrite ){
// Free the MDL associated with the packet
NdisUnchainBufferAtFront(pPacket, &TmpMdl);
else{
if((Open->Nwrites - Open->Multiple_Write_Counter) %100 == 99)
NdisSetEvent(&Open->WriteEvent);
-
+
Open->Multiple_Write_Counter--;
}
-
+
// recyle the packet
NdisReinitializePacket(pPacket);
-
+
// Put the packet back on the free list
NdisFreePacket(pPacket);
-
+
if( !(RESERVED(pPacket)->FreeBufAfterWrite) ){
if(Open->Multiple_Write_Counter==0){
// Release the buffer and awake the application
NdisUnchainBufferAtFront(pPacket, &TmpMdl);
-
+
Irp=RESERVED(pPacket)->Irp;
irpSp = IoGetCurrentIrpStackLocation(Irp);
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = irpSp->Parameters.Write.Length;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
-
+
}
}
LIST_ENTRY LanSendCompleteList;
VOID LanChainCompletion( PLAN_ADAPTER Adapter, PNDIS_PACKET NdisPacket ) {
- PLAN_WQ_ITEM PendingCompletion =
+ PLAN_WQ_ITEM PendingCompletion =
ExAllocatePool( NonPagedPool, sizeof(LAN_WQ_ITEM) );
-
+
if( !PendingCompletion ) return;
PendingCompletion->Packet = NdisPacket;
ListEntry = ListEntry->Flink ) {
CompleteEntry = CONTAINING_RECORD(ListEntry, LAN_WQ_ITEM, ListEntry);
- if( CompleteEntry->Adapter == Adapter &&
+ if( CompleteEntry->Adapter == Adapter &&
CompleteEntry->Packet == NdisPacket ) {
RemoveEntryList( ListEntry );
KeReleaseSpinLock( &LanSendCompleteLock, OldIrql );
IP_PACKET IPPacket;
TI_DbgPrint(DEBUG_DATALINK, ("Called.\n"));
-
- while( (ListEntry =
+
+ while( (ListEntry =
ExInterlockedRemoveHeadList( &LanWorkList, &LanWorkLock )) ) {
WorkItem = CONTAINING_RECORD(ListEntry, LAN_WQ_ITEM, ListEntry);
ExFreePool( WorkItem );
IPPacket.NdisPacket = Packet;
-
+
NdisGetFirstBufferFromPacket(Packet,
&NdisBuffer,
&IPPacket.Header,
(DEBUG_DATALINK,
("Ether Type = %x ContigSize = %d Total = %d\n",
PacketType, IPPacket.ContigSize, IPPacket.TotalSize));
-
+
switch (PacketType) {
case ETYPE_IPv4:
case ETYPE_IPv6:
LanReceiveWorkerBusy = FALSE;
}
-VOID LanSubmitReceiveWork(
+VOID LanSubmitReceiveWork(
NDIS_HANDLE BindingContext,
PNDIS_PACKET Packet,
NDIS_STATUS Status,
TI_DbgPrint(DEBUG_DATALINK,("called\n"));
TcpipAcquireSpinLock( &LanWorkLock, &OldIrql );
-
+
WQItem = ExAllocatePool( NonPagedPool, sizeof(LAN_WQ_ITEM) );
if( !WQItem ) {
TcpipReleaseSpinLock( &LanWorkLock, OldIrql );
/* Get a transfer data packet */
- TI_DbgPrint(DEBUG_DATALINK, ("Adapter: %x (MTU %d)\n",
+ TI_DbgPrint(DEBUG_DATALINK, ("Adapter: %x (MTU %d)\n",
Adapter, Adapter->MTU));
TcpipAcquireSpinLock( &LanWorkLock, &OldIrql );
ASSERT(PacketSize <= Adapter->MTU);
NdisTransferData(&NdisStatus, Adapter->NdisHandle,
- MacReceiveContext, 0, PacketSize,
+ MacReceiveContext, 0, PacketSize,
NdisPacket, &BytesTransferred);
}
else
KIRQL OldIrql;
PLAN_ADAPTER Adapter = (PLAN_ADAPTER)Context;
- TI_DbgPrint(DEBUG_DATALINK,
+ TI_DbgPrint(DEBUG_DATALINK,
("Called( NdisPacket %x, Offset %d, Adapter %x )\n",
NdisPacket, Offset, Adapter));
Adapter->HWAddress[4] & 0xff,
Adapter->HWAddress[5] & 0xff));
- /* XXX arty -- Handled adjustment in a saner way than before ...
+ /* XXX arty -- Handled adjustment in a saner way than before ...
* not needed immediately */
GetDataPtr( NdisPacket, 0, &Data, &Size );
- LanChainCompletion( Adapter, NdisPacket );
+ LanChainCompletion( Adapter, NdisPacket );
if (Adapter->State == LAN_STATE_STARTED) {
switch (Adapter->Media) {
TI_DbgPrint( MID_TRACE, ("LinkAddress: %x\n", LinkAddress));
if( LinkAddress ) {
TI_DbgPrint
- ( MID_TRACE,
- ("Link Address [%02x %02x %02x %02x %02x %02x]\n",
+ ( MID_TRACE,
+ ("Link Address [%02x %02x %02x %02x %02x %02x]\n",
((PCHAR)LinkAddress)[0] & 0xff,
((PCHAR)LinkAddress)[1] & 0xff,
((PCHAR)LinkAddress)[2] & 0xff,
TcpipAcquireSpinLock( &Adapter->Lock, &OldIrql );
TI_DbgPrint(MID_TRACE, ("NdisSend\n"));
NdisSend(&NdisStatus, Adapter->NdisHandle, NdisPacket);
- TI_DbgPrint(MID_TRACE, ("NdisSend %s\n",
+ TI_DbgPrint(MID_TRACE, ("NdisSend %s\n",
NdisStatus == NDIS_STATUS_PENDING ?
"Pending" : "Complete"));
TcpipReleaseSpinLock( &Adapter->Lock, OldIrql );
- /* I had a talk with vizzini: these really ought to be here.
- * we're supposed to see these completed by ndis *only* when
+ /* I had a talk with vizzini: these really ought to be here.
+ * we're supposed to see these completed by ndis *only* when
* status_pending is returned. Note that this is different from
* the situation with IRPs. */
if (NdisStatus != NDIS_STATUS_PENDING)
}
}
-static NTSTATUS
+static NTSTATUS
OpenRegistryKey( PNDIS_STRING RegistryPath, PHANDLE RegHandle ) {
OBJECT_ATTRIBUTES Attributes;
NTSTATUS Status;
-
+
InitializeObjectAttributes(&Attributes, RegistryPath, OBJ_CASE_INSENSITIVE, 0, 0);
Status = ZwOpenKey(RegHandle, KEY_ALL_ACCESS, &Attributes);
return Status;
PKEY_VALUE_PARTIAL_INFORMATION Information = (PKEY_VALUE_PARTIAL_INFORMATION)buf;
RtlInitUnicodeString(&ValueName, RegistryValue);
- Status =
- ZwQueryValueKey(RegHandle,
- &ValueName,
- KeyValuePartialInformation,
- Information,
- sizeof(buf),
+ Status =
+ ZwQueryValueKey(RegHandle,
+ &ValueName,
+ KeyValuePartialInformation,
+ Information,
+ sizeof(buf),
&ResultLength);
if (!NT_SUCCESS(Status))
return Status;
/* IP address is stored as a REG_MULTI_SZ - we only pay attention to the first one though */
TI_DbgPrint(MIN_TRACE, ("Information DataLength: 0x%x\n", Information->DataLength));
-
+
UnicodeString.Buffer = (PWCHAR)&Information->Data;
UnicodeString.Length = Information->DataLength - sizeof(WCHAR);
UnicodeString.MaximumLength = Information->DataLength;
-
- String->Buffer =
- (PWCHAR)exAllocatePool( NonPagedPool,
+
+ String->Buffer =
+ (PWCHAR)exAllocatePool( NonPagedPool,
UnicodeString.MaximumLength + sizeof(WCHAR) );
if( !String->Buffer ) return STATUS_NO_MEMORY;
return STATUS_SUCCESS;
}
-/*
+/*
* Utility to copy and append two unicode strings.
*
* IN OUT PUNICODE_STRING ResultFirst -> First string and result
ResultFirst->Length = Ustr.Length + Second->Length;
ResultFirst->MaximumLength = ResultFirst->Length;
new_string[ResultFirst->Length / sizeof(WCHAR)] = 0;
- Status = RtlCreateUnicodeString(ResultFirst,new_string) ?
+ Status = RtlCreateUnicodeString(ResultFirst,new_string) ?
STATUS_SUCCESS : STATUS_NO_MEMORY;
ExFreePool(new_string);
return Status;
HANDLE EnumKey;
NTSTATUS Status;
ULONG i;
- KEY_BASIC_INFORMATION *Kbio =
+ KEY_BASIC_INFORMATION *Kbio =
ExAllocatePool(NonPagedPool, sizeof(KEY_BASIC_INFORMATION));
ULONG KbioLength = sizeof(KEY_BASIC_INFORMATION), ResultLength;
Status = OpenRegistryKey( &EnumKeyName, &EnumKey );
if( !NT_SUCCESS(Status) )
- TI_DbgPrint(DEBUG_DATALINK,("Couldn't open Enum key %wZ: %x\n",
+ TI_DbgPrint(DEBUG_DATALINK,("Couldn't open Enum key %wZ: %x\n",
&EnumKeyName, Status));
-
+
for( i = 0; NT_SUCCESS(Status); i++ ) {
- Status = ZwEnumerateKey( EnumKey, i, KeyBasicInformation,
+ Status = ZwEnumerateKey( EnumKey, i, KeyBasicInformation,
Kbio, KbioLength, &ResultLength );
if( Status == STATUS_BUFFER_TOO_SMALL ) {
}
if( NT_SUCCESS(Status) ) {
- TargetKeyName.Length = TargetKeyName.MaximumLength =
+ TargetKeyName.Length = TargetKeyName.MaximumLength =
Kbio->NameLength;
TargetKeyName.Buffer = Kbio->Name;
VOID GetShortName( PUNICODE_STRING RegistryKey,
PUNICODE_STRING ShortNameOut ) {
PWCHAR Ptr;
- ShortNameOut->Buffer =
+ ShortNameOut->Buffer =
RegistryKey->Buffer + wcslen(CCS_ROOT L"\\Services\\");
Ptr = ShortNameOut->Buffer;
- while( *Ptr != L'\\' &&
- ((PCHAR)Ptr) < ((PCHAR)RegistryKey->Buffer) + RegistryKey->Length )
+ while( *Ptr != L'\\' &&
+ ((PCHAR)Ptr) < ((PCHAR)RegistryKey->Buffer) + RegistryKey->Length )
Ptr++;
- ShortNameOut->Length = ShortNameOut->MaximumLength =
+ ShortNameOut->Length = ShortNameOut->MaximumLength =
(Ptr - ShortNameOut->Buffer) * sizeof(WCHAR);
}
return;
}
- /*
- * Query per-adapter configuration from the registry
+ /*
+ * Query per-adapter configuration from the registry
* In case anyone is curious: there *is* an Ndis configuration api
* for this sort of thing, but it doesn't really support things like
* REG_MULTI_SZ very well, and there is a note in the DDK that says that
* protocol drivers developed for win2k and above just use the native
* services (ZwOpenKey, etc).
*/
-
+
Status = OpenRegistryKey( RegistryPath, &RegHandle );
-
+
if(NT_SUCCESS(Status)) {
Status = FindDeviceNameForAdapter( &ShortName, &IF->Name );
TI_DbgPrint(DEBUG_DATALINK,("Adapter Name: %wZ\n", &IF->Name));
IF->Netmask = DefaultMask;
IF->Broadcast.Type = IP_ADDRESS_V4;
- IF->Broadcast.Address.IPv4Address =
- IF->Unicast.Address.IPv4Address |
+ IF->Broadcast.Address.IPv4Address =
+ IF->Unicast.Address.IPv4Address |
~IF->Netmask.Address.IPv4Address;
TI_DbgPrint(DEBUG_DATALINK,("BCAST(IF) %s\n", A2S(&IF->Broadcast)));
IF->HeaderSize = sizeof(ETH_HEADER);
IF->MinFrameSize = 60;
AddressOID = OID_802_3_CURRENT_ADDRESS;
- IF->PacketFilter =
+ IF->PacketFilter =
NDIS_PACKET_TYPE_BROADCAST |
NDIS_PACKET_TYPE_DIRECTED |
NDIS_PACKET_TYPE_MULTICAST;
ULONG Metric3;
ULONG Metric4;
ULONG Gw;
- ULONG Type;
+ ULONG Type;
ULONG Proto;
- ULONG Age;
+ ULONG Age;
ULONG Mask;
ULONG Metric5;
ULONG Info;
ULONG OutQLen;
ULONG DescrLen;
} IFENTRY, *PIFENTRY;
-
+
#define IP_MIB_STATS_ID 1
#define IF_MIB_STATS_ID 1
/* Packet context */
typedef struct _PACKET_CONTEXT {
PACKET_COMPLETION_ROUTINE DLComplete; /* Data link level completion handler
- * Also used to link to next packet
+ * Also used to link to next packet
* in a queue */
PVOID Context; /* Context information for handler */
UINT PacketType; /* Type of packet */
VOID LANStartup();
VOID LANShutdown();
-NTSTATUS TcpipLanGetDwordOid( PIP_INTERFACE Interface, NDIS_OID Oid,
+NTSTATUS TcpipLanGetDwordOid( PIP_INTERFACE Interface, NDIS_OID Oid,
PDWORD Result );
NDIS_STATUS NDISCall(
/*
* Those macros may have been defined in <gnu/types.h>. But we always
- * use the ones here.
+ * use the ones here.
*/
#undef __NFDBITS
#define __NFDBITS (8 * sizeof(unsigned long))
#define ____cacheline_aligned
-typedef struct
+typedef struct
{
volatile unsigned int lock;
} rwlock_t;
/**
* atomic_read - read atomic variable
* @v: pointer of type atomic_t
- *
+ *
* Atomically reads the value of @v. Note that the guaranteed
* useful range of an atomic_t is only 24 bits.
- */
+ */
#define atomic_read(v) ((v)->counter)
/**
* atomic_set - set atomic variable
* @v: pointer of type atomic_t
* @i: required value
- *
+ *
* Atomically sets the value of @v to @i. Note that the guaranteed
* useful range of an atomic_t is only 24 bits.
- */
+ */
#define atomic_set(v,i) (((v)->counter) = (i))
/**
* atomic_add - add integer to atomic variable
* @i: integer value to add
* @v: pointer of type atomic_t
- *
+ *
* Atomically adds @i to @v. Note that the guaranteed useful range
* of an atomic_t is only 24 bits.
*/
* atomic_sub - subtract the atomic variable
* @i: integer value to subtract
* @v: pointer of type atomic_t
- *
+ *
* Atomically subtracts @i from @v. Note that the guaranteed
* useful range of an atomic_t is only 24 bits.
*/
* atomic_sub_and_test - subtract value from variable and test result
* @i: integer value to subtract
* @v: pointer of type atomic_t
- *
+ *
* Atomically subtracts @i from @v and returns
* true if the result is zero, or false for all
* other cases. Note that the guaranteed
/**
* atomic_inc - increment atomic variable
* @v: pointer of type atomic_t
- *
+ *
* Atomically increments @v by 1. Note that the guaranteed
* useful range of an atomic_t is only 24 bits.
- */
+ */
static __inline__ void atomic_inc(atomic_t *v)
{
#if 0
/**
* atomic_dec - decrement atomic variable
* @v: pointer of type atomic_t
- *
+ *
* Atomically decrements @v by 1. Note that the guaranteed
* useful range of an atomic_t is only 24 bits.
- */
+ */
static __inline__ void atomic_dec(atomic_t *v)
{
#if 0
/**
* atomic_dec_and_test - decrement and test
* @v: pointer of type atomic_t
- *
+ *
* Atomically decrements @v by 1 and
* returns true if the result is 0, or false for all other
* cases. Note that the guaranteed
* useful range of an atomic_t is only 24 bits.
- */
+ */
static __inline__ int atomic_dec_and_test(atomic_t *v)
{
#if 0
}
/**
- * atomic_inc_and_test - increment and test
+ * atomic_inc_and_test - increment and test
* @v: pointer of type atomic_t
- *
+ *
* Atomically increments @v by 1
* and returns true if the result is zero, or false for all
* other cases. Note that the guaranteed
* useful range of an atomic_t is only 24 bits.
- */
+ */
static __inline__ int atomic_inc_and_test(atomic_t *v)
{
#if 0
* atomic_add_negative - add and test if negative
* @v: pointer of type atomic_t
* @i: integer value to add
- *
+ *
* Atomically adds @i to @v and returns true
* if the result is negative, or false when
* result is greater than or equal to zero. Note that the guaranteed
* useful range of an atomic_t is only 24 bits.
- */
+ */
static __inline__ int atomic_add_negative(int i, atomic_t *v)
{
#if 0
} while (0)
/*
- * Insert a new entry between two known consecutive entries.
+ * Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
{
#if 0
__list_del(entry->prev, entry->next);
- INIT_LIST_HEAD(entry);
+ INIT_LIST_HEAD(entry);
#endif
}
#if 0
for (pos = (head)->prev, prefetch(pos->prev); pos != (head); \
pos = pos->prev, prefetch(pos->prev))
-#endif
+#endif
/**
* list_for_each_safe - iterate over a list safe against removal of list entry
/*
* UIO_MAXIOV shall be at least 16 1003.1g (5.4.1.1)
*/
-
+
#define UIO_FASTIOV 8
#define UIO_MAXIOV 1024
#if 0
-#define UIO_MAXIOV 16 /* Maximum iovec's in one operation
+#define UIO_MAXIOV 16 /* Maximum iovec's in one operation
16 matches BSD */
/* Beg pardon: BSD has 1024 --ANK */
#endif
extern VOID TcpipAcquireFastMutex( PFAST_MUTEX Mutex );
extern VOID TcpipReleaseFastMutex( PFAST_MUTEX Mutex );
extern VOID TcpipRecursiveMutexInit( PRECURSIVE_MUTEX RecMutex );
-extern UINT TcpipRecursiveMutexEnter( PRECURSIVE_MUTEX RecMutex,
+extern UINT TcpipRecursiveMutexEnter( PRECURSIVE_MUTEX RecMutex,
BOOL ToWrite );
extern VOID TcpipRecursiveMutexLeave( PRECURSIVE_MUTEX RecMutex );
#ifdef MEMTRACK
#define MTMARK() TrackDumpFL(__FILE__, __LINE__)
-#define exAllocatePool(x,y) ExAllocatePoolX(x,y,__FILE__,__LINE__)
+#define exAllocatePool(x,y) ExAllocatePoolX(x,y,__FILE__,__LINE__)
#define exAllocatePoolWithTag(x,y,z) ExAllocatePoolX(x,y,__FILE__,__LINE__)
#define exFreePool(x) ExFreePoolX(x,__FILE__,__LINE__)
PVOID Buffer);
PVOID TcpipAllocateFromNPagedLookasideList( PNPAGED_LOOKASIDE_LIST List );
-VOID TcpipFreeToNPagedLookasideList( PNPAGED_LOOKASIDE_LIST List,
+VOID TcpipFreeToNPagedLookasideList( PNPAGED_LOOKASIDE_LIST List,
PVOID Thing );
NDIS_STATUS PrependPacket( PNDIS_PACKET Packet, PCHAR Data, UINT Len,
BOOLEAN Copy );
FAST_MUTEX Mutex;
} PORT_SET, *PPORT_SET;
-VOID PortsStartup( PPORT_SET PortSet,
+VOID PortsStartup( PPORT_SET PortSet,
UINT StartingPort,
UINT PortsToManage );
VOID PortsShutdown( PPORT_SET PortSet );
PCHAR File, UINT Line );
void GetDataPtr( PNDIS_PACKET Packet,
- UINT Offset,
+ UINT Offset,
PCHAR *DataOut,
PUINT Size );
#ifndef __TCP_H
#define __TCP_H
-typedef VOID
+typedef VOID
(*PTCP_COMPLETION_ROUTINE)( PVOID Context, NTSTATUS Status, ULONG Count );
/* TCPv4 header structure */
PCONNECTION_ENDPOINT TCPAllocateConnectionEndpoint( PVOID ClientContext );
VOID TCPFreeConnectionEndpoint( PCONNECTION_ENDPOINT Connection );
-NTSTATUS TCPSocket( PCONNECTION_ENDPOINT Connection,
+NTSTATUS TCPSocket( PCONNECTION_ENDPOINT Connection,
UINT Family, UINT Type, UINT Proto );
PTCP_SEGMENT TCPCreateSegment(
PVOID Context);
NTSTATUS TCPReceiveData(
- PCONNECTION_ENDPOINT Connection,
+ PCONNECTION_ENDPOINT Connection,
PNDIS_BUFFER Buffer,
ULONG ReceiveLength,
PULONG BytesReceived,
VOID TCPFreePort( UINT Port );
NTSTATUS TCPGetPeerAddress
-( PCONNECTION_ENDPOINT Connection,
+( PCONNECTION_ENDPOINT Connection,
PTRANSPORT_ADDRESS TransportAddress );
NTSTATUS TCPStartup(
struct ipxhdr *ipxh;
unsigned char *raw;
} nh;
-
+
/* Link layer header */
- union
- {
+ union
+ {
struct ethhdr *ethernet;
unsigned char *raw;
} mac;
struct dst_entry *dst;
- /*
+ /*
* This is the control buffer. It is free to use for every
* layer. Please put your private variables there. If you
* want to keep them across layers you have to do a skb_clone()
* first. This is owned by whoever has the skb queued ATM.
- */
- char cb[48];
+ */
+ char cb[48];
unsigned int len; /* Length of actual data */
unsigned int data_len;
extern struct sk_buff * pskb_copy(struct sk_buff *skb, int gfp_mask);
extern int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail, int gfp_mask);
extern struct sk_buff * skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom);
-extern struct sk_buff * skb_copy_expand(const struct sk_buff *skb,
+extern struct sk_buff * skb_copy_expand(const struct sk_buff *skb,
int newheadroom,
int newtailroom,
int priority);
*
* Returns true if the queue is empty, false otherwise.
*/
-
+
static inline int skb_queue_empty(struct sk_buff_head *list)
{
return (list->next == (struct sk_buff *) list);
* Makes another reference to a socket buffer and returns a pointer
* to the buffer.
*/
-
+
static inline struct sk_buff *skb_get(struct sk_buff *skb)
{
atomic_inc(&skb->users);
* If users==1, we are the only owner and are can avoid redundant
* atomic change.
*/
-
+
/**
* kfree_skb - free an sk_buff
* @skb: buffer to free
* Drop a reference to the buffer and free it if the usage count has
* hit zero.
*/
-
+
static inline void kfree_skb(struct sk_buff *skb)
{
if (atomic_read(&skb->users) == 1 || atomic_dec_and_test(&skb->users))
static inline void kfree_skb_fast(struct sk_buff *skb)
{
if (atomic_read(&skb->users) == 1 || atomic_dec_and_test(&skb->users))
- kfree_skbmem(skb);
+ kfree_skbmem(skb);
}
/**
* Returns true if more than one person has a reference to this
* buffer.
*/
-
+
static inline int skb_shared(struct sk_buff *skb)
{
return (atomic_read(&skb->users) != 1);
}
-/**
+/**
* skb_share_check - check if buffer is shared and if so clone it
* @skb: buffer to check
* @pri: priority for memory allocation
- *
+ *
* If the buffer is shared the buffer is cloned and the old copy
* drops a reference. A new clone with a single reference is returned.
* If the buffer is not shared the original buffer is returned. When
*
* NULL is returned on a memory allocation failure.
*/
-
+
static inline struct sk_buff *skb_share_check(struct sk_buff *skb, int pri)
{
if (skb_shared(skb)) {
* and a couple of other messy ones. The normal one is tcpdumping
* a packet thats being forwarded.
*/
-
+
/**
* skb_unshare - make a copy of a shared buffer
* @skb: buffer to check
*
* %NULL is returned on a memory allocation failure.
*/
-
+
static inline struct sk_buff *skb_unshare(struct sk_buff *skb, int pri)
{
struct sk_buff *nskb;
* The reference count is not incremented and the reference is therefore
* volatile. Use with caution.
*/
-
+
static inline struct sk_buff *skb_peek(struct sk_buff_head *list_)
{
struct sk_buff *list = ((struct sk_buff *)list_)->next;
* skb_queue_len - get queue length
* @list_: list to measure
*
- * Return the length of an &sk_buff queue.
+ * Return the length of an &sk_buff queue.
*/
-
+
static inline __u32 skb_queue_len(struct sk_buff_head *list_)
{
return(list_->qlen);
* and you must therefore hold required locks before calling it.
*
* A buffer cannot be placed on two lists at the same time.
- */
-
+ */
+
static inline void __skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
{
struct sk_buff *prev, *next;
* safely.
*
* A buffer cannot be placed on two lists at the same time.
- */
+ */
static inline void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
{
* and you must therefore hold required locks before calling it.
*
* A buffer cannot be placed on two lists at the same time.
- */
-
+ */
+
static inline void __skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
{
* safely.
*
* A buffer cannot be placed on two lists at the same time.
- */
+ */
static inline void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
{
* remove sk_buff from list. _Must_ be called atomically, and with
* the list known..
*/
-
+
static inline void __skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
{
struct sk_buff * next, * prev;
*
* Place a packet after a given packet in a list. The list locks are taken
* and this function is atomic with respect to other list locked calls
- *
- * Works even without knowing the list it is sitting on, which can be
- * handy at times. It also means that THE LIST MUST EXIST when you
+ *
+ * Works even without knowing the list it is sitting on, which can be
+ * handy at times. It also means that THE LIST MUST EXIST when you
* unlink. Thus a list must have its contents unlinked before it is
* destroyed.
*/
static inline struct sk_buff *__skb_dequeue_tail(struct sk_buff_head *list)
{
- struct sk_buff *skb = skb_peek_tail(list);
+ struct sk_buff *skb = skb_peek_tail(list);
if (skb)
__skb_unlink(skb, list);
return skb;
/*
* Add data to an sk_buff
*/
-
+
static inline unsigned char *__skb_put(struct sk_buff *skb, unsigned int len)
{
unsigned char *tmp=skb->tail;
/**
* skb_put - add data to a buffer
- * @skb: buffer to use
+ * @skb: buffer to use
* @len: amount of data to add
*
* This function extends the used data area of the buffer. If this would
* exceed the total buffer size the kernel will panic. A pointer to the
* first byte of the extra data is returned.
*/
-
+
static inline unsigned char *skb_put(struct sk_buff *skb, unsigned int len)
{
#if 0
/**
* skb_push - add data to the start of a buffer
- * @skb: buffer to use
+ * @skb: buffer to use
* @len: amount of data to add
*
* This function extends the used data area of the buffer at the buffer
/**
* skb_pull - remove data from the start of a buffer
- * @skb: buffer to use
+ * @skb: buffer to use
* @len: amount of data to remove
*
* This function removes data from the start of a buffer, returning
*/
static inline unsigned char * skb_pull(struct sk_buff *skb, unsigned int len)
-{
+{
if (len > skb->len)
return NULL;
return __skb_pull(skb,len);
}
static inline unsigned char * pskb_pull(struct sk_buff *skb, unsigned int len)
-{
+{
if (len > skb->len)
return NULL;
return __pskb_pull(skb,len);
*
* Return the number of bytes of free space at the head of an &sk_buff.
*/
-
+
static inline int skb_headroom(const struct sk_buff *skb)
{
return skb->data-skb->head;
*
* %NULL is returned in there is no free memory.
*/
-
+
static inline struct sk_buff *__dev_alloc_skb(unsigned int length,
int gfp_mask)
{
* %NULL is returned in there is no free memory. Although this function
* allocates memory it can be called from an interrupt.
*/
-
+
static inline struct sk_buff *dev_alloc_skb(unsigned int length)
{
#if 0
return kmap_atomic(frag->page, KM_SKB_DATA_SOFTIRQ);
#else
return NULL;
-#endif
+#endif
}
static inline void kunmap_skb_frag(void *vaddr)
* transport -> network interface is defined by struct inet_proto
*/
struct proto {
- void (*close)(struct sock *sk,
+ void (*close)(struct sock *sk,
long timeout);
int (*connect)(struct sock *sk,
- struct sockaddr *uaddr,
+ struct sockaddr *uaddr,
int addr_len);
int (*disconnect)(struct sock *sk, int flags);
int (*init)(struct sock *sk);
int (*destroy)(struct sock *sk);
void (*shutdown)(struct sock *sk, int how);
- int (*setsockopt)(struct sock *sk, int level,
+ int (*setsockopt)(struct sock *sk, int level,
int optname, char *optval, int optlen);
- int (*getsockopt)(struct sock *sk, int level,
- int optname, char *optval,
- int *option);
+ int (*getsockopt)(struct sock *sk, int level,
+ int optname, char *optval,
+ int *option);
int (*sendmsg)(struct sock *sk, struct msghdr *msg,
int len);
int (*recvmsg)(struct sock *sk, struct msghdr *msg,
- int len, int noblock, int flags,
+ int len, int noblock, int flags,
int *addr_len);
- int (*bind)(struct sock *sk,
+ int (*bind)(struct sock *sk,
struct sockaddr *uaddr, int addr_len);
- int (*backlog_rcv) (struct sock *sk,
+ int (*backlog_rcv) (struct sock *sk,
struct sk_buff *skb);
/* Keeping track of sk's, looking them up, and port selection methods. */
unsigned long timeout; /* Currently scheduled timeout */
__u32 lrcvtime; /* timestamp of last received data packet*/
__u16 last_seg_size; /* Size of last incoming segment */
- __u16 rcv_mss; /* MSS used for delayed ACK decisions */
+ __u16 rcv_mss; /* MSS used for delayed ACK decisions */
} ack;
/* Data for direct copy to user */
unsigned int keepalive_intvl; /* time interval between keep alive probes */
int linger2;
- unsigned long last_synq_overflow;
+ unsigned long last_synq_overflow;
};
#endif /* CONFIG_FILTER */
/* This is where all the private (optional) areas that don't
- * overlap will eventually live.
+ * overlap will eventually live.
*/
union {
void *destruct_hook;
#if defined(CONFIG_WAN_ROUTER) || defined(CONFIG_WAN_ROUTER_MODULE)
struct wanpipe_opt *af_wanpipe;
#endif
- } protinfo;
+ } protinfo;
/* This part is used for the timeout functions. */
/* RPC layer private data */
void *user_data;
-
+
/* Callbacks */
void (*state_change)(struct sock *sk);
void (*data_ready)(struct sock *sk,int bytes);
void (*error_report)(struct sock *sk);
int (*backlog_rcv) (struct sock *sk,
- struct sk_buff *skb);
+ struct sk_buff *skb);
void (*destruct)(struct sock *sk);
};
#endif
struct dst_ops *ops;
-
+
char info[0];
};
#define MAX_TCP_HEADER (128 + MAX_HEADER)
-/*
+/*
* Never offer a window over 32767 without using window scaling. Some
- * poor stacks do signed 16bit maths!
+ * poor stacks do signed 16bit maths!
*/
#define MAX_TCP_WINDOW 32767U
/*
* TCP option
*/
-
+
#define TCPOPT_NOP 1 /* Padding */
#define TCPOPT_EOL 0 /* End of options */
#define TCPOPT_MSS 2 /* Segment size negotiating */
__u16 mss;
__u8 retrans;
__u8 __pad;
- __u16 snd_wscale : 4,
- rcv_wscale : 4,
+ __u16 snd_wscale : 4,
+ rcv_wscale : 4,
tstamp_ok : 1,
sack_ok : 1,
wscale_ok : 1,
struct sk_buff *skb,
struct open_request *req,
struct dst_entry *dst);
-
+
int (*remember_stamp) (struct sock *sk);
__u16 net_header_len;
- int (*setsockopt) (struct sock *sk,
- int level,
- int optname,
- char *optval,
+ int (*setsockopt) (struct sock *sk,
+ int level,
+ int optname,
+ char *optval,
int optlen);
- int (*getsockopt) (struct sock *sk,
- int level,
- int optname,
- char *optval,
+ int (*getsockopt) (struct sock *sk,
+ int level,
+ int optname,
+ char *optval,
int *optlen);
extern int tcp_sendmsg(struct sock *sk, struct msghdr *msg, int size);
extern ssize_t tcp_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags);
-extern int tcp_ioctl(struct sock *sk,
- int cmd,
+extern int tcp_ioctl(struct sock *sk,
+ int cmd,
unsigned long arg);
-extern int tcp_rcv_state_process(struct sock *sk,
+extern int tcp_rcv_state_process(struct sock *sk,
struct sk_buff *skb,
struct tcphdr *th,
unsigned len);
-extern int tcp_rcv_established(struct sock *sk,
+extern int tcp_rcv_established(struct sock *sk,
struct sk_buff *skb,
- struct tcphdr *th,
+ struct tcphdr *th,
unsigned len);
enum tcp_ack_state_t
extern void tcp_clear_retrans(struct tcp_opt *tp);
extern void tcp_update_metrics(struct sock *sk);
-extern void tcp_close(struct sock *sk,
+extern void tcp_close(struct sock *sk,
long timeout);
extern struct sock * tcp_accept(struct sock *sk, int flags, int *err);
extern unsigned int tcp_poll(struct file * file, struct socket *sock, struct poll_table_struct *wait);
-extern void tcp_write_space(struct sock *sk);
+extern void tcp_write_space(struct sock *sk);
-extern int tcp_getsockopt(struct sock *sk, int level,
- int optname, char *optval,
+extern int tcp_getsockopt(struct sock *sk, int level,
+ int optname, char *optval,
int *optlen);
-extern int tcp_setsockopt(struct sock *sk, int level,
- int optname, char *optval,
+extern int tcp_setsockopt(struct sock *sk, int level,
+ int optname, char *optval,
int optlen);
extern void tcp_set_keepalive(struct sock *sk, int val);
-extern int tcp_recvmsg(struct sock *sk,
+extern int tcp_recvmsg(struct sock *sk,
struct msghdr *msg,
- int len, int nonblock,
+ int len, int nonblock,
int flags, int *addr_len);
extern int tcp_listen_start(struct sock *sk);
extern int tcp_v4_rebuild_header(struct sock *sk);
-extern int tcp_v4_build_header(struct sock *sk,
+extern int tcp_v4_build_header(struct sock *sk,
struct sk_buff *skb);
-extern void tcp_v4_send_check(struct sock *sk,
- struct tcphdr *th, int len,
+extern void tcp_v4_send_check(struct sock *sk,
+ struct tcphdr *th, int len,
struct sk_buff *skb);
extern int tcp_v4_conn_request(struct sock *sk,
/* From syncookies.c */
-extern struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb,
+extern struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb,
struct ip_options *opt);
-extern __u32 cookie_v4_init_sequence(struct sock *sk, struct sk_buff *skb,
+extern __u32 cookie_v4_init_sequence(struct sock *sk, struct sk_buff *skb,
__u16 *mss);
/* tcp_output.c */
{
#if 0
struct tcp_opt *tp = &sk->tp_pinfo.af_tcp;
-
+
switch (what) {
case TCP_TIME_RETRANS:
case TCP_TIME_PROBE0:
#if 0
struct tcp_opt *tp = &sk->tp_pinfo.af_tcp;
struct dst_entry *dst = __sk_dst_get(sk);
- int mss_now = tp->mss_cache;
+ int mss_now = tp->mss_cache;
if (dst && dst->pmtu != tp->pmtu_cookie)
mss_now = tcp_sync_mss(sk, dst->pmtu);
/*
- * Compute minimal free write space needed to queue new packets.
+ * Compute minimal free write space needed to queue new packets.
*/
static inline int tcp_min_write_space(struct sock *sk)
{
return 0;
#endif
}
-
+
static inline int tcp_wspace(struct sock *sk)
{
#if 0
* Calculate(/check) TCP checksum
*/
static __inline__ u16 tcp_v4_check(struct tcphdr *th, int len,
- unsigned long saddr, unsigned long daddr,
+ unsigned long saddr, unsigned long daddr,
unsigned long base)
{
#if 0
#ifdef STATE_TRACE
SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n",sk, statename[oldstate],statename[state]);
-#endif
+#endif
#endif
}
#endif
}
-/* Note: caller must be prepared to deal with negative returns */
+/* Note: caller must be prepared to deal with negative returns */
static inline int tcp_space(struct sock *sk)
{
#if 0
#else
return 0;
#endif
-}
+}
static inline int tcp_full_space( struct sock *sk)
{
#if 0
- return tcp_win_from_space(sk->rcvbuf);
+ return tcp_win_from_space(sk->rcvbuf);
#else
return 0;
#endif
TCPF_CLOSE_WAIT = (1 << 8),
TCPF_LAST_ACK = (1 << 9),
TCPF_LISTEN = (1 << 10),
- TCPF_CLOSING = (1 << 11)
+ TCPF_CLOSING = (1 << 11)
};
/*
* (union is compatible to any of its members)
* This means this part of the code is -fstrict-aliasing safe now.
*/
-union tcp_word_hdr {
+union tcp_word_hdr {
struct tcphdr hdr;
__u32 words[5];
-};
-
-#define tcp_flag_word(tp) ( ((union tcp_word_hdr *)(tp))->words [3])
-
-enum {
- TCP_FLAG_CWR = 0x00800000, // __constant_htonl(0x00800000),
- TCP_FLAG_ECE = 0x00400000, //__constant_htonl(0x00400000),
- TCP_FLAG_URG = 0x00200000, //__constant_htonl(0x00200000),
- TCP_FLAG_ACK = 0x00100000, //__constant_htonl(0x00100000),
- TCP_FLAG_PSH = 0x00080000, //__constant_htonl(0x00080000),
- TCP_FLAG_RST = 0x00040000, //__constant_htonl(0x00040000),
- TCP_FLAG_SYN = 0x00020000, //__constant_htonl(0x00020000),
+};
+
+#define tcp_flag_word(tp) ( ((union tcp_word_hdr *)(tp))->words [3])
+
+enum {
+ TCP_FLAG_CWR = 0x00800000, // __constant_htonl(0x00800000),
+ TCP_FLAG_ECE = 0x00400000, //__constant_htonl(0x00400000),
+ TCP_FLAG_URG = 0x00200000, //__constant_htonl(0x00200000),
+ TCP_FLAG_ACK = 0x00100000, //__constant_htonl(0x00100000),
+ TCP_FLAG_PSH = 0x00080000, //__constant_htonl(0x00080000),
+ TCP_FLAG_RST = 0x00040000, //__constant_htonl(0x00040000),
+ TCP_FLAG_SYN = 0x00020000, //__constant_htonl(0x00020000),
TCP_FLAG_FIN = 0x00010000, //__constant_htonl(0x00010000),
TCP_RESERVED_BITS = 0x0F000000, //__constant_htonl(0x0F000000),
TCP_DATA_OFFSET = 0xF0000000, //__constant_htonl(0xF0000000)
-};
+};
/* TCP socket options */
#define TCP_NODELAY 1 /* Turn off Nagle's algorithm. */
#endif /* i386 */
-typedef TDI_STATUS (*InfoRequest_f)( UINT InfoClass,
+typedef TDI_STATUS (*InfoRequest_f)( UINT InfoClass,
UINT InfoType,
UINT InfoId,
PVOID Context,
PNDIS_BUFFER Buffer,
PUINT BufferSize );
-typedef TDI_STATUS (*InfoSet_f)( UINT InfoClass,
+typedef TDI_STATUS (*InfoSet_f)( UINT InfoClass,
UINT InfoType,
UINT InfoId,
PVOID Context,
PVOID ClientContext; /* Pointer to client context information */
PADDRESS_FILE AddressFile; /* Associated address file object (NULL if none) */
PVOID SocketContext; /* Context for lower layer */
-
+
UINT State; /* Socket state W.R.T. oskit */
/* Requests */
/*
* FUNCTION: Copies data from a buffer to an NDIS buffer chain
* ARGUMENTS:
- * DstBuffer = Pointer to destination NDIS buffer
+ * DstBuffer = Pointer to destination NDIS buffer
* DstOffset = Destination start offset
* SrcData = Pointer to source buffer
* Length = Number of bytes to copy
PCHAR SrcData;
TI_DbgPrint(DEBUG_PBUFFER, ("DstData 0x%X SrcBuffer 0x%X SrcOffset 0x%X Length %d\n",DstData,SrcBuffer, SrcOffset, Length));
-
+
/* Skip SrcOffset bytes in the source buffer chain */
if (SkipToOffset(SrcBuffer, SrcOffset, &SrcData, &SrcSize) == -1)
return 0;
}
void GetDataPtr( PNDIS_PACKET Packet,
- UINT Offset,
+ UINT Offset,
PCHAR *DataOut,
PUINT Size ) {
PNDIS_BUFFER Buffer;
PCHAR NewData;
NewData = ExAllocatePool( NonPagedPool, Len );
- if( !NewData ) return NDIS_STATUS_NOT_ACCEPTED; // XXX
+ if( !NewData ) return NDIS_STATUS_NOT_ACCEPTED; // XXX
TrackWithTag(EXALLOC_TAG, NewData, File, Line);
if( Data ) RtlCopyMemory(NewData, Data, Len);
}
/* IRP has already been cancelled */
-
+
IoReleaseCancelSpinLock(OldIrql);
Irp->IoStatus.Status = STATUS_CANCELLED;
/*KIRQL OldIrql;*/
PFILE_OBJECT FileObject;
PTRANSPORT_CONTEXT TranContext;
-
+
TI_DbgPrint(DEBUG_IRP, ("Called.\n"));
FileObject = (PFILE_OBJECT)Context;
PTRANSPORT_CONTEXT TranContext;
KIRQL OldIrql;
- TI_DbgPrint(DEBUG_IRP, ("Called for irp %x (%x, %d).\n",
+ TI_DbgPrint(DEBUG_IRP, ("Called for irp %x (%x, %d).\n",
Context, Status, Count));
Irp = Context;
}
IoReleaseCancelSpinLock(Irp->CancelIrql);
-
+
DispCancelComplete(FileObject);
TI_DbgPrint(MAX_TRACE, ("Leaving.\n"));
IoReleaseCancelSpinLock(Irp->CancelIrql);
DispDataRequestComplete(Irp, STATUS_CANCELLED, 0);
-
+
DispCancelComplete(FileObject);
TI_DbgPrint(MAX_TRACE, ("Leaving.\n"));
Parameters->ReturnConnectionInformation,
DispDataRequestComplete,
Irp );
-
+
TI_DbgPrint(MAX_TRACE, ("TCP Connect returned %08x\n", Status));
return Status;
DisReq->ReturnConnectionInformation,
DispDataRequestComplete,
Irp );
-
+
TI_DbgPrint(MAX_TRACE, ("TCP Connect returned %08x\n", Status));
return Status;
Parameters = (PTDI_REQUEST_KERNEL)&IrpSp->Parameters;
- TI_DbgPrint(MIN_TRACE, ("Connection->AddressFile: %x\n",
+ TI_DbgPrint(MIN_TRACE, ("Connection->AddressFile: %x\n",
Connection->AddressFile ));
if( Connection->AddressFile ) {
TI_DbgPrint(MIN_TRACE, ("Connection->AddressFile->Listener: %x\n",
/* The important thing to note here is that the irp we'll complete belongs
* to the socket to be accepted onto, not the listener */
if( !Connection->AddressFile->Listener ) {
- Connection->AddressFile->Listener =
+ Connection->AddressFile->Listener =
TCPAllocateConnectionEndpoint( NULL );
- if( !Connection->AddressFile->Listener )
+ if( !Connection->AddressFile->Listener )
Status = STATUS_NO_MEMORY;
if( NT_SUCCESS(Status) ) {
- Connection->AddressFile->Listener->AddressFile =
+ Connection->AddressFile->Listener->AddressFile =
Connection->AddressFile;
-
+
Status = TCPSocket( Connection->AddressFile->Listener,
Connection->AddressFile->Family,
SOCK_STREAM,
}
if( NT_SUCCESS(Status) )
- Status = TCPListen( Connection->AddressFile->Listener, 1024 );
+ Status = TCPListen( Connection->AddressFile->Listener, 1024 );
/* BACKLOG */
}
if( NT_SUCCESS(Status) ) {
Status = DispPrepareIrpForCancel
- (TranContext->Handle.ConnectionContext,
- Irp,
+ (TranContext->Handle.ConnectionContext,
+ Irp,
(PDRIVER_CANCEL)DispCancelListenRequest);
}
if( NT_SUCCESS(Status) ) {
Status = TCPAccept
- ( (PTDI_REQUEST)Parameters,
+ ( (PTDI_REQUEST)Parameters,
Connection->AddressFile->Listener,
Connection,
DispDataRequestComplete,
break;
case TDI_CONNECTION_FILE:
- AddrFile =
+ AddrFile =
((PCONNECTION_ENDPOINT)TranContext->Handle.ConnectionContext)->
AddressFile;
break;
Address->Address[0].AddressLength = TDI_ADDRESS_LENGTH_IP;
Address->Address[0].AddressType = TDI_ADDRESS_TYPE_IP;
Address->Address[0].Address[0].sin_port = AddrFile->Port;
- Address->Address[0].Address[0].in_addr =
- AddrFile->Address.Address.IPv4Address;
+ Address->Address[0].Address[0].in_addr =
+ AddrFile->Address.Address.IPv4Address;
RtlZeroMemory(
&Address->Address[0].Address[0].sin_zero,
sizeof(Address->Address[0].Address[0].sin_zero));
break;
case TDI_CONNECTION_FILE:
- Endpoint =
+ Endpoint =
(PCONNECTION_ENDPOINT)TranContext->Handle.ConnectionContext;
break;
/* Initialize a receive request */
Status = DispPrepareIrpForCancel
- (TranContext->Handle.ConnectionContext,
- Irp,
+ (TranContext->Handle.ConnectionContext,
+ Irp,
(PDRIVER_CANCEL)DispCancelRequest);
TI_DbgPrint(MID_TRACE,("TCPIP<<< Got an MDL: %x\n", Irp->MdlAddress));
UINT Len;
NdisQueryBuffer( Irp->MdlAddress, &Data, &Len );
-
+
TI_DbgPrint(MID_TRACE,("About to TCPSendData\n"));
Status = TCPSendData(
TranContext->Handle.ConnectionContext,
if (Status != STATUS_PENDING)
{
DispDataRequestComplete(Irp, Status, BytesReceived);
- } else
+ } else
IoMarkIrpPending( Irp );
}
if (NT_SUCCESS(Status)) {
PCHAR DataBuffer;
UINT BufferSize;
-
+
TI_DbgPrint(MID_TRACE,("About to query buffer %x\n", Irp->MdlAddress));
NdisQueryBuffer( (PNDIS_BUFFER)Irp->MdlAddress,
&DataBuffer,
&BufferSize );
-
- /* FIXME: DgramInfo->SendDatagramInformation->RemoteAddress
+
+ /* FIXME: DgramInfo->SendDatagramInformation->RemoteAddress
must be of type PTDI_ADDRESS_IP */
TI_DbgPrint(MID_TRACE,
- ("About to call send routine %x\n",
+ ("About to call send routine %x\n",
(*((PADDRESS_FILE)Request.Handle.AddressHandle)->Send)));
-
- if( (*((PADDRESS_FILE)Request.Handle.AddressHandle)->Send) )
+
+ if( (*((PADDRESS_FILE)Request.Handle.AddressHandle)->Send) )
Status = (*((PADDRESS_FILE)Request.Handle.AddressHandle)->Send)(
- Request.Handle.AddressHandle,
+ Request.Handle.AddressHandle,
DgramInfo->SendDatagramInformation,
DataBuffer,
BufferSize,
Parameters = (PTDI_REQUEST_KERNEL_SET_EVENT)&IrpSp->Parameters;
Status = STATUS_SUCCESS;
-
+
TcpipAcquireSpinLock(&AddrFile->Lock, &OldIrql);
/* Set the event handler. if an event handler is associated with
ExFreePool(QueryContext);
} else
Status = STATUS_INSUFFICIENT_RESOURCES;
- } else if( InputBufferLength ==
+ } else if( InputBufferLength ==
sizeof(TCP_REQUEST_QUERY_INFORMATION_EX) ) {
/* Handle the case where the user is probing the buffer for length */
TI_DbgPrint(MAX_TRACE, ("InputBufferLength %d OutputBufferLength %d\n",
MmProbeAndLockPages(InputMdl, Irp->RequestorMode,
IoModifyAccess);
-
+
InputMdlLocked = TRUE;
Status = STATUS_SUCCESS;
} _SEH_HANDLE {
Request.RequestNotifyObject = DispTdiQueryInformationExComplete;
Request.RequestContext = QueryContext;
Status = InfoTdiQueryInformationEx(&Request,
- &QueryContext->QueryInfo.ID,
+ &QueryContext->QueryInfo.ID,
NULL,
- &Size,
+ &Size,
&QueryContext->QueryInfo.Context);
DispTdiQueryInformationExComplete(QueryContext, Status, Size);
TI_DbgPrint(MAX_TRACE, ("Leaving. Status = (0x%X)\n", Status));
NTSTATUS DispTdiSetIPAddress( PIRP Irp, PIO_STACK_LOCATION IrpSp ) {
NTSTATUS Status = STATUS_DEVICE_DOES_NOT_EXIST;
- PIP_SET_ADDRESS IpAddrChange =
+ PIP_SET_ADDRESS IpAddrChange =
(PIP_SET_ADDRESS)Irp->AssociatedIrp.SystemBuffer;
IF_LIST_ITER(IF);
IF->Netmask.Type = IP_ADDRESS_V4;
IF->Netmask.Address.IPv4Address = IpAddrChange->Netmask;
- TI_DbgPrint(MID_TRACE,("New Unicast Address: %x\n",
+ TI_DbgPrint(MID_TRACE,("New Unicast Address: %x\n",
IF->Unicast.Address.IPv4Address));
- TI_DbgPrint(MID_TRACE,("New Netmask : %x\n",
+ TI_DbgPrint(MID_TRACE,("New Netmask : %x\n",
IF->Netmask.Address.IPv4Address));
IPAddInterfaceRoute( IF );
-
+
IpAddrChange->Address = IF->Index;
Status = STATUS_SUCCESS;
Irp->IoStatus.Information = IF->Index;
return AddrSearchNext(SearchContext);
}
-BOOLEAN AddrIsBroadcast(
+BOOLEAN AddrIsBroadcast(
PIP_ADDRESS PossibleMatch,
PIP_ADDRESS TargetAddress ) {
IF_LIST_ITER(IF);
CurrentEntry = AddrFile->TransmitQueue.Flink;
while (CurrentEntry != &AddrFile->TransmitQueue) {
NextEntry = CurrentEntry->Flink;
- SendRequest = CONTAINING_RECORD(CurrentEntry,
+ SendRequest = CONTAINING_RECORD(CurrentEntry,
DATAGRAM_SEND_REQUEST, ListEntry);
/* Abort the request and free its resources */
TcpipReleaseSpinLock(&AddrFile->Lock, OldIrql);
/* Protocol specific handling */
switch (Protocol) {
case IPPROTO_TCP:
- AddrFile->Port =
+ AddrFile->Port =
TCPAllocatePort(Address->Address[0].Address[0].sin_port);
AddrFile->Send = NULL; /* TCPSendData */
break;
case IPPROTO_UDP:
TI_DbgPrint(MID_TRACE,("Allocating udp port\n"));
- AddrFile->Port =
+ AddrFile->Port =
UDPAllocatePort(Address->Address[0].Address[0].sin_port);
- TI_DbgPrint(MID_TRACE,("Setting port %d (wanted %d)\n",
- AddrFile->Port,
+ TI_DbgPrint(MID_TRACE,("Setting port %d (wanted %d)\n",
+ AddrFile->Port,
Address->Address[0].Address[0].sin_port));
AddrFile->Send = UDPSendDatagram;
break;
/* Set protocol */
AddrFile->Protocol = Protocol;
-
+
/* Initialize receive and transmit queues */
InitializeListHead(&AddrFile->ReceiveQueue);
InitializeListHead(&AddrFile->TransmitQueue);
/* Set address file object exclusive to us */
AF_SET_BUSY(AddrFile);
AF_CLR_VALID(AddrFile);
-
+
TcpipReleaseSpinLock(&AddrFile->Lock, OldIrql);
/* Protocol specific handling */
switch (AddrFile->Protocol) {
case IPPROTO_TCP:
TCPFreePort( AddrFile->Port );
- if( AddrFile->Listener )
+ if( AddrFile->Listener )
TCPClose( AddrFile->Listener );
break;
UDPFreePort( AddrFile->Port );
break;
}
-
+
DeleteAddress(AddrFile);
-
+
TI_DbgPrint(MAX_TRACE, ("Leaving.\n"));
return Status;
PCONNECTION_ENDPOINT Connection;
TI_DbgPrint(MID_TRACE, ("Called.\n"));
-
+
Connection = TCPAllocateConnectionEndpoint( ClientContext );
-
+
if( !Connection ) return STATUS_NO_MEMORY;
Status = TCPSocket( Connection, AF_INET, SOCK_STREAM, IPPROTO_TCP );
/*
* FUNCTION: Find a connection by examining the context field. This
- * is needed in some situations where a FIN reply is needed after a
+ * is needed in some situations where a FIN reply is needed after a
* socket is formally broken.
* ARGUMENTS:
* Request = Pointer to TDI request structure for this request
TcpipAcquireSpinLock( &ConnectionEndpointListLock, &OldIrql );
- for( Entry = ConnectionEndpointListHead.Flink;
+ for( Entry = ConnectionEndpointListHead.Flink;
Entry != &ConnectionEndpointListHead;
- Entry = Entry->Flink ) {
- Connection =
+ Entry = Entry->Flink ) {
+ Connection =
CONTAINING_RECORD( Entry, CONNECTION_ENDPOINT, ListEntry );
if( Connection->SocketContext == Context ) break;
else Connection = NULL;
ULONG Size;
UINT DescrLenMax = MAX_IFDESCR_LEN - 1;
- TI_DbgPrint(DEBUG_INFO,
+ TI_DbgPrint(DEBUG_INFO,
("Getting IFEntry MIB (IF %08x LA %08x) (%04x:%d)\n",
Interface, IF, ID->tei_entity, ID->tei_instance));
- OutData =
- (PIFENTRY)ExAllocatePool( NonPagedPool,
+ OutData =
+ (PIFENTRY)ExAllocatePool( NonPagedPool,
sizeof(IFENTRY) + MAX_IFDESCR_LEN );
-
+
if( !OutData ) return TDI_INVALID_REQUEST; /* Out of memory */
RtlZeroMemory( OutData, sizeof(IFENTRY) + MAX_IFDESCR_LEN );
OutData->Index = Interface->Index;
/* viz: tcpip keeps those indices */
- OutData->Type = Interface ==
+ OutData->Type = Interface ==
Loopback ? MIB_IF_TYPE_LOOPBACK : MIB_IF_TYPE_ETHERNET;
OutData->Mtu = Interface->MTU;
- TI_DbgPrint(DEBUG_INFO,
+ TI_DbgPrint(DEBUG_INFO,
("Getting interface speed\n"));
OutData->PhysAddrLen = Interface->AddressLength;
OutData->AdminStatus = MIB_IF_ADMIN_STATUS_UP;
Status = GetInterfaceConnectionStatus( Interface, &OutData->OperStatus );
/* Not sure what to do here, but not ready seems a safe bet on failure */
- if( !NT_SUCCESS(Status) )
+ if( !NT_SUCCESS(Status) )
OutData->OperStatus = NdisHardwareStatusNotReady;
IFDescr = (PCHAR)&OutData[1];
return Status;
}
-
+
TDI_STATUS InfoInterfaceTdiQueryEx( UINT InfoClass,
UINT InfoType,
UINT InfoId,
InfoId == ENTITY_TYPE_ID ) {
ULONG Temp = IF_MIB;
return InfoCopyOut( (PCHAR)&Temp, sizeof(Temp), Buffer, BufferSize );
- } else if( InfoClass == INFO_CLASS_PROTOCOL &&
+ } else if( InfoClass == INFO_CLASS_PROTOCOL &&
InfoType == INFO_TYPE_PROVIDER &&
InfoId == IF_MIB_STATS_ID ) {
return InfoTdiQueryGetInterfaceMIB( id, Context, Buffer, BufferSize );
- } else
+ } else
return TDI_INVALID_REQUEST;
}
KIRQL OldIrql;
UINT Count = 0, i;
- TI_DbgPrint(DEBUG_INFO,
- ("Inserting interface %08x (%d entities already)\n",
+ TI_DbgPrint(DEBUG_INFO,
+ ("Inserting interface %08x (%d entities already)\n",
Interface, EntityCount));
TcpipAcquireSpinLock( &EntityListLock, &OldIrql );
for( i = 0; i < EntityCount; i++ )
if( EntityList[i].tei_entity == IF_ENTITY ) {
Count++;
- TI_DbgPrint(DEBUG_INFO, ("Entity %d is an IF. Found %d\n",
+ TI_DbgPrint(DEBUG_INFO, ("Entity %d is an IF. Found %d\n",
i, Count));
}
-
+
EntityList[EntityCount].tei_entity = IF_ENTITY;
EntityList[EntityCount].tei_instance = Count;
EntityList[EntityCount].context = Interface;
EntityList[EntityCount].info_req = InfoInterfaceTdiQueryEx;
EntityList[EntityCount].info_set = InfoInterfaceTdiSetEx;
-
+
EntityCount++;
TcpipReleaseSpinLock( &EntityListLock, OldIrql );
UINT i;
TcpipAcquireSpinLock( &EntityListLock, &OldIrql );
-
+
/* Remove entities that have this interface as context
* In the future, this might include AT_ENTITY types, too
*/
for( i = 0; i < EntityCount; i++ ) {
if( EntityList[i].context == Interface ) {
- if( i != EntityCount-1 )
- memcpy( &EntityList[i],
+ if( i != EntityCount-1 )
+ memcpy( &EntityList[i],
&EntityList[--EntityCount],
sizeof(EntityList[i]) );
}
TI_DbgPrint(DEBUG_INFO,("About to copy %d TDIEntityIDs to user\n",
EntityCount));
-
+
TcpipAcquireSpinLock(&EntityListLock, &OldIrql);
Size = EntityCount * sizeof(TDIEntityID);
*BufferSize = Size;
-
+
if (BufSize < Size)
{
TcpipReleaseSpinLock( &EntityListLock, OldIrql );
/* The buffer is too small to contain requested data */
return TDI_BUFFER_TOO_SMALL;
}
-
+
/* Return entity list -- Copy only the TDIEntityID parts. */
for( Count = 0; Count < EntityCount; Count++ ) {
- CopyBufferToBufferChain(Buffer,
- Count * sizeof(TDIEntityID),
- (PCHAR)&EntityList[Count],
+ CopyBufferToBufferChain(Buffer,
+ Count * sizeof(TDIEntityID),
+ (PCHAR)&EntityList[Count],
sizeof(TDIEntityID));
}
-
+
TcpipReleaseSpinLock(&EntityListLock, OldIrql);
-
+
return TDI_SUCCESS;
}
Status = InfoTdiQueryListEntities(Buffer, BufferSize);
} else {
TcpipAcquireSpinLock( &EntityListLock, &OldIrql );
-
+
for( i = 0; i < EntityCount; i++ ) {
if( EntityList[i].tei_entity == ID->toi_entity.tei_entity &&
EntityList[i].tei_instance == ID->toi_entity.tei_instance ) {
break;
}
}
-
+
TcpipReleaseSpinLock( &EntityListLock, OldIrql );
-
+
if( FoundEntity ) {
TI_DbgPrint(DEBUG_INFO,
("Calling Entity %d (%04x:%d) InfoEx (%x,%x,%x)\n",
}
break;
}
-
+
return TDI_INVALID_PARAMETER;
}
* ErrorCode = An error code to put in the log entry
* UniqueErrorValue = UniqueErrorValue in the error log packet
* FinalStatus = FinalStatus in the error log packet
- * String = If not NULL, a pointer to a string to put in log
+ * String = If not NULL, a pointer to a string to put in log
* entry
* DumpDataCount = Number of ULONGs of dump data
* DumpData = Pointer to dump data for the log entry
PUCHAR pString;
static WCHAR DriverName[] = L"TCP/IP";
- EntrySize = sizeof(IO_ERROR_LOG_PACKET) +
+ EntrySize = sizeof(IO_ERROR_LOG_PACKET) +
(DumpDataCount * sizeof(ULONG)) + sizeof(DriverName);
if (String) {
Request.RequestContext = Irp;
CP
/* Branch to the right handler */
- if (EaInfo &&
- (EaInfo->EaNameLength == TDI_TRANSPORT_ADDRESS_LENGTH) &&
+ if (EaInfo &&
+ (EaInfo->EaNameLength == TDI_TRANSPORT_ADDRESS_LENGTH) &&
(RtlCompareMemory
(&EaInfo->EaName, TdiTransportAddress,
TDI_TRANSPORT_ADDRESS_LENGTH) == TDI_TRANSPORT_ADDRESS_LENGTH)) {
TI_DbgPrint(MIN_TRACE, ("Parameters are invalid:\n"));
TI_DbgPrint(MIN_TRACE, ("AddressCount: %d\n", Address->TAAddressCount));
if( Address->TAAddressCount == 1 ) {
- TI_DbgPrint(MIN_TRACE, ("AddressLength: %\n",
+ TI_DbgPrint(MIN_TRACE, ("AddressLength: %\n",
Address->Address[0].AddressLength));
- TI_DbgPrint(MIN_TRACE, ("AddressType: %\n",
+ TI_DbgPrint(MIN_TRACE, ("AddressType: %\n",
Address->Address[0].AddressType));
}
PoolFreeBuffer(Context);
Context->Handle.AddressHandle = Request.Handle.AddressHandle;
}
CP
- } else if (EaInfo &&
- (EaInfo->EaNameLength == TDI_CONNECTION_CONTEXT_LENGTH) &&
+ } else if (EaInfo &&
+ (EaInfo->EaNameLength == TDI_CONNECTION_CONTEXT_LENGTH) &&
(RtlCompareMemory
(&EaInfo->EaName, TdiConnectionContext,
- TDI_CONNECTION_CONTEXT_LENGTH) ==
+ TDI_CONNECTION_CONTEXT_LENGTH) ==
TDI_CONNECTION_CONTEXT_LENGTH)) {
/* This is a request to open a connection endpoint */
CP
TranContext = (PTRANSPORT_CONTEXT)IrpSp->FileObject->FsContext;
Irp->IoStatus.Status = Status;
-
+
IoAcquireCancelSpinLock(&OldIrql);
KeSetEvent(&TranContext->CleanupEvent, 0, FALSE);
KIRQL OldIrql;
IrpSp = IoGetCurrentIrpStackLocation(Irp);
- Context = IrpSp->FileObject->FsContext;
+ Context = IrpSp->FileObject->FsContext;
if (!Context) {
TI_DbgPrint(MIN_TRACE, ("Parameters are invalid.\n"));
return STATUS_INVALID_PARAMETER;
if (Status != STATUS_PENDING)
TiCleanupFileObjectComplete(Irp, Status);
-
+
KeWaitForSingleObject(&Context->CleanupEvent,
UserRequest, KernelMode, FALSE, NULL);
-
+
return Irp->IoStatus.Status;
}
Status = STATUS_SUCCESS;
break;
- /* Release resources bound to an address file, connection endpoint,
+ /* Release resources bound to an address file, connection endpoint,
or control connection */
case IRP_MJ_CLEANUP:
Status = TiCleanupFileObject(DeviceObject, Irp);
TI_DbgPrint(DEBUG_IRP, ("Leaving. Status = (0x%X).\n", Status));
- if( Complete )
+ if( Complete )
IRPFinish( Irp, Status );
return Status;
/* See if this request is TCP/IP specific */
switch (IrpSp->Parameters.DeviceIoControl.IoControlCode) {
case IOCTL_TCP_QUERY_INFORMATION_EX:
- TI_DbgPrint(MIN_TRACE, ("TCP_QUERY_INFORMATION_EX\n"));
+ TI_DbgPrint(MIN_TRACE, ("TCP_QUERY_INFORMATION_EX\n"));
Status = DispTdiQueryInformationEx(Irp, IrpSp);
break;
case IOCTL_TCP_SET_INFORMATION_EX:
- TI_DbgPrint(MIN_TRACE, ("TCP_SET_INFORMATION_EX\n"));
+ TI_DbgPrint(MIN_TRACE, ("TCP_SET_INFORMATION_EX\n"));
Status = DispTdiSetInformationEx(Irp, IrpSp);
break;
LARGE_INTEGER DueTime;
TI_DbgPrint(MAX_TRACE, ("Called.\n"));
-
+
TrackingInit();
TrackTag(NDIS_BUFFER_TAG);
TrackTag(NDIS_PACKET_TAG);
/* Register protocol with NDIS */
/* This used to be IP_DEVICE_NAME but the DDK says it has to match your entry in the SCM */
- RtlInitUnicodeString(&strNdisDeviceName, TCPIP_PROTOCOL_NAME);
+ RtlInitUnicodeString(&strNdisDeviceName, TCPIP_PROTOCOL_NAME);
Status = LANRegisterProtocol(&strNdisDeviceName);
if (!NT_SUCCESS(Status)) {
TI_DbgPrint(MIN_TRACE,("Failed to register protocol with NDIS; status 0x%x\n", Status));
ExInitializeWorkItem( &IpWorkItem, IPTimeout, NULL );
KeInitializeDpc(&IPTimeoutDpc, IPTimeoutDpcFn, NULL);
KeInitializeTimer(&IPTimer);
-
+
/* Start the periodic timer with an initial and periodic
relative expiration time of IP_TIMEOUT milliseconds */
DueTime.QuadPart = -(LONGLONG)IP_TIMEOUT * 10000;
#include "precomp.h"
-VOID XNdisGetFirstBufferFromPacket(PNDIS_PACKET Packet,
- PNDIS_BUFFER *FirstBuffer,
- PVOID *FirstBufferVA,
- PUINT FirstBufferLength,
- PUINT TotalBufferLength)
-{
- PNDIS_BUFFER _Buffer;
-
- _Buffer = (Packet)->Private.Head;
- *(FirstBuffer) = _Buffer;
- *(FirstBufferVA) = MmGetMdlVirtualAddress(_Buffer);
- if (_Buffer != NULL) {
- *(FirstBufferLength) = MmGetMdlByteCount(_Buffer);
- _Buffer = _Buffer->Next;
- } else
- *(FirstBufferLength) = 0;
- *(TotalBufferLength) = *(FirstBufferLength);
- while (_Buffer != NULL) {
- *(TotalBufferLength) += MmGetMdlByteCount(_Buffer);
- _Buffer = _Buffer->Next;
- }
+VOID XNdisGetFirstBufferFromPacket(PNDIS_PACKET Packet,
+ PNDIS_BUFFER *FirstBuffer,
+ PVOID *FirstBufferVA,
+ PUINT FirstBufferLength,
+ PUINT TotalBufferLength)
+{
+ PNDIS_BUFFER _Buffer;
+
+ _Buffer = (Packet)->Private.Head;
+ *(FirstBuffer) = _Buffer;
+ *(FirstBufferVA) = MmGetMdlVirtualAddress(_Buffer);
+ if (_Buffer != NULL) {
+ *(FirstBufferLength) = MmGetMdlByteCount(_Buffer);
+ _Buffer = _Buffer->Next;
+ } else
+ *(FirstBufferLength) = 0;
+ *(TotalBufferLength) = *(FirstBufferLength);
+ while (_Buffer != NULL) {
+ *(TotalBufferLength) += MmGetMdlByteCount(_Buffer);
+ _Buffer = _Buffer->Next;
+ }
}
/*
/*
* FUNCTION: Copies data from a buffer to an NDIS buffer chain
* ARGUMENTS:
- * DstBuffer = Pointer to destination NDIS buffer
+ * DstBuffer = Pointer to destination NDIS buffer
* DstOffset = Destination start offset
* SrcData = Pointer to source buffer
* Length = Number of bytes to copy
PCHAR SrcData;
TI_DbgPrint(DEBUG_PBUFFER, ("DstData 0x%X SrcBuffer 0x%X SrcOffset 0x%X Length %d\n",DstData,SrcBuffer, SrcOffset, Length));
-
+
/* Skip SrcOffset bytes in the source buffer chain */
if (SkipToOffset(SrcBuffer, SrcOffset, &SrcData, &SrcSize) == -1)
return 0;
}
void GetDataPtr( PNDIS_PACKET Packet,
- UINT Offset,
+ UINT Offset,
PCHAR *DataOut,
PUINT Size ) {
PNDIS_BUFFER Buffer;
PCHAR NewData;
NewData = ExAllocatePool( NonPagedPool, Len );
- if( !NewData ) return NDIS_STATUS_NOT_ACCEPTED; // XXX
+ if( !NewData ) return NDIS_STATUS_NOT_ACCEPTED; // XXX
TrackWithTag(EXALLOC_TAG, NewData, File, Line);
- if( Data )
+ if( Data )
RtlCopyMemory(NewData, Data, Len);
NdisAllocatePacket( &Status, &Packet, GlobalPacketPool );
return PoolAllocateBuffer( List->Size );
}
-VOID TcpipFreeToNPagedLookasideList( PNPAGED_LOOKASIDE_LIST List,
+VOID TcpipFreeToNPagedLookasideList( PNPAGED_LOOKASIDE_LIST List,
PVOID Thing ) {
PoolFreeBuffer( Thing );
}
#define IP_ROUTE_TYPE_ADD 3
#define IP_ROUTE_TYPE_DEL 2
-TDI_STATUS InfoTdiQueryGetAddrTable( PNDIS_BUFFER Buffer,
+TDI_STATUS InfoTdiQueryGetAddrTable( PNDIS_BUFFER Buffer,
PUINT BufferSize ) {
-
+
IF_LIST_ITER(CurrentIF);
TDI_STATUS Status = TDI_INVALID_REQUEST;
KIRQL OldIrql;
UINT Count = 1; /* Start adapter indices at 1 */
UINT IfCount = CountInterfaces();
- PIPADDR_ENTRY IpAddress =
+ PIPADDR_ENTRY IpAddress =
ExAllocatePool( NonPagedPool, sizeof( IPADDR_ENTRY ) * IfCount );
PIPADDR_ENTRY IpCurrent = IpAddress;
TI_DbgPrint(DEBUG_INFO, ("Called.\n"));
-
+
TcpipAcquireSpinLock(&InterfaceListLock, &OldIrql);
-
+
ForEachInterface(CurrentIF) {
IpCurrent->Index = CurrentIF->Index;
IpCurrent->Addr = 0;
IpCurrent->BcastAddr = 0;
IpCurrent->Mask = 0;
-
+
/* Locate the diffrent addresses and put them the right place */
GetInterfaceIPv4Address( CurrentIF,
ADE_UNICAST,
IpCurrent++;
Count++;
} EndFor(CurrentIF);
-
+
TcpipReleaseSpinLock(&InterfaceListLock, OldIrql);
Status = InfoCopyOut( (PCHAR)IpAddress, sizeof(*IpAddress) * Count,
Buffer, BufferSize );
-
+
ExFreePool( IpAddress );
TI_DbgPrint(DEBUG_INFO, ("Returning %08x\n", Status));
KIRQL OldIrql;
UINT RtCount = CountFIBs(),
Size = sizeof( IPROUTE_ENTRY ) * RtCount;
- PFIB_ENTRY RCache =
+ PFIB_ENTRY RCache =
ExAllocatePool( NonPagedPool, sizeof( FIB_ENTRY ) * RtCount ),
RCacheCur = RCache;
PIPROUTE_ENTRY RouteEntries = ExAllocatePool( NonPagedPool, Size ),
RtCurrent = RouteEntries;
- TI_DbgPrint(DEBUG_INFO, ("Called, routes = %d, RCache = %08x\n",
+ TI_DbgPrint(DEBUG_INFO, ("Called, routes = %d, RCache = %08x\n",
RtCount, RCache));
if( !RCache || !RouteEntries ) {
RtlZeroMemory( RouteEntries, Size );
RtCount = CopyFIBs( RCache );
-
+
while( RtCurrent < RouteEntries + RtCount ) {
/* Copy Desitnation */
- RtlCopyMemory( &RtCurrent->Dest,
+ RtlCopyMemory( &RtCurrent->Dest,
&RCacheCur->NetworkAddress.Address,
sizeof(RtCurrent->Dest) );
RtlCopyMemory( &RtCurrent->Mask,
sizeof(RtCurrent->Gw) );
else
RtlZeroMemory( &RtCurrent->Gw, sizeof(RtCurrent->Gw) );
-
+
RtCurrent->Metric1 = RCacheCur->Metric;
RtCurrent->Type = TDI_ADDRESS_TYPE_IP;
-
+
TI_DbgPrint
- (DEBUG_INFO,
+ (DEBUG_INFO,
("%d: NA %08x NM %08x GW %08x MT %x\n",
RtCurrent - RouteEntries,
- RtCurrent->Dest,
+ RtCurrent->Dest,
RtCurrent->Mask,
RtCurrent->Gw,
RtCurrent->Metric1 ));
-
+
TcpipAcquireSpinLock(&EntityListLock, &OldIrql);
- for( RtCurrent->Index = EntityCount;
+ for( RtCurrent->Index = EntityCount;
RtCurrent->Index > 0 &&
- RCacheCur->Router->Interface !=
+ RCacheCur->Router->Interface !=
EntityList[RtCurrent->Index - 1].context;
RtCurrent->Index-- );
-
+
RtCurrent->Index = EntityList[RtCurrent->Index - 1].tei_instance;
TcpipReleaseSpinLock(&EntityListLock, OldIrql);
-
+
RtCurrent++; RCacheCur++;
}
return Status;
}
-
+
TDI_STATUS InfoTdiQueryGetIPSnmpInfo( PNDIS_BUFFER Buffer,
PUINT BufferSize ) {
IPSNMP_INFO SnmpInfo;
SnmpInfo.NumAddr = 1;
SnmpInfo.NumRoutes = RouteCount;
- Status = InfoCopyOut( (PCHAR)&SnmpInfo, sizeof(SnmpInfo),
+ Status = InfoCopyOut( (PCHAR)&SnmpInfo, sizeof(SnmpInfo),
Buffer, BufferSize );
TI_DbgPrint(DEBUG_INFO, ("Returning %08x\n", Status));
PNDIS_BUFFER Buffer,
PUINT BufferSize ) {
TDI_STATUS Status = TDI_INVALID_REQUEST;
-
+
TI_DbgPrint(DEBUG_INFO, ("Called.\n"));
switch( InfoClass ) {
case INFO_CLASS_GENERIC:
if( InfoType == INFO_TYPE_PROVIDER && InfoId == ENTITY_TYPE_ID ) {
ULONG Return = CL_NL_IP;
- Status = InfoCopyOut( (PCHAR)&Return, sizeof(Return),
+ Status = InfoCopyOut( (PCHAR)&Return, sizeof(Return),
Buffer, BufferSize );
}
break;
/* Find the existing route this belongs to */
NCE = RouterGetRoute( &Router );
/* Really add the route */
- if( NCE &&
- RouterCreateRoute( &Address, &Netmask, &Router,
- NCE->Interface, Route->Metric1 ) )
+ if( NCE &&
+ RouterCreateRoute( &Address, &Netmask, &Router,
+ NCE->Interface, Route->Metric1 ) )
Status = STATUS_SUCCESS;
else
Status = STATUS_UNSUCCESSFUL;
} else Status = TDI_INVALID_REQUEST;
}
- TI_DbgPrint(DEBUG_INFO,("Returning %x\n", Status));
+ TI_DbgPrint(DEBUG_INFO,("Returning %x\n", Status));
return Status;
}
return ExAllocateFromNPagedLookasideList( List );
}
-VOID TcpipFreeToNPagedLookasideList( PNPAGED_LOOKASIDE_LIST List,
+VOID TcpipFreeToNPagedLookasideList( PNPAGED_LOOKASIDE_LIST List,
PVOID Thing ) {
ExFreeToNPagedLookasideList( List, Thing );
}
ULONG Temp = CL_TL_UDP;
return InfoCopyOut( (PCHAR)&Temp, sizeof(Temp), Buffer, BufferSize );
}
-
+
return TDI_INVALID_REQUEST;
}
STDCALL
CTEInitString (
DWORD Unknown0,
- DWORD Unknown1
+ DWORD Unknown1
)
{
return FALSE;
/* FIXME: what should it initialize? */
return TRUE;
}
-
+
/*
* @unimplemented
{
#if 0
PKEVENT kevent = (PKEVENT) Unknown0;
-
+
return KeSetEvent (
kevent,
0,
/* De-/Register Action IDs for TdiDeRegister */
typedef
-enum
+enum
{
R_NOTIFICATION_HANDLER = 0,
DT_NOTIFICATION_HANDLER,
DWORD Unknown2
)
{
-#if 0
+#if 0
NTSTATUS Status = STATUS_SUCCESS;
Status = TdiDeRegister (
R_ADDRESS_CHANGE_HANDLER,
DWORD Unknown1
)
{
-#if 0
+#if 0
NTSTATUS Status = STATUS_SUCCESS;
Status = TdiDeRegister (
R_DEVICE_OBJECT,
DWORD Unknown1
)
{
-#if 0
+#if 0
NTSTATUS Status = STATUS_SUCCESS;
Status = TdiDeRegister (
R_NET_ADDRESS,
DWORD Unknown2
)
{
-#if 0
+#if 0
NTSTATUS Status = STATUS_SUCCESS;
Status = TdiDeRegister (
R_NOTIFICATION_HANDLER,
*
* @unimplemented
*/
-NTSTATUS
+NTSTATUS
STDCALL
TdiDefaultErrorHandler (
IN PVOID TdiEventContext,
*
* @unimplemented
*/
-NTSTATUS
+NTSTATUS
STDCALL
TdiDefaultReceiveHandler (
IN PVOID TdiEventContext,
*
* @unimplemented
*/
-TDI_STATUS
+TDI_STATUS
STDCALL
TdiDefaultSendPossibleHandler (
IN PVOID TdiEventContext,
/*
* @unimplemented
*/
-VOID
+VOID
STDCALL
TdiBuildNetbiosAddress (
IN PUCHAR NetbiosName,
/*
* @unimplemented
*/
-NTSTATUS
+NTSTATUS
STDCALL
TdiCopyBufferToMdl (
IN PVOID SourceBuffer,
/*
* @unimplemented
*/
-NTSTATUS
+NTSTATUS
STDCALL
TdiCopyMdlToBuffer (
IN PMDL SourceMdlChain,
* Vizzini (vizzini@plasmic.com)
* REVISIONS:
* CSH 01/08-2000 Created
- * 26-Nov-2003 Vizzini Updated to run properly on Win2ksp4
+ * 26-Nov-2003 Vizzini Updated to run properly on Win2ksp4
*/
#include <tditest.h>
PKEVENT Events[2];
NTSTATUS Status;
Events[0] = &StopEvent;
- Events[1] = &Event;
+ Events[1] = &Event;
KeInitializeEvent(&Event, NotificationEvent, FALSE);
Irp->UserEvent = &Event;
Status = IoCallDriver(DeviceObject, Irp);
- if (Status == STATUS_PENDING)
+ if (Status == STATUS_PENDING)
{
- if (CanCancel)
+ if (CanCancel)
{
Status = KeWaitForMultipleObjects(2, (PVOID)Events, WaitAny, Executive, KernelMode, FALSE, NULL, NULL);
- if (KeReadStateEvent(&StopEvent) != 0)
+ if (KeReadStateEvent(&StopEvent) != 0)
{
- if (IoCancelIrp(Irp))
+ if (IoCancelIrp(Irp))
{
TDI_DbgPrint(MAX_TRACE, ("Cancelled IRP.\n"));
- }
- else
+ }
+ else
{
TDI_DbgPrint(MIN_TRACE, ("Could not cancel IRP.\n"));
}
return STATUS_CANCELLED;
}
- }
+ }
else
Status = KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
}
EaInfo, /* EA buffer */
EaLength); /* EA length */
- if (NT_SUCCESS(Status))
+ if (NT_SUCCESS(Status))
{
Status = ObReferenceObjectByHandle(
*Handle, /* Handle to open file */
(PVOID*)Object, /* Pointer to object */
NULL); /* Handle information */
- if (!NT_SUCCESS(Status))
+ if (!NT_SUCCESS(Status))
{
TDI_DbgPrint(MIN_TRACE, ("ObReferenceObjectByHandle() failed with status (0x%X).\n", Status));
ZwClose(*Handle);
}
- }
- else
+ }
+ else
{
TDI_DbgPrint(MIN_TRACE, ("ZwCreateFile() failed with status (0x%X)\n", Status));
}
EaLength = sizeof(FILE_FULL_EA_INFORMATION) + TDI_TRANSPORT_ADDRESS_LENGTH + sizeof(TA_IP_ADDRESS) + 1;
EaInfo = (PFILE_FULL_EA_INFORMATION)ExAllocatePool(NonPagedPool, EaLength);
- if (!EaInfo)
+ if (!EaInfo)
{
TDI_DbgPrint(MIN_TRACE, ("Insufficient resources.\n"));
return STATUS_INSUFFICIENT_RESOURCES;
Irp = IoBuildDeviceIoControlRequest(IoControlCode, DeviceObject, InputBuffer, InputBufferLength, OutputBuffer,
OutputBufferLength, FALSE, NULL, NULL);
- if (!Irp)
+ if (!Irp)
{
TDI_DbgPrint(MIN_TRACE, ("IoBuildDeviceIoControlRequest() failed.\n"));
return STATUS_INSUFFICIENT_RESOURCES;
BufferSize = sizeof(TDIEntityID) * 20;
Entities = (TDIEntityID*)ExAllocatePool(NonPagedPool, BufferSize);
- if (!Entities)
+ if (!Entities)
{
TDI_DbgPrint(MIN_TRACE, ("Insufficient resources.\n"));
return STATUS_INSUFFICIENT_RESOURCES;
Entities, /* Output buffer */
&BufferSize); /* Output buffer size */
- if (!NT_SUCCESS(Status))
+ if (!NT_SUCCESS(Status))
{
TDI_DbgPrint(MIN_TRACE, ("Unable to get list of supported entities (Status = 0x%X).\n", Status));
ExFreePool(Entities);
TDI_DbgPrint(MAX_TRACE, ("EntityCount = %d\n", EntityCount));
- for (i = 0; i < EntityCount; i++)
+ for (i = 0; i < EntityCount; i++)
{
- if (Entities[i].tei_entity == CL_NL_ENTITY)
+ if (Entities[i].tei_entity == CL_NL_ENTITY)
{
/* Query device for entity type */
BufferSize = sizeof(EntityType);
&EntityType, /* Output buffer */
&BufferSize); /* Output buffer size */
- if (!NT_SUCCESS(Status) || (EntityType != CL_NL_IP))
+ if (!NT_SUCCESS(Status) || (EntityType != CL_NL_IP))
{
TDI_DbgPrint(MIN_TRACE, ("Unable to get entity of type IP (Status = 0x%X).\n", Status));
break;
&SnmpInfo, /* Output buffer */
&BufferSize); /* Output buffer size */
- if (!NT_SUCCESS(Status) || (SnmpInfo.NumAddr == 0))
+ if (!NT_SUCCESS(Status) || (SnmpInfo.NumAddr == 0))
{
TDI_DbgPrint(MIN_TRACE, ("Unable to get SNMP information or no IP addresses available (Status = 0x%X).\n", Status));
break;
}
/* Query device for all IP addresses */
- if (SnmpInfo.NumAddr != 0)
+ if (SnmpInfo.NumAddr != 0)
{
BufferSize = SnmpInfo.NumAddr * sizeof(IPADDR_ENTRY);
IpAddress = (PIPADDR_ENTRY)ExAllocatePool(NonPagedPool, BufferSize);
- if (!IpAddress)
+ if (!IpAddress)
{
TDI_DbgPrint(MIN_TRACE, ("Insufficient resources.\n"));
break;
IpAddress, /* Output buffer */
&BufferSize); /* Output buffer size */
- if (!NT_SUCCESS(Status))
+ if (!NT_SUCCESS(Status))
{
TDI_DbgPrint(MIN_TRACE, ("Unable to get IP address (Status = 0x%X).\n", Status));
ExFreePool(IpAddress);
break;
}
- if (SnmpInfo.NumAddr != 1)
+ if (SnmpInfo.NumAddr != 1)
{
/* Skip loopback address */
*Address = DN2H(((PIPADDR_ENTRY)((ULONG)IpAddress + sizeof(IPADDR_ENTRY)))->Addr);
}
- else
+ else
{
/* Select the first address returned */
*Address = DN2H(IpAddress->Addr);
ExFreePool(IpAddress);
}
- else
+ else
{
Status = STATUS_UNSUCCESSFUL;
break;
NULL, /* Event */
NULL); /* Return buffer */
- if (!Irp)
+ if (!Irp)
{
TDI_DbgPrint(MIN_TRACE, ("TdiBuildInternalDeviceControlIrp() failed.\n"));
ExFreePool(ConnectInfo);
FALSE, /* Don't charge quota */
NULL); /* Don't use IRP */
- if (!Mdl)
+ if (!Mdl)
{
TDI_DbgPrint(MIN_TRACE, ("IoAllocateMdl() failed.\n"));
IoFreeIrp(Irp);
}
#ifdef _MSC_VER
- try
+ try
{
#endif
MmProbeAndLockPages(Mdl, KernelMode, IoModifyAccess);
#ifdef _MSC_VER
- }
- except(EXCEPTION_EXECUTE_HANDLER)
+ }
+ except(EXCEPTION_EXECUTE_HANDLER)
{
TDI_DbgPrint(MIN_TRACE, ("MmProbeAndLockPages() failed.\n"));
IoFreeMdl(Mdl);
if (!MdlBuffer)
return STATUS_INSUFFICIENT_RESOURCES;
- RtlZeroMemory(ReceiveInfo, sizeof(TDI_CONNECTION_INFORMATION) + sizeof(TDI_CONNECTION_INFORMATION) +
+ RtlZeroMemory(ReceiveInfo, sizeof(TDI_CONNECTION_INFORMATION) + sizeof(TDI_CONNECTION_INFORMATION) +
sizeof(TA_IP_ADDRESS));
RtlCopyMemory(MdlBuffer, Buffer, *BufferSize);
NULL, /* Event */
NULL); /* Return buffer */
- if (!Irp)
+ if (!Irp)
{
ExFreePool(MdlBuffer);
ExFreePool(ReceiveInfo);
FALSE, /* Don't charge quota */
NULL); /* Don't use IRP */
- if (!Mdl)
+ if (!Mdl)
{
IoFreeIrp(Irp);
ExFreePool(MdlBuffer);
}
#ifdef _MSC_VER
- try
+ try
{
#endif
MmProbeAndLockPages(Mdl, KernelMode, IoModifyAccess);
#ifdef _MSC_VER
- }
- except (EXCEPTION_EXECUTE_HANDLER)
+ }
+ except (EXCEPTION_EXECUTE_HANDLER)
{
TDI_DbgPrint(MIN_TRACE, ("MmProbeAndLockPages() failed.\n"));
IoFreeMdl(Mdl);
ReceiveInfo, /* Connection information */
ReturnInfo, /* Connection information */
TDI_RECEIVE_NORMAL); /* Flags */
-
+
Status = TdiCall(Irp, DeviceObject, &Iosb, TRUE);
- if (NT_SUCCESS(Status))
+ if (NT_SUCCESS(Status))
{
RtlCopyMemory(Buffer, MdlBuffer, Iosb.Information);
*BufferSize = Iosb.Information;
NTSTATUS Status = STATUS_SUCCESS;
UCHAR Data[40] = "Testing one, two, three, ...";
- if (!OpenError)
+ if (!OpenError)
{
Timeout.QuadPart = 10000000L; /* Second factor */
Timeout.QuadPart *= 2; /* Number of seconds */
Events[0] = &StopEvent;
Events[1] = &Event;
- while (NT_SUCCESS(Status))
+ while (NT_SUCCESS(Status))
{
/* Wait until timeout or stop flag is set */
KeWaitForMultipleObjects( 2, (PVOID)Events, WaitAny, Executive, KernelMode, FALSE, &Timeout, NULL);
- if (KeReadStateEvent(&StopEvent) != 0)
+ if (KeReadStateEvent(&StopEvent) != 0)
{
TDI_DbgPrint(MAX_TRACE, ("Received terminate signal...\n"));
break;
ULONG Size;
NTSTATUS Status = STATUS_SUCCESS;
- if (!OpenError)
+ if (!OpenError)
{
- while (NT_SUCCESS(Status))
+ while (NT_SUCCESS(Status))
{
Size = sizeof(Data);
RtlZeroMemory(Data, Size);
Status = TdiReceiveDatagram(TdiTransportObject, TEST_PORT, &Address, Data, &Size);
- if (NT_SUCCESS(Status))
+ if (NT_SUCCESS(Status))
{
DbgPrint("Received data - '%s'\n", Data);
- }
+ }
else
- if (Status != STATUS_CANCELLED)
+ if (Status != STATUS_CANCELLED)
{
TDI_DbgPrint(MIN_TRACE, ("Receive error (Status = 0x%X).\n", Status));
- }
- else
+ }
+ else
{
TDI_DbgPrint(MAX_TRACE, ("IRP was cancelled.\n"));
}
Status = TdiOpenTransport(UDP_DEVICE_NAME, TEST_PORT, &TdiTransport, &TdiTransportObject);
- if (NT_SUCCESS(Status))
+ if (NT_SUCCESS(Status))
{
Status = TdiQueryAddress(TdiTransportObject, &LocalAddress);
- if (NT_SUCCESS(Status))
+ if (NT_SUCCESS(Status))
{
OpenError = FALSE;
DbgPrint("Using local IP address 0x%X\n", LocalAddress);
- }
- else
+ }
+ else
{
TDI_DbgPrint(MIN_TRACE, ("Unable to determine local IP address.\n"));
}
- }
+ }
else
TDI_DbgPrint(MIN_TRACE, ("Cannot open transport (Status = 0x%X).\n", Status));
(PKSTART_ROUTINE)TdiSendThread, /* Start routine */
NULL); /* Start context */
- if (!NT_SUCCESS(Status))
+ if (!NT_SUCCESS(Status))
{
TDI_DbgPrint(MIN_TRACE, ("PsCreateSystemThread() failed for send thread (Status = 0x%X).\n", Status));
return STATUS_INSUFFICIENT_RESOURCES;
(PKSTART_ROUTINE)TdiReceiveThread, /* Start routine */
NULL); /* Start context */
- if (!NT_SUCCESS(Status))
+ if (!NT_SUCCESS(Status))
{
TDI_DbgPrint(MIN_TRACE, ("PsCreateSystemThread() failed for receive thread (Status = 0x%X).\n", Status));
ZwClose(SendThread);
* FILE: drivers/storage/atapi/atapi.c
* PURPOSE: ATAPI miniport driver
* PROGRAMMERS: Eric Kohl (ekohl@rz-online.de)
- * Hartmut Birr
+ * Hartmut Birr
* REVISIONS:
* 09-09-2001 Created
*/
}
PCI_NATIVE_CONTROLLER, *PPCI_NATIVE_CONTROLLER;
-PCI_NATIVE_CONTROLLER const PciNativeController[] =
+PCI_NATIVE_CONTROLLER const PciNativeController[] =
{
{
- 0x105A, // Promise
+ 0x105A, // Promise
0x4D68, // PDC20268, Ultra100TX2
},
{
- 0x105A, // Promise
+ 0x105A, // Promise
0x4D30, // PDC20267, Ultra100
}
};
#ifdef ALLOC_PRAGMA
-// make the initialization routines discardable, so that they
+// make the initialization routines discardable, so that they
// don't waste space
#pragma alloc_text(init, DriverEntry)
// ---------------------------------------------------- Forward Declarations
#ifdef ENABLE_DMA
-static BOOLEAN
+static BOOLEAN
AtapiInitDma(PATAPI_MINIPORT_EXTENSION DevExt,
PSCSI_REQUEST_BLOCK Srb,
BYTE cmd);
IN PSCSI_REQUEST_BLOCK Srb);
static VOID
-AtapiExecuteCommand(PATAPI_MINIPORT_EXTENSION DevExt,
- BYTE command,
+AtapiExecuteCommand(PATAPI_MINIPORT_EXTENSION DevExt,
+ BYTE command,
BOOLEAN FASTCALL (*Handler)(PATAPI_MINIPORT_EXTENSION));
static BOOLEAN STDCALL
// DriverEntry
//
// DESCRIPTION:
-// This function initializes the driver, locates and claims
+// This function initializes the driver, locates and claims
// hardware resources, and creates various NT objects needed
// to process I/O requests.
//
// ARGUMENTS:
// IN PDRIVER_OBJECT DriverObject System allocated Driver Object
// for this driver
-// IN PUNICODE_STRING RegistryPath Name of registry driver service
+// IN PUNICODE_STRING RegistryPath Name of registry driver service
// key
//
// RETURNS:
ConfigInfo->NeedPhysicalAddresses = TRUE;
ConfigInfo->MapBuffers = TRUE;
- DevExt->PRDMaxCount = PAGE_SIZE / sizeof(PRD);
+ DevExt->PRDMaxCount = PAGE_SIZE / sizeof(PRD);
DevExt->PRDTable = ScsiPortGetUncachedExtension(DevExt, ConfigInfo, sizeof(PRD) * DevExt->PRDMaxCount);
if (DevExt->PRDTable != NULL)
{
continue;
}
}
-
+
DPRINT("%x %x\n", PciConfig.BaseClass, PciConfig.SubClass);
if (PciConfig.BaseClass == 0x01 &&
PciConfig.SubClass == 0x01) // &&
{
break;
}
- }
+ }
StartFunctionNumber = 0;
}
DPRINT("AtapiFindCompatiblePciController() returns: SP_RETURN_NOT_FOUND\n");
break;
}
}
- if (Count < sizeof(PciNativeController)/sizeof(PCI_NATIVE_CONTROLLER))
+ if (Count < sizeof(PciNativeController)/sizeof(PCI_NATIVE_CONTROLLER))
{
/* We have found a known native pci ide controller */
if ((PciConfig.ProgIf & 0x80) && (PciConfig.u.type0.BaseAddresses[4] & PCI_ADDRESS_IO_SPACE))
We must not store and use the last tested slot number. If there is a recall
to the some device and we will claim the primary channel again than the call
to ScsiPortGetDeviceBase in AtapiClaimHwResource will fail and we can try to
- claim the secondary channel.
+ claim the secondary channel.
*/
ChannelFound = FALSE;
if (LastSlotNumber.u.AsULONG != SlotNumber.u.AsULONG)
{
static ULONG Count = 0;
Count++;
- DPRINT1("Unexpected Interrupt, CommandPort=%04x, Status=%02x, Count=%ld\n",
+ DPRINT1("Unexpected Interrupt, CommandPort=%04x, Status=%02x, Count=%ld\n",
DevExt->CommandPortBase, Status, Count);
}
return FALSE;
{
if ((DeviceExtension->DeviceParams[UnitNumber].MultiDmaModes & 0x0404) == 0x0404)
{
- Result = TRUE;
+ Result = TRUE;
}
#if 0
/* FIXME:
*/
else if ((DeviceExtension->DeviceParams[UnitNumber].DmaModes & 0x0404) == 0x0404)
{
- Result = TRUE;
+ Result = TRUE;
}
#endif
}
#ifdef ENABLE_DMA
if (AtapiConfigDma(DeviceExtension, UnitNumber))
{
- DeviceExtension->DeviceFlags[UnitNumber] |= DEVICE_DMA_CMD;
+ DeviceExtension->DeviceFlags[UnitNumber] |= DEVICE_DMA_CMD;
}
#endif
DeviceFound = TRUE;
DPRINT(" IDE drive found!\n");
DeviceExtension->DeviceFlags[UnitNumber] |= DEVICE_PRESENT;
DeviceExtension->TransferSize[UnitNumber] = DeviceExtension->DeviceParams[UnitNumber].BytesPerSector;
- if ((DeviceExtension->DeviceParams[UnitNumber].RWMultImplemented & 0x8000) &&
+ if ((DeviceExtension->DeviceParams[UnitNumber].RWMultImplemented & 0x8000) &&
(DeviceExtension->DeviceParams[UnitNumber].RWMultImplemented & 0xff) &&
(DeviceExtension->DeviceParams[UnitNumber].RWMultCurrent & 0x100) &&
(DeviceExtension->DeviceParams[UnitNumber].RWMultCurrent & 0xff))
#ifdef ENABLE_DMA
if (AtapiConfigDma(DeviceExtension, UnitNumber))
{
- DeviceExtension->DeviceFlags[UnitNumber] |= DEVICE_DMA_CMD;
+ DeviceExtension->DeviceFlags[UnitNumber] |= DEVICE_DMA_CMD;
}
#endif
DeviceFound = TRUE;
{
if (DeviceExtension->DeviceFlags[Srb->TargetId] & DEVICE_48BIT_ADDRESS)
{
- ((PUSHORT)&LastSector)[0] = DeviceParams->Max48BitAddress[0];
- ((PUSHORT)&LastSector)[1] = DeviceParams->Max48BitAddress[1];
- ((PUSHORT)&LastSector)[2] = DeviceParams->Max48BitAddress[2];
- ((PUSHORT)&LastSector)[3] = DeviceParams->Max48BitAddress[3];
+ ((PUSHORT)&LastSector)[0] = DeviceParams->Max48BitAddress[0];
+ ((PUSHORT)&LastSector)[1] = DeviceParams->Max48BitAddress[1];
+ ((PUSHORT)&LastSector)[2] = DeviceParams->Max48BitAddress[2];
+ ((PUSHORT)&LastSector)[3] = DeviceParams->Max48BitAddress[3];
LastSector.QuadPart -= 1;
}
SectorNumber[0] = StartingSector & 0xff;
CylinderLow[0] = (StartingSector >> 8) & 0xff;
CylinderHigh[0] = (StartingSector >> 16) & 0xff;
- DrvHead = ((StartingSector >> 24) & 0x0f) |
+ DrvHead = ((StartingSector >> 24) & 0x0f) |
(Srb->TargetId ? IDE_DH_DRV1 : 0) |
IDE_DH_LBA;
{
SectorNumber[0] = (StartingSector % DeviceParams->SectorsPerTrack) + 1;
StartingSector /= DeviceParams->SectorsPerTrack;
- DrvHead = (StartingSector % DeviceParams->LogicalHeads) |
+ DrvHead = (StartingSector % DeviceParams->LogicalHeads) |
(Srb->TargetId ? IDE_DH_DRV1 : 0);
StartingSector /= DeviceParams->LogicalHeads;
CylinderLow[0] = StartingSector & 0xff;
DPRINT("%s:BUS=%04x:DRV=%d:LBA=0:CH=%02x:CL=%02x:HD=%01x:SN=%02x:SC=%02x:CM=%02x\n",
(Srb->SrbFlags & SRB_FLAGS_DATA_IN) ? "READ" : "WRITE",
DeviceExtension->CommandPortBase,
- DrvHead & IDE_DH_DRV1 ? 1 : 0,
+ DrvHead & IDE_DH_DRV1 ? 1 : 0,
CylinderHigh[0],
CylinderLow[0],
DrvHead & 0x0f,
IDEWriteDriveHead(DeviceExtension->CommandPortBase, IDE_DH_FIXED | DrvHead);
#ifdef ENABLE_DMA
- if (DeviceExtension->PRDTable &&
+ if (DeviceExtension->PRDTable &&
DeviceExtension->DeviceFlags[Srb->TargetId] & DEVICE_DMA_CMD)
{
DeviceExtension->UseDma = AtapiInitDma(DeviceExtension, Srb, Srb->SrbFlags & SRB_FLAGS_DATA_IN ? 1 << 3 : 0);
DmaCommand = IDEReadDMACommand(DeviceExtension->BusMasterRegisterBase);
IDEWriteDMACommand(DeviceExtension->BusMasterRegisterBase, DmaCommand|0x01);
}
- else
+ else
#endif
{
if (Srb->SrbFlags & SRB_FLAGS_DATA_OUT)
DPRINT("The drive doesn't support FLUSH_CACHE\n");
return SRB_STATUS_INVALID_REQUEST;
}
-
+
/* Wait for BUSY to clear */
for (Retries = 0; Retries < IDE_MAX_BUSY_RETRIES; Retries++)
{
ScsiPortStallExecution(10);
/* Issue command to drive */
- AtapiExecuteCommand(DeviceExtension,
- DeviceExtension->DeviceFlags[Srb->TargetId] & DEVICE_48BIT_ADDRESS ? IDE_CMD_FLUSH_CACHE_EXT : IDE_CMD_FLUSH_CACHE,
- AtapiNoDataInterrupt);
+ AtapiExecuteCommand(DeviceExtension,
+ DeviceExtension->DeviceFlags[Srb->TargetId] & DEVICE_48BIT_ADDRESS ? IDE_CMD_FLUSH_CACHE_EXT : IDE_CMD_FLUSH_CACHE,
+ AtapiNoDataInterrupt);
/* Wait for controller ready */
for (Retries = 0; Retries < IDE_MAX_WRITE_RETRIES; Retries++)
}
static VOID FASTCALL
-AtapiCompleteRequest(PATAPI_MINIPORT_EXTENSION DevExt,
+AtapiCompleteRequest(PATAPI_MINIPORT_EXTENSION DevExt,
UCHAR SrbStatus)
{
PSCSI_REQUEST_BLOCK Srb;
{
Srb->DataTransferLength -= DevExt->DataTransferLength;
}
-
+
DevExt->Handler = NULL;
ScsiPortNotification(RequestComplete, (PVOID)DevExt, Srb);
ScsiPortNotification(NextRequest, (PVOID)DevExt, NULL);
}
#endif
-static BOOLEAN FASTCALL
+static BOOLEAN FASTCALL
AtapiPacketInterrupt(PATAPI_MINIPORT_EXTENSION DevExt)
{
PSCSI_REQUEST_BLOCK Srb;
DPRINT("AtapiPacketInterrupt() done\n");
return TRUE;
}
-
+
IntReason = IDEReadSectorCount(DevExt->CommandPortBase);
TransferSize = IDEReadCylinderLow(DevExt->CommandPortBase);
TransferSize += IDEReadCylinderHigh(DevExt->CommandPortBase) << 8;
{
if (DevExt->DataTransferLength > 0)
{
- DPRINT1("AtapiPacketInterrupt: data underrun (%d bytes), command was %02x\n",
+ DPRINT1("AtapiPacketInterrupt: data underrun (%d bytes), command was %02x\n",
DevExt->DataTransferLength, Srb->Cdb[0]);
SrbStatus = SRB_STATUS_DATA_OVERRUN;
}
return TRUE;
}
-static BOOLEAN FASTCALL
+static BOOLEAN FASTCALL
AtapiNoDataInterrupt(PATAPI_MINIPORT_EXTENSION DevExt)
{
BYTE Status;
AtapiCompleteRequest(DevExt, SRB_STATUS_ERROR);
DPRINT1("AtapiDmaReadInterrupt() done\n");
return TRUE;
-}
+}
#endif
static BOOLEAN FASTCALL
}
static VOID
-AtapiExecuteCommand(PATAPI_MINIPORT_EXTENSION DevExt,
- BYTE command,
+AtapiExecuteCommand(PATAPI_MINIPORT_EXTENSION DevExt,
+ BYTE command,
BOOLEAN FASTCALL (*Handler)(PATAPI_MINIPORT_EXTENSION))
{
if (DevExt->Handler != NULL)
while (Length)
{
- /* calculate the length up to the next 64k boundary */
+ /* calculate the length up to the next 64k boundary */
tmpLength = 0x10000 - (PhysicalAddress.u.LowPart & 0xffff);
if (tmpLength > Length)
{
}
if (tmpLength == 0x10000)
{
- /* Some dirty controllers cannot handle 64k transfers. We split a 64k transfer in two 32k. */
+ /* Some dirty controllers cannot handle 64k transfers. We split a 64k transfer in two 32k. */
tmpLength = 0x8000;
- DPRINT("PRD Nr. %d VirtualAddress %08x PhysicalAddress %08x, Length %04x\n",
+ DPRINT("PRD Nr. %d VirtualAddress %08x PhysicalAddress %08x, Length %04x\n",
DevExt->PRDCount - 1, StartAddress, PhysicalAddress.u.LowPart, tmpLength);
PRDEntry->PhysAddress = PhysicalAddress.u.LowPart;
PRDEntry->Length = tmpLength;
Length -= tmpLength;
PRDEntry->PhysAddress = PhysicalAddress.u.LowPart;
}
- DPRINT("PRD Nr. %d VirtualAddress %08x PhysicalAddress %08x, Length %04x\n",
+ DPRINT("PRD Nr. %d VirtualAddress %08x PhysicalAddress %08x, Length %04x\n",
DevExt->PRDCount - 1, StartAddress, PhysicalAddress.u.LowPart, tmpLength);
PRDEntry->PhysAddress = PhysicalAddress.u.LowPart;
PRDEntry->Length = tmpLength;
PRDEntry++;
StartAddress += tmpLength;
- PhysicalAddress.u.LowPart += tmpLength;
+ PhysicalAddress.u.LowPart += tmpLength;
Length -= tmpLength;
}
}
#define IDEWriteDMAStatus(Address, Data) \
(ScsiPortWritePortUchar((PUCHAR)((Address) + 2), (Data)))
#define IDEWritePRDTable(Address, Data) \
- (ScsiPortWritePortUlong((PULONG)((Address) + 4), (Data)))
+ (ScsiPortWritePortUlong((PULONG)((Address) + 4), (Data)))
//
* DriverEntry
*
* DESCRIPTION:
- * This function initializes the driver, locates and claims
+ * This function initializes the driver, locates and claims
* hardware resources, and creates various NT objects needed
* to process I/O requests.
*
Cdb->MODE_SENSE.AllocationLength = (UCHAR)Length;
Buffer = ExAllocatePool (NonPagedPool,
- max(sizeof(ERROR_RECOVERY_DATA6),
- max(sizeof(ERROR_RECOVERY_DATA10),
- max(sizeof(MODE_CAPABILITIES_DATA6),
+ max(sizeof(ERROR_RECOVERY_DATA6),
+ max(sizeof(ERROR_RECOVERY_DATA10),
+ max(sizeof(MODE_CAPABILITIES_DATA6),
sizeof(MODE_CAPABILITIES_DATA10)))));
if (Buffer == NULL)
{
/* Try the 10 byte version */
Length = sizeof(MODE_READ_RECOVERY_PAGE) + MODE_HEADER_LENGTH10;
- RtlZeroMemory (&Srb,
+ RtlZeroMemory (&Srb,
sizeof(SCSI_REQUEST_BLOCK));
Srb.CdbLength = 10;
Srb.TimeOutValue = DiskDeviceExtension->TimeOutValue;
{
DbgPrint(" Drive supports software slot selection\n");
}
- DbgPrint(" Maximum speed is %d kB/s\n",
- (CapabilitiesData->MaximumSpeedSupported[0] << 8)
+ DbgPrint(" Maximum speed is %d kB/s\n",
+ (CapabilitiesData->MaximumSpeedSupported[0] << 8)
| CapabilitiesData->MaximumSpeedSupported[1]);
- DbgPrint(" Current speed is %d kB/s\n",
- (CapabilitiesData->CurrentSpeed[0] << 8)
+ DbgPrint(" Current speed is %d kB/s\n",
+ (CapabilitiesData->CurrentSpeed[0] << 8)
| CapabilitiesData->CurrentSpeed[1]);
DbgPrint(" Number of discrete volume levels is %d\n",
- (CapabilitiesData->Reserved3 << 8)
+ (CapabilitiesData->Reserved3 << 8)
| CapabilitiesData->NumberVolumeLevels);
DbgPrint(" Buffer size is %d kB\n",
- (CapabilitiesData->BufferSize[0] << 8)
+ (CapabilitiesData->BufferSize[0] << 8)
| CapabilitiesData->BufferSize[1]);
#endif
}
/*
* BUGBUG -> Srb = IrpStack->Parameters.Scsi.Srb;
- * Must pass Srb as Context arg!! See comment about Completion routines in
+ * Must pass Srb as Context arg!! See comment about Completion routines in
* IofCallDriver for more info.
*/
/*
* BUGBUG -> Srb = Srb = IrpStack->Parameters.Scsi.Srb;
- * Must pass Srb as Context arg!! See comment about Completion routines in
+ * Must pass Srb as Context arg!! See comment about Completion routines in
* IofCallDriver for more info.
*/
}
/* Adjust partition-relative starting offset to absolute offset */
- IrpStack->Parameters.Read.ByteOffset.QuadPart +=
+ IrpStack->Parameters.Read.ByteOffset.QuadPart +=
(DeviceExtension->StartingOffset.QuadPart + DeviceExtension->DMByteSkew);
/* Calculate number of pages in this transfer */
Srb->ScsiStatus = 0;
/* Don't modify the flags */
-// Srb->Flags =
+// Srb->Flags =
// Srb->QueueTag = SP_UNTAGGED;
NextIrpStack->MajorFunction = IRP_MJ_SCSI;
TRUE,
TRUE,
TRUE);
- }
+ }
else
{
IoSetCompletionRoutine(Irp,
static VOID
DiskClassCreateMediaChangeEvent(IN PDEVICE_EXTENSION DeviceExtension,
- IN ULONG DeviceNumber);
+ IN ULONG DeviceNumber);
static NTSTATUS
DiskClassCreateDeviceObject(IN PDRIVER_OBJECT DriverObject,
* DriverEntry
*
* DESCRIPTION
- * This function initializes the driver, locates and claims
+ * This function initializes the driver, locates and claims
* hardware resources, and creates various NT objects needed
* to process I/O requests.
*
- IrpStack = IoGetCurrentIrpStackLocation(Irp);
+ IrpStack = IoGetCurrentIrpStackLocation(Irp);
EndingOffset.QuadPart = IrpStack->Parameters.Read.ByteOffset.QuadPart +
IrpStack->Parameters.Read.Length;
if ((DiskDeviceObject->Characteristics & FILE_REMOVABLE_MEDIA) &&
(DiskDeviceExtension->DiskGeometry->MediaType == RemovableMedia))
{
- DiskClassCreateMediaChangeEvent(DiskDeviceExtension,DiskNumber);
+ DiskClassCreateMediaChangeEvent(DiskDeviceExtension,DiskNumber);
if (DiskDeviceExtension->MediaChangeEvent != NULL)
{
DPRINT("Allocated media change event!\n");
NTSTATUS STDCALL
DiskClassDeviceControl(IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp)
-{
+{
PDEVICE_EXTENSION DeviceExtension;
PIO_STACK_LOCATION IrpStack;
ULONG ControlCode, InputLength, OutputLength;
/* Update a partition list for a single entry. */
Status = DiskBuildPartitionTable(DeviceObject,Irp);
}
-
+
if (IrpStack->Parameters.DeviceIoControl.OutputBufferLength <
sizeof(PARTITION_INFORMATION))
{
RtlZeroMemory(Cdb, MAXIMUM_CDB_SIZE);
Cdb->CDB10.LogicalUnitNumber = CoreDumpClass2DeviceExtension->Lun;
- TransferBlocks = (USHORT)(PAGE_SIZE >>
+ TransferBlocks = (USHORT)(PAGE_SIZE >>
CoreDumpClass2DeviceExtension->SectorShift);
/* Copy little endian values into CDB in big endian format */
{
DbgPrint("DISKDUMP: Error: Crash inside high priority interrupt routine.\n");
return(STATUS_UNSUCCESSFUL);
- }
+ }
CoreDumpPortDeviceExtension->Interrupt->ServiceRoutine = DiskDumpIsr;
-
+
return(STATUS_SUCCESS);
}
if (CurrentIrql < (CoreDumpPortDeviceExtension->Interrupt->SynchLevel - 1))
{
KeRaiseIrql(CoreDumpPortDeviceExtension->Interrupt->SynchLevel - 1, &OldIrql);
- }
+ }
/* Adjust the address for the start of the partition. */
Address.QuadPart +=
while (!IrqComplete || !IrqNextRequest)
{
__asm__ ("hlt\n\t");
- }
+ }
if (CurrentIrql < (CoreDumpPortDeviceExtension->Interrupt->SynchLevel - 1))
{
KeLowerIrql(OldIrql);
}
/* Get the import address list */
- ImportAddressList = (PVOID *) ((PUCHAR)DriverBase +
+ ImportAddressList = (PVOID *) ((PUCHAR)DriverBase +
ImportModuleDirectory->dwRVAFunctionAddressList);
-
+
/* Get the list of functions to import */
if (ImportModuleDirectory->dwRVAFunctionNameList != 0)
{
- FunctionNameList = (PULONG) ((PUCHAR)DriverBase +
+ FunctionNameList = (PULONG) ((PUCHAR)DriverBase +
ImportModuleDirectory->dwRVAFunctionNameList);
}
else
{
- FunctionNameList = (PULONG) ((PUCHAR)DriverBase +
+ FunctionNameList = (PULONG) ((PUCHAR)DriverBase +
ImportModuleDirectory->dwRVAFunctionAddressList);
}
/* Walk through function list and fixup addresses */
if ((*FunctionNameList) & 0x80000000) // hint
{
Name = NULL;
-
+
Hint = (*FunctionNameList) & 0xffff;
}
else // hint-name
{
- Name = (PCHAR)((DWORD)DriverBase +
+ Name = (PCHAR)((DWORD)DriverBase +
*FunctionNameList + 2);
Hint = *(PWORD)((DWORD)DriverBase + *FunctionNameList);
}
}
DiskDumpExports[i].OldFunction = *ImportAddressList;
if (DiskDumpExports[i].NewFunction != NULL)
- {
+ {
*ImportAddressList = DiskDumpExports[i].NewFunction;
}
-
+
ImportAddressList++;
FunctionNameList++;
}
* DriverEntry
*
* DESCRIPTION
- * This function initializes the driver, locates and claims
+ * This function initializes the driver, locates and claims
* hardware resources, and creates various NT objects needed
* to process I/O requests.
*
KSPIN_LOCK IrpQueueLock;
KSEMAPHORE QueueSemaphore;
-/*
- * CSQ Callbacks
+/*
+ * CSQ Callbacks
*/
\f
-VOID NTAPI CsqRemoveIrp(PIO_CSQ UnusedCsq,
+VOID NTAPI CsqRemoveIrp(PIO_CSQ UnusedCsq,
PIRP Irp)
/*
* FUNCTION: Remove an IRP from the queue
}
\f
-PIRP NTAPI CsqPeekNextIrp(PIO_CSQ UnusedCsq,
- PIRP Irp,
+PIRP NTAPI CsqPeekNextIrp(PIO_CSQ UnusedCsq,
+ PIRP Irp,
PVOID PeekContext)
/*
* FUNCTION: Find the next matching IRP in the queue
}
\f
-VOID NTAPI CsqAcquireLock(PIO_CSQ UnusedCsq,
+VOID NTAPI CsqAcquireLock(PIO_CSQ UnusedCsq,
PKIRQL Irql)
/*
* FUNCTION: Acquire the queue lock
}
\f
-VOID NTAPI CsqReleaseLock(PIO_CSQ UnusedCsq,
+VOID NTAPI CsqReleaseLock(PIO_CSQ UnusedCsq,
KIRQL Irql)
/*
* FUNCTION: Release the queue lock
}
\f
-VOID NTAPI CsqCompleteCanceledIrp(PIO_CSQ UnusedCsq,
+VOID NTAPI CsqCompleteCanceledIrp(PIO_CSQ UnusedCsq,
PIRP Irp)
/*
* FUNCTION: Complete a canceled IRP
}
\f
-VOID NTAPI CsqInsertIrp(PIO_CSQ UnusedCsq,
+VOID NTAPI CsqInsertIrp(PIO_CSQ UnusedCsq,
PIRP Irp)
/*
* FUNCTION: Queue an IRP
* Irp: IRP to add to the queue
* NOTES:
* - Called under the protection of the queue lock
- * - Releases the semaphore for each queued packet, which is how
+ * - Releases the semaphore for each queued packet, which is how
* the queue management thread knows that there might be
* an IRP in the queue
* - Note that the semaphore will get released more times than
extern KSPIN_LOCK IrpQueueLock;
extern KSEMAPHORE QueueSemaphore;
-VOID NTAPI CsqInsertIrp(PIO_CSQ Csq,
- PIRP Irp);
+VOID NTAPI CsqInsertIrp(PIO_CSQ Csq,
+ PIRP Irp);
-VOID NTAPI CsqRemoveIrp(PIO_CSQ Csq,
+VOID NTAPI CsqRemoveIrp(PIO_CSQ Csq,
PIRP Irp);
-PIRP NTAPI CsqPeekNextIrp(PIO_CSQ Csq,
- PIRP Irp,
+PIRP NTAPI CsqPeekNextIrp(PIO_CSQ Csq,
+ PIRP Irp,
PVOID PeekContext);
-VOID NTAPI CsqAcquireLock(PIO_CSQ Csq,
+VOID NTAPI CsqAcquireLock(PIO_CSQ Csq,
PKIRQL Irql);
-VOID NTAPI CsqReleaseLock(PIO_CSQ Csq,
+VOID NTAPI CsqReleaseLock(PIO_CSQ Csq,
KIRQL Irql);
-VOID NTAPI CsqCompleteCanceledIrp(PIO_CSQ Csq,
+VOID NTAPI CsqCompleteCanceledIrp(PIO_CSQ Csq,
PIRP Irp);
* interrupts without modification. I don't think these controllers exist.
*
* ---- General to-do items ----
- * TODO: Figure out why CreateClose isn't called any more. Seems to correspond
+ * TODO: Figure out why CreateClose isn't called any more. Seems to correspond
* with the driver not being unloadable.
* TODO: Think about StopDpcQueued -- could be a race; too tired atm to tell
* TODO: Clean up drive start/stop responsibilities (currently a mess...)
#include "readwrite.h"
/*
- * Global controller info structures. Each controller gets one. Since the system
+ * Global controller info structures. Each controller gets one. Since the system
* will probably have only one, with four being a very unlikely maximum, a static
* global array is easiest to deal with.
*/
}
\f
-static NTSTATUS NTAPI CreateClose(PDEVICE_OBJECT DeviceObject,
+static NTSTATUS NTAPI CreateClose(PDEVICE_OBJECT DeviceObject,
PIRP Irp)
/*
* FUNCTION: Dispatch function called for Create and Close IRPs
* - No state to track, so this routine is easy
* - Can be called <= DISPATCH_LEVEL
*
- * TODO: Figure out why this isn't getting called
+ * TODO: Figure out why this isn't getting called
*/
{
UNREFERENCED_PARAMETER(DeviceObject);
*/
{
PKEY_VALUE_FULL_INFORMATION ControllerFullDescriptor = ControllerInformation[IoQueryDeviceConfigurationData];
- PCM_FULL_RESOURCE_DESCRIPTOR ControllerResourceDescriptor = (PCM_FULL_RESOURCE_DESCRIPTOR)((PCHAR)ControllerFullDescriptor +
+ PCM_FULL_RESOURCE_DESCRIPTOR ControllerResourceDescriptor = (PCM_FULL_RESOURCE_DESCRIPTOR)((PCHAR)ControllerFullDescriptor +
ControllerFullDescriptor->DataOffset);
PKEY_VALUE_FULL_INFORMATION PeripheralFullDescriptor = PeripheralInformation[IoQueryDeviceConfigurationData];
- PCM_FULL_RESOURCE_DESCRIPTOR PeripheralResourceDescriptor = (PCM_FULL_RESOURCE_DESCRIPTOR)((PCHAR)PeripheralFullDescriptor +
+ PCM_FULL_RESOURCE_DESCRIPTOR PeripheralResourceDescriptor = (PCM_FULL_RESOURCE_DESCRIPTOR)((PCHAR)PeripheralFullDescriptor +
PeripheralFullDescriptor->DataOffset);
PCM_PARTIAL_RESOURCE_DESCRIPTOR PartialDescriptor;
* triggered, this is safe to not do here, as we can just wait for the DPC.
* - Either way, we don't want to do this here. The controller shouldn't interrupt again, so we'll
* schedule a DPC to take care of it.
- * - This driver really cannot shrare interrupts, as I don't know how to conclusively say
+ * - This driver really cannot shrare interrupts, as I don't know how to conclusively say
* whether it was our controller that interrupted or not. I just have to assume that any time
- * my ISR gets called, it was my board that called it. Dumb design, yes, but it goes back to
+ * my ISR gets called, it was my board that called it. Dumb design, yes, but it goes back to
* the semantics of ISA buses. That, and I don't know much about ISA drivers. :-)
* UPDATE: The high bit of Status Register A seems to work on non-AT controllers.
* - Called at DIRQL
* UnusedDpc: Pointer to the DPC object that represents our function
* DeviceObject: Device that this DPC is running for
* Irp: Unused
- * Context: Pointer to our ControllerInfo struct
+ * Context: Pointer to our ControllerInfo struct
* NOTES:
* - This function just kicks off whatever the SynchEvent is and returns. We depend on
* the thing that caused the drive to interrupt to handle the work of clearing the interrupt.
KdPrint(("floppy: InitController: unable to set up implied seek\n"));
ControllerInfo->ImpliedSeeks = FALSE;
}
- else
+ else
{
KdPrint(("floppy: InitController: implied seeks set!\n"));
ControllerInfo->ImpliedSeeks = TRUE;
}
- /*
+ /*
* FIXME: Figure out the answer to the below
*
* I must admit that I'm really confused about the Model 30 issue. At least one
ControllerInfo->ImpliedSeeks = FALSE;
ControllerInfo->Model30 = FALSE;
}
-
+
/* Specify */
KdPrint(("FLOPPY: FIXME: Figure out speed\n"));
HeadLoadTime = SPECIFY_HLT_500K;
StepRateTime = SPECIFY_SRT_500K;
KdPrint(("floppy: InitController: issuing specify command to controller\n"));
-
+
/* Don't disable DMA --> enable dma (dumb & confusing) */
if(HwSpecify(ControllerInfo, HeadLoadTime, HeadUnloadTime, StepRateTime, FALSE) != STATUS_SUCCESS)
{
KeInitializeEvent(&ControllerInfo->MotorStoppedEvent, NotificationEvent, FALSE);
ControllerInfo->StopDpcQueued = FALSE;
- /*
- * Recalibrate each drive on the controller (depends on StartMotor, which depends on the timer stuff above)
+ /*
+ * Recalibrate each drive on the controller (depends on StartMotor, which depends on the timer stuff above)
* We don't even know if there is a disk in the drive, so this may not work, but that's OK.
*/
for(i = 0; i < ControllerInfo->NumberOfDrives; i++)
* FALSE if we can't allocate a device, adapter, or interrupt object, or if we fail to find any controllers
* TRUE otherwise (i.e. we have at least one fully-configured controller)
* NOTES:
- * - Currently we only support ISA buses.
+ * - Currently we only support ISA buses.
* - BUG: Windows 2000 seems to clobber the response from the IoQueryDeviceDescription callback, so now we
* just test a boolean value in the first object to see if it was completely populated. The same value
* is tested for each controller before we build device objects for it.
/* Find our controllers on all ISA buses */
IoQueryDeviceDescription(&InterfaceType, 0, &ControllerType, 0, &PeripheralType, 0, ConfigCallback, 0);
- /*
+ /*
* w2k breaks the return val from ConfigCallback, so we have to hack around it, rather than just
* looking for a return value from ConfigCallback. We expect at least one controller.
- */
+ */
if(!gControllerInfo[0].Populated)
{
KdPrint(("floppy: AddControllers: failed to get controller info from registry\n"));
KdPrint(("floppy: AddControllers(): Configuring drive %d on controller %d\n", i, j));
- /*
+ /*
* 3a: create a device object for the drive
* Controllers and drives are 0-based, so the combos are:
* 0: 0,0
* 5: 1,1
* ...
* 14: 3,2
- * 15: 3,3
- */
+ * 15: 3,3
+ */
DriveNumber = (UCHAR)(i*4 + j); /* loss of precision is OK; there are only 16 of 'em */
swprintf(DeviceNameBuf, L"\\Device\\Floppy%d", DriveNumber);
RtlInitUnicodeString(&DeviceName, DeviceNameBuf);
- if(IoCreateDevice(DriverObject, sizeof(PVOID), &DeviceName,
+ if(IoCreateDevice(DriverObject, sizeof(PVOID), &DeviceName,
FILE_DEVICE_DISK, FILE_REMOVABLE_MEDIA | FILE_FLOPPY_DISKETTE, FALSE,
&gControllerInfo[i].DriveInfo[j].DeviceObject) != STATUS_SUCCESS)
{
Irp->IoStatus.Status = STATUS_VERIFY_REQUIRED;
Irp->IoStatus.Information = 0;
- /*
+ /*
* If this is a user-based, threaded request, let the IO manager know to pop up a box asking
* the user to supply the correct media, but only if the error (which we just picked out above)
* is deemed by the IO manager to be "user induced". The reason we don't just unconditionally
DriverObject->DriverUnload = Unload;
/*
- * We depend on some zeroes in these structures. I know this is supposed to be
+ * We depend on some zeroes in these structures. I know this is supposed to be
* initialized to 0 by the complier but this makes me feel beter.
*/
memset(&gControllerInfo, 0, sizeof(gControllerInfo));
/*
* Set up queue. This routine cannot fail (trust me, I wrote it).
*/
- IoCsqInitialize(&Csq, CsqInsertIrp, CsqRemoveIrp, CsqPeekNextIrp,
+ IoCsqInitialize(&Csq, CsqInsertIrp, CsqRemoveIrp, CsqPeekNextIrp,
CsqAcquireLock, CsqReleaseLock, CsqCompleteCanceledIrp);
/*
InitializeListHead(&IrpQueue);
/*
- * The queue is counted by a semaphore. The queue management thread
+ * The queue is counted by a semaphore. The queue management thread
* blocks on this semaphore, so if requests come in faster than the queue
- * thread can handle them, the semaphore count goes up.
+ * thread can handle them, the semaphore count goes up.
*/
KeInitializeSemaphore(&QueueSemaphore, 0, 0x7fffffff);
return STATUS_UNSUCCESSFUL;
}
- /*
- * Close the handle, now that we have the object pointer and a reference of our own.
+ /*
+ * Close the handle, now that we have the object pointer and a reference of our own.
* The handle will certainly not be valid in the context of the caller next time we
* need it, as handles are process-specific.
*/
/*
* Start the device discovery proces. Returns STATUS_SUCCESS if
- * it finds even one drive attached to one controller.
+ * it finds even one drive attached to one controller.
*/
if(!AddControllers(DriverObject))
return STATUS_NO_SUCH_DEVICE;
#if 0
#define KdPrint(x) DbgPrint x
#else
-#define KdPrint(x)
+#define KdPrint(x)
#endif
#endif
/*
* MEDIA TYPES
*
- * This table was found at http://www.nondot.org/sabre/os/files/Disk/FloppyMediaIDs.txt.
+ * This table was found at http://www.nondot.org/sabre/os/files/Disk/FloppyMediaIDs.txt.
* Thanks to raster@indirect.com for this information.
*
* Format Size Cyls Heads Sec/Trk FATs Sec/FAT Sec/Root Media
* REVISIONS:
* 15-Feb-2004 vizzini - Created
* NOTES:
- * - Many of these functions are based directly on information from the
+ * - Many of these functions are based directly on information from the
* Intel datasheet for their enhanced floppy controller. Send_Byte and
- * Get_Byte are direct C implementations of their flowcharts, and the
+ * Get_Byte are direct C implementations of their flowcharts, and the
* read/write routine and others are loose adaptations of their charts.
* - These routines are generally designed to be small, atomic operations. They
* do not wait for interrupts, deal with DMA, or do any other Windows-
* it's illegal to block. The floppy controller is a *dumb* piece of hardware,
* too - it is slow and difficult to deal with. The solution is to do all
* of the blocking and servicing of the controller in a dedicated worker
- * thread.
+ * thread.
* - Some information taken from Intel 82077AA data sheet (order #290166-007)
*
* TODO: ATM the constants defined in hardware.h *might* be shifted to line up
* TRUE if the controller can accept a byte right now
* FALSE otherwise
* NOTES:
- * - it is necessary to check both that the FIFO is set to "outbound"
+ * - it is necessary to check both that the FIFO is set to "outbound"
* and that the "ready for i/o" bit is set.
*/
{
UCHAR Status = READ_PORT_UCHAR(ControllerInfo->BaseAddress + MAIN_STATUS_REGISTER);
-
+
if((Status & MSR_IO_DIRECTION)) /* 0 for out */
return FALSE;
* TRUE if the controller can read a byte right now
* FALSE otherwise
* NOTES:
- * - it is necessary to check both that the FIFO is set to "inbound"
+ * - it is necessary to check both that the FIFO is set to "inbound"
* and that the "ready for i/o" bit is set.
*/
{
UCHAR Status = READ_PORT_UCHAR(ControllerInfo->BaseAddress + MAIN_STATUS_REGISTER);
-
+
if(!(Status & MSR_IO_DIRECTION)) /* Read = 1 */
return FALSE;
}
\f
-static NTSTATUS NTAPI Send_Byte(PCONTROLLER_INFO ControllerInfo,
+static NTSTATUS NTAPI Send_Byte(PCONTROLLER_INFO ControllerInfo,
UCHAR Byte)
/*
* FUNCTION: Send a byte from the host to the controller's FIFO
* ARGUMENTS:
* ControllerInfo: Info structure for the controller we're writing to
- * Offset: Offset over the controller's base address that we're writing to
+ * Offset: Offset over the controller's base address that we're writing to
* Byte: Byte to write to the bus
* RETURNS:
* STATUS_SUCCESS if the byte was written successfully
continue;
}
-
+
WRITE_PORT_UCHAR(Address, Byte);
return STATUS_SUCCESS;
}
}
\f
-static NTSTATUS NTAPI Get_Byte(PCONTROLLER_INFO ControllerInfo,
+static NTSTATUS NTAPI Get_Byte(PCONTROLLER_INFO ControllerInfo,
PUCHAR Byte)
/*
* FUNCTION: Read a byte from the controller to the host
continue;
}
-
+
*Byte = READ_PORT_UCHAR(Address);
return STATUS_SUCCESS;
}
\f
-NTSTATUS NTAPI HwSetDataRate(PCONTROLLER_INFO ControllerInfo,
+NTSTATUS NTAPI HwSetDataRate(PCONTROLLER_INFO ControllerInfo,
UCHAR DataRate)
/*
* FUNCTION: Set the data rte on a controller
}
\f
-NTSTATUS NTAPI HwTurnOnMotor(PDRIVE_INFO DriveInfo)
+NTSTATUS NTAPI HwTurnOnMotor(PDRIVE_INFO DriveInfo)
/*
* FUNCTION: Turn on the motor on the selected drive
* ARGUMENTS:
Buffer |= DOR_FDC_ENABLE;
Buffer |= DOR_DMA_IO_INTERFACE_ENABLE;
-
+
if(Unit == 0)
Buffer |= DOR_FLOPPY_MOTOR_ON_A;
else if (Unit == 1)
}
\f
-NTSTATUS NTAPI HwReadWriteData(PCONTROLLER_INFO ControllerInfo,
+NTSTATUS NTAPI HwReadWriteData(PCONTROLLER_INFO ControllerInfo,
BOOLEAN Read,
- UCHAR Unit,
- UCHAR Cylinder,
- UCHAR Head,
+ UCHAR Unit,
+ UCHAR Cylinder,
+ UCHAR Head,
UCHAR Sector,
UCHAR BytesPerSector,
UCHAR EndOfTrack,
/* Build the command to send */
if(Read)
- Buffer[0] = COMMAND_READ_DATA;
+ Buffer[0] = COMMAND_READ_DATA;
else
- Buffer[0] = COMMAND_WRITE_DATA;
+ Buffer[0] = COMMAND_WRITE_DATA;
Buffer[0] |= READ_DATA_MFM | READ_DATA_MT;
* - This function tests the error conditions itself, and boils the
* whole thing down to a single SUCCESS or FAILURE result
* - Called post-interrupt; does not interrupt
- * TODO
+ * TODO
* - perhaps handle more status
*/
{
return STATUS_UNSUCCESSFUL;
}
- /* Validate that it did what we told it to */
+ /* Validate that it did what we told it to */
KdPrint(("floppy: HwRecalibrateResult results: ST0: 0x%x PCN: 0x%x\n", Buffer[0], Buffer[1]));
/*
return STATUS_UNSUCCESSFUL;
}
- /* Validate that it did what we told it to */
+ /* Validate that it did what we told it to */
KdPrint(("floppy: HwReadWriteResult results: 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n", Buffer[0], Buffer[1], Buffer[2], Buffer[3],
Buffer[4], Buffer[5], Buffer[6]));
}
\f
-NTSTATUS NTAPI HwFormatTrack(PCONTROLLER_INFO ControllerInfo,
+NTSTATUS NTAPI HwFormatTrack(PCONTROLLER_INFO ControllerInfo,
UCHAR Unit,
- UCHAR Head,
+ UCHAR Head,
UCHAR BytesPerSector,
UCHAR SectorsPerTrack,
UCHAR Gap3Length,
\f
NTSTATUS NTAPI HwSeek(PDRIVE_INFO DriveInfo,
- UCHAR Cylinder)
+ UCHAR Cylinder)
/*
* FUNCTION: Seek the heads to a particular cylinder
* ARGUMENTS:
}
\f
-NTSTATUS NTAPI HwConfigure(PCONTROLLER_INFO ControllerInfo,
+NTSTATUS NTAPI HwConfigure(PCONTROLLER_INFO ControllerInfo,
BOOLEAN EIS,
BOOLEAN EFIFO,
BOOLEAN POLL,
UCHAR FIFOTHR,
- UCHAR PRETRK)
+ UCHAR PRETRK)
/*
* FUNCTION: Sends configuration to the drive
* ARGUMENTS:
return Buffer;
}
-NTSTATUS NTAPI HwDiskChanged(PDRIVE_INFO DriveInfo,
+NTSTATUS NTAPI HwDiskChanged(PDRIVE_INFO DriveInfo,
PBOOLEAN DiskChanged)
/*
* FUNCTION: Detect whether the hardware has sensed a disk change
return STATUS_SUCCESS;
}
-NTSTATUS NTAPI HwSenseDriveStatusResult(PCONTROLLER_INFO ControllerInfo,
+NTSTATUS NTAPI HwSenseDriveStatusResult(PCONTROLLER_INFO ControllerInfo,
PUCHAR Status)
/*
* FUNCTION: Get the result of a sense drive status command
* - This function tests the error conditions itself, and boils the
* whole thing down to a single SUCCESS or FAILURE result
* - Called post-interrupt; does not interrupt
- * TODO
+ * TODO
* - perhaps handle more status
*/
{
return STATUS_UNSUCCESSFUL;
}
- /* Validate that it did what we told it to */
+ /* Validate that it did what we told it to */
KdPrint(("floppy: ReadId results: 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n", Buffer[0], Buffer[1], Buffer[2], Buffer[3],
Buffer[4], Buffer[5], Buffer[6]));
#define DSRB_MOTOR_ENABLE_0 0x1
#define DSRB_MOTOR_ENABLE_1 0x2
#define DSRB_WRITE_ENABLE 0x4
-#define DSRB_READ_DATA 0x8
+#define DSRB_READ_DATA 0x8
#define DSRB_WRTITE_DATA 0x10
#define DSRB_DRIVE_SELECT 0x20
#define CCR_DRC_250000 0x2
/* Commands */
-#define COMMAND_READ_TRACK 0x2
+#define COMMAND_READ_TRACK 0x2
#define COMMAND_SPECIFY 0x3
#define COMMAND_SENSE_DRIVE_STATUS 0x4
#define COMMAND_WRITE_DATA 0x5
NTSTATUS NTAPI HwSenseDriveStatus(PDRIVE_INFO DriveInfo);
-NTSTATUS NTAPI HwReadWriteData(PCONTROLLER_INFO ControllerInfo,
+NTSTATUS NTAPI HwReadWriteData(PCONTROLLER_INFO ControllerInfo,
BOOLEAN Read,
- UCHAR Unit,
- UCHAR Cylinder,
- UCHAR Head,
+ UCHAR Unit,
+ UCHAR Cylinder,
+ UCHAR Head,
UCHAR Sector,
UCHAR BytesPerSector,
UCHAR EndOfTrack,
NTSTATUS NTAPI HwSenseInterruptStatus(PCONTROLLER_INFO ControllerInfo);
-NTSTATUS NTAPI HwReadId(PDRIVE_INFO DriveInfo,
+NTSTATUS NTAPI HwReadId(PDRIVE_INFO DriveInfo,
UCHAR Head);
-NTSTATUS NTAPI HwFormatTrack(PCONTROLLER_INFO ControllerInfo,
+NTSTATUS NTAPI HwFormatTrack(PCONTROLLER_INFO ControllerInfo,
UCHAR Unit,
- UCHAR Head,
+ UCHAR Head,
UCHAR BytesPerSector,
UCHAR SectorsPerTrack,
UCHAR Gap3Length,
NTSTATUS NTAPI HwGetVersion(PCONTROLLER_INFO ControllerInfo);
-NTSTATUS NTAPI HwConfigure(PCONTROLLER_INFO ControllerInfo,
+NTSTATUS NTAPI HwConfigure(PCONTROLLER_INFO ControllerInfo,
BOOLEAN EIS,
BOOLEAN EFIFO,
BOOLEAN POLL,
NTSTATUS NTAPI HwRecalibrateResult(PCONTROLLER_INFO ControllerInfo);
-NTSTATUS NTAPI HwDiskChanged(PDRIVE_INFO DriveInfo,
+NTSTATUS NTAPI HwDiskChanged(PDRIVE_INFO DriveInfo,
PBOOLEAN DiskChanged);
-NTSTATUS NTAPI HwSenseDriveStatusResult(PCONTROLLER_INFO ControllerInfo,
+NTSTATUS NTAPI HwSenseDriveStatusResult(PCONTROLLER_INFO ControllerInfo,
PUCHAR Status);
NTSTATUS NTAPI HwSpecify(PCONTROLLER_INFO ControllerInfo,
PUCHAR CurCylinder,
PUCHAR CurHead);
-NTSTATUS NTAPI HwSetDataRate(PCONTROLLER_INFO ControllerInfo,
+NTSTATUS NTAPI HwSetDataRate(PCONTROLLER_INFO ControllerInfo,
UCHAR DataRate);
NTSTATUS NTAPI HwReset(PCONTROLLER_INFO Controller);
#include "ioctl.h"
\f
-NTSTATUS NTAPI DeviceIoctl(PDEVICE_OBJECT DeviceObject,
+NTSTATUS NTAPI DeviceIoctl(PDEVICE_OBJECT DeviceObject,
PIRP Irp)
/*
* FUNCTION: Queue IOCTL IRPs
* STATUS_SUCCESS in all cases, so far
* NOTES:
* - We can't just service these immediately because, even though some
- * are able to run at DISPATCH, they'll get out of sync with other
+ * are able to run at DISPATCH, they'll get out of sync with other
* read/write or ioctl irps.
*/
{
}
\f
-VOID NTAPI DeviceIoctlPassive(PDRIVE_INFO DriveInfo,
+VOID NTAPI DeviceIoctlPassive(PDRIVE_INFO DriveInfo,
PIRP Irp)
/*
* FUNCTION: Handlees IOCTL requests at PASSIVE_LEVEL
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
- /*
- * First the non-change-sensitive ioctls
- */
+ /*
+ * First the non-change-sensitive ioctls
+ */
if(Code == IOCTL_DISK_GET_MEDIA_TYPES)
{
PDISK_GEOMETRY Geometry = OutputBuffer;
return;
}
- /*
- * for now, this driver only supports 3.5" HD media
+ /*
+ * for now, this driver only supports 3.5" HD media
*/
Geometry->MediaType = F3_1Pt44_512;
Geometry->Cylinders.QuadPart = 80;
return;
}
- /*
+ /*
* Now, check to see if the volume needs to be verified. If so,
- * return STATUS_VERIFY_REQUIRED.
+ * return STATUS_VERIFY_REQUIRED.
*
- * NOTE: This code, which is outside of the switch and if/else blocks,
- * will implicity catch and correctly service IOCTL_DISK_CHECK_VERIFY.
+ * NOTE: This code, which is outside of the switch and if/else blocks,
+ * will implicity catch and correctly service IOCTL_DISK_CHECK_VERIFY.
* Therefore if we see one below in the switch, we can return STATUS_SUCCESS
* immediately.
*/
- if(DriveInfo->DeviceObject->Flags & DO_VERIFY_VOLUME && !(DriveInfo->DeviceObject->Flags & SL_OVERRIDE_VERIFY_VOLUME))
+ if(DriveInfo->DeviceObject->Flags & DO_VERIFY_VOLUME && !(DriveInfo->DeviceObject->Flags & SL_OVERRIDE_VERIFY_VOLUME))
{
KdPrint(("floppy: DeviceIoctl(): completing with STATUS_VERIFY_REQUIRED\n"));
Irp->IoStatus.Status = STATUS_VERIFY_REQUIRED;
KdPrint(("floppy: DeviceIoctl(): detected disk changed; signalling media change and completing\n"));
SignalMediaChanged(DriveInfo->DeviceObject, Irp);
- /*
+ /*
* Just guessing here - I have a choice of returning NO_MEDIA or VERIFY_REQUIRED. If there's
* really no disk in the drive, I'm thinking I can save time by just reporting that fact, rather
* than forcing windows to ask me twice. If this doesn't work, we'll need to split this up and
* 15-Feb-2004 vizzini - Created
*/
-NTSTATUS NTAPI DeviceIoctl(PDEVICE_OBJECT DeviceObject,
+NTSTATUS NTAPI DeviceIoctl(PDEVICE_OBJECT DeviceObject,
PIRP Irp);
VOID NTAPI DeviceIoctlPassive(PDRIVE_INFO DriveInfo,
return STATUS_INVALID_PARAMETER;
}
- /*
- * Queue the irp to the thread.
- * The de-queue thread will look in DriverContext[0] for the Device Object.
+ /*
+ * Queue the irp to the thread.
+ * The de-queue thread will look in DriverContext[0] for the Device Object.
*/
Irp->Tail.Overlay.DriverContext[0] = DeviceObject;
IoCsqInsertIrp(&Csq, Irp, NULL);
KdPrint(("floppy: RWDetermineMediaType(): unable to set data rate\n"));
return STATUS_UNSUCCESSFUL;
}
-
+
/* Specify */
HeadLoadTime = SPECIFY_HLT_500K;
HeadUnloadTime = SPECIFY_HUT_500K;
StepRateTime = SPECIFY_SRT_500K;
-
+
/* Don't disable DMA --> enable dma (dumb & confusing) */
if(HwSpecify(DriveInfo->ControllerInfo, HeadLoadTime, HeadUnloadTime, StepRateTime, FALSE) != STATUS_SUCCESS)
{
WaitForControllerInterrupt(DriveInfo->ControllerInfo);
RecalStatus = HwRecalibrateResult(DriveInfo->ControllerInfo);
-
+
if(RecalStatus == STATUS_SUCCESS)
break;
KdPrint(("floppy: RWDetermineMediaType(): ReadId failed\n"));
return STATUS_UNSUCCESSFUL; /* if we can't even write to the controller, it's hopeless */
}
-
+
/* Wait for the ReadID to finish */
WaitForControllerInterrupt(DriveInfo->ControllerInfo);
AbsoluteSector = DiskByteOffset / DriveInfo->DiskGeometry.BytesPerSector; /* Num full sectors */
/* Cylinder number is floor(AbsoluteSector / SectorsPerCylinder) */
- *Cylinder = (CHAR)(AbsoluteSector / SectorsPerCylinder);
+ *Cylinder = (CHAR)(AbsoluteSector / SectorsPerCylinder);
/* Head number is 0 if the sector within the cylinder < SectorsPerTrack; 1 otherwise */
*Head = AbsoluteSector % SectorsPerCylinder < DriveInfo->DiskGeometry.SectorsPerTrack ? 0 : 1;
- /*
- * Sector number is the sector within the cylinder if on head 0; that minus SectorsPerTrack if it's on head 1
+ /*
+ * Sector number is the sector within the cylinder if on head 0; that minus SectorsPerTrack if it's on head 1
* (lots of casts to placate msvc). 1-based!
*/
*Sector = ((UCHAR)(AbsoluteSector % SectorsPerCylinder) + 1) - ((*Head) * (UCHAR)DriveInfo->DiskGeometry.SectorsPerTrack);
KdPrint(("floppy: ReadWritePassive called to %s 0x%x bytes from offset 0x%x\n",
(Stack->MajorFunction == IRP_MJ_READ ? "read" : "write"),
(Stack->MajorFunction == IRP_MJ_READ ? Stack->Parameters.Read.Length : Stack->Parameters.Write.Length),
- (Stack->MajorFunction == IRP_MJ_READ ? Stack->Parameters.Read.ByteOffset.u.LowPart :
+ (Stack->MajorFunction == IRP_MJ_READ ? Stack->Parameters.Read.ByteOffset.u.LowPart :
Stack->Parameters.Write.ByteOffset.u.LowPart)));
/* Default return codes */
Irp->IoStatus.Status = STATUS_UNSUCCESSFUL;
Irp->IoStatus.Information = 0;
- /*
+ /*
* Check to see if the volume needs to be verified. If so,
* we can get out of here quickly.
*/
- if(DeviceObject->Flags & DO_VERIFY_VOLUME && !(DeviceObject->Flags & SL_OVERRIDE_VERIFY_VOLUME))
+ if(DeviceObject->Flags & DO_VERIFY_VOLUME && !(DeviceObject->Flags & SL_OVERRIDE_VERIFY_VOLUME))
{
KdPrint(("floppy: ReadWritePassive(): DO_VERIFY_VOLUME set; Completing with STATUS_VERIFY_REQUIRED\n"));
Irp->IoStatus.Status = STATUS_VERIFY_REQUIRED;
StopMotor(DriveInfo->ControllerInfo);
return;
}
-
+
if(DiskChanged)
{
KdPrint(("floppy: ReadWritePhase1(): signalling media changed; Completing with STATUS_MEDIA_CHANGED\n"));
return;
}
- /*
- * Figure out the media type, if we don't know it already
- */
+ /*
+ * Figure out the media type, if we don't know it already
+ */
if(DriveInfo->DiskGeometry.MediaType == Unknown)
{
if(RWDetermineMediaType(DriveInfo) != STATUS_SUCCESS)
WriteToDevice = TRUE;
}
- /*
+ /*
* FIXME:
- * FloppyDeviceData.ReadWriteGapLength specify the value for the physical drive.
+ * FloppyDeviceData.ReadWriteGapLength specify the value for the physical drive.
* We should set this value depend on the format of the inserted disk and possible
* depend on the request (read or write). A value of 0 results in one rotation
* between the sectors (7.2sec for reading a track).
*/
Gap = DriveInfo->FloppyDeviceData.ReadWriteGapLength;
- /*
- * Set up DMA transfer
+ /*
+ * Set up DMA transfer
*
* This is as good of a place as any to document something that used to confuse me
* greatly (and I even wrote some of the kernel's DMA code, so if it confuses me, it
- * probably confuses at least a couple of other people too).
+ * probably confuses at least a couple of other people too).
*
* MmGetMdlVirtualAddress() returns the virtal address, as mapped in the buffer's original
* process context, of the MDL. In other words: say you start with a buffer at address X, then
* you build an MDL out of that buffer called Mdl. If you call MmGetMdlVirtualAddress(Mdl), it
- * will return X.
+ * will return X.
*
* There are two parameters that the function looks at to produce X again, given the MDL: the
* first is the StartVa, which is the base virtual address of the page that the buffer starts
* above 0x80000000 (default; 0xc0000000 on current ReactOS or /3GB Windows)), but it will
* (possibly) be mapped at a different address.
*
- * The second parameter is the ByteOffset. Given an original buffer address of 0x12345678,
+ * The second parameter is the ByteOffset. Given an original buffer address of 0x12345678,
* the ByteOffset would be 0x678. Because MDLs can only describe full pages (and therefore
* StartVa always points to the start address of a page), the ByteOffset must be used to
* find the real start of the buffer.
* There is a somewhat weird but very common use of the virtual address associated with a MDL
* that pops up often in the context of DMA. DMA APIs (particularly MapTransfer()) need to
* know where the memory is that they should DMA into and out of. This memory is described
- * by a MDL. The controller eventually needs to know a physical address on the host side,
+ * by a MDL. The controller eventually needs to know a physical address on the host side,
* which is generally a 32-bit linear address (on x86), and not just a page address. Therefore,
* the DMA APIs look at the ByteOffset field of the MDL to reconstruct the real address that
* should be programmed into the DMA controller.
* the MDL. The way it computes how far into the page to start the transfer is by masking off all but
* the bottom 12 bits (on x86) of the number you supply as the CurrentVa and using *that* as the
* ByteOffset instead of the one in the MDL. (OK, this varies a bit by OS and version, but this
- * is the effect).
+ * is the effect).
*
- * In other words, you get a number back from MmGetMdlVirtualAddress that represents the start of your
+ * In other words, you get a number back from MmGetMdlVirtualAddress that represents the start of your
* buffer, and you pass it to the first MapTransfer call. Then, for each successive operation
* on the same buffer, you increment that address to point to the next spot in the MDL that
* you want to DMA to/from. The fact that the virtual address you're manipulating is probably not
* mapped into the process context that you're running in is irrelevant, since it's only being
* used to index into the MDL.
- */
+ */
/* Get map registers for DMA */
KeRaiseIrql(DISPATCH_LEVEL, &OldIrql);
ULONG CurrentTransferBytes;
UCHAR CurrentTransferSectors;
- KdPrint(("floppy: ReadWritePassive(): iterating in while (TransferByteOffset = 0x%x of 0x%x total) - allocating %d registers\n",
+ KdPrint(("floppy: ReadWritePassive(): iterating in while (TransferByteOffset = 0x%x of 0x%x total) - allocating %d registers\n",
TransferByteOffset, Length, DriveInfo->ControllerInfo->MapRegisters));
-
- KeClearEvent(&DriveInfo->ControllerInfo->SynchEvent);
+
+ KeClearEvent(&DriveInfo->ControllerInfo->SynchEvent);
/*
* Compute starting CHS
KdPrint(("floppy: ReadWritePassive(): computing number of sectors to transfer (StartSector 0x%x): ", StartSector));
/* 1-based sector number */
- if( (((DriveInfo->DiskGeometry.TracksPerCylinder - Head) * DriveInfo->DiskGeometry.SectorsPerTrack - StartSector) + 1 ) <
+ if( (((DriveInfo->DiskGeometry.TracksPerCylinder - Head) * DriveInfo->DiskGeometry.SectorsPerTrack - StartSector) + 1 ) <
(Length - TransferByteOffset) / DriveInfo->DiskGeometry.BytesPerSector)
{
CurrentTransferSectors = (UCHAR)((DriveInfo->DiskGeometry.TracksPerCylinder - Head) * DriveInfo->DiskGeometry.SectorsPerTrack - StartSector) + 1;
if(BYTES_TO_PAGES(CurrentTransferBytes) > DriveInfo->ControllerInfo->MapRegisters)
{
- CurrentTransferSectors = (UCHAR)((DriveInfo->ControllerInfo->MapRegisters * PAGE_SIZE) /
+ CurrentTransferSectors = (UCHAR)((DriveInfo->ControllerInfo->MapRegisters * PAGE_SIZE) /
DriveInfo->DiskGeometry.BytesPerSector);
CurrentTransferBytes = CurrentTransferSectors * DriveInfo->DiskGeometry.BytesPerSector;
/* param 2 is ReadOperation --> opposite of WriteToDevice that IoMapTransfer takes. BAD MS. */
KeFlushIoBuffers(Irp->MdlAddress, !WriteToDevice, TRUE);
- IoMapTransfer(DriveInfo->ControllerInfo->AdapterObject, Irp->MdlAddress,
- DriveInfo->ControllerInfo->MapRegisterBase,
- (PUCHAR)((ULONG_PTR)MmGetMdlVirtualAddress(Irp->MdlAddress) + TransferByteOffset),
+ IoMapTransfer(DriveInfo->ControllerInfo->AdapterObject, Irp->MdlAddress,
+ DriveInfo->ControllerInfo->MapRegisterBase,
+ (PUCHAR)((ULONG_PTR)MmGetMdlVirtualAddress(Irp->MdlAddress) + TransferByteOffset),
&CurrentTransferBytes, WriteToDevice);
/*
* Read or Write
*/
- KeClearEvent(&DriveInfo->ControllerInfo->SynchEvent);
+ KeClearEvent(&DriveInfo->ControllerInfo->SynchEvent);
- /* Issue the read/write command to the controller. Note that it expects the opposite of WriteToDevice. */
- if(HwReadWriteData(DriveInfo->ControllerInfo, !WriteToDevice, DriveInfo->UnitNumber, Cylinder, Head, StartSector,
+ /* Issue the read/write command to the controller. Note that it expects the opposite of WriteToDevice. */
+ if(HwReadWriteData(DriveInfo->ControllerInfo, !WriteToDevice, DriveInfo->UnitNumber, Cylinder, Head, StartSector,
DriveInfo->BytesPerSectorCode, DriveInfo->DiskGeometry.SectorsPerTrack, Gap, 0xff) != STATUS_SUCCESS)
{
KdPrint(("floppy: ReadWritePassive(): HwReadWriteData returned failure; unable to read; completing with STATUS_UNSUCCESSFUL\n"));
KdPrint(("floppy: ReadWritePassive(): HwReadWriteData returned -- waiting on event\n"));
- /*
+ /*
* At this point, we block and wait for an interrupt
* FIXME: this seems to take too long
*/
WaitForControllerInterrupt(DriveInfo->ControllerInfo);
/* Read is complete; flush & free adapter channel */
- IoFlushAdapterBuffers(DriveInfo->ControllerInfo->AdapterObject, Irp->MdlAddress,
- DriveInfo->ControllerInfo->MapRegisterBase,
+ IoFlushAdapterBuffers(DriveInfo->ControllerInfo->AdapterObject, Irp->MdlAddress,
+ DriveInfo->ControllerInfo->MapRegisterBase,
(PVOID)((ULONG_PTR)MmGetMdlVirtualAddress(Irp->MdlAddress) + TransferByteOffset),
CurrentTransferBytes, WriteToDevice);
static ULONG InternalDebugLevel = 0;
static VOID
-SpiProcessRequests(IN PSCSI_PORT_DEVICE_EXTENSION DeviceExtension,
+SpiProcessRequests(IN PSCSI_PORT_DEVICE_EXTENSION DeviceExtension,
PIRP NextIrp);
-static VOID
+static VOID
SpiStartIo(PSCSI_PORT_DEVICE_EXTENSION DeviceExtension,
PIRP Irp);
- if (PathId == (UCHAR)SP_UNTAGGED ||
+ if (PathId == (UCHAR)SP_UNTAGGED ||
(PathId == LunExtension->PathId && TargetId == (UCHAR)SP_UNTAGGED) ||
(PathId == LunExtension->PathId && TargetId == LunExtension->TargetId && Lun == (UCHAR)SP_UNTAGGED) ||
(PathId == LunExtension->PathId && TargetId == LunExtension->TargetId && Lun == LunExtension->Lun))
else
{
/*
- * The given virtual address is not within the range
+ * The given virtual address is not within the range
* of the drivers uncached extension or srb extension.
*/
/*
- * FIXME:
+ * FIXME:
* Check if the address is a sense info buffer of an active srb.
*/
PhysicalAddress = MmGetPhysicalAddress(VirtualAddress);
DeviceExtensionSize = sizeof(SCSI_PORT_DEVICE_EXTENSION) +
HwInitializationData->DeviceExtensionSize;
- PortConfigSize = sizeof(PORT_CONFIGURATION_INFORMATION) +
+ PortConfigSize = sizeof(PORT_CONFIGURATION_INFORMATION) +
HwInitializationData->NumberOfAccessRanges * sizeof(ACCESS_RANGE);
PortConfig,
0);
}
-
+
/* Register an interrupt handler for this device */
MappedIrq = HalGetInterruptVector(PortConfig->AdapterInterfaceType,
PortConfig->SystemIoBusNumber,
PortConfig->BusInterruptLevel,
#if 1
-/*
+/*
* FIXME:
- * Something is wrong in our interrupt conecting code.
+ * Something is wrong in our interrupt conecting code.
* The promise Ultra100TX driver returns 0 for BusInterruptVector
- * and a nonzero value for BusInterruptLevel. The driver does only
+ * and a nonzero value for BusInterruptLevel. The driver does only
* work with this fix.
*/
PortConfig->BusInterruptLevel,
&Dirql,
&Affinity);
DPRINT("AdapterInterfaceType %x, SystemIoBusNumber %x, BusInterruptLevel %x, BusInterruptVector %x\n",
- PortConfig->AdapterInterfaceType, PortConfig->SystemIoBusNumber,
- PortConfig->BusInterruptLevel, PortConfig->BusInterruptVector);
+ PortConfig->AdapterInterfaceType, PortConfig->SystemIoBusNumber,
+ PortConfig->BusInterruptLevel, PortConfig->BusInterruptVector);
Status = IoConnectInterrupt(&DeviceExtension->Interrupt,
ScsiPortIsr,
DeviceExtension,
PortCapabilities->MaximumTransferLength =
PortConfig->NumberOfPhysicalBreaks * PAGE_SIZE;
}
-
+
PortCapabilities->MaximumPhysicalPages =
PortCapabilities->MaximumTransferLength / PAGE_SIZE;
PortCapabilities->SupportedAsynchronousEvents = 0; /* FIXME */
DPRINT(" IOCTL_SCSI_GET_DUMP_POINTERS\n");
DumpPointers = (PDUMP_POINTERS)Irp->AssociatedIrp.SystemBuffer;
DumpPointers->DeviceObject = DeviceObject;
-
+
Irp->IoStatus.Information = sizeof(DUMP_POINTERS);
}
break;
return(STATUS_SUCCESS);
}
-static VOID
+static VOID
SpiAllocateSrbExtension(PSCSI_PORT_DEVICE_EXTENSION DeviceExtension,
PSCSI_REQUEST_BLOCK Srb)
{
DPRINT("SpiAllocateSrbExtension\n");
- DPRINT("DeviceExtension->VirtualAddress %x, DeviceExtension->SrbExtensionSize %x\n",
+ DPRINT("DeviceExtension->VirtualAddress %x, DeviceExtension->SrbExtensionSize %x\n",
DeviceExtension->VirtualAddress, DeviceExtension->SrbExtensionSize);
Srb->SrbExtension = NULL;
if (DeviceExtension->VirtualAddress != NULL &&
DeviceExtension->SrbExtensionSize > 0)
{
- index = RtlFindClearBitsAndSet(&DeviceExtension->SrbExtensionAllocMap, 1, 0);
+ index = RtlFindClearBitsAndSet(&DeviceExtension->SrbExtensionAllocMap, 1, 0);
if (index != 0xffffffff)
{
- DeviceExtension->CurrentSrbExtensions++;
+ DeviceExtension->CurrentSrbExtensions++;
Srb->SrbExtension = DeviceExtension->VirtualAddress + index * DeviceExtension->SrbExtensionSize;
}
}
PIO_STACK_LOCATION IrpStack;
DPRINT("ScsiPortStartPacket(Context %x) called\n", Context);
-
+
Srb = (PSCSI_REQUEST_BLOCK)Context;
Irp = (PIRP)Srb->OriginalRequest;
IrpStack = IoGetCurrentIrpStackLocation(Irp);
ULONG ActiveCount;
PVOID* EventArray;
PKWAIT_BLOCK WaitBlockArray;
-
+
DPRINT ("SpiScanAdapter() called\n");
- MaxCount = DeviceExtension->PortConfig->NumberOfBuses *
+ MaxCount = DeviceExtension->PortConfig->NumberOfBuses *
DeviceExtension->PortConfig->MaximumNumberOfTargets;
ScanDataArray = ExAllocatePool(NonPagedPool, MaxCount * (sizeof(SCSI_PORT_SCAN_ADAPTER) + sizeof(PVOID) + sizeof(KWAIT_BLOCK)));
DPRINT ("DeviceTypeQualifier %x\n", ((PINQUIRYDATA)Srb->DataBuffer)->DeviceTypeQualifier);
if (NT_SUCCESS(ScanData->Status) &&
- (Srb->SrbStatus == SRB_STATUS_SUCCESS ||
- (Srb->SrbStatus == SRB_STATUS_DATA_OVERRUN &&
+ (Srb->SrbStatus == SRB_STATUS_SUCCESS ||
+ (Srb->SrbStatus == SRB_STATUS_DATA_OVERRUN &&
/*
- * FIXME:
- * The NT 4.0 driver from an inic950 based scsi controller
- * returns only 4 byte of inquiry data, but the device name
- * is visible on NT 4.0. We must implement an other way
- * to get the complete inquiry data.
+ * FIXME:
+ * The NT 4.0 driver from an inic950 based scsi controller
+ * returns only 4 byte of inquiry data, but the device name
+ * is visible on NT 4.0. We must implement an other way
+ * to get the complete inquiry data.
*/
Srb->DataTransferLength >= /*INQUIRYDATABUFFERSIZE*/4)) &&
((PINQUIRYDATA)Srb->DataBuffer)->DeviceTypeQualifier == 0)
NULL,
WaitBlockArray);
}
- }
+ }
while (ActiveCount > 0);
ExFreePool(ScanDataArray);
-
+
DPRINT ("SpiScanAdapter() done\n");
}
UnitInfo = (PSCSI_INQUIRY_DATA)
((PUCHAR)AdapterBusInfo + sizeof(SCSI_ADAPTER_BUS_INFO) +
(sizeof(SCSI_BUS_DATA) * (AdapterBusInfo->NumberOfBuses - 1)));
-
+
for (Bus = 0; Bus < AdapterBusInfo->NumberOfBuses; Bus++)
{
AdapterBusInfo->BusData[Bus].InitiatorBusId =
PCDB Cdb;
Length = sizeof(SCSI_REQUEST_BLOCK) + sizeof(SENSE_DATA) + 32;
- Srb = ExAllocatePoolWithTag(NonPagedPool,
+ Srb = ExAllocatePoolWithTag(NonPagedPool,
Length,
TAG('S', 'S', 'r', 'b'));
if (Srb == NULL)
Srb->TimeOutValue = 4;
Srb->CdbLength = 6;
- /* The DataBuffer must be located in contiguous physical memory if
- * the miniport driver uses dma for the sense info. The size of
- * the sense data is 18 byte. If the buffer starts at a 32 byte
- * boundary than is the buffer always in one memory page.
+ /* The DataBuffer must be located in contiguous physical memory if
+ * the miniport driver uses dma for the sense info. The size of
+ * the sense data is 18 byte. If the buffer starts at a 32 byte
+ * boundary than is the buffer always in one memory page.
*/
Srb->DataBuffer = (PVOID)ROUND_UP((ULONG_PTR)(Srb + 1), 32);
Srb->DataTransferLength = sizeof(SENSE_DATA);
return Status;
}
-static VOID
-SpiRemoveActiveIrp(PSCSI_PORT_DEVICE_EXTENSION DeviceExtension,
+static VOID
+SpiRemoveActiveIrp(PSCSI_PORT_DEVICE_EXTENSION DeviceExtension,
PIRP Irp,
PIRP PrevIrp)
{
InterlockedDecrement((PLONG)&DeviceExtension->ActiveIrpCount);
if (PrevIrp)
{
- InterlockedExchangePointer(&PrevIrp->Tail.Overlay.DriverContext[0],
+ InterlockedExchangePointer(&PrevIrp->Tail.Overlay.DriverContext[0],
Irp->Tail.Overlay.DriverContext[0]);
}
else
}
static VOID
-SpiProcessRequests(IN PSCSI_PORT_DEVICE_EXTENSION DeviceExtension,
+SpiProcessRequests(IN PSCSI_PORT_DEVICE_EXTENSION DeviceExtension,
IN PIRP NextIrp)
{
/*
* Irp->Tail.Overlay.DriverContext[2] -> sort key (from Srb->QueueSortKey)
* Irp->Tail.Overlay.DriverContext[3] -> current Srb (original or sense request)
* IoStack->Parameters.Scsi.Srb -> original Srb
- *
+ *
* Irp is within the active irp list or while other processing:
* Srb->OriginalRequest -> Irp
* Irp->Tail.Overlay.DriverContext[0] -> next irp, DeviceExtension->NextIrp is head.
if (NextIrp)
{
Srb = NextIrp->Tail.Overlay.DriverContext[3];
- /*
+ /*
* FIXME:
* Is this the right place to set this flag ?
*/
}
while (DeviceExtension->Flags & IRP_FLAG_COMPLETE ||
- (((DeviceExtension->SrbExtensionSize == 0 || DeviceExtension->CurrentSrbExtensions < DeviceExtension->MaxSrbExtensions) &&
+ (((DeviceExtension->SrbExtensionSize == 0 || DeviceExtension->CurrentSrbExtensions < DeviceExtension->MaxSrbExtensions) &&
DeviceExtension->PendingIrpCount > 0 &&
(DeviceExtension->Flags & (IRP_FLAG_NEXT|IRP_FLAG_NEXT_LU) || DeviceExtension->NextIrp == NULL))))
{
- DPRINT ("RequestComplete %d, NextRequest %d, NextLuRequest %d, PendingIrpCount %d, ActiveIrpCount %d\n",
- DeviceExtension->Flags & IRP_FLAG_COMPLETE ? 1 : 0,
+ DPRINT ("RequestComplete %d, NextRequest %d, NextLuRequest %d, PendingIrpCount %d, ActiveIrpCount %d\n",
+ DeviceExtension->Flags & IRP_FLAG_COMPLETE ? 1 : 0,
DeviceExtension->Flags & IRP_FLAG_NEXT ? 1 : 0,
- DeviceExtension->Flags & IRP_FLAG_NEXT_LU ? 1 : 0,
- DeviceExtension->PendingIrpCount,
+ DeviceExtension->Flags & IRP_FLAG_NEXT_LU ? 1 : 0,
+ DeviceExtension->PendingIrpCount,
DeviceExtension->ActiveIrpCount);
DPRINT("ErrorCode: %x\n", SenseInfoBuffer->ErrorCode);
DPRINT("SenseKey: %x\n", SenseInfoBuffer->SenseKey);
DPRINT("SenseCode: %x\n", SenseInfoBuffer->AdditionalSenseCode);
-
+
/* Copy sense data */
RtlCopyMemory(OriginalSrb->SenseInfoBuffer,
SenseInfoBuffer,
}
Irp = NextIrp;
continue;
- }
+ }
PrevIrp = Irp;
Irp = NextIrp;
}
KeAcquireSpinLockAtDpcLevel(&DeviceExtension->Lock);
}
if (DeviceExtension->Flags & (IRP_FLAG_NEXT|IRP_FLAG_NEXT_LU) &&
- (DeviceExtension->SrbExtensionSize == 0 || DeviceExtension->CurrentSrbExtensions < DeviceExtension->MaxSrbExtensions))
+ (DeviceExtension->SrbExtensionSize == 0 || DeviceExtension->CurrentSrbExtensions < DeviceExtension->MaxSrbExtensions))
{
BOOLEAN StartThisRequest;
ListEntry = DeviceExtension->PendingIrpListHead.Flink;
LunExtension->Flags &= ~IRP_FLAG_NEXT_LU;
DeviceExtension->Flags &= ~IRP_FLAG_NEXT_LU;
}
- else if (DeviceExtension->Flags & IRP_FLAG_NEXT &&
+ else if (DeviceExtension->Flags & IRP_FLAG_NEXT &&
LunExtension->ActiveIrpCount == 0)
{
StartThisRequest = TRUE;
Srb->OriginalRequest = Irp;
SpiAllocateSrbExtension(DeviceExtension, Srb);
- InsertHeadList(&NextIrpListHead, (PLIST_ENTRY)&Irp->Tail.Overlay.DriverContext[0]);
+ InsertHeadList(&NextIrpListHead, (PLIST_ENTRY)&Irp->Tail.Overlay.DriverContext[0]);
}
}
}
DPRINT1("Synchronization failed!\n");
DPRINT1("Irp %x, Srb->Function %02x, Srb->Cdb[0] %02x, Srb->SrbStatus %02x\n", Irp, Srb->Function, Srb->Cdb[0], Srb->SrbStatus);
ScsiPortNotification(RequestComplete,
- &DeviceExtension->MiniPortDeviceExtension,
+ &DeviceExtension->MiniPortDeviceExtension,
Srb);
}
/* Device object */
PDEVICE_OBJECT DeviceObject;
-/*
- * CSQ Callbacks
+/*
+ * CSQ Callbacks
*/
VOID NTAPI CsqInsertIrp(PIO_CSQ Csq, PIRP Irp)
{
}
NTSTATUS NTAPI DispatchIoctl(PDEVICE_OBJECT DeviceObject, PIRP Irp)
-/*
- * all IOCTL requests flush the irp queue
- */
+/*
+ * all IOCTL requests flush the irp queue
+ */
{
PIRP CurrentIrp;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchIoctl;
DriverObject->DriverUnload = Unload;
- Status = IoCsqInitialize(&Csq, CsqInsertIrp, CsqRemoveIrp, CsqPeekNextIrp,
+ Status = IoCsqInitialize(&Csq, CsqInsertIrp, CsqRemoveIrp, CsqPeekNextIrp,
CsqAcquireLock, CsqReleaseLock, CsqCompleteCancelledIrp);
if(Status != STATUS_SUCCESS)
KdPrint(("csqtest: Unable to create link: 0x%x\n", Status));
return Status;
}
-
+
DeviceObject->Flags |= DO_BUFFERED_IO;
return STATUS_SUCCESS;
unsigned long flags;
spin_lock_irqsave(&uhci->frame_list_lock, flags);
- uhci->term_td->status |= cpu_to_le32(TD_CTRL_IOC);
+ uhci->term_td->status |= cpu_to_le32(TD_CTRL_IOC);
spin_unlock_irqrestore(&uhci->frame_list_lock, flags);
}
urbp->fsbrtime = jiffies;
urbp->urb = urb;
urbp->dev = urb->dev;
-
+
INIT_LIST_HEAD(&urbp->td_list);
INIT_LIST_HEAD(&urbp->queue_list);
INIT_LIST_HEAD(&urbp->complete_list);
/* Alternate Data0/1 (start with Data1) */
destination ^= TD_TOKEN_TOGGLE;
-
+
uhci_add_td_to_urb(urb, td);
uhci_fill_td(td, status, destination | uhci_explen(pktsze - 1),
data);
}
/*
- * Build the final TD for control status
+ * Build the final TD for control status
*/
td = uhci_alloc_td(uhci, urb->dev);
if (!td)
uhci_packetout(td_token(td)));
err:
- /*
+ /*
* Enable this chunk of code if you want to see some more debugging.
* But be careful, it has the tendancy to starve out khubd and prevent
* disconnects from happening successfully if you have a slow debug
irq++;
if (i & 2) {
irq++;
- if (i & 4) {
+ if (i & 4) {
irq++;
- if (i & 8) {
+ if (i & 8) {
irq++;
if (i & 16) {
irq++;
.resume = usb_hcd_pci_resume,
#endif /* PM */
};
-
+
int __init uhci_hcd_init(void)
{
int retval = -ENOMEM;
return retval;
}
-void __exit uhci_hcd_cleanup(void)
+void __exit uhci_hcd_cleanup(void)
{
pci_unregister_driver(&uhci_pci_driver);
-
+
if (kmem_cache_destroy(uhci_up_cachep))
printk(KERN_INFO "uhci: not all urb_priv's were freed\n");
*
* #1 uhci->urb_list_lock
* #2 urb->lock
- * #3 uhci->urb_remove_list_lock, uhci->frame_list_lock,
+ * #3 uhci->urb_remove_list_lock, uhci->frame_list_lock,
* uhci->qh_remove_list_lock
* #4 uhci->complete_list_lock
*
* If you're going to grab 2 or more locks at once, ALWAYS grab the lock
* at the lowest level FIRST and NEVER grab locks at the same level at the
* same time.
- *
+ *
* So, if you need uhci->urb_list_lock, grab it before you grab urb->lock
*/
ppdev->RedMask, ppdev->GreenMask, ppdev->BlueMask);
}
else
- {
+ {
ppdev->PaletteEntries = EngAllocMem(0, sizeof(PALETTEENTRY) << 8, ALLOC_TAG);
if (ppdev->PaletteEntries == NULL)
{
pClut->FirstEntry = iStart;
pClut->NumEntries = cColors;
memcpy(&pClut->LookupTable[0].RgbLong, ppalent, sizeof(ULONG) * cColors);
-
+
if (((PPDEV)dhpdev)->PaletteShift)
{
while (cColors--)
pClut->LookupTable[cColors].RgbArray.Unused = 0;
}
}
-
+
/*
* Set the palette registers.
*/
/*
* Copy the pixels under the cursor to temporary surface.
*/
-
+
if (ppdev->PointerSaveSurface != NULL)
{
RECTL DestRect;
{
PPDEV ppdev = (PPDEV)pso->dhpdev;
SURFOBJ *TempSurfObj;
-
+
IntHideMousePointer(ppdev, pso);
if (ppdev->PointerColorSurface != NULL)
{
case BMF_8BPP: lDelta = Size.cx; break;
case BMF_16BPP: lDelta = Size.cx << 1; break;
- case BMF_24BPP: lDelta = Size.cx * 3; break;
+ case BMF_24BPP: lDelta = Size.cx * 3; break;
case BMF_32BPP: lDelta = Size.cx << 2; break;
}
{
ModeInfoPtr->Length = 0;
}
-
+
ModeInfoPtr = (PVIDEO_MODE_INFORMATION)
(((PUCHAR)ModeInfoPtr) + Modes.ModeInformationLength);
}
/*
* Call miniport to get information about video modes.
*/
-
+
ModeCount = GetAvailableModes(ppdev->hDriver, &ModeInfo, &ModeInfoSize);
if (ModeCount == 0)
{
}
/*
- * Select the video mode depending on the info passed in pDevMode.
+ * Select the video mode depending on the info passed in pDevMode.
*/
if (pDevMode->dmPelsWidth == 0 && pDevMode->dmPelsHeight == 0 &&
EngFreeMem(ModeInfo);
return FALSE;
}
-
+
/*
* Fill in the GDIINFO data structure with the information returned from
* the kernel driver.
{
return 0;
}
-
+
if (pdm == NULL)
{
EngFreeMem(ModeInfo);
memset(pdm, 0, sizeof(DEVMODEW));
memcpy(pdm->dmDeviceName, DEVICE_NAME, sizeof(DEVICE_NAME));
- pdm->dmSpecVersion =
+ pdm->dmSpecVersion =
pdm->dmDriverVersion = DM_SPECVERSION;
pdm->dmSize = sizeof(DEVMODEW);
pdm->dmDriverExtra = 0;
return;
}
-// ----------------------------------------------- Driver Implementation
+// ----------------------------------------------- Driver Implementation
// DrvEnablePDEV
// information, and should not yet initialize the mode.
// ARGUMENTS:
// IN DEVMODEW * DM Describes the mode requested
-// IN LPWSTR LogAddress
+// IN LPWSTR LogAddress
// IN ULONG PatternCount number of patterns expected
// OUT HSURF * SurfPatterns array to contain pattern handles
// IN ULONG GDIInfoSize the size of the GDIInfo object passed in
return FALSE;
}
-BOOL
+BOOL
VGAtoDIB(SURFOBJ *Dest, SURFOBJ *Source, XLATEOBJ *ColorTranslation,
RECTL *DestRect, POINTL *SourcePoint)
{
LONG i, j, dx, dy;
BYTE *GDIpos, *initial;
-
+
// Used by the temporary DFB
DEVSURF DestDevSurf;
return FALSE;
}
-BOOL
+BOOL
DFBtoVGA(SURFOBJ *Dest, SURFOBJ *Source, XLATEOBJ *ColorTranslation,
RECTL *DestRect, POINTL *SourcePoint)
{
/* Punt pattern fills. */
if ((GET_OPINDEX_FROM_ROP4(Rop4) == GET_OPINDEX_FROM_ROP3(PATCOPY)
- || GET_OPINDEX_FROM_ROP4(Rop4) == GET_OPINDEX_FROM_ROP3(PATINVERT)) &&
+ || GET_OPINDEX_FROM_ROP4(Rop4) == GET_OPINDEX_FROM_ROP3(PATINVERT)) &&
Brush->iSolidColor == 0xFFFFFFFF)
{
return(FALSE);
/* Set up data rotate. */
WRITE_PORT_UCHAR((PUCHAR)GRA_I, 0x03);
WRITE_PORT_UCHAR((PUCHAR)GRA_D, RasterOp);
-
+
/* Fill any pixels on the left which don't fall into a full row of eight. */
if ((DestRect->left % 8) != 0)
{
return TRUE;
}
- }
+ }
/* Fill any whole rows of eight pixels. */
Left = (DestRect->left + 7) & ~0x7;
else if (SourceType == STYPE_DEVICE && Dest->iType == STYPE_DEVICE)
{
BltOperation = VGAtoVGA;
- }
+ }
else if (SourceType == STYPE_DEVBITMAP && Dest->iType == STYPE_DEVICE)
{
BltOperation = DFBtoVGA;
- }
+ }
else if (SourceType == STYPE_DEVICE && Dest->iType == STYPE_DEVBITMAP)
{
BltOperation = VGAtoDFB;
- }
+ }
else
{
/* Punt blts not involving a device or a device-bitmap. */
#include <debug.h>
BOOL STDCALL
-DrvCopyBits(OUT SURFOBJ* DestObj,
- IN SURFOBJ* SourceObj,
- IN CLIPOBJ* ClipObj,
- IN XLATEOBJ* XLateObj,
- IN RECTL* DestRectL,
+DrvCopyBits(OUT SURFOBJ* DestObj,
+ IN SURFOBJ* SourceObj,
+ IN CLIPOBJ* ClipObj,
+ IN XLATEOBJ* XLateObj,
+ IN RECTL* DestRectL,
IN POINTL* SrcPointL)
{
BOOL Done = FALSE;
ULONG CursorWidth = 32, CursorHeight = 32;
ULONG PointerAttributesSize;
ULONG SavedMemSize;
-
+
ppdev->xyHotSpot.x = 0;
ppdev->xyHotSpot.y = 0;
ULONG NewWidth, NewHeight;
PUCHAR Src, Dest;
ULONG i;
-
+
if (! psoMask)
{
return SPS_DECLINE;
{
LONG cx, cy;
RECTL Rect;
-
+
ppdev->pPointerAttributes->Enable = 0;
-
+
cx = ppdev->pPointerAttributes->Column - ppdev->xyHotSpot.x;
cy = ppdev->pPointerAttributes->Row - ppdev->xyHotSpot.y;
-
+
VGADDI_ComputePointerRect(ppdev, cx, cy, &Rect);
/* Display what was behind cursor */
PUCHAR AndMask, XorMask;
ULONG SizeX, SizeY;
RECTL Rect;
-
+
if(ppdev->pPointerAttributes->Enable)
{
return;
case BMF_24BPP:
return 3;
-
+
case BMF_32BPP:
return 4;
for (j = 0; j < 256; j++)
{
- PreCalcReverseByte[j] =
+ PreCalcReverseByte[j] =
(((j >> 0) & 0x1) << 7) |
(((j >> 1) & 0x1) << 6) |
(((j >> 2) & 0x1) << 5) |
{
ULONG plane;
ULONG left = x >> 3;
- ULONG shift = x - (x & ~0x7);
- UCHAR pixel, nextpixel;
+ ULONG shift = x - (x & ~0x7);
+ UCHAR pixel, nextpixel;
ULONG rightcount;
ULONG i, j;
ULONG stride = w >> 3;
-
+
/* Calculate the number of rightmost bytes not in a dword block. */
if (w >= 8)
{
for (plane = 0; plane < 4; plane++)
{
PUCHAR dest = b;
-
+
/* Select the plane we are reading in this iteration. */
WRITE_PORT_UCHAR((PUCHAR)GRA_I, 0x04);
WRITE_PORT_UCHAR((PUCHAR)GRA_D, plane);
-
+
for (j = 0; j < h; j++)
{
PULONG destline = (PULONG)dest;
/* Form the data for one plane for an aligned block in the destination. */
pixel = nextpixel;
pixel >>= shift;
-
+
nextpixel = PreCalcReverseByte[READ_REGISTER_UCHAR(src + 1)];
pixel |= (nextpixel << (8 - shift));
/* Form the data for a complete block. */
pixel = nextpixel;
pixel >>= shift;
-
+
nextpixel = PreCalcReverseByte[READ_REGISTER_UCHAR(src + 1)];
pixel |= (nextpixel << (8 - shift));
-
+
row = UnpackPixel[pixel] << plane;
/* Store the data for each pixel in the destination. */
InitData.HwGetPowerState = VBEGetPowerState;
InitData.HwSetPowerState = VBESetPowerState;
InitData.HwDeviceExtensionSize = sizeof(VBE_DEVICE_EXTENSION);
-
+
return VideoPortInitialize(Context1, Context2, &InitData, NULL);
}
VbeModeInfoA->BitsPerPixel,
VbeModeInfoB->XResolution, VbeModeInfoB->YResolution,
VbeModeInfoB->BitsPerPixel));
-
+
/*
* FIXME: Until some reasonable method for changing video modes will
* be available we favor more bits per pixel. It should be changed
{
INT10_BIOS_ARGUMENTS BiosRegisters;
VP_STATUS Status;
- PVBE_DEVICE_EXTENSION VBEDeviceExtension =
+ PVBE_DEVICE_EXTENSION VBEDeviceExtension =
(PVBE_DEVICE_EXTENSION)HwDeviceExtension;
ULONG Length;
ULONG ModeCount;
DPRINT(("Failed to get Int 10 service functions (Status %x)\n", Status));
return FALSE;
}
-
+
/*
* Allocate a bit of memory that will be later used for VBE transport
* buffer. This memory must be accessible from V86 mode so it must fit
/*
* Get the VBE general information.
*/
-
+
VBEDeviceExtension->Int10Interface.Int10WriteMemory(
VBEDeviceExtension->Int10Interface.Context,
VBEDeviceExtension->TrampolineMemorySegment,
VBEDeviceExtension->Int10Interface.Int10CallBios(
VBEDeviceExtension->Int10Interface.Context,
&BiosRegisters);
-
+
if (BiosRegisters.Eax == VBE_SUCCESS)
{
VBEDeviceExtension->Int10Interface.Int10ReadMemory(
/*
* Get the actual mode infos.
*/
-
+
for (CurrentMode = 0, SuitableModeCount = 0;
CurrentMode < ModeCount;
CurrentMode++)
DPRINT(("VBEMP: No video modes supported\n"));
return FALSE;
}
-
+
VBEDeviceExtension->ModeCount = SuitableModeCount;
/*
switch (RequestPacket->IoControlCode)
{
case IOCTL_VIDEO_SET_CURRENT_MODE:
- if (RequestPacket->InputBufferLength < sizeof(VIDEO_MODE))
+ if (RequestPacket->InputBufferLength < sizeof(VIDEO_MODE))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
case IOCTL_VIDEO_MAP_VIDEO_MEMORY:
if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MEMORY_INFORMATION) ||
- RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
+ RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
break;
case IOCTL_VIDEO_UNMAP_VIDEO_MEMORY:
- if (RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
+ if (RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
break;
case IOCTL_VIDEO_QUERY_NUM_AVAIL_MODES:
- if (RequestPacket->OutputBufferLength < sizeof(VIDEO_NUM_MODES))
+ if (RequestPacket->OutputBufferLength < sizeof(VIDEO_NUM_MODES))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
case IOCTL_VIDEO_QUERY_AVAIL_MODES:
if (RequestPacket->OutputBufferLength <
- ((PVBE_DEVICE_EXTENSION)HwDeviceExtension)->ModeCount * sizeof(VIDEO_MODE_INFORMATION))
+ ((PVBE_DEVICE_EXTENSION)HwDeviceExtension)->ModeCount * sizeof(VIDEO_MODE_INFORMATION))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
break;
case IOCTL_VIDEO_QUERY_CURRENT_MODE:
- if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MODE_INFORMATION))
+ if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MODE_INFORMATION))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
(PVIDEO_MODE_INFORMATION)RequestPacket->OutputBuffer,
RequestPacket->StatusBlock);
break;
-
+
default:
RequestPacket->StatusBlock->Status = STATUS_NOT_IMPLEMENTED;
return FALSE;
}
-
+
if (Result)
RequestPacket->StatusBlock->Status = STATUS_SUCCESS;
ULONG Rows)
{
INT10_BIOS_ARGUMENTS BiosRegisters;
- PVBE_DEVICE_EXTENSION VBEDeviceExtension =
+ PVBE_DEVICE_EXTENSION VBEDeviceExtension =
(PVBE_DEVICE_EXTENSION)DeviceExtension;
-
+
if (!VBEResetDevice(DeviceExtension, NULL))
return FALSE;
-
+
/* Change number of columns/rows */
VideoPortZeroMemory(&BiosRegisters, sizeof(BiosRegisters));
-
+
if (Columns == 80 && Rows == 25)
{
/* Default text size, don't change anything. */
VBEDeviceExtension->Int10Interface.Int10CallBios(
VBEDeviceExtension->Int10Interface.Context,
&BiosRegisters);
-
+
BiosRegisters.Eax = 0x1112;
}
else if (Columns == 80 && Rows == 50)
}
else
return FALSE;
-
+
VBEDeviceExtension->Int10Interface.Int10CallBios(
VBEDeviceExtension->Int10Interface.Context,
&BiosRegisters);
-
+
return TRUE;
}
PVIDEO_POWER_MANAGEMENT VideoPowerControl)
{
INT10_BIOS_ARGUMENTS BiosRegisters;
- PVBE_DEVICE_EXTENSION VBEDeviceExtension =
+ PVBE_DEVICE_EXTENSION VBEDeviceExtension =
(PVBE_DEVICE_EXTENSION)HwDeviceExtension;
if (HwId != DISPLAY_ADAPTER_HW_ID ||
VideoPortZeroMemory(&BiosRegisters, sizeof(BiosRegisters));
BiosRegisters.Eax = VBE_POWER_MANAGEMENT_EXTENSIONS;
- BiosRegisters.Ebx = 0;
+ BiosRegisters.Ebx = 0;
BiosRegisters.Edi = 0;
BiosRegisters.SegEs = 0;
VBEDeviceExtension->Int10Interface.Int10CallBios(
&BiosRegisters);
if (BiosRegisters.Eax == VBE_NOT_SUPPORTED)
- return ERROR_NOT_SUPPORTED;
+ return ERROR_NOT_SUPPORTED;
if (BiosRegisters.Eax != VBE_SUCCESS)
- return ERROR_INVALID_FUNCTION;
-
+ return ERROR_INVALID_FUNCTION;
+
/*
* Get current power state.
*/
PVIDEO_POWER_MANAGEMENT VideoPowerControl)
{
INT10_BIOS_ARGUMENTS BiosRegisters;
- PVBE_DEVICE_EXTENSION VBEDeviceExtension =
+ PVBE_DEVICE_EXTENSION VBEDeviceExtension =
(PVBE_DEVICE_EXTENSION)HwDeviceExtension;
if (HwId != DISPLAY_ADAPTER_HW_ID ||
&BiosRegisters);
if (BiosRegisters.Eax == VBE_NOT_SUPPORTED)
- return ERROR_NOT_SUPPORTED;
+ return ERROR_NOT_SUPPORTED;
if (BiosRegisters.Eax != VBE_SUCCESS)
- return ERROR_INVALID_FUNCTION;
+ return ERROR_INVALID_FUNCTION;
return VBE_SUCCESS;
}
* VBEResetDevice
*
* Resets the video hardware to the default mode, to which it was initialized
- * at system boot.
+ * at system boot.
*/
BOOL FASTCALL
* VBEMapVideoMemory
*
* Maps the video hardware frame buffer and video RAM into the virtual address
- * space of the requestor.
+ * space of the requestor.
*/
BOOL FASTCALL
if (DeviceExtension->ModeInfo[DeviceExtension->CurrentMode].ModeAttributes &
VBE_MODEATTR_LINEAR)
- {
+ {
FrameBuffer.QuadPart =
DeviceExtension->ModeInfo[DeviceExtension->CurrentMode].PhysBasePtr;
MapInformation->VideoRamBase = RequestedAddress->RequestedVirtualAddress;
if (DeviceExtension->VbeInfo.Version < 0x300)
{
- MapInformation->VideoRamLength =
+ MapInformation->VideoRamLength =
DeviceExtension->ModeInfo[DeviceExtension->CurrentMode].BytesPerScanLine *
DeviceExtension->ModeInfo[DeviceExtension->CurrentMode].YResolution;
}
else
{
- MapInformation->VideoRamLength =
+ MapInformation->VideoRamLength =
DeviceExtension->ModeInfo[DeviceExtension->CurrentMode].LinBytesPerScanLine *
DeviceExtension->ModeInfo[DeviceExtension->CurrentMode].YResolution;
}
#ifdef VBE12_SUPPORT
else
{
- FrameBuffer.QuadPart = 0xA0000;
+ FrameBuffer.QuadPart = 0xA0000;
MapInformation->VideoRamBase = RequestedAddress->RequestedVirtualAddress;
MapInformation->VideoRamLength = 0x10000;
}
VideoPortUnmapMemory(DeviceExtension, VideoMemory->RequestedVirtualAddress,
NULL);
return TRUE;
-}
+}
/*
* VBEQueryNumAvailModes
* Returns information about one particular video mode.
*/
-VOID FASTCALL
+VOID FASTCALL
VBEQueryMode(
PVBE_DEVICE_EXTENSION DeviceExtension,
PVIDEO_MODE_INFORMATION VideoMode,
}
else
{
- VideoMode->NumberRedBits =
- VideoMode->NumberGreenBits =
+ VideoMode->NumberRedBits =
+ VideoMode->NumberGreenBits =
VideoMode->NumberBlueBits = 6;
- VideoMode->RedMask =
- VideoMode->GreenMask =
+ VideoMode->RedMask =
+ VideoMode->GreenMask =
VideoMode->BlueMask = 0;
}
VideoMode->VideoMemoryBitmapWidth = VBEMode->XResolution;
* Returns information about current video mode.
*/
-BOOL FASTCALL
+BOOL FASTCALL
VBEQueryCurrentMode(
PVBE_DEVICE_EXTENSION DeviceExtension,
PVIDEO_MODE_INFORMATION VideoModeInfo,
else
{
/*
- * We can't just copy the values, because we need to swap the Red
+ * We can't just copy the values, because we need to swap the Red
* and Blue values.
*/
#define VBE_SAVE_RESTORE_STATE 0x4F04
#define VBE_DISPLAY_WINDOW_CONTROL 0x4F05
#define VBE_SET_GET_LOGICAL_SCAN_LINE_LENGTH 0x4F06
-#define VBE_SET_GET_DISPLAY_START 0x4F07
+#define VBE_SET_GET_DISPLAY_START 0x4F07
#define VBE_SET_GET_DAC_PALETTE_FORMAT 0x4F08
#define VBE_SET_GET_PALETTE_DATA 0x4F09
/* VBE 2.0+ */
-#define VBE_RETURN_PROTECTED_MODE_INTERFACE 0x4F0A
+#define VBE_RETURN_PROTECTED_MODE_INTERFACE 0x4F0A
#define VBE_GET_SET_PIXEL_CLOCK 0x4F0B
/* Extensions */
#define VBE_POWER_MANAGEMENT_EXTENSIONS 0x4F10
#define VBE_FLAT_PANEL_INTERFACE_EXTENSIONS 0x4F11
-#define VBE_AUDIO_INTERFACE_EXTENSIONS 0x4F12
+#define VBE_AUDIO_INTERFACE_EXTENSIONS 0x4F12
#define VBE_OEM_EXTENSIONS 0x4F13
#define VBE_DISPLAY_DATA_CHANNEL 0x4F14
* VBE Return Codes
*/
-#define VBE_SUCCESS 0x4F
+#define VBE_SUCCESS 0x4F
#define VBE_UNSUCCESSFUL 0x14F
#define VBE_NOT_SUPPORTED 0x24F
#define VBE_FUNCTION_INVALID 0x34F
PVIDEO_MODE_INFORMATION ReturnedModes,
PSTATUS_BLOCK StatusBlock);
-BOOL FASTCALL
+BOOL FASTCALL
VBEQueryCurrentMode(
PVBE_DEVICE_EXTENSION DeviceExtension,
PVIDEO_MODE_INFORMATION VideoModeInfo,
vgaSetRegisters(&Mode12Regs);
}
-VOID
+VOID
VGAResetDevice(OUT PSTATUS_BLOCK StatusBlock)
{
vgaSetRegisters(&TextModeRegs);
/*
* VGA.C - a generic VGA miniport driver
- *
+ *
*/
// ------------------------------------------------------- Includes
VIDEO_HW_INITIALIZATION_DATA InitData;
VideoPortZeroMemory(&InitData, sizeof InitData);
-
+
InitData.HwInitDataSize = sizeof(InitData);
/* FIXME: Fill in InitData members */
InitData.StartingDeviceNumber = 0;
-
+
/* Export driver entry points... */
InitData.HwFindAdapter = VGAFindAdapter;
InitData.HwInitialize = VGAInitialize;
/* InitData.HwInterrupt = VGAInterrupt; */
InitData.HwResetHw = VGAResetHw;
/* InitData.HwTimer = VGATimer; */
-
+
return VideoPortInitialize(Context1, Context2, &InitData, NULL);
}
*Again = FALSE;
return STATUS_SUCCESS;
-
+
/* FIXME: Claim any necessary memory/IO resources for the adapter */
/* FIXME: Map resources into system memory for the adapter */
/* FIXME: Fill in relevant information in the VIDEO_PORT_CONFIG_INFO buffer */
// This function gets called in responce to GDI EngDeviceIoControl
// calls. Device requests are passed in VRPs.
// Required VRPs:
-// IOCTL_VIDEO_QUERY_NUM_AVAIL_MODES
-// IOCTL_VIDEO_QUERY_AVAIL_MODES
-// IOCTL_VIDEO_QUERY_CURRENT_MODE
-// IOCTL_VIDEO_SET_CURRENT_MODE
-// IOCTL_VIDEO_RESET_DEVICE
-// IOCTL_VIDEO_MAP_VIDEO_MEMORY
-// IOCTL_VIDEO_UNMAP_VIDEO_MEMORY
-// IOCTL_VIDEO_SHARE_VIDEO_MEMORY
-// IOCTL_VIDEO_UNSHARE_VIDEO_MEMORY
+// IOCTL_VIDEO_QUERY_NUM_AVAIL_MODES
+// IOCTL_VIDEO_QUERY_AVAIL_MODES
+// IOCTL_VIDEO_QUERY_CURRENT_MODE
+// IOCTL_VIDEO_SET_CURRENT_MODE
+// IOCTL_VIDEO_RESET_DEVICE
+// IOCTL_VIDEO_MAP_VIDEO_MEMORY
+// IOCTL_VIDEO_UNMAP_VIDEO_MEMORY
+// IOCTL_VIDEO_SHARE_VIDEO_MEMORY
+// IOCTL_VIDEO_UNSHARE_VIDEO_MEMORY
// Optional VRPs:
-// IOCTL_VIDEO_GET_PUBLIC_ACCESS_RANGES
-// IOCTL_VIDEO_FREE_PUBLIC_ACCESS_RANGES
-// IOCTL_VIDEO_GET_POWER_MANAGEMENT
-// IOCTL_VIDEO_SET_POWER_MANAGEMENT
-// IOCTL_QUERY_COLOR_CAPABILITIES
-// IOCTL_VIDEO_SET_COLOR_REGISTERS (required if the device has a palette)
-// IOCTL_VIDEO_DISABLE_POINTER
-// IOCTL_VIDEO_ENABLE_POINTER
-// IOCTL_VIDEO_QUERY_POINTER_CAPABILITIES
-// IOCTL_VIDEO_QUERY_POINTER_ATTR
-// IOCTL_VIDEO_SET_POINTER_ATTR
-// IOCTL_VIDEO_QUERY_POINTER_POSITION
-// IOCTL_VIDEO_SET_POINTER_POSITION
-// IOCTL_VIDEO_SAVE_HARDWARE_STATE
-// IOCTL_VIDEO_RESTORE_HARDWARE_STATE
-// IOCTL_VIDEO_DISABLE_CURSOR
-// IOCTL_VIDEO_ENABLE_CURSOR
-// IOCTL_VIDEO_QUERY_CURSOR_ATTR
-// IOCTL_VIDEO_SET_CURSOR_ATTR
-// IOCTL_VIDEO_QUERY_CURSOR_POSITION
-// IOCTL_VIDEO_SET_CURSOR_POSITION
-// IOCTL_VIDEO_GET_BANK_SELECT_CODE
-// IOCTL_VIDEO_SET_PALETTE_REGISTERS
-// IOCTL_VIDEO_LOAD_AND_SET_FONT
+// IOCTL_VIDEO_GET_PUBLIC_ACCESS_RANGES
+// IOCTL_VIDEO_FREE_PUBLIC_ACCESS_RANGES
+// IOCTL_VIDEO_GET_POWER_MANAGEMENT
+// IOCTL_VIDEO_SET_POWER_MANAGEMENT
+// IOCTL_QUERY_COLOR_CAPABILITIES
+// IOCTL_VIDEO_SET_COLOR_REGISTERS (required if the device has a palette)
+// IOCTL_VIDEO_DISABLE_POINTER
+// IOCTL_VIDEO_ENABLE_POINTER
+// IOCTL_VIDEO_QUERY_POINTER_CAPABILITIES
+// IOCTL_VIDEO_QUERY_POINTER_ATTR
+// IOCTL_VIDEO_SET_POINTER_ATTR
+// IOCTL_VIDEO_QUERY_POINTER_POSITION
+// IOCTL_VIDEO_SET_POINTER_POSITION
+// IOCTL_VIDEO_SAVE_HARDWARE_STATE
+// IOCTL_VIDEO_RESTORE_HARDWARE_STATE
+// IOCTL_VIDEO_DISABLE_CURSOR
+// IOCTL_VIDEO_ENABLE_CURSOR
+// IOCTL_VIDEO_QUERY_CURSOR_ATTR
+// IOCTL_VIDEO_SET_CURSOR_ATTR
+// IOCTL_VIDEO_QUERY_CURSOR_POSITION
+// IOCTL_VIDEO_SET_CURSOR_POSITION
+// IOCTL_VIDEO_GET_BANK_SELECT_CODE
+// IOCTL_VIDEO_SET_PALETTE_REGISTERS
+// IOCTL_VIDEO_LOAD_AND_SET_FONT
//
// RUN LEVEL:
// PASSIVE_LEVEL
PVIDEO_REQUEST_PACKET RequestPacket)
{
BOOL Result;
-
+
RequestPacket->StatusBlock->Status = STATUS_UNSUCCESSFUL;
-
+
switch (RequestPacket->IoControlCode)
{
case IOCTL_VIDEO_MAP_VIDEO_MEMORY:
if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MEMORY_INFORMATION) ||
- RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
+ RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
}
Result = VGAMapVideoMemory(DeviceExtension,
(PVIDEO_MEMORY) RequestPacket->InputBuffer,
- (PVIDEO_MEMORY_INFORMATION)
+ (PVIDEO_MEMORY_INFORMATION)
RequestPacket->OutputBuffer,
RequestPacket->StatusBlock);
break;
-
+
case IOCTL_VIDEO_QUERY_AVAIL_MODES:
- if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MODE_INFORMATION))
+ if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MODE_INFORMATION))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
Result = VGAQueryAvailModes((PVIDEO_MODE_INFORMATION) RequestPacket->OutputBuffer,
RequestPacket->StatusBlock);
break;
-
+
case IOCTL_VIDEO_QUERY_CURRENT_MODE:
- if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MODE_INFORMATION))
+ if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MODE_INFORMATION))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
Result = VGAQueryCurrentMode((PVIDEO_MODE_INFORMATION) RequestPacket->OutputBuffer,
RequestPacket->StatusBlock);
break;
-
+
case IOCTL_VIDEO_QUERY_NUM_AVAIL_MODES:
- if (RequestPacket->OutputBufferLength < sizeof(VIDEO_NUM_MODES))
+ if (RequestPacket->OutputBufferLength < sizeof(VIDEO_NUM_MODES))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
Result = VGAQueryNumAvailModes((PVIDEO_NUM_MODES) RequestPacket->OutputBuffer,
RequestPacket->StatusBlock);
break;
-
+
case IOCTL_VIDEO_RESET_DEVICE:
Result = VGAResetDevice(RequestPacket->StatusBlock);
break;
Result = VGASetColorRegisters((PVIDEO_CLUT) RequestPacket->InputBuffer,
RequestPacket->StatusBlock);
break;
-
+
case IOCTL_VIDEO_SET_CURRENT_MODE:
- if (RequestPacket->InputBufferLength < sizeof(VIDEO_MODE))
+ if (RequestPacket->InputBufferLength < sizeof(VIDEO_MODE))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
Result = VGASetCurrentMode((PVIDEO_MODE) RequestPacket->InputBuffer,
RequestPacket->StatusBlock);
break;
-
+
case IOCTL_VIDEO_SHARE_VIDEO_MEMORY:
if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MEMORY_INFORMATION) ||
- RequestPacket->InputBufferLength < sizeof(VIDEO_SHARE_MEMORY))
+ RequestPacket->InputBufferLength < sizeof(VIDEO_SHARE_MEMORY))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
(PVIDEO_MEMORY_INFORMATION) RequestPacket->OutputBuffer,
RequestPacket->StatusBlock);
break;
-
+
case IOCTL_VIDEO_UNMAP_VIDEO_MEMORY:
- if (RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
+ if (RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
(PVIDEO_MEMORY) RequestPacket->InputBuffer,
RequestPacket->StatusBlock);
break;
-
+
case IOCTL_VIDEO_UNSHARE_VIDEO_MEMORY:
- if (RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
+ if (RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
case IOCTL_VIDEO_SET_POINTER_POSITION:
case IOCTL_VIDEO_SET_POWER_MANAGEMENT:
-#endif
-
+#endif
+
default:
RequestPacket->StatusBlock->Status = STATUS_NOT_IMPLEMENTED;
return FALSE;
}
-
+
if (Result)
RequestPacket->StatusBlock->Status = STATUS_SUCCESS;
-
+
return TRUE;
}
CurrentMode->Frequency = 60;
CurrentMode->XMillimeter = 0; /* FIXME */
CurrentMode->YMillimeter = 0; /* FIXME */
- CurrentMode->NumberRedBits =
- CurrentMode->NumberGreenBits =
+ CurrentMode->NumberRedBits =
+ CurrentMode->NumberGreenBits =
CurrentMode->NumberBlueBits = 6;
- CurrentMode->RedMask =
- CurrentMode->GreenMask =
+ CurrentMode->RedMask =
+ CurrentMode->GreenMask =
CurrentMode->BlueMask = 0; /* FIXME */
CurrentMode->VideoMemoryBitmapWidth = 640;
CurrentMode->VideoMemoryBitmapHeight = 480;
CurrentMode->AttributeFlags = VIDEO_MODE_GRAPHICS | VIDEO_MODE_COLOR |
VIDEO_MODE_NO_OFF_SCREEN;
CurrentMode->DriverSpecificAttributeFlags = 0;
-
+
StatusBlock->Information = sizeof(VIDEO_MODE_INFORMATION);
return TRUE;
}
VideoPortWritePortUchar((PUCHAR)0x03c9, ColorLookUpTable->LookupTable[i].RgbArray.Green);
VideoPortWritePortUchar((PUCHAR)0x03c9, ColorLookUpTable->LookupTable[i].RgbArray.Blue);
}
-
+
return TRUE;
}
OUT PSTATUS_BLOCK StatusBlock)
{
UNIMPLEMENTED;
-
+
StatusBlock->Status = STATUS_NOT_IMPLEMENTED;
return FALSE;
}
OUT PSTATUS_BLOCK StatusBlock)
{
UNIMPLEMENTED;
-
+
StatusBlock->Status = STATUS_NOT_IMPLEMENTED;
return FALSE;
}
InitData.HwGetPowerState = XboxVmpGetPowerState;
InitData.HwSetPowerState = XboxVmpSetPowerState;
InitData.HwDeviceExtensionSize = sizeof(XBOXVMP_DEVICE_EXTENSION);
-
+
return VideoPortInitialize(Context1, Context2, &InitData, NULL);
}
XboxVmpDeviceExtension->ControlLength = AccessRanges[0].RangeLength;
XboxVmpDeviceExtension->PhysFrameBufferStart = AccessRanges[1].RangeStart;
}
-
+
return Status;
}
{
case IOCTL_VIDEO_SET_CURRENT_MODE:
DPRINT("XboxVmpStartIO IOCTL_VIDEO_SET_CURRENT_MODE\n");
- if (RequestPacket->InputBufferLength < sizeof(VIDEO_MODE))
+ if (RequestPacket->InputBufferLength < sizeof(VIDEO_MODE))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
case IOCTL_VIDEO_MAP_VIDEO_MEMORY:
DPRINT("XboxVmpStartIO IOCTL_VIDEO_MAP_VIDEO_MEMORY\n");
if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MEMORY_INFORMATION) ||
- RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
+ RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
case IOCTL_VIDEO_UNMAP_VIDEO_MEMORY:
DPRINT("XboxVmpStartIO IOCTL_VIDEO_UNMAP_VIDEO_MEMORY\n");
- if (RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
+ if (RequestPacket->InputBufferLength < sizeof(VIDEO_MEMORY))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
case IOCTL_VIDEO_QUERY_NUM_AVAIL_MODES:
DPRINT("XboxVmpStartIO IOCTL_VIDEO_QUERY_NUM_AVAIL_MODES\n");
- if (RequestPacket->OutputBufferLength < sizeof(VIDEO_NUM_MODES))
+ if (RequestPacket->OutputBufferLength < sizeof(VIDEO_NUM_MODES))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
case IOCTL_VIDEO_QUERY_AVAIL_MODES:
DPRINT("XboxVmpStartIO IOCTL_VIDEO_QUERY_AVAIL_MODES\n");
- if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MODE_INFORMATION))
+ if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MODE_INFORMATION))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
case IOCTL_VIDEO_QUERY_CURRENT_MODE:
DPRINT("XboxVmpStartIO IOCTL_VIDEO_QUERY_CURRENT_MODE\n");
- if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MODE_INFORMATION))
+ if (RequestPacket->OutputBufferLength < sizeof(VIDEO_MODE_INFORMATION))
{
RequestPacket->StatusBlock->Status = ERROR_INSUFFICIENT_BUFFER;
return TRUE;
(PVIDEO_MODE_INFORMATION)RequestPacket->OutputBuffer,
RequestPacket->StatusBlock);
break;
-
+
default:
DPRINT("XboxVmpStartIO 0x%x not implemented\n");
RequestPacket->StatusBlock->Status = STATUS_NOT_IMPLEMENTED;
return FALSE;
}
-
+
if (Result)
{
RequestPacket->StatusBlock->Status = STATUS_SUCCESS;
{
return FALSE;
}
-
+
return TRUE;
}
{
DPRINT1("XboxVmpGetPowerState is not supported\n");
- return ERROR_NOT_SUPPORTED;
+ return ERROR_NOT_SUPPORTED;
}
/*
{
DPRINT1("XboxVmpSetPowerState not supported\n");
- return ERROR_NOT_SUPPORTED;
+ return ERROR_NOT_SUPPORTED;
}
/*
* XboxVmpResetDevice
*
* Resets the video hardware to the default mode, to which it was initialized
- * at system boot.
+ * at system boot.
*/
BOOL FASTCALL
* XboxVmpMapVideoMemory
*
* Maps the video hardware frame buffer and video RAM into the virtual address
- * space of the requestor.
+ * space of the requestor.
*/
BOOL FASTCALL
DPRINT1("ZwQueryBasicInformation failed, assuming 64MB total memory\n");
FrameBuffer.u.LowPart = 60 * 1024 * 1024;
}
-
+
FrameBuffer.QuadPart += DeviceExtension->PhysFrameBufferStart.QuadPart;
MapInformation->VideoRamBase = RequestedAddress->RequestedVirtualAddress;
MapInformation->VideoRamLength = 4 * 1024 * 1024;
* Returns information about current video mode.
*/
-BOOL FASTCALL
+BOOL FASTCALL
XboxVmpQueryCurrentMode(
PXBOXVMP_DEVICE_EXTENSION DeviceExtension,
PVIDEO_MODE_INFORMATION VideoMode,
PVIDEO_MODE_INFORMATION ReturnedModes,
PSTATUS_BLOCK StatusBlock);
-BOOL FASTCALL
+BOOL FASTCALL
XboxVmpQueryCurrentMode(
PXBOXVMP_DEVICE_EXTENSION DeviceExtension,
PVIDEO_MODE_INFORMATION VideoModeInfo,
DPRINT("- Returned status: %x\n", Irp->IoStatus.Status);
- if (Irp->IoStatus.Status != STATUS_SUCCESS)
- {
- /* Map from win32 error codes to NT status values. */
- switch (Irp->IoStatus.Status)
- {
+ if (Irp->IoStatus.Status != STATUS_SUCCESS)
+ {
+ /* Map from win32 error codes to NT status values. */
+ switch (Irp->IoStatus.Status)
+ {
case ERROR_NOT_ENOUGH_MEMORY: Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; break;
case ERROR_MORE_DATA: Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; break;
case ERROR_INVALID_FUNCTION: Irp->IoStatus.Status = STATUS_NOT_IMPLEMENTED; break;
case ERROR_INVALID_PARAMETER: Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; break;
- case ERROR_INSUFFICIENT_BUFFER: Irp->IoStatus.Status = STATUS_BUFFER_TOO_SMALL; break;
+ case ERROR_INSUFFICIENT_BUFFER: Irp->IoStatus.Status = STATUS_BUFFER_TOO_SMALL; break;
case ERROR_DEV_NOT_EXIST: Irp->IoStatus.Status = STATUS_DEVICE_DOES_NOT_EXIST; break;
case ERROR_IO_PENDING: Irp->IoStatus.Status = STATUS_PENDING; break;
- }
- }
+ }
+ }
Status = Irp->IoStatus.Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
break;
-
+
default:
return STATUS_NOT_IMPLEMENTED;
break;
}
-
+
return Status;
}
DeviceExtension = VIDEO_PORT_GET_DEVICE_EXTENSION(HwDeviceExtension);
DPRINT("VideoPortGetDmaAdapter\n");
-
+
DeviceDescription.Version = DEVICE_DESCRIPTION_VERSION;
DeviceDescription.Master = TRUE /* ?? */;
DeviceDescription.ScatterGather = VpDeviceExtension->ScatterGather;
DeviceDescription.MaximumLength = VpDeviceExtension->MaximumLength;
DeviceDescription.DmaPort = 0;
- Adapter =
+ Adapter =
(PVP_DMA_ADAPTER)HalGetAdapter(&DeviceDescription, &NumberOfMapRegisters);
DPRINT("Adapter %X\n", Adapter);
return(Adapter);
OUT PEVENT *Event)
{
EVENT_TYPE Type;
-
+
(*Event) = ExAllocatePoolWithTag(
NonPagedPool,
- sizeof(KEVENT),
+ sizeof(KEVENT),
TAG_VIDEO_PORT);
if ((*Event) == NULL)
{
PVOID MemoryAddress;
NTSTATUS Status;
- PEPROCESS CallingProcess;
- PEPROCESS PrevAttachedProcess;
+ PEPROCESS CallingProcess;
+ PEPROCESS PrevAttachedProcess;
DPRINT("IntInt10AllocateBuffer\n");
{
PVOID MemoryAddress = (PVOID)((Seg << 4) | Off);
NTSTATUS Status;
- PEPROCESS CallingProcess;
- PEPROCESS PrevAttachedProcess;
+ PEPROCESS CallingProcess;
+ PEPROCESS PrevAttachedProcess;
DPRINT("IntInt10FreeBuffer\n");
DPRINT("- Segment: %x\n", Seg);
OUT PVOID Buffer,
IN ULONG Length)
{
- PEPROCESS CallingProcess;
- PEPROCESS PrevAttachedProcess;
+ PEPROCESS CallingProcess;
+ PEPROCESS PrevAttachedProcess;
DPRINT("IntInt10ReadMemory\n");
DPRINT("- Segment: %x\n", Seg);
IN PVOID Buffer,
IN ULONG Length)
{
- PEPROCESS CallingProcess;
- PEPROCESS PrevAttachedProcess;
+ PEPROCESS CallingProcess;
+ PEPROCESS PrevAttachedProcess;
DPRINT("IntInt10WriteMemory\n");
DPRINT("- Segment: %x\n", Seg);
{
KV86M_REGISTERS Regs;
NTSTATUS Status;
- PEPROCESS CallingProcess;
- PEPROCESS PrevAttachedProcess;
+ PEPROCESS CallingProcess;
+ PEPROCESS PrevAttachedProcess;
DPRINT("IntInt10CallBios\n");
{
KV86M_REGISTERS Regs;
NTSTATUS Status;
- PEPROCESS CallingProcess;
- PEPROCESS PrevAttachedProcess;
+ PEPROCESS CallingProcess;
+ PEPROCESS PrevAttachedProcess;
DPRINT("VideoPortInt10\n");
{
return ERROR_INVALID_PARAMETER;
}
-
+
IntAttachToCSRSS(&CallingProcess, &PrevAttachedProcess);
memset(&Regs, 0, sizeof(Regs));
VOID STDCALL
VideoPortFreeDeviceBase(
- IN PVOID HwDeviceExtension,
+ IN PVOID HwDeviceExtension,
IN PVOID MappedAddress)
{
DPRINT("VideoPortFreeDeviceBase\n");
IN ULONG Size,
OUT PVOID *Buffer)
{
- DPRINT("VideoPortAllocateBuffer\n");
+ DPRINT("VideoPortAllocateBuffer\n");
*Buffer = ExAllocatePool(PagedPool, Size);
return *Buffer == NULL ? ERROR_NOT_ENOUGH_MEMORY : NO_ERROR;
}
{
DPRINT("VideoPortReleaseBuffer\n");
ExFreePool(Ptr);
-}
+}
/*
* @unimplemented
}
return HalGetBusDataByOffset(
- BusDataType,
+ BusDataType,
DeviceExtension->SystemIoBusNumber,
SlotNumber,
- Buffer,
- Offset,
+ Buffer,
+ Offset,
Length);
}
DPRINT("VideoPortSetBusData\n");
DeviceExtension = VIDEO_PORT_GET_DEVICE_EXTENSION(HwDeviceExtension);
-
+
if (BusDataType != Cmos)
{
/* Legacy vs. PnP behaviour */
IN PVOID HwDeviceExtension,
OUT PSPIN_LOCK *SpinLock)
{
- DPRINT("VideoPortCreateSpinLock\n");
+ DPRINT("VideoPortCreateSpinLock\n");
*SpinLock = ExAllocatePool(NonPagedPool, sizeof(KSPIN_LOCK));
if (*SpinLock == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
{
PIMAGE_NT_HEADERS NtHeader;
ULONG Va;
-
+
NtHeader = RtlImageNtHeader(BaseAddress);
if (NtHeader == NULL)
return NULL;
-
+
if (Directory >= NtHeader->OptionalHeader.NumberOfRvaAndSizes)
return NULL;
-
+
Va = NtHeader->OptionalHeader.DataDirectory[Directory].VirtualAddress;
if (Va == 0)
return NULL;
-
+
return (PVOID)(BaseAddress + Va);
}
RtlInitUnicodeString(&GdiDriverInfo.ModuleName, L"videoprt");
Status = ZwSetSystemInformation(
SystemLoadImage,
- &GdiDriverInfo,
+ &GdiDriverInfo,
sizeof(SYSTEM_LOAD_IMAGE));
if (!NT_SUCCESS(Status))
{
if (!_strnicmp((PCHAR)FunctionName, (PCHAR)(BaseAddress + *NamePtr),
strlen((PCHAR)FunctionName)))
{
- return (PVOID)((ULONG_PTR)BaseAddress +
- (ULONG_PTR)AddressPtr[*OrdinalPtr]);
+ return (PVOID)((ULONG_PTR)BaseAddress +
+ (ULONG_PTR)AddressPtr[*OrdinalPtr]);
}
}
IN PVOID SystemArgument1,
IN PVOID SystemArgument2)
{
- PVOID HwDeviceExtension =
+ PVOID HwDeviceExtension =
&((PVIDEO_PORT_DEVICE_EXTENSION)DeferredContext)->MiniPortDeviceExtension;
((PMINIPORT_DPC_ROUTINE)SystemArgument1)(HwDeviceExtension, SystemArgument2);
}
WCHAR DeviceBuffer[20];
UNICODE_STRING DeviceName;
PDEVICE_OBJECT DeviceObject_;
-
+
if (DeviceObject == NULL)
DeviceObject = &DeviceObject_;
if (NT_SUCCESS(Status))
{
ConfigInfo.SystemMemorySize =
- SystemBasicInfo.NumberOfPhysicalPages *
+ SystemBasicInfo.NumberOfPhysicalPages *
SystemBasicInfo.PhysicalPageSize;
}
{
LegacyDetection = TRUE;
}
-
+
if (LegacyDetection)
{
ULONG BusNumber, MaxBuses;
DeviceExtension->SystemIoBusNumber =
ConfigInfo.SystemIoBusNumber = BusNumber;
- RtlZeroMemory(&DeviceExtension->MiniPortDeviceExtension,
+ RtlZeroMemory(&DeviceExtension->MiniPortDeviceExtension,
DriverExtension->InitializationData.HwDeviceExtensionSize);
-
+
/* FIXME: Need to figure out what string to pass as param 3. */
Status = DriverExtension->InitializationData.HwFindAdapter(
&DeviceExtension->MiniPortDeviceExtension,
return STATUS_SUCCESS;
}
-VOID FASTCALL
-IntAttachToCSRSS(PEPROCESS *CallingProcess, PEPROCESS *PrevAttachedProcess)
-{
- *CallingProcess = PsGetCurrentProcess();
- if (*CallingProcess != Csrss)
- {
+VOID FASTCALL
+IntAttachToCSRSS(PEPROCESS *CallingProcess, PEPROCESS *PrevAttachedProcess)
+{
+ *CallingProcess = PsGetCurrentProcess();
+ if (*CallingProcess != Csrss)
+ {
if (PsGetCurrentThread()->ThreadsProcess != *CallingProcess)
- {
- *PrevAttachedProcess = *CallingProcess;
- KeDetachProcess();
- }
- else
- {
- *PrevAttachedProcess = NULL;
- }
- KeAttachProcess(Csrss);
- }
-}
-
-VOID FASTCALL
-IntDetachFromCSRSS(PEPROCESS *CallingProcess, PEPROCESS *PrevAttachedProcess)
-{
- if (*CallingProcess != Csrss)
- {
- KeDetachProcess();
- if (NULL != *PrevAttachedProcess)
- {
- KeAttachProcess(*PrevAttachedProcess);
- }
- }
-}
+ {
+ *PrevAttachedProcess = *CallingProcess;
+ KeDetachProcess();
+ }
+ else
+ {
+ *PrevAttachedProcess = NULL;
+ }
+ KeAttachProcess(Csrss);
+ }
+}
+
+VOID FASTCALL
+IntDetachFromCSRSS(PEPROCESS *CallingProcess, PEPROCESS *PrevAttachedProcess)
+{
+ if (*CallingProcess != Csrss)
+ {
+ KeDetachProcess();
+ if (NULL != *PrevAttachedProcess)
+ {
+ KeAttachProcess(*PrevAttachedProcess);
+ }
+ }
+}
/* PUBLIC FUNCTIONS ***********************************************************/
/*
* @implemented
- */
+ */
VP_STATUS STDCALL
VideoPortGetVgaStatus(
}
}
- return ERROR_INVALID_FUNCTION;
+ return ERROR_INVALID_FUNCTION;
}
/*
IN ULONG Length)
{
static PVOID RomImageBuffer = NULL;
- PEPROCESS CallingProcess;
- PEPROCESS PrevAttachedProcess;
+ PEPROCESS CallingProcess;
+ PEPROCESS PrevAttachedProcess;
DPRINT("VideoPortGetRomImage(HwDeviceExtension 0x%X Length 0x%X)\n",
HwDeviceExtension, Length);
else
{
/*
- * The DDK says we shouldn't use the legacy C0000 method but get the
- * rom base address from the corresponding pci or acpi register but
+ * The DDK says we shouldn't use the legacy C0000 method but get the
+ * rom base address from the corresponding pci or acpi register but
* lets ignore that and use C0000 anyway. We have already mapped the
- * bios area into memory so we'll copy from there.
+ * bios area into memory so we'll copy from there.
*/
/* Copy the bios. */
BOOLEAN STDCALL
VideoPortScanRom(
- IN PVOID HwDeviceExtension,
+ IN PVOID HwDeviceExtension,
IN PUCHAR RomBase,
IN ULONG RomLength,
IN PUCHAR String)
case VpLowPriority:
Ret = (*SynchronizeRoutine)(Context);
break;
-
+
case VpMediumPriority:
DeviceExtension = VIDEO_PORT_GET_DEVICE_EXTENSION(HwDeviceExtension);
if (DeviceExtension->InterruptObject == NULL)
IN PVOID Context)
{
return KeInsertQueueDpc(
- &VIDEO_PORT_GET_DEVICE_EXTENSION(HwDeviceExtension)->DpcObject,
+ &VIDEO_PORT_GET_DEVICE_EXTENSION(HwDeviceExtension)->DpcObject,
(PVOID)CallbackRoutine,
(PVOID)Context);
}
/*
* @implemented
*/
-
+
VOID STDCALL
VideoPortAcquireDeviceLock(
IN PVOID HwDeviceExtension)
BOOLEAN STDCALL
HalDisableSystemInterrupt(ULONG Vector,
KIRQL Irql);
-
+
BOOLEAN STDCALL
HalEnableSystemInterrupt(ULONG Vector,
KIRQL Irql,
IN PVOID HwDeviceExtension,
IN PUCHAR FunctionName);
-VOID FASTCALL
+VOID FASTCALL
IntAttachToCSRSS(PEPROCESS *CallingProcess, PEPROCESS *PrevAttachedProcess);
-VOID FASTCALL
+VOID FASTCALL
IntDetachFromCSRSS(PEPROCESS *CallingProcess, PEPROCESS *PrevAttachedProcess);
NTSTATUS STDCALL