Commit Graph

150 Commits

Author SHA1 Message Date
Poul-Henning Kamp
be1bf4d2b8 s/SLIST/STAILQ/
/imp/a\
pointy hat
.
2005-03-18 11:57:44 +00:00
Bill Paul
58a6edd121 When you call MiniportInitialize() for an 802.11 driver, it will
at some point result in a status event being triggered (it should
be a link down event: the Microsoft driver design guide says you
should generate one when the NIC is initialized). Some drivers
generate the event during MiniportInitialize(), such that by the
time MiniportInitialize() completes, the NIC is ready to go. But
some drivers, in particular the ones for Atheros wireless NICs,
don't generate the event until after a device interrupt occurs
at some point after MiniportInitialize() has completed.

The gotcha is that you have to wait until the link status event
occurs one way or the other before you try to fiddle with any
settings (ssid, channel, etc...). For the drivers that set the
event sycnhronously this isn't a problem, but for the others
we have to pause after calling ndis_init_nic() and wait for the event
to arrive before continuing. Failing to wait can cause big trouble:
on my SMP system, calling ndis_setstate_80211() after ndis_init_nic()
completes, but _before_ the link event arrives, will lock up or
reset the system.

What we do now is check to see if a link event arrived while
ndis_init_nic() was running, and if it didn't we msleep() until
it does.

Along the way, I discovered a few other problems:

- Defered procedure calls run at PASSIVE_LEVEL, not DISPATCH_LEVEL.
  ntoskrnl_run_dpc() has been fixed accordingly. (I read the documentation
  wrong.)

- Similarly, the NDIS interrupt handler, which is essentially a
  DPC, also doesn't need to run at DISPATCH_LEVEL. ndis_intrtask()
  has been fixed accordingly.

- MiniportQueryInformation() and MiniportSetInformation() run at
  DISPATCH_LEVEL, and each request must complete before another
  can be submitted. ndis_get_info() and ndis_set_info() have been
  fixed accordingly.

- Turned the sleep lock that guards the NDIS thread job list into
  a spin lock. We never do anything with this lock held except manage
  the job list (no other locks are held), so it's safe to do this,
  and it's possible that ndis_sched() and ndis_unsched() can be
  called from DISPATCH_LEVEL, so using a sleep lock here is
  semantically incorrect. Also updated subr_witness.c to add the
  lock to the order list.
2005-03-07 03:05:31 +00:00
Bill Paul
7d962e5cc5 MAXPATHLEN is 1024, which means NdisOpenFile() and ndis_find_sym() were
both consuming 1K of stack space. This is unfriendly. Allocate the buffers
off the heap instead. It's a little slower, but these aren't performance
critical routines.

Also, add a spinlock to NdisAllocatePacketPool(), NdisAllocatePacket(),
NdisFreePacketPool() and NdisFreePacket(). The pool is maintained as a
linked list. I don't know for a fact that it can be corrupted, but why
take chances.
2005-03-03 03:51:02 +00:00
Bill Paul
2628b0b7ab In windrv_load(), I was allocating the driver object using
malloc(sizeof(device_object), ...) by mistake. Correct this, and
rename "dobj" to "drv" to make it a bit clearer what this variable
is supposed to be.

Spotted by: Mikore Li at Sun dot comnospamplzkthx
2005-03-01 17:21:25 +00:00
Bill Paul
303ff38659 Don't need to do MmInitializeMdl() in ndis_mtop() anymore:
IoInitializeMdl() does it internally (and doing it again here
messes things up).
2005-02-26 07:11:17 +00:00
Bill Paul
a944e196da MDLs are supposed to be variable size (they include an array of pages
that describe a buffer of variable size). The problem is, allocating
MDLs off the heap is slow, and it can happen that drivers will allocate
lots and lots of lots of MDLs as they run.

As a compromise, we now do the following: we pre-allocate a zone for
MDLs big enough to describe any buffer with 16 or less pages. If
IoAllocateMdl() needs a MDL for a buffer with 16 or less pages, we'll
allocate it from the zone. Otherwise, we allocate it from the heap.
MDLs allocate from the zone have a flag set in their mdl_flags field.
When the MDL is released, IoMdlFree() will uma_zfree() the MDL if
it has the MDL_ZONE_ALLOCED flag set, otherwise it will release it
to the heap.

The assumption is that 16 pages is a "big number" and we will rarely
need MDLs larger than that.

- Moved the ndis_buffer zone to subr_ntoskrnl.c from kern_ndis.c
  and named it mdl_zone.

- Modified IoAllocateMdl() and IoFreeMdl() to use uma_zalloc() and
  uma_zfree() if necessary.

- Made ndis_mtop() use IoAllocateMdl() instead of calling uma_zalloc()
  directly.

Inspired by: discussion with Giridhar Pemmasani
2005-02-26 00:22:16 +00:00
Bill Paul
849bcccac9 Add macros to construct Windows IOCTL codes, and to extract function
codes from an IOCTL. (The USB module will need them later.)
2005-02-25 18:25:48 +00:00
Bill Paul
ed7003a9f3 Fix a couple of callback instances that should have been wrapped with
MSCALLx().

Add definition for STATUS_PENDING error code.
2005-02-25 08:34:32 +00:00
Bill Paul
17bd4e32e1 Compute the right length to use with bzero() when initializing an IRP
in IoInitializeIrp() (must use IoSizeOfIrp() to account for the stack
locations).
2005-02-25 06:31:45 +00:00
Bill Paul
63ba67b69c - Correct one aspect of the driver_object/device_object/IRP framework:
when we create a PDO, the driver_object associated with it is that
  of the parent driver, not the driver we're trying to attach. For
  example, if we attach a PCI device, the PDO we pass to the NdisAddDevice()
  function should contain a pointer to fake_pci_driver, not to the NDIS
  driver itself. For PCI or PCMCIA devices this doesn't matter because
  the child never needs to talk to the parent bus driver, but for USB,
  the child needs to be able to send IRPs to the parent USB bus driver, and
  for that to work the parent USB bus driver has to be hung off the PDO.

  This involves modifying windrv_lookup() so that we can search for
  bus drivers by name, if necessary. Our fake bus drivers attach themselves
  as "PCI Bus," "PCCARD Bus" and "USB Bus," so we can search for them
  using those names.

  The individual attachment stubs now create and attach PDOs to the
  parent bus drivers instead of hanging them off the NDIS driver's
  object, and in if_ndis.c, we now search for the correct driver
  object depending on the bus type, and use that to find the correct PDO.

  With this fix, I can get my sample USB ethernet driver to deliver
  an IRP to my fake parent USB bus driver's dispatch routines.

- Add stub modules for USB support: subr_usbd.c, usbd_var.h and
  if_ndis_usb.c. The subr_usbd.c module is hooked up the build
  but currently doesn't do very much. It provides the stub USB
  parent driver object and a dispatch routine for
  IRM_MJ_INTERNAL_DEVICE_CONTROL. The only exported function at
  the moment is USBD_GetUSBDIVersion(). The if_ndis_usb.c stub
  compiles, but is not hooked up to the build yet. I'm putting
  these here so I can keep them under source code control as I
  flesh them out.
2005-02-24 21:49:14 +00:00
Bill Paul
70211f5ef5 Couple of lessons learned during USB driver testing:
- In kern_ndis.c:ndis_unload_driver(), test that ndis_block->nmb_rlist
  is not NULL before trying to free() it.

- In subr_pe.c:pe_get_import_descriptor(), do a case-insensitive
  match on the import module name. Most drivers I have encountered
  link against "ntoskrnl.exe" but the ASIX USB ethernet driver I'm
  testing with wants "NTOSKRNL.EXE."

- In subr_ntoskrnl.c:IoAllocateIrp(), return a pointer to the IRP
  instead of NULL. (Stub code leftover.)

- Also in subr_ntoskrnl.c, add ExAllocatePoolWithTag() and ExFreePool()
  to the function table list so they'll get exported to drivers properly.
2005-02-24 17:58:27 +00:00
Bill Paul
d3e4cd0609 Implement IoCancelIrp(), IoAcquireCancelSpinLock(), IoReleaseCancelSpinLock()
and a machine-independent though inefficient InterlockedExchange().
In Windows, InterlockedExchange() appears to be implemented in header
files via inline assembly. I would prefer using an atomic.h macro for
this, but there doesn't seem to be one that just does a plain old
atomic exchange (as opposed to compare and exchange). Also implement
IoSetCancelRoutine(), which is just a macro that uses InterlockedExchange().

Fill in IoBuildSynchronousFsdRequest(), IoBuildAsynchronousFsdRequest()
and IoBuildDeviceIoControlRequest() so that they do something useful,
and add a bunch of #defines to ntoskrnl_var.h to help make these work.
These may require some tweaks later.
2005-02-23 16:44:33 +00:00
Bill Paul
e6f328fb03 Fix a couple of u_int_foos that should have been uint_foos. 2005-02-18 04:33:34 +00:00
Bill Paul
6e121c5427 Make the Win64 -> ELF64 template a little smaller by using a string
copy op to shift arguments on the stack instead of transfering each
argument one by one through a register. Probably doesn't affect overall
operation, but makes the code a little less grotty and easier to update
later if I choose to make the wrapper handle more args. Also add
comments.
2005-02-18 03:22:37 +00:00
Bill Paul
2b0dcd6b18 Remove redundant label. 2005-02-16 21:24:04 +00:00
Bill Paul
513c5292f8 Fix freeing of custom driver extensions. (ExFreePool() was being
called with the wrong pointer.)
2005-02-16 19:21:07 +00:00
Bill Paul
2adbfd5436 KeAcquireSpinLockRaiseToDpc() and KeReleaseSpinLock() are (at least
for now) exactly the same as KfAcquireSpinLock() and KfReleaseSpinLock().
I implemented the former as small routines in subr_ntoskrnl.c that just
turned around and invoked the latter. But I don't really need the wrapper
routines: I can just create an entries in the ntoskrnl func table that
map KeAcquireSpinLockRaiseToDpc() and KeReleaseSpinLock() to
KfAcquireSpinLock() and KfReleaseSpinLock() directly. This means
the stubs can go away.
2005-02-16 18:18:30 +00:00
Bill Paul
d8f2dda739 Add support for Windows/x86-64 binaries to Project Evil.
Ville-Pertti Keinonen (will at exomi dot comohmygodnospampleasekthx)
deserves a big thanks for submitting initial patches to make it
work. I have mangled his contributions appropriately.

The main gotcha with Windows/x86-64 is that Microsoft uses a different
calling convention than everyone else. The standard ABI requires using
6 registers for argument passing, with other arguments on the stack.
Microsoft uses only 4 registers, and requires the caller to leave room
on the stack for the register arguments incase the callee needs to
spill them. Unlike x86, where Microsoft uses a mix of _cdecl, _stdcall
and _fastcall, all routines on Windows/x86-64 uses the same convention.
This unfortunately means that all the functions we export to the
driver require an intermediate translation wrapper. Similarly, we have
to wrap all calls back into the driver binary itself.

The original patches provided macros to wrap every single routine at
compile time, providing a secondary jump table with a customized
wrapper for each exported routine. I decided to use a different approach:
the call wrapper for each function is created from a template at
runtime, and the routine to jump to is patched into the wrapper as
it is created. The subr_pe module has been modified to patch in the
wrapped function instead of the original. (On x86, the wrapping
routine is a no-op.)

There are some minor API differences that had to be accounted for:

- KeAcquireSpinLock() is a real function on amd64, not a macro wrapper
  around KfAcquireSpinLock()
- NdisFreeBuffer() is actually IoFreeMdl(). I had to change the whole
  NDIS_BUFFER API a bit to accomodate this.

Bugs fixed along the way:
- IoAllocateMdl() always returned NULL
- kern_windrv.c:windrv_unload() wasn't releasing private driver object
  extensions correctly (found thanks to memguard)

This has only been tested with the driver for the Broadcom 802.11g
chipset, which was the only Windows/x86-64 driver I could find.
2005-02-16 05:41:18 +00:00
Bill Paul
b545a3b822 Next step on the road to IRPs: create and use an imitation of the
Windows DRIVER_OBJECT and DEVICE_OBJECT mechanism so that we can
simulate driver stacking.

In Windows, each loaded driver image is attached to a DRIVER_OBJECT
structure. Windows uses the registry to match up a given vendor/device
ID combination with a corresponding DRIVER_OBJECT. When a driver image
is first loaded, its DriverEntry() routine is invoked, which sets up
the AddDevice() function pointer in the DRIVER_OBJECT and creates
a dispatch table (based on IRP major codes). When a Windows bus driver
detects a new device, it creates a Physical Device Object (PDO) for
it. This is a DEVICE_OBJECT structure, with semantics analagous to
that of a device_t in FreeBSD. The Windows PNP manager will invoke
the driver's AddDevice() function and pass it pointers to the DRIVER_OBJECT
and the PDO.

The AddDevice() function then creates a new DRIVER_OBJECT structure of
its own. This is known as the Functional Device Object (FDO) and
corresponds roughly to a private softc instance. The driver uses
IoAttachDeviceToDeviceStack() to add this device object to the
driver stack for this PDO. Subsequent drivers (called filter drivers
in Windows-speak) can be loaded which add themselves to the stack.
When someone issues an IRP to a device, it travel along the stack
passing through several possible filter drivers until it reaches
the functional driver (which actually knows how to talk to the hardware)
at which point it will be completed. This is how Windows achieves
driver layering.

Project Evil now simulates most of this. if_ndis now has a modevent
handler which will use MOD_LOAD and MOD_UNLOAD events to drive the
creation and destruction of DRIVER_OBJECTs. (The load event also
does the relocation/dynalinking of the image.) We don't have a registry,
so the DRIVER_OBJECTS are stored in a linked list for now. Eventually,
the list entry will contain the vendor/device ID list extracted from
the .INF file. When ndis_probe() is called and detectes a supported
device, it will create a PDO for the device instance and attach it
to the DRIVER_OBJECT just as in Windows. ndis_attach() will then call
our NdisAddDevice() handler to create the FDO. The NDIS miniport block
is now a device extension hung off the FDO, just as it is in Windows.
The miniport characteristics table is now an extension hung off the
DRIVER_OBJECT as well (the characteristics are the same for all devices
handled by a given driver, so they don't need to be per-instance.)
We also do an IoAttachDeviceToDeviceStack() to put the FDO on the
stack for the PDO. There are a couple of fake bus drivers created
for the PCI and pccard buses. Eventually, there will be one for USB,
which will actually accept USB IRP.s

Things should still work just as before, only now we do things in
the proper order and maintain the correct framework to support passing
IRPs between drivers.

Various changes:

- corrected the comments about IRQL handling in subr_hal.c to more
  accurately reflect reality
- update ndiscvt to make the drv_data symbol in ndis_driver_data.h a
  global so that if_ndis_pci.o and/or if_ndis_pccard.o can see it.
- Obtain the softc pointer from the miniport block by referencing
  the PDO rather than a private pointer of our own (nmb_ifp is no
  longer used)
- implement IoAttachDeviceToDeviceStack(), IoDetachDevice(),
  IoGetAttachedDevice(), IoAllocateDriverObjectExtension(),
  IoGetDriverObjectExtension(), IoCreateDevice(), IoDeleteDevice(),
  IoAllocateIrp(), IoReuseIrp(), IoMakeAssociatedIrp(), IoFreeIrp(),
  IoInitializeIrp()
- fix a few mistakes in the driver_object and device_object definitions
- add a new module, kern_windrv.c, to handle the driver registration
  and relocation/dynalinkign duties (which don't really belong in
  kern_ndis.c).
- made ndis_block and ndis_chars in the ndis_softc stucture pointers
  and modified all references to it
- fixed NdisMRegisterMiniport() and NdisInitializeWrapper() so they
  work correctly with the new driver_object mechanism
- changed ndis_attach() to call NdisAddDevice() instead of ndis_load_driver()
  (which is now deprecated)
- used ExAllocatePoolWithTag()/ExFreePool() in lookaside list routines
  instead of kludged up alloc/free routines
- added kern_windrv.c to sys/modules/ndis/Makefile and files.i386.
2005-02-08 17:23:25 +00:00
Bill Paul
26805b1855 Apparently, the Intel icc compiler doesn't like it when you use
attributes in casts (i.e. foo = (__stdcall sometype)bar). This only
happens in two places where we need to set up function pointers, so
work around the problem with some void pointer magic.
2005-01-25 17:00:54 +00:00
Bill Paul
df7b7cf4c3 Begin the first phase of trying to add IRP support (and ultimately
USB device support):

- Convert all of my locally chosen function names to their actual
  Windows equivalents, where applicable. This is a big no-op change
  since it doesn't affect functionality, but it helps avoid a bit
  of confusion (it's now a lot easier to see which functions are
  emulated Windows API routines and which are just locally defined).

- Turn ndis_buffer into an mdl, like it should have been. The structure
  is the same, but now it belongs to the subr_ntoskrnl module.

- Implement a bunch of MDL handling macros from Windows and use them where
  applicable.

- Correct the implementation of IoFreeMdl().

- Properly implement IoAllocateMdl() and MmBuildMdlForNonPagedPool().

- Add the definitions for struct irp and struct driver_object.

- Add IMPORT_FUNC() and IMPORT_FUNC_MAP() macros to make formatting
  the module function tables a little cleaner. (Should also help
  with AMD64 support later on.)

- Fix if_ndis.c to use KeRaiseIrql() and KeLowerIrql() instead of
  the previous calls to hal_raise_irql() and hal_lower_irql() which
  have been renamed.

The function renaming generated a lot of churn here, but there should
be very little operational effect.
2005-01-24 18:18:12 +00:00
Bill Paul
52378c7ead Fix a problem reported by Pierre Beyssac. Sometinmes when ndis_get_info()
calls MiniportQueryInformation(), it will return NDIS_STATUS_PENDING.
When this happens, ndis_get_info() will sleep waiting for a completion
event. If two threads call ndis_get_info() and both end up having to
sleep, they will both end up waiting on the same wait channel, which
can cause a panic in sleepq_add() if INVARIANTS are turned on.

Fix this by having ndis_get_info() use a common mutex rather than
using the process mutex with PROC_LOCK(). Also do the same for
ndis_set_info(). Note that Pierre's original patch also made ndis_thsuspend()
use the new mutex, but ndis_thsuspend() shouldn't need this since
it will make each thread that calls it sleep on a unique wait channel.

Also, it occured to me that we probably don't want to enter
MiniportQueryInformation() or MiniportSetInformation() from more
than one thread at any given time, so now we acquire a Windows
spinlock before calling either of them. The Microsoft documentation
says that MiniportQueryInformation() and MiniportSetInformation()
are called at DISPATCH_LEVEL, and previously we would call
KeRaiseIrql() to set the IRQL to DISPATCH_LEVEL before entering
either routine, but this only guarantees mutual exclusion on
uniprocessor machines. To make it SMP safe, we need to use a real
spinlock. For now, I'm abusing the spinlock embedded in the
NDIS_MINIPORT_BLOCK structure for this purpose. (This may need to be
applied to some of the other routines in kern_ndis.c at a later date.)

Export ntoskrnl_init_lock() (KeInitializeSpinlock()) from subr_ntoskrnl.c
since we need to use in in kern_ndis.c, and since it's technically part
of the Windows kernel DDK API along with the other spinlock routines. Use
it in subr_ndis.c too rather than frobbing the spinlock directly.
2005-01-14 22:39:44 +00:00
Warner Losh
898b0535b7 Start each of the license/copyright comments with /*- 2005-01-05 22:34:37 +00:00
John Baldwin
63710c4d35 Stop explicitly touching td_base_pri outside of the scheduler and simply
set a thread's priority via sched_prio() when that is the desired action.
The schedulers will start managing td_base_pri internally shortly.
2004-12-30 20:29:58 +00:00
Bruce M Simpson
6120a003b4 Fix compiler warnings, when __stdcall is #defined, by adding explicit casts.
These normally only manifest if the ndis compat module is statically
compiled into a kernel image by way of 'options NDISAPI'.

Submitted by:	Dmitri Nikulin
Approved by:	wpaul
PR:		kern/71449
MFC after:	1 week
2004-09-17 19:54:26 +00:00
Bill Paul
ae58ccaa60 I'm a dumbass: remember to initialize fh->nf_map to NULL in
ndis_open_file() in the module loading case.
2004-08-16 19:25:27 +00:00
Bill Paul
161a639981 The Texas Instruments ACX111 driver wants srand(), so provide it. 2004-08-16 18:52:37 +00:00
Bill Paul
f454f98c31 Make the Texas Instruments 802.11g chipset work with the NDISulator.
This was tested with a Netgear WG311v2 802.11b/g PCI card. Things
that were fixed:

- This chip has two memory mapped regions, one at PCIR_BAR(0) and the
  other at PCIR_BAR(1). This is a little different from the other
  chips I've seen with two PCI shared memory regions, since they tend
  to have the second BAR ad PCIR_BAR(2). if_ndis_pci.c tests explicitly
  for PCIR_BAR(2). This has been changed to simply fill in ndis_res_mem
  first and ndis_res_altmem second, if a second shared memory range
  exists. Given that NDIS drivers seem to scan for BARs in ascending
  order, I think this should be ok.

- Fixed the code that tries to process firmware images that have been
  loaded as .ko files. To save a step, I was setting up the address
  mapping in ndis_open_file(), but ndis_map_file() flags pre-existing
  mappings as an error (to avoid duplicate mappings). Changed this so
  that the mapping is now donw in ndis_map_file() as expected.

- Made the typedef for 'driver_entry' explicitly include __stdcall
  to silence gcc warning in ndis_load_driver().

NOTE: the Texas Instruments ACX111 driver needs firmware. With my
card, there were 3 .bin files shipped with the driver. You must
either put these files in /compat/ndis or convert them with
ndiscvt -f and kldload them so the driver can use them. Without
the firmware image, the NIC won't work.
2004-08-16 18:50:20 +00:00
Bill Paul
6f4481422e More minor cleanups and one small bug fix:
- In ntoskrnl_var.h, I had defined compat macros for
  ntoskrnl_acquire_spinlock() and ntoskrnl_release_spinlock() but
  never used them. This is fortunate since they were stale. Fix them
  to work properly. (In Windows/x86 KeAcquireSpinLock() is a macro that
  calls KefAcquireSpinLock(), which lives in HAL.dll. To imitate this,
  ntoskrnl_acquire_spinlock() is just a macro that calls hal_lock(),
  which lives in subr_hal.o.)

- Add macros for ntoskrnl_raise_irql() and ntoskrnl_lower_irql() that
  call hal_raise_irql() and hal_lower_irql().

- Use these macros in kern_ndis.c, subr_ndis.c and subr_ntoskrnl.c.

- Along the way, I realised subr_ndis.c:ndis_lock() was not calling
  hal_lock() correctly (it was using the FASTCALL2() wrapper when
  in reality this routine is FASTCALL1()). Using the
  ntoskrnl_acquire_spinlock() fixes this. Not sure if this actually
  caused any bugs since hal_lock() would have just ignored what
  was in %edx, but it was still bogus.

This hides many of the uses of the FASTCALLx() macros which makes the
code a little cleaner. Should not have any effect on generated object
code, other than the one fix in ndis_lock().
2004-08-04 18:22:50 +00:00
Bill Paul
20b03f4992 In ndis_alloc_bufpool() and ndis_alloc_packetpool(), the test to see if
allocating pool memory succeeded was checking the wrong pointer (should
have been looking at *pool, not pool). Corrected this.
2004-08-01 21:15:29 +00:00
Bill Paul
f13b900a9e Big mess 'o changes:
- Give ndiscvt(8) the ability to process a .SYS file directly into
  a .o file so that we don't have to emit big messy char arrays into
  the ndis_driver_data.h file. This behavior is currently optional, but
  may become the default some day.

- Give ndiscvt(8) the ability to turn arbitrary files into .ko files
  so that they can be pre-loaded or kldloaded. (Both this and the
  previous change involve using objcopy(1)).

- Give NdisOpenFile() the ability to 'read' files out of kernel memory
  that have been kldloaded or pre-loaded, and disallow the use of
  the normal vn_open() file opening method during bootstrap (when no
  filesystems have been mounted yet). Some people have reported that
  kldloading if_ndis.ko works fine when the system is running multiuser
  but causes a panic when the modile is pre-loaded by /boot/loader. This
  happens with drivers that need to use NdisOpenFile() to access
  external files (i.e. firmware images). NdisOpenFile() won't work
  during kernel bootstrapping because no filesystems have been mounted.
  To get around this, you can now do the following:

        o Say you have a firmware file called firmware.img
        o Do: ndiscvt -f firmware.img -- this creates firmware.img.ko
        o Put the firmware.img.ko in /boot/kernel
        o add firmware.img_load="YES" in /boot/loader.conf
        o add if_ndis_load="YES" and ndis_load="YES" as well

  Now the loader will suck the additional file into memory as a .ko. The
  phony .ko has two symbols in it: filename_start and filename_end, which
  are generated by objcopy(1). ndis_open_file() will traverse each module
  in the module list looking for these symbols and, if it finds them, it'll
  use them to generate the file mapping address and length values that
  the caller of NdisOpenFile() wants.

  As a bonus, this will even work if the file has been statically linked
  into the kernel itself, since the "kernel" module is searched too.
  (ndiscvt(8) will generate both filename.o and filename.ko for you).

- Modify the mechanism used to provide make-pretend FASTCALL support.
  Rather than using inline assembly to yank the first two arguments
  out of %ecx and %edx, we now use the __regparm__(3) attribute (and
  the __stdcall__ attribute) and use some macro magic to re-order
  the arguments and provide dummy arguments as needed so that the
  arguments passed in registers end up in the right place. Change
  taken from DragonflyBSD version of the NDISulator.
2004-08-01 20:04:31 +00:00
Bill Paul
020732be39 *sigh* Fix source code compatibility with 5.2.1-RELEASE _again_.
(Make kdb stuff conditional.)
2004-07-20 20:28:57 +00:00
Bill Paul
7602de354f Make NdisReadPcmciaAttributeMemory() and NdisWritePcmciaAttributeMemory()
actually work.

Make the PCI and PCCARD attachments provide a bus_get_resource_list()
method so that resource listing for PCCARD works. PCCARD does not
have a bus_get_resource_list() method (yet), so I faked up the
resource list management in if_ndis_pccard.c, and added
bus_get_resource_list() methods to both if_ndis_pccard.c and if_ndis_pci.c.
The one in the PCI attechment just hands off to the PCI bus code.
The difference is transparent to the NDIS resource handler code.

Fixed ndis_open_file() so that opening files which live on NFS
filesystems work: pass an actual ucred structure to VOP_GETATTR()
(NFS explodes if the ucred structure is NOCRED).

Make NdisMMapIoSpace() handle mapping of PCMCIA attribute memory
resources correctly.

Turn subr_ndis.c:my_strcasecmp() into ndis_strcasecmp() and export
it so that if_ndis_pccard.c can use it, and junk the other copy
of my_strcasecmp() from if_ndis_pccard.c.
2004-07-11 00:19:30 +00:00
Marcel Moolenaar
bc1c6224b7 Update for the KDB framework:
o  Call kdb_enter() instead of Debugger().

While here, remove a redundant return.
2004-07-10 20:55:15 +00:00
Bill Paul
06794990cb Fix two problems:
- In subr_ndis.c:ndis_allocate_sharemem(), create the busdma tags
  used for shared memory allocations with a lowaddr of 0x3E7FFFFF.
  This forces the buffers to be mapped to physical/bus addresses within
  the first 1GB of physical memory. It seems that at least one card
  (Linksys Instant Wireless PCI V2.7) depends on this behavior. I
  don't know if this is a hardware restriction, or if the NDIS
  driver for this card is truncating the addresses itself, but using
  physical/bus addresses beyong the 1GB limit causes initialization
  failures.

- Create am NDIS_INITIALIZED() macro in if_ndisvar.h and use it in
  if_ndis.c to test whether the device has been initialized rather
  than checking for the presence of the IFF_UP flag in if_flags.
  While debugging the previous problem, I noticed that bringing
  up the device would always produce failures from ndis_setmulti().
  It turns out that the following steps now occur during device
  initialization:

	- IFF_UP flag is set in if_flags
	- ifp->if_ioctl() called with SIOCSIFADDR (which we don't handle)
	- ifp->if_ioctl() called with SIOCADDMULTI
	- ifp->if_ioctl() called with SIOCADDMULTI (again)
	- ifp->if_ioctl() called with SIOCADDMULTI (yet again)
	- ifp->if_ioctl() called with SIOCSIFFLAGS

  Setting the receive filter and multicast filters can only be done
  when the underlying NDIS driver has been initialized, which is done
  by ifp->if_init(). However, we don't call ifp->if_init() until
  ifp->if_ioctl() is called with SIOCSIFFLAGS and IFF_UP has been
  set. It appears that now, the network stack tries to add multicast
  addresses to interface's filter before those steps occur. Normally,
  ndis_setmulti() would trap this condition by checking for the IFF_UP
  flag, but the network code has in fact set this flag already, so
  ndis_setmulti() is fooled into thinking the interface has been
  initialized when it really hasn't.

  It turns out this is usually harmless because the ifp->if_init()
  routine (in this case ndis_init()) will set up the multicast
  filter when it initializes the hardware anyway, and the underlying
  routines (ndis_get_info()/ndis_set_info()) know that the driver/NIC
  haven't been initialized yet, but you end up spurious error messages
  on the console all the time.

Something tells me this new behavior isn't really correct. I think
the intention was to fix it so that ifp->if_init() is only called
once when we ifconfig an interface up, but the end result seems a
little bogus: the change of the IFF_UP flag should be propagated
down to the driver before calling any other ioctl() that might actually
require the hardware to be up and running.
2004-07-07 17:46:30 +00:00
Bill Paul
bd610e47e2 Add another 5.2.1 source compatibility tweak: acquire Giant before calling
kthread_exit() if FreeBSD_version is old enough.
2004-06-07 01:22:48 +00:00
Dag-Erling Smørgrav
63eaecc921 Take advantage of the dev sysctl tree.
Approved by:	wpaul
2004-06-04 22:24:46 +00:00
Bill Paul
38f0f45fb5 Grrr. Really check subr_ndis.c in this time. (fixed my_strcasecmp()) 2004-06-04 04:45:38 +00:00
Bill Paul
8c2dd02b27 Explicitly #include <sys/module.h> instead of depending on <sys/kernel.h>
to do it for us.
2004-06-01 23:24:17 +00:00
Bill Paul
3a7dc24c44 Fix build with ndisulator: Add prototype for my_strcasecmp(). 2004-05-29 22:34:08 +00:00
Bill Paul
d1a5f43855 In subr_ndis.c, when searching for keys in our make-pretend registry,
make the key name matching case-insensitive. There are some drivers
and .inf files that have mismatched cases, e.g. the driver will look
for "AdhocBand" whereas the .inf file specifies a registry key to be
created called "AdHocBand." The mismatch is probably a typo that went
undetected (so much for QA), but since Windows seems to be case-insensitive,
we should be too.

In if_ndis.c, initialize rates and channels correctly so that specify
frequences correctly when trying to set channels in the 5Ghz band, and
so that 802.11b rates show up for some a/b/g cards (which otherwise
appear to have no 802.11b modes).

Also, when setting OID_802_11_CONFIGURATION in ndis_80211_setstate(),
provide default values for the beacon interval, ATIM window and dwelltime.
The Atheros "Aries" driver will crash if you try to select ad-hoc mode
and leave the beacon interval set to 0: it blindly uses this value and
does a division by 0 in the interrupt handler, causing an integer
divide trap.
2004-05-29 06:41:17 +00:00
Bill Paul
a1788fb41e Small timer cleanups:
- Use the dh_inserted member of the dispatch header in the Windows
  timer structure to indicate that the timer has been "inserted into
  the timer queue" (i.e. armed via timeout()). Use this as the value
  to return to the caller in KeCancelTimer(). Previously, I was using
  callout_pending(), but you can't use that with timeout()/untimeout()
  without creating a potential race condition.

- Make ntoskrnl_init_timer() just a wrapper around ntoskrnl_init_timer_ex()
  (reduces some code duplication).

- Drop Giant when entering if_ndis.c:ndis_tick() and
  subr_ntorkrnl.c:ntoskrnl_timercall(). At the moment, I'm forced to
  use system callwheel via timeout()/untimeout() to handle timers rather
  than the callout API (struct callout is too big to fit inside the
  Windows struct KTIMER, so I'm kind of hosed). Unfortunately, all
  the callouts in the callwhere are not marked as MPSAFE, so when
  one of them fires, it implicitly acquires Giant before invoking the
  callback routine (and releases it when it returns). I don't need to
  hold Giant, but there's no way to stop the callout code from acquiring
  it as long as I'm using timeout()/untimeout(), so for now we cheat
  by just dropping Giant right away (and re-acquiring it right before
  the routine returns so keep the callout code happy). At some point,
  I will need to solve this better, but for now this should be a suitable
  workaround.
2004-04-30 20:51:55 +00:00
Bill Paul
b1084a1e96 Ok, _really_ fix the Intel 2100B Centrino deadlock problems this time.
(I hope.)

My original instinct to make ndis_return_packet() asynchronous was correct.
Making ndis_rxeof() submit packets to the stack asynchronously fixes
one recursive spinlock acquisition, but it's also possible for it to
happen via the ndis_txeof() path too. So:

- In if_ndis.c, revert ndis_rxeof() to its old behavior (and don't bother
  putting ndis_rxeof_serial() back since we don't need it anymore).

- In kern_ndis.c, make ndis_return_packet() submit the call to the
  MiniportReturnPacket() function to the "ndis swi" thread so that
  it always happens in another context no matter who calls it.
2004-04-22 07:08:39 +00:00
Bill Paul
e3a62f4d54 Correct the AT_DISPATCH_LEVEL() macro to match earlier changes. 2004-04-20 02:27:38 +00:00
Bill Paul
1906853bd2 Try to handle recursive attempts to raise IRQL to DISPATCH_LEVEL better
(among other things).
2004-04-19 22:39:04 +00:00
Bill Paul
e1c0113ffd In ntoskrnl_unlock_dpc(), use atomic_store instead of atomic_cmpset
to give up the spinlock.

Suggested by: bde
2004-04-18 18:38:59 +00:00
Bill Paul
ef617c0842 - Use memory barrier with atomic operations in ntoskrnl_lock_dpc() and
ntoskrnl_unlocl_dpc().
- hal_raise_irql(), hal_lower_irql() and hal_irql() didn't work right
  on SMP (priority inheritance makes things... interesting). For now,
  use only two states: DISPATCH_LEVEL (PI_REALTIME) and PASSIVE_LEVEL
  (everything else). Tested on a dual PIII box.
- Use ndis_thsuspend() in ndis_sleep() instead of tsleep(). (I added
  ndis_thsuspend() and ndis_thresume() to replace kthread_suspend()
  and kthread_resume(); the former will preserve a thread's priority
  when it wakes up, the latter will not.)
- Change use of tsleep() in ndis_stop_thread() to prevent priority
  change on wakeup.
2004-04-16 00:04:28 +00:00
Bill Paul
2b94c69d1d Continue my efforts to imitate Windows as closely as possible by
attempting to duplicate Windows spinlocks. Windows spinlocks differ
from FreeBSD spinlocks in the way they block preemption. FreeBSD
spinlocks use critical_enter(), which masks off _all_ interrupts.
This prevents any other threads from being scheduled, but it also
prevents ISRs from running. In Windows, preemption is achieved by
raising the processor IRQL to DISPATCH_LEVEL, which prevents other
threads from preempting you, but does _not_ prevent device ISRs
from running. (This is essentially what Solaris calls dispatcher
locks.) The Windows spinlock itself (kspin_lock) is just an integer
value which is atomically set when you acquire the lock and atomically
cleared when you release it.

FreeBSD doesn't have IRQ levels, so we have to cheat a little by
using thread priorities: normal thread priority is PASSIVE_LEVEL,
lowest interrupt thread priority is DISPATCH_LEVEL, highest thread
priority is DEVICE_LEVEL (PI_REALTIME) and critical_enter() is
HIGH_LEVEL. In practice, only PASSIVE_LEVEL and DISPATCH_LEVEL
matter to us. The immediate benefit of all this is that I no
longer have to rely on a mutex pool.

Now, I'm sure many people will be seized by the urge to criticize
me for doing an end run around our own spinlock implementation, but
it makes more sense to do it this way. Well, it does to me anyway.

Overview of the changes:

- Properly implement hal_lock(), hal_unlock(), hal_irql(),
  hal_raise_irql() and hal_lower_irql() so that they more closely
  resemble their Windows counterparts. The IRQL is determined by
  thread priority.

- Make ntoskrnl_lock_dpc() and ntoskrnl_unlock_dpc() do what they do
  in Windows, which is to atomically set/clear the lock value. These
  routines are designed to be called from DISPATCH_LEVEL, and are
  actually half of the work involved in acquiring/releasing spinlocks.

- Add FASTCALL1(), FASTCALL2() and FASTCALL3() macros/wrappers
  that allow us to call a _fastcall function in spite of the fact
  that our version of gcc doesn't support __attribute__((__fastcall__))
  yet. The macros take 1, 2 or 3 arguments, respectively. We need
  to call hal_lock(), hal_unlock() etc... ourselves, but can't really
  invoke the function directly. I could have just made the underlying
  functions native routines and put _fastcall wrappers around them for
  the benefit of Windows binaries, but that would create needless bloat.

- Remove ndis_mtxpool and all references to it. We don't need it
  anymore.

- Re-implement the NdisSpinLock routines so that they use hal_lock()
  and friends like they do in Windows.

- Use the new spinlock methods for handling lookaside lists and
  linked list updates in place of the mutex locks that were there
  before.

- Remove mutex locking from ndis_isr() and ndis_intrhand() since they're
  already called with ndis_intrmtx held in if_ndis.c.

- Put ndis_destroy_lock() code under explicit #ifdef notdef/#endif.
  It turns out there are some drivers which stupidly free the memory
  in which their spinlocks reside before calling ndis_destroy_lock()
  on them (touch-after-free bug). The ADMtek wireless driver
  is guilty of this faux pas. (Why this doesn't clobber Windows I
  have no idea.)

- Make NdisDprAcquireSpinLock() and NdisDprReleaseSpinLock() into
  real functions instead of aliasing them to NdisAcaquireSpinLock()
  and NdisReleaseSpinLock(). The Dpr routines use
  KeAcquireSpinLockAtDpcLevel() level and KeReleaseSpinLockFromDpcLevel(),
  which acquires the lock without twiddling the IRQL.

- In ndis_linksts_done(), do _not_ call ndis_80211_getstate(). Some
  drivers may call the status/status done callbacks as the result of
  setting an OID: ndis_80211_getstate() gets OIDs, which means we
  might cause the driver to recursively access some of its internal
  structures unexpectedly. The ndis_ticktask() routine will call
  ndis_80211_getstate() for us eventually anyway.

- Fix the channel setting code a little in ndis_80211_setstate(),
  and initialize the channel to IEEE80211_CHAN_ANYC. (The Microsoft
  spec says you're not supposed to twiddle the channel in BSS mode;
  I may need to enforce this later.) This fixes the problems I was
  having with the ADMtek adm8211 driver: we were setting the channel
  to a non-standard default, which would cause it to fail to associate
  in BSS mode.

- Use hal_raise_irql() to raise our IRQL to DISPATCH_LEVEL when
  calling certain miniport routines, per the Microsoft documentation.

I think that's everything. Hopefully, other than fixing the ADMtek
driver, there should be no apparent change in behavior.
2004-04-14 07:48:03 +00:00
Bill Paul
7b764c37e4 In ndis_convert_res(), initialize the head of our temporary list
before calling BUS_GET_RESOURCE_LIST(). Previously, the list head would
only be initialized if BUS_GET_RESOURCE_LIST() succeeded; it needs to
be initialized unconditionally so that the list cleanup code won't
trip over potential stack garbage.
2004-04-07 17:02:55 +00:00
Bill Paul
6a50285516 - The MiniportReset() function can return NDIS_STATUS_PENDING, in which
case we should wait for the resetdone handler to be called before
  returning.

- When providing resources via ndis_query_resources(), uses the
  computed rsclen when using bcopy() to copy out the resource data
  rather than the caller-supplied buffer length.

- Avoid using ndis_reset_nic() in if_ndis.c unless we really need
  to reset the NIC because of a problem.

- Allow interrupts to be fielded during ndis_attach(), at least
  as far as allowing ndis_isr() and ndis_intrhand() to run.

- Use ndis_80211_rates_ex when probing for supported rates. Technically,
  this isn't supposed to work since, although Microsoft added the extended
  rate structure with the NDIS 5.1 update, the spec still says that
  the OID_802_11_SUPPORTED_RATES OID uses ndis_80211_rates. In spite of
  this, it appears some drivers use it anyway.

- When adding in our guessed rates, check to see if they already exist
  so that we avoid any duplicates.

- Add a printf() to ndis_open_file() that alerts the user when a
  driver attempts to open a file under /compat/ndis.

With these changes, I can get the driver for the SMC 2802W 54g PCI
card to load and run. This board uses a Prism54G chip. Note that in
order for this driver to work, you must place the supplied smc2802w.arm
firmware image under /compat/ndis. (The firmware is not resident on
the device.)

Note that this should also allow the 3Com 3CRWE154G72 card to work
as well; as far as I can tell, these cards also use a Prism54G chip.
2004-04-05 08:26:52 +00:00