Merge branch 'vendor/FILE'
[dragonfly.git] / sys / emulation / ndis / subr_ndis.c
1 /*-
2  * Copyright (c) 2003
3  *      Bill Paul <wpaul@windriver.com>.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by Bill Paul.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30  * THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * $FreeBSD: src/sys/compat/ndis/subr_ndis.c,v 1.125 2010/12/06 20:54:53 bschmidt Exp $
33  */
34
35 /*
36  * This file implements a translation layer between the BSD networking
37  * infrasturcture and Windows(R) NDIS network driver modules. A Windows
38  * NDIS driver calls into several functions in the NDIS.SYS Windows
39  * kernel module and exports a table of functions designed to be called
40  * by the NDIS subsystem. Using the PE loader, we can patch our own
41  * versions of the NDIS routines into a given Windows driver module and
42  * convince the driver that it is in fact running on Windows.
43  *
44  * We provide a table of all our implemented NDIS routines which is patched
45  * into the driver object code. All our exported routines must use the
46  * _stdcall calling convention, since that's what the Windows object code
47  * expects.
48  */
49
50 #include <sys/ctype.h>
51 #include <sys/param.h>
52 #include <sys/types.h>
53 #include <sys/errno.h>
54
55 #include <sys/callout.h>
56 #include <sys/kernel.h>
57 #include <sys/systm.h>
58 #include <sys/malloc.h>
59 #include <sys/lock.h>
60 #include <sys/mutex.h>
61 #include <sys/socket.h>
62 #include <sys/sysctl.h>
63 #include <sys/queue.h>
64 #include <sys/proc.h>
65 #include <sys/filedesc.h>
66 #include <sys/nlookup.h>
67 #include <sys/fcntl.h>
68 #include <sys/vnode.h>
69 #include <sys/kthread.h>
70 #include <sys/linker.h>
71 #include <sys/mount.h>
72 #include <sys/sysproto.h>
73
74 #include <net/if.h>
75 #include <net/if_arp.h>
76 #include <net/ethernet.h>
77 #include <net/if_dl.h>
78 #include <net/if_media.h>
79
80 #include <machine/atomic.h>
81
82 #include <sys/bus.h>
83 #include <sys/rman.h>
84
85 #include <netproto/802_11/ieee80211_var.h>
86 #include <netproto/802_11/ieee80211_ioctl.h>
87
88 #include <bus/pci/pcireg.h>
89 #include <bus/pci/pcivar.h>
90 #include <bus/u4b/usb.h>
91 #include <bus/u4b/usbdi.h>
92
93 #include <emulation/ndis/pe_var.h>
94 #include <emulation/ndis/cfg_var.h>
95 #include <emulation/ndis/resource_var.h>
96 #include <emulation/ndis/ntoskrnl_var.h>
97 #include <emulation/ndis/hal_var.h>
98 #include <emulation/ndis/ndis_var.h>
99 #include <dev/netif/ndis/if_ndisvar.h>
100
101 #include <vm/vm.h>
102 #include <vm/vm_param.h>
103 #include <vm/pmap.h>
104 #include <vm/vm_kern.h>
105 #include <vm/vm_map.h>
106
107 static char ndis_filepath[MAXPATHLEN];
108
109 SYSCTL_STRING(_hw, OID_AUTO, ndis_filepath, CTLFLAG_RW, ndis_filepath,
110         MAXPATHLEN, "Path used by NdisOpenFile() to search for files");
111
112 static void NdisInitializeWrapper(ndis_handle *,
113         driver_object *, void *, void *);
114 static ndis_status NdisMRegisterMiniport(ndis_handle,
115         ndis_miniport_characteristics *, int);
116 static ndis_status NdisAllocateMemoryWithTag(void **,
117         uint32_t, uint32_t);
118 static ndis_status NdisAllocateMemory(void **,
119         uint32_t, uint32_t, ndis_physaddr);
120 static void NdisFreeMemory(void *, uint32_t, uint32_t);
121 static ndis_status NdisMSetAttributesEx(ndis_handle, ndis_handle,
122         uint32_t, uint32_t, ndis_interface_type);
123 static void NdisOpenConfiguration(ndis_status *,
124         ndis_handle *, ndis_handle);
125 static void NdisOpenConfigurationKeyByIndex(ndis_status *,
126         ndis_handle, uint32_t, unicode_string *, ndis_handle *);
127 static void NdisOpenConfigurationKeyByName(ndis_status *,
128         ndis_handle, unicode_string *, ndis_handle *);
129 static ndis_status ndis_encode_parm(ndis_miniport_block *,
130         struct sysctl_oid *, ndis_parm_type, ndis_config_parm **);
131 static ndis_status ndis_decode_parm(ndis_miniport_block *,
132         ndis_config_parm *, char *);
133 static void NdisReadConfiguration(ndis_status *, ndis_config_parm **,
134         ndis_handle, unicode_string *, ndis_parm_type);
135 static void NdisWriteConfiguration(ndis_status *, ndis_handle,
136         unicode_string *, ndis_config_parm *);
137 static void NdisCloseConfiguration(ndis_handle);
138 static void NdisAllocateSpinLock(ndis_spin_lock *);
139 static void NdisFreeSpinLock(ndis_spin_lock *);
140 static void NdisAcquireSpinLock(ndis_spin_lock *);
141 static void NdisReleaseSpinLock(ndis_spin_lock *);
142 static void NdisDprAcquireSpinLock(ndis_spin_lock *);
143 static void NdisDprReleaseSpinLock(ndis_spin_lock *);
144 static void NdisInitializeReadWriteLock(ndis_rw_lock *);
145 static void NdisAcquireReadWriteLock(ndis_rw_lock *,
146         uint8_t, ndis_lock_state *);
147 static void NdisReleaseReadWriteLock(ndis_rw_lock *, ndis_lock_state *);
148 static uint32_t NdisReadPciSlotInformation(ndis_handle, uint32_t,
149         uint32_t, void *, uint32_t);
150 static uint32_t NdisWritePciSlotInformation(ndis_handle, uint32_t,
151         uint32_t, void *, uint32_t);
152 static void NdisWriteErrorLogEntry(ndis_handle, ndis_error_code, uint32_t, ...);
153 static void ndis_map_cb(void *, bus_dma_segment_t *, int, int);
154 static void NdisMStartBufferPhysicalMapping(ndis_handle,
155         ndis_buffer *, uint32_t, uint8_t, ndis_paddr_unit *, uint32_t *);
156 static void NdisMCompleteBufferPhysicalMapping(ndis_handle,
157         ndis_buffer *, uint32_t);
158 static void NdisMInitializeTimer(ndis_miniport_timer *, ndis_handle,
159         ndis_timer_function, void *);
160 static void NdisInitializeTimer(ndis_timer *,
161         ndis_timer_function, void *);
162 static void NdisSetTimer(ndis_timer *, uint32_t);
163 static void NdisMSetPeriodicTimer(ndis_miniport_timer *, uint32_t);
164 static void NdisMCancelTimer(ndis_timer *, uint8_t *);
165 static void ndis_timercall(kdpc *, ndis_miniport_timer *,
166         void *, void *);
167 static void NdisMQueryAdapterResources(ndis_status *, ndis_handle,
168         ndis_resource_list *, uint32_t *);
169 static ndis_status NdisMRegisterIoPortRange(void **,
170         ndis_handle, uint32_t, uint32_t);
171 static void NdisMDeregisterIoPortRange(ndis_handle,
172         uint32_t, uint32_t, void *);
173 static void NdisReadNetworkAddress(ndis_status *, void **,
174         uint32_t *, ndis_handle);
175 static ndis_status NdisQueryMapRegisterCount(uint32_t, uint32_t *);
176 static ndis_status NdisMAllocateMapRegisters(ndis_handle,
177         uint32_t, uint8_t, uint32_t, uint32_t);
178 static void NdisMFreeMapRegisters(ndis_handle);
179 static void ndis_mapshared_cb(void *, bus_dma_segment_t *, int, int);
180 static void NdisMAllocateSharedMemory(ndis_handle, uint32_t,
181         uint8_t, void **, ndis_physaddr *);
182 static void ndis_asyncmem_complete(device_object *, void *);
183 static ndis_status NdisMAllocateSharedMemoryAsync(ndis_handle,
184         uint32_t, uint8_t, void *);
185 static void NdisMFreeSharedMemory(ndis_handle, uint32_t,
186         uint8_t, void *, ndis_physaddr);
187 static ndis_status NdisMMapIoSpace(void **, ndis_handle,
188         ndis_physaddr, uint32_t);
189 static void NdisMUnmapIoSpace(ndis_handle, void *, uint32_t);
190 static uint32_t NdisGetCacheFillSize(void);
191 static void *NdisGetRoutineAddress(unicode_string *);
192 static uint32_t NdisMGetDmaAlignment(ndis_handle);
193 static ndis_status NdisMInitializeScatterGatherDma(ndis_handle,
194         uint8_t, uint32_t);
195 static void NdisUnchainBufferAtFront(ndis_packet *, ndis_buffer **);
196 static void NdisUnchainBufferAtBack(ndis_packet *, ndis_buffer **);
197 static void NdisAllocateBufferPool(ndis_status *,
198         ndis_handle *, uint32_t);
199 static void NdisFreeBufferPool(ndis_handle);
200 static void NdisAllocateBuffer(ndis_status *, ndis_buffer **,
201         ndis_handle, void *, uint32_t);
202 static void NdisFreeBuffer(ndis_buffer *);
203 static uint32_t NdisBufferLength(ndis_buffer *);
204 static void NdisQueryBuffer(ndis_buffer *, void **, uint32_t *);
205 static void NdisQueryBufferSafe(ndis_buffer *, void **,
206         uint32_t *, uint32_t);
207 static void *NdisBufferVirtualAddress(ndis_buffer *);
208 static void *NdisBufferVirtualAddressSafe(ndis_buffer *, uint32_t);
209 static void NdisAdjustBufferLength(ndis_buffer *, int);
210 static uint32_t NdisInterlockedIncrement(uint32_t *);
211 static uint32_t NdisInterlockedDecrement(uint32_t *);
212 static void NdisInitializeEvent(ndis_event *);
213 static void NdisSetEvent(ndis_event *);
214 static void NdisResetEvent(ndis_event *);
215 static uint8_t NdisWaitEvent(ndis_event *, uint32_t);
216 static ndis_status NdisUnicodeStringToAnsiString(ansi_string *,
217         unicode_string *);
218 static ndis_status
219         NdisAnsiStringToUnicodeString(unicode_string *, ansi_string *);
220 static ndis_status NdisMPciAssignResources(ndis_handle,
221         uint32_t, ndis_resource_list **);
222 static ndis_status NdisMRegisterInterrupt(ndis_miniport_interrupt *,
223         ndis_handle, uint32_t, uint32_t, uint8_t,
224         uint8_t, ndis_interrupt_mode);
225 static void NdisMDeregisterInterrupt(ndis_miniport_interrupt *);
226 static void NdisMRegisterAdapterShutdownHandler(ndis_handle, void *,
227         ndis_shutdown_handler);
228 static void NdisMDeregisterAdapterShutdownHandler(ndis_handle);
229 static uint32_t NDIS_BUFFER_TO_SPAN_PAGES(ndis_buffer *);
230 static void NdisGetBufferPhysicalArraySize(ndis_buffer *,
231         uint32_t *);
232 static void NdisQueryBufferOffset(ndis_buffer *,
233         uint32_t *, uint32_t *);
234 static uint32_t NdisReadPcmciaAttributeMemory(ndis_handle,
235         uint32_t, void *, uint32_t);
236 static uint32_t NdisWritePcmciaAttributeMemory(ndis_handle,
237         uint32_t, void *, uint32_t);
238 static list_entry *NdisInterlockedInsertHeadList(list_entry *,
239         list_entry *, ndis_spin_lock *);
240 static list_entry *NdisInterlockedRemoveHeadList(list_entry *,
241         ndis_spin_lock *);
242 static list_entry *NdisInterlockedInsertTailList(list_entry *,
243         list_entry *, ndis_spin_lock *);
244 static uint8_t
245         NdisMSynchronizeWithInterrupt(ndis_miniport_interrupt *,
246         void *, void *);
247 static void NdisGetCurrentSystemTime(uint64_t *);
248 static void NdisGetSystemUpTime(uint32_t *);
249 static uint32_t NdisGetVersion(void);
250 static void NdisInitializeString(unicode_string *, char *);
251 static void NdisInitAnsiString(ansi_string *, char *);
252 static void NdisInitUnicodeString(unicode_string *, uint16_t *);
253 static void NdisFreeString(unicode_string *);
254 static ndis_status NdisMRemoveMiniport(ndis_handle *);
255 static void NdisTerminateWrapper(ndis_handle, void *);
256 static void NdisMGetDeviceProperty(ndis_handle, device_object **,
257         device_object **, device_object **, cm_resource_list *,
258         cm_resource_list *);
259 static void NdisGetFirstBufferFromPacket(ndis_packet *,
260         ndis_buffer **, void **, uint32_t *, uint32_t *);
261 static void NdisGetFirstBufferFromPacketSafe(ndis_packet *,
262         ndis_buffer **, void **, uint32_t *, uint32_t *, uint32_t);
263 static int ndis_find_sym(linker_file_t, char *, char *, caddr_t *);
264 static void NdisOpenFile(ndis_status *, ndis_handle *, uint32_t *,
265         unicode_string *, ndis_physaddr);
266 static void NdisMapFile(ndis_status *, void **, ndis_handle);
267 static void NdisUnmapFile(ndis_handle);
268 static void NdisCloseFile(ndis_handle);
269 static uint8_t NdisSystemProcessorCount(void);
270 static void NdisGetCurrentProcessorCounts(uint32_t *, uint32_t *, uint32_t *);
271 static void NdisMIndicateStatusComplete(ndis_handle);
272 static void NdisMIndicateStatus(ndis_handle, ndis_status,
273         void *, uint32_t);
274 static uint8_t ndis_intr(kinterrupt *, void *);
275 static void ndis_intrhand(kdpc *, ndis_miniport_interrupt *, void *, void *);
276 static funcptr ndis_findwrap(funcptr);
277 static void NdisCopyFromPacketToPacket(ndis_packet *,
278         uint32_t, uint32_t, ndis_packet *, uint32_t, uint32_t *);
279 static void NdisCopyFromPacketToPacketSafe(ndis_packet *,
280         uint32_t, uint32_t, ndis_packet *, uint32_t, uint32_t *, uint32_t);
281 static void NdisIMCopySendPerPacketInfo(ndis_packet *, ndis_packet *);
282 static ndis_status NdisMRegisterDevice(ndis_handle,
283         unicode_string *, unicode_string *, driver_dispatch **,
284         void **, ndis_handle *);
285 static ndis_status NdisMDeregisterDevice(ndis_handle);
286 static ndis_status
287         NdisMQueryAdapterInstanceName(unicode_string *, ndis_handle);
288 static void NdisMRegisterUnloadHandler(ndis_handle, void *);
289 static void dummy(void);
290
291 /*
292  * Some really old drivers do not properly check the return value
293  * from NdisAllocatePacket() and NdisAllocateBuffer() and will
294  * sometimes allocate few more buffers/packets that they originally
295  * requested when they created the pool. To prevent this from being
296  * a problem, we allocate a few extra buffers/packets beyond what
297  * the driver asks for. This #define controls how many.
298  */
299 #define NDIS_POOL_EXTRA         16
300
301 int
302 ndis_libinit(void)
303 {
304         image_patch_table       *patch;
305
306         strcpy(ndis_filepath, "/compat/ndis");
307
308         patch = ndis_functbl;
309         while (patch->ipt_func != NULL) {
310                 windrv_wrap((funcptr)patch->ipt_func,
311                     (funcptr *)&patch->ipt_wrap,
312                     patch->ipt_argcnt, patch->ipt_ftype);
313                 patch++;
314         }
315
316         return (0);
317 }
318
319 int
320 ndis_libfini(void)
321 {
322         image_patch_table       *patch;
323
324         patch = ndis_functbl;
325         while (patch->ipt_func != NULL) {
326                 windrv_unwrap(patch->ipt_wrap);
327                 patch++;
328         }
329
330         return (0);
331 }
332
333 static funcptr
334 ndis_findwrap(funcptr func)
335 {
336         image_patch_table       *patch;
337
338         patch = ndis_functbl;
339         while (patch->ipt_func != NULL) {
340                 if ((funcptr)patch->ipt_func == func)
341                         return((funcptr)patch->ipt_wrap);
342                 patch++;
343         }
344
345         return (NULL);
346 }
347
348 /*
349  * This routine does the messy Windows Driver Model device attachment
350  * stuff on behalf of NDIS drivers. We register our own AddDevice
351  * routine here
352  */
353 static void
354 NdisInitializeWrapper(ndis_handle *wrapper, driver_object *drv, void *path,
355     void *unused)
356 {
357         /*
358          * As of yet, I haven't come up with a compelling
359          * reason to define a private NDIS wrapper structure,
360          * so we use a pointer to the driver object as the
361          * wrapper handle. The driver object has the miniport
362          * characteristics struct for this driver hung off it
363          * via IoAllocateDriverObjectExtension(), and that's
364          * really all the private data we need.
365          */
366
367         *wrapper = drv;
368
369         /*
370          * If this was really Windows, we'd be registering dispatch
371          * routines for the NDIS miniport module here, but we're
372          * not Windows so all we really need to do is set up an
373          * AddDevice function that'll be invoked when a new device
374          * instance appears.
375          */
376
377         drv->dro_driverext->dre_adddevicefunc = NdisAddDevice;
378 }
379
380 static void
381 NdisTerminateWrapper(ndis_handle handle, void *syspec)
382 {
383         /* Nothing to see here, move along. */
384 }
385
386 static ndis_status
387 NdisMRegisterMiniport(ndis_handle handle,
388     ndis_miniport_characteristics *characteristics, int len)
389 {
390         ndis_miniport_characteristics   *ch = NULL;
391         driver_object           *drv;
392
393         drv = (driver_object *)handle;
394
395         /*
396          * We need to save the NDIS miniport characteristics
397          * somewhere. This data is per-driver, not per-device
398          * (all devices handled by the same driver have the
399          * same characteristics) so we hook it onto the driver
400          * object using IoAllocateDriverObjectExtension().
401          * The extra extension info is automagically deleted when
402          * the driver is unloaded (see windrv_unload()).
403          */
404
405         if (IoAllocateDriverObjectExtension(drv, (void *)1,
406             sizeof(ndis_miniport_characteristics), (void **)&ch) !=
407             STATUS_SUCCESS) {
408                 return (NDIS_STATUS_RESOURCES);
409         }
410
411         bzero((char *)ch, sizeof(ndis_miniport_characteristics));
412
413         bcopy((char *)characteristics, (char *)ch, len);
414
415         if (ch->nmc_version_major < 5 || ch->nmc_version_minor < 1) {
416                 ch->nmc_shutdown_handler = NULL;
417                 ch->nmc_canceltxpkts_handler = NULL;
418                 ch->nmc_pnpevent_handler = NULL;
419         }
420
421         return (NDIS_STATUS_SUCCESS);
422 }
423
424 static ndis_status
425 NdisAllocateMemoryWithTag(void **vaddr, uint32_t len, uint32_t tag)
426 {
427         void                    *mem;
428
429         mem = ExAllocatePoolWithTag(NonPagedPool, len, tag);
430         if (mem == NULL) {
431                 return (NDIS_STATUS_RESOURCES);
432         }
433         *vaddr = mem;
434
435         return (NDIS_STATUS_SUCCESS);
436 }
437
438 static ndis_status
439 NdisAllocateMemory(void **vaddr, uint32_t len, uint32_t flags,
440     ndis_physaddr highaddr)
441 {
442         void                    *mem;
443
444         mem = ExAllocatePoolWithTag(NonPagedPool, len, 0);
445         if (mem == NULL)
446                 return (NDIS_STATUS_RESOURCES);
447         *vaddr = mem;
448
449         return (NDIS_STATUS_SUCCESS);
450 }
451
452 static void
453 NdisFreeMemory(void *vaddr, uint32_t len, uint32_t flags)
454 {
455         if (len == 0)
456                 return;
457
458         ExFreePool(vaddr);
459 }
460
461 static ndis_status
462 NdisMSetAttributesEx(ndis_handle adapter_handle, ndis_handle adapter_ctx,
463     uint32_t hangsecs, uint32_t flags, ndis_interface_type iftype)
464 {
465         ndis_miniport_block             *block;
466
467         /*
468          * Save the adapter context, we need it for calling
469          * the driver's internal functions.
470          */
471         block = (ndis_miniport_block *)adapter_handle;
472         block->nmb_miniportadapterctx = adapter_ctx;
473         block->nmb_checkforhangsecs = hangsecs;
474         block->nmb_flags = flags;
475
476         return (NDIS_STATUS_SUCCESS);
477 }
478
479 static void
480 NdisOpenConfiguration(ndis_status *status, ndis_handle *cfg,
481     ndis_handle wrapctx)
482 {
483         *cfg = wrapctx;
484         *status = NDIS_STATUS_SUCCESS;
485 }
486
487 static void
488 NdisOpenConfigurationKeyByName(ndis_status *status, ndis_handle cfg,
489     unicode_string *subkey, ndis_handle *subhandle)
490 {
491         *subhandle = cfg;
492         *status = NDIS_STATUS_SUCCESS;
493 }
494
495 static void
496 NdisOpenConfigurationKeyByIndex(ndis_status *status, ndis_handle cfg,
497     uint32_t idx, unicode_string *subkey, ndis_handle *subhandle)
498 {
499         *status = NDIS_STATUS_FAILURE;
500 }
501
502 static ndis_status
503 ndis_encode_parm(ndis_miniport_block *block, struct sysctl_oid *oid,
504     ndis_parm_type type, ndis_config_parm **parm)
505 {
506         ndis_config_parm        *p;
507         ndis_parmlist_entry     *np;
508         unicode_string          *us;
509         ansi_string             as;
510         int                     base = 0;
511         uint32_t                val;
512         char                    tmp[32];
513
514         np = ExAllocatePoolWithTag(NonPagedPool,
515             sizeof(ndis_parmlist_entry), 0);
516         if (np == NULL)
517                 return (NDIS_STATUS_RESOURCES);
518         InsertHeadList((&block->nmb_parmlist), (&np->np_list));
519         *parm = p = &np->np_parm;
520
521         switch(type) {
522         case ndis_parm_string:
523                 /* See if this might be a number. */
524                 val = strtoul((char *)oid->oid_arg1, NULL, 10);
525                 us = &p->ncp_parmdata.ncp_stringdata;
526                 p->ncp_type = ndis_parm_string;
527                 if (val) {
528                         ksnprintf(tmp, 32, "%x", val);
529                         RtlInitAnsiString(&as, tmp);
530                 } else {
531                         RtlInitAnsiString(&as, (char *)oid->oid_arg1);
532                 }
533
534                 if (RtlAnsiStringToUnicodeString(us, &as, TRUE)) {
535                         ExFreePool(np);
536                         return (NDIS_STATUS_RESOURCES);
537                 }
538                 break;
539         case ndis_parm_int:
540                 if (strncmp((char *)oid->oid_arg1, "0x", 2) == 0)
541                         base = 16;
542                 else
543                         base = 10;
544                 p->ncp_type = ndis_parm_int;
545                 p->ncp_parmdata.ncp_intdata =
546                     strtol((char *)oid->oid_arg1, NULL, base);
547                 break;
548         case ndis_parm_hexint:
549 #ifdef notdef
550                 if (strncmp((char *)oid->oid_arg1, "0x", 2) == 0)
551                         base = 16;
552                 else
553                         base = 10;
554 #endif
555                 base = 16;
556                 p->ncp_type = ndis_parm_hexint;
557                 p->ncp_parmdata.ncp_intdata =
558                     strtoul((char *)oid->oid_arg1, NULL, base);
559                 break;
560         default:
561                 return (NDIS_STATUS_FAILURE);
562                 break;
563         }
564
565         return (NDIS_STATUS_SUCCESS);
566 }
567
568 static void
569 NdisReadConfiguration(ndis_status *status, ndis_config_parm **parm,
570     ndis_handle cfg, unicode_string *key, ndis_parm_type type)
571 {
572         char                    *keystr = NULL;
573         ndis_miniport_block     *block;
574         struct ndis_softc       *sc;
575         struct sysctl_oid       *oidp;
576         struct sysctl_ctx_entry *e;
577         ansi_string             as;
578
579         block = (ndis_miniport_block *)cfg;
580         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
581
582         if (key->us_len == 0 || key->us_buf == NULL) {
583                 *status = NDIS_STATUS_FAILURE;
584                 return;
585         }
586
587         if (RtlUnicodeStringToAnsiString(&as, key, TRUE)) {
588                 *status = NDIS_STATUS_RESOURCES;
589                 return;
590         }
591
592         keystr = as.as_buf;
593
594         /*
595          * See if registry key is already in a list of known keys
596          * included with the driver.
597          */
598         TAILQ_FOREACH(e, device_get_sysctl_ctx(sc->ndis_dev), link) {
599                 oidp = e->entry;
600                 if (strcasecmp(oidp->oid_name, keystr) == 0) {
601                         if (strcmp((char *)oidp->oid_arg1, "UNSET") == 0) {
602                                 RtlFreeAnsiString(&as);
603                                 *status = NDIS_STATUS_FAILURE;
604                                 return;
605                         }
606
607                         *status = ndis_encode_parm(block, oidp, type, parm);
608                         RtlFreeAnsiString(&as);
609                         return;
610                 }
611         }
612
613         /*
614          * If the key didn't match, add it to the list of dynamically
615          * created ones. Sometimes, drivers refer to registry keys
616          * that aren't documented in their .INF files. These keys
617          * are supposed to be created by some sort of utility or
618          * control panel snap-in that comes with the driver software.
619          * Sometimes it's useful to be able to manipulate these.
620          * If the driver requests the key in the form of a string,
621          * make its default value an empty string, otherwise default
622          * it to "0".
623          */
624
625         if (type == ndis_parm_int || type == ndis_parm_hexint)
626                 ndis_add_sysctl(sc, keystr, "(dynamic integer key)",
627                     "UNSET", CTLFLAG_RW);
628         else
629                 ndis_add_sysctl(sc, keystr, "(dynamic string key)",
630                     "UNSET", CTLFLAG_RW);
631
632         RtlFreeAnsiString(&as);
633         *status = NDIS_STATUS_FAILURE;
634 }
635
636 static ndis_status
637 ndis_decode_parm(ndis_miniport_block *block, ndis_config_parm *parm, char *val)
638 {
639         unicode_string          *ustr;
640         ansi_string             as;
641
642         switch(parm->ncp_type) {
643         case ndis_parm_string:
644                 ustr = &parm->ncp_parmdata.ncp_stringdata;
645                 if (RtlUnicodeStringToAnsiString(&as, ustr, TRUE))
646                         return (NDIS_STATUS_RESOURCES);
647                 bcopy(as.as_buf, val, as.as_len);
648                 RtlFreeAnsiString(&as);
649                 break;
650         case ndis_parm_int:
651                 ksprintf(val, "%d", parm->ncp_parmdata.ncp_intdata);
652                 break;
653         case ndis_parm_hexint:
654                 ksprintf(val, "%xu", parm->ncp_parmdata.ncp_intdata);
655                 break;
656         default:
657                 return (NDIS_STATUS_FAILURE);
658                 break;
659         }
660         return (NDIS_STATUS_SUCCESS);
661 }
662
663 static void
664 NdisWriteConfiguration(ndis_status *status, ndis_handle cfg,
665     unicode_string *key, ndis_config_parm *parm)
666 {
667         ansi_string             as;
668         char                    *keystr = NULL;
669         ndis_miniport_block     *block;
670         struct ndis_softc       *sc;
671         struct sysctl_oid       *oidp;
672         struct sysctl_ctx_entry *e;
673         char                    val[256];
674
675         block = (ndis_miniport_block *)cfg;
676         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
677
678         if (RtlUnicodeStringToAnsiString(&as, key, TRUE)) {
679                 *status = NDIS_STATUS_RESOURCES;
680                 return;
681         }
682
683         keystr = as.as_buf;
684
685         /* Decode the parameter into a string. */
686         bzero(val, sizeof(val));
687         *status = ndis_decode_parm(block, parm, val);
688         if (*status != NDIS_STATUS_SUCCESS) {
689                 RtlFreeAnsiString(&as);
690                 return;
691         }
692
693         /* See if the key already exists. */
694
695         TAILQ_FOREACH(e, device_get_sysctl_ctx(sc->ndis_dev), link) {
696                 oidp = e->entry;
697                 if (strcasecmp(oidp->oid_name, keystr) == 0) {
698                         /* Found it, set the value. */
699                         strcpy((char *)oidp->oid_arg1, val);
700                         RtlFreeAnsiString(&as);
701                         return;
702                 }
703         }
704
705         /* Not found, add a new key with the specified value. */
706         ndis_add_sysctl(sc, keystr, "(dynamically set key)",
707                     val, CTLFLAG_RW);
708
709         RtlFreeAnsiString(&as);
710         *status = NDIS_STATUS_SUCCESS;
711 }
712
713 static void
714 NdisCloseConfiguration(ndis_handle cfg)
715 {
716         list_entry              *e;
717         ndis_parmlist_entry     *pe;
718         ndis_miniport_block     *block;
719         ndis_config_parm        *p;
720
721         block = (ndis_miniport_block *)cfg;
722
723         while (!IsListEmpty(&block->nmb_parmlist)) {
724                 e = RemoveHeadList(&block->nmb_parmlist);
725                 pe = CONTAINING_RECORD(e, ndis_parmlist_entry, np_list);
726                 p = &pe->np_parm;
727                 if (p->ncp_type == ndis_parm_string)
728                         RtlFreeUnicodeString(&p->ncp_parmdata.ncp_stringdata);
729                 ExFreePool(e);
730         }
731 }
732
733 /*
734  * Initialize a Windows spinlock.
735  */
736 static void
737 NdisAllocateSpinLock(ndis_spin_lock *lock)
738 {
739         KeInitializeSpinLock(&lock->nsl_spinlock);
740         lock->nsl_kirql = 0;
741 }
742
743 /*
744  * Destroy a Windows spinlock. This is a no-op for now. There are two reasons
745  * for this. One is that it's sort of superfluous: we don't have to do anything
746  * special to deallocate the spinlock. The other is that there are some buggy
747  * drivers which call NdisFreeSpinLock() _after_ calling NdisFreeMemory() on
748  * the block of memory in which the spinlock resides. (Yes, ADMtek, I'm
749  * talking to you.)
750  */
751 static void
752 NdisFreeSpinLock(ndis_spin_lock *lock)
753 {
754 #ifdef notdef
755         KeInitializeSpinLock(&lock->nsl_spinlock);
756         lock->nsl_kirql = 0;
757 #endif
758 }
759
760 /*
761  * Acquire a spinlock from IRQL <= DISPATCH_LEVEL.
762  */
763
764 static void
765 NdisAcquireSpinLock(ndis_spin_lock *lock)
766 {
767         KeAcquireSpinLock(&lock->nsl_spinlock, &lock->nsl_kirql);
768 }
769
770 /*
771  * Release a spinlock from IRQL == DISPATCH_LEVEL.
772  */
773
774 static void
775 NdisReleaseSpinLock(ndis_spin_lock *lock)
776 {
777         KeReleaseSpinLock(&lock->nsl_spinlock, lock->nsl_kirql);
778 }
779
780 /*
781  * Acquire a spinlock when already running at IRQL == DISPATCH_LEVEL.
782  */
783 static void
784 NdisDprAcquireSpinLock(ndis_spin_lock *lock)
785 {
786         KeAcquireSpinLockAtDpcLevel(&lock->nsl_spinlock);
787 }
788
789 /*
790  * Release a spinlock without leaving IRQL == DISPATCH_LEVEL.
791  */
792 static void
793 NdisDprReleaseSpinLock(ndis_spin_lock *lock)
794 {
795         KeReleaseSpinLockFromDpcLevel(&lock->nsl_spinlock);
796 }
797
798 static void
799 NdisInitializeReadWriteLock(ndis_rw_lock *lock)
800 {
801         KeInitializeSpinLock(&lock->nrl_spinlock);
802         bzero((char *)&lock->nrl_rsvd, sizeof(lock->nrl_rsvd));
803 }
804
805 static void
806 NdisAcquireReadWriteLock(ndis_rw_lock *lock, uint8_t writeacc,
807     ndis_lock_state *state)
808 {
809         if (writeacc == TRUE) {
810                 KeAcquireSpinLock(&lock->nrl_spinlock, &state->nls_oldirql);
811                 lock->nrl_rsvd[0]++;
812         } else
813                 lock->nrl_rsvd[1]++;
814 }
815
816 static void
817 NdisReleaseReadWriteLock(ndis_rw_lock *lock, ndis_lock_state *state)
818 {
819         if (lock->nrl_rsvd[0]) {
820                 lock->nrl_rsvd[0]--;
821                 KeReleaseSpinLock(&lock->nrl_spinlock, state->nls_oldirql);
822         } else
823                 lock->nrl_rsvd[1]--;
824 }
825
826 static uint32_t
827 NdisReadPciSlotInformation(ndis_handle adapter, uint32_t slot, uint32_t offset,
828     void *buf, uint32_t len)
829 {
830         ndis_miniport_block     *block;
831         int                     i;
832         char                    *dest;
833         device_t                dev;
834
835         block = (ndis_miniport_block *)adapter;
836         dest = buf;
837         if (block == NULL)
838                 return (0);
839
840         dev = block->nmb_physdeviceobj->do_devext;
841
842         /*
843          * I have a test system consisting of a Sun w2100z
844          * dual 2.4Ghz Opteron machine and an Atheros 802.11a/b/g
845          * "Aries" miniPCI NIC. (The NIC is installed in the
846          * machine using a miniPCI to PCI bus adapter card.)
847          * When running in SMP mode, I found that
848          * performing a large number of consecutive calls to
849          * NdisReadPciSlotInformation() would result in a
850          * sudden system reset (or in some cases a freeze).
851          * My suspicion is that the multiple reads are somehow
852          * triggering a fatal PCI bus error that leads to a
853          * machine check. The 1us delay in the loop below
854          * seems to prevent this problem.
855          */
856
857         for (i = 0; i < len; i++) {
858                 DELAY(1);
859                 dest[i] = pci_read_config(dev, i + offset, 1);
860         }
861
862         return (len);
863 }
864
865 static uint32_t
866 NdisWritePciSlotInformation(ndis_handle adapter, uint32_t slot,
867     uint32_t offset, void *buf, uint32_t len)
868 {
869         ndis_miniport_block     *block;
870         int                     i;
871         char                    *dest;
872         device_t                dev;
873
874         block = (ndis_miniport_block *)adapter;
875         dest = buf;
876
877         if (block == NULL)
878                 return (0);
879
880         dev = block->nmb_physdeviceobj->do_devext;
881         for (i = 0; i < len; i++) {
882                 DELAY(1);
883                 pci_write_config(dev, i + offset, dest[i], 1);
884         }
885
886         return (len);
887 }
888
889 /*
890  * The errorlog routine uses a variable argument list, so we
891  * have to declare it this way.
892  */
893
894 #define ERRMSGLEN 512
895 static void
896 NdisWriteErrorLogEntry(ndis_handle adapter, ndis_error_code code,
897         uint32_t numerrors, ...)
898 {
899         ndis_miniport_block     *block;
900         __va_list               ap;
901         int                     i, error;
902         char                    *str = NULL;
903         uint16_t                flags;
904         device_t                dev;
905         driver_object           *drv;
906         struct ndis_softc       *sc;
907         struct ifnet            *ifp;
908         unicode_string          us;
909         ansi_string             as = { 0, 0, NULL };
910
911         block = (ndis_miniport_block *)adapter;
912         dev = block->nmb_physdeviceobj->do_devext;
913         drv = block->nmb_deviceobj->do_drvobj;
914         sc = device_get_softc(dev);
915         ifp = sc->ifp;
916
917         if (ifp != NULL && ifp->if_flags & IFF_DEBUG) {
918                 error = pe_get_message((vm_offset_t)drv->dro_driverstart,
919                     code, &str, &i, &flags);
920                 if (error == 0) {
921                         if (flags & MESSAGE_RESOURCE_UNICODE) {
922                                 RtlInitUnicodeString(&us, (uint16_t *)str);
923                                 if (RtlUnicodeStringToAnsiString(&as,
924                                     &us, TRUE) == STATUS_SUCCESS)
925                                         str = as.as_buf;
926                                 else
927                                         str = NULL;
928                         }
929                 }
930         }
931
932         device_printf(dev, "NDIS ERROR: %x (%s)\n", code,
933             str == NULL ? "unknown error" : str);
934
935         if (ifp != NULL && ifp->if_flags & IFF_DEBUG) {
936                 device_printf(dev, "NDIS NUMERRORS: %x\n", numerrors);
937                 __va_start(ap, numerrors);
938                 for (i = 0; i < numerrors; i++)
939                         device_printf(dev, "argptr: %p\n",
940                             __va_arg(ap, void *));
941                 __va_end(ap);
942         }
943
944         if (as.as_len)
945                 RtlFreeAnsiString(&as);
946 }
947
948 static void
949 ndis_map_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
950 {
951         struct ndis_map_arg     *ctx;
952         int                     i;
953
954         if (error)
955                 return;
956
957         ctx = arg;
958
959         for (i = 0; i < nseg; i++) {
960                 ctx->nma_fraglist[i].npu_physaddr.np_quad = segs[i].ds_addr;
961                 ctx->nma_fraglist[i].npu_len = segs[i].ds_len;
962         }
963
964         ctx->nma_cnt = nseg;
965 }
966
967 static void
968 NdisMStartBufferPhysicalMapping(ndis_handle adapter, ndis_buffer *buf,
969     uint32_t mapreg, uint8_t writedev, ndis_paddr_unit *addrarray,
970     uint32_t *arraysize)
971 {
972         ndis_miniport_block     *block;
973         struct ndis_softc       *sc;
974         struct ndis_map_arg     nma;
975         bus_dmamap_t            map;
976         int                     error;
977
978         if (adapter == NULL)
979                 return;
980
981         block = (ndis_miniport_block *)adapter;
982         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
983
984         if (mapreg > sc->ndis_mmapcnt)
985                 return;
986
987         map = sc->ndis_mmaps[mapreg];
988         nma.nma_fraglist = addrarray;
989
990         error = bus_dmamap_load(sc->ndis_mtag, map,
991             MmGetMdlVirtualAddress(buf), MmGetMdlByteCount(buf), ndis_map_cb,
992             (void *)&nma, BUS_DMA_NOWAIT);
993
994         if (error)
995                 return;
996
997         bus_dmamap_sync(sc->ndis_mtag, map,
998             writedev ? BUS_DMASYNC_PREWRITE : BUS_DMASYNC_PREREAD);
999
1000         *arraysize = nma.nma_cnt;
1001 }
1002
1003 static void
1004 NdisMCompleteBufferPhysicalMapping(ndis_handle adapter, ndis_buffer *buf,
1005     uint32_t mapreg)
1006 {
1007         ndis_miniport_block     *block;
1008         struct ndis_softc       *sc;
1009         bus_dmamap_t            map;
1010
1011         if (adapter == NULL)
1012                 return;
1013
1014         block = (ndis_miniport_block *)adapter;
1015         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
1016
1017         if (mapreg > sc->ndis_mmapcnt)
1018                 return;
1019
1020         map = sc->ndis_mmaps[mapreg];
1021
1022         bus_dmamap_sync(sc->ndis_mtag, map,
1023             BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
1024
1025         bus_dmamap_unload(sc->ndis_mtag, map);
1026 }
1027
1028 /*
1029  * This is an older (?) timer init routine which doesn't
1030  * accept a miniport context handle. Serialized miniports should
1031  * never call this function.
1032  */
1033
1034 static void
1035 NdisInitializeTimer(ndis_timer *timer, ndis_timer_function func, void *ctx)
1036 {
1037         KeInitializeTimer(&timer->nt_ktimer);
1038         KeInitializeDpc(&timer->nt_kdpc, func, ctx);
1039         KeSetImportanceDpc(&timer->nt_kdpc, KDPC_IMPORTANCE_LOW);
1040 }
1041
1042 static void
1043 ndis_timercall(kdpc *dpc, ndis_miniport_timer *timer, void *sysarg1,
1044     void *sysarg2)
1045 {
1046         /*
1047          * Since we're called as a DPC, we should be running
1048          * at DISPATCH_LEVEL here. This means to acquire the
1049          * spinlock, we can use KeAcquireSpinLockAtDpcLevel()
1050          * rather than KeAcquireSpinLock().
1051          */
1052         if (NDIS_SERIALIZED(timer->nmt_block))
1053                 KeAcquireSpinLockAtDpcLevel(&timer->nmt_block->nmb_lock);
1054
1055         MSCALL4(timer->nmt_timerfunc, dpc, timer->nmt_timerctx,
1056             sysarg1, sysarg2);
1057
1058         if (NDIS_SERIALIZED(timer->nmt_block))
1059                 KeReleaseSpinLockFromDpcLevel(&timer->nmt_block->nmb_lock);
1060 }
1061
1062 /*
1063  * For a long time I wondered why there were two NDIS timer initialization
1064  * routines, and why this one needed an NDIS_MINIPORT_TIMER and the
1065  * MiniportAdapterHandle. The NDIS_MINIPORT_TIMER has its own callout
1066  * function and context pointers separate from those in the DPC, which
1067  * allows for another level of indirection: when the timer fires, we
1068  * can have our own timer function invoked, and from there we can call
1069  * the driver's function. But why go to all that trouble? Then it hit
1070  * me: for serialized miniports, the timer callouts are not re-entrant.
1071  * By trapping the callouts and having access to the MiniportAdapterHandle,
1072  * we can protect the driver callouts by acquiring the NDIS serialization
1073  * lock. This is essential for allowing serialized miniports to work
1074  * correctly on SMP systems. On UP hosts, setting IRQL to DISPATCH_LEVEL
1075  * is enough to prevent other threads from pre-empting you, but with
1076  * SMP, you must acquire a lock as well, otherwise the other CPU is
1077  * free to clobber you.
1078  */
1079 static void
1080 NdisMInitializeTimer(ndis_miniport_timer *timer, ndis_handle handle,
1081     ndis_timer_function func, void *ctx)
1082 {
1083         /* Save the driver's funcptr and context */
1084
1085         timer->nmt_timerfunc = func;
1086         timer->nmt_timerctx = ctx;
1087         timer->nmt_block = handle;
1088
1089         /*
1090          * Set up the timer so it will call our intermediate DPC.
1091          * Be sure to use the wrapped entry point, since
1092          * ntoskrnl_run_dpc() expects to invoke a function with
1093          * Microsoft calling conventions.
1094          */
1095         KeInitializeTimer(&timer->nmt_ktimer);
1096         KeInitializeDpc(&timer->nmt_kdpc,
1097             ndis_findwrap((funcptr)ndis_timercall), timer);
1098         timer->nmt_ktimer.k_dpc = &timer->nmt_kdpc;
1099 }
1100
1101 /*
1102  * In Windows, there's both an NdisMSetTimer() and an NdisSetTimer(),
1103  * but the former is just a macro wrapper around the latter.
1104  */
1105 static void
1106 NdisSetTimer(ndis_timer *timer, uint32_t msecs)
1107 {
1108         /*
1109          * KeSetTimer() wants the period in
1110          * hundred nanosecond intervals.
1111          */
1112         KeSetTimer(&timer->nt_ktimer,
1113             ((int64_t)msecs * -10000), &timer->nt_kdpc);
1114 }
1115
1116 static void
1117 NdisMSetPeriodicTimer(ndis_miniport_timer *timer, uint32_t msecs)
1118 {
1119         KeSetTimerEx(&timer->nmt_ktimer,
1120             ((int64_t)msecs * -10000), msecs, &timer->nmt_kdpc);
1121 }
1122
1123 /*
1124  * Technically, this is really NdisCancelTimer(), but we also
1125  * (ab)use it for NdisMCancelTimer(), since in our implementation
1126  * we don't need the extra info in the ndis_miniport_timer
1127  * structure just to cancel a timer.
1128  */
1129
1130 static void
1131 NdisMCancelTimer(ndis_timer *timer, uint8_t *cancelled)
1132 {
1133
1134         *cancelled = KeCancelTimer(&timer->nt_ktimer);
1135 }
1136
1137 static void
1138 NdisMQueryAdapterResources(ndis_status *status, ndis_handle adapter,
1139     ndis_resource_list *list, uint32_t *buflen)
1140 {
1141         ndis_miniport_block     *block;
1142         struct ndis_softc       *sc;
1143         int                     rsclen;
1144
1145         block = (ndis_miniport_block *)adapter;
1146         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
1147
1148         rsclen = sizeof(ndis_resource_list) +
1149             (sizeof(cm_partial_resource_desc) * (sc->ndis_rescnt - 1));
1150         if (*buflen < rsclen) {
1151                 *buflen = rsclen;
1152                 *status = NDIS_STATUS_INVALID_LENGTH;
1153                 return;
1154         }
1155
1156         bcopy((char *)block->nmb_rlist, (char *)list, rsclen);
1157         *status = NDIS_STATUS_SUCCESS;
1158 }
1159
1160 static ndis_status
1161 NdisMRegisterIoPortRange(void **offset, ndis_handle adapter, uint32_t port,
1162     uint32_t numports)
1163 {
1164         struct ndis_miniport_block      *block;
1165         struct ndis_softc       *sc;
1166
1167         if (adapter == NULL)
1168                 return (NDIS_STATUS_FAILURE);
1169
1170         block = (ndis_miniport_block *)adapter;
1171         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
1172
1173         if (sc->ndis_res_io == NULL)
1174                 return (NDIS_STATUS_FAILURE);
1175
1176         /* Don't let the device map more ports than we have. */
1177         if (rman_get_size(sc->ndis_res_io) < numports)
1178                 return (NDIS_STATUS_INVALID_LENGTH);
1179
1180         *offset = (void *)rman_get_start(sc->ndis_res_io);
1181
1182         return (NDIS_STATUS_SUCCESS);
1183 }
1184
1185 static void
1186 NdisMDeregisterIoPortRange(ndis_handle adapter, uint32_t port,
1187     uint32_t numports, void *offset)
1188 {
1189 }
1190
1191 static void
1192 NdisReadNetworkAddress(ndis_status *status, void **addr, uint32_t *addrlen,
1193     ndis_handle adapter)
1194 {
1195         struct ndis_softc       *sc;
1196         ndis_miniport_block     *block;
1197         uint8_t                 empty[] = { 0, 0, 0, 0, 0, 0 };
1198
1199         block = (ndis_miniport_block *)adapter;
1200         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
1201         if (sc->ifp == NULL) {
1202                 *status = NDIS_STATUS_FAILURE;
1203                 return;
1204         }
1205
1206         if (sc->ifp->if_lladdr == NULL ||
1207             bcmp(IF_LLADDR(sc->ifp), empty, ETHER_ADDR_LEN) == 0)
1208                 *status = NDIS_STATUS_FAILURE;
1209         else {
1210                 *addr = IF_LLADDR(sc->ifp);
1211                 *addrlen = ETHER_ADDR_LEN;
1212                 *status = NDIS_STATUS_SUCCESS;
1213         }
1214 }
1215
1216 static ndis_status
1217 NdisQueryMapRegisterCount(uint32_t bustype, uint32_t *cnt)
1218 {
1219         *cnt = 8192;
1220         return (NDIS_STATUS_SUCCESS);
1221 }
1222
1223 static ndis_status
1224 NdisMAllocateMapRegisters(ndis_handle adapter, uint32_t dmachannel,
1225     uint8_t dmasize, uint32_t physmapneeded, uint32_t maxmap)
1226 {
1227         struct ndis_softc       *sc;
1228         ndis_miniport_block     *block;
1229         int                     error, i, nseg = NDIS_MAXSEG;
1230
1231         block = (ndis_miniport_block *)adapter;
1232         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
1233
1234         sc->ndis_mmaps = kmalloc(sizeof(bus_dmamap_t) * physmapneeded,
1235             M_DEVBUF, M_NOWAIT|M_ZERO);
1236
1237         if (sc->ndis_mmaps == NULL)
1238                 return (NDIS_STATUS_RESOURCES);
1239
1240         error = bus_dma_tag_create(sc->ndis_parent_tag, ETHER_ALIGN, 0,
1241             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
1242             NULL, maxmap * nseg, nseg, maxmap, BUS_DMA_ALLOCNOW,
1243             &sc->ndis_mtag);
1244
1245         if (error) {
1246                 kfree(sc->ndis_mmaps, M_DEVBUF);
1247                 return (NDIS_STATUS_RESOURCES);
1248         }
1249
1250         for (i = 0; i < physmapneeded; i++)
1251                 bus_dmamap_create(sc->ndis_mtag, 0, &sc->ndis_mmaps[i]);
1252
1253         sc->ndis_mmapcnt = physmapneeded;
1254
1255         return (NDIS_STATUS_SUCCESS);
1256 }
1257
1258 static void
1259 NdisMFreeMapRegisters(ndis_handle adapter)
1260 {
1261         struct ndis_softc       *sc;
1262         ndis_miniport_block     *block;
1263         int                     i;
1264
1265         block = (ndis_miniport_block *)adapter;
1266         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
1267
1268         for (i = 0; i < sc->ndis_mmapcnt; i++)
1269                 bus_dmamap_destroy(sc->ndis_mtag, sc->ndis_mmaps[i]);
1270
1271         kfree(sc->ndis_mmaps, M_DEVBUF);
1272
1273         bus_dma_tag_destroy(sc->ndis_mtag);
1274 }
1275
1276 static void
1277 ndis_mapshared_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1278 {
1279         ndis_physaddr           *p;
1280
1281         if (error || nseg > 1)
1282                 return;
1283
1284         p = arg;
1285
1286         p->np_quad = segs[0].ds_addr;
1287 }
1288
1289 /*
1290  * This maps to bus_dmamem_alloc().
1291  */
1292
1293 static void
1294 NdisMAllocateSharedMemory(ndis_handle adapter, uint32_t len, uint8_t cached,
1295     void **vaddr, ndis_physaddr *paddr)
1296 {
1297         ndis_miniport_block     *block;
1298         struct ndis_softc       *sc;
1299         struct ndis_shmem       *sh;
1300         int                     error;
1301
1302         if (adapter == NULL)
1303                 return;
1304
1305         block = (ndis_miniport_block *)adapter;
1306         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
1307
1308         sh = kmalloc(sizeof(struct ndis_shmem), M_DEVBUF, M_NOWAIT|M_ZERO);
1309         if (sh == NULL)
1310                 return;
1311
1312         InitializeListHead(&sh->ndis_list);
1313
1314         /*
1315          * When performing shared memory allocations, create a tag
1316          * with a lowaddr limit that restricts physical memory mappings
1317          * so that they all fall within the first 1GB of memory.
1318          * At least one device/driver combination (Linksys Instant
1319          * Wireless PCI Card V2.7, Broadcom 802.11b) seems to have
1320          * problems with performing DMA operations with physical
1321          * addresses that lie above the 1GB mark. I don't know if this
1322          * is a hardware limitation or if the addresses are being
1323          * truncated within the driver, but this seems to be the only
1324          * way to make these cards work reliably in systems with more
1325          * than 1GB of physical memory.
1326          */
1327
1328         error = bus_dma_tag_create(sc->ndis_parent_tag, 64,
1329             0, NDIS_BUS_SPACE_SHARED_MAXADDR, BUS_SPACE_MAXADDR, NULL,
1330             NULL, len, 1, len, BUS_DMA_ALLOCNOW, &sh->ndis_stag);
1331
1332         if (error) {
1333                 kfree(sh, M_DEVBUF);
1334                 return;
1335         }
1336
1337         error = bus_dmamem_alloc(sh->ndis_stag, vaddr,
1338             BUS_DMA_NOWAIT | BUS_DMA_ZERO, &sh->ndis_smap);
1339
1340         if (error) {
1341                 bus_dma_tag_destroy(sh->ndis_stag);
1342                 kfree(sh, M_DEVBUF);
1343                 return;
1344         }
1345
1346         error = bus_dmamap_load(sh->ndis_stag, sh->ndis_smap, *vaddr,
1347             len, ndis_mapshared_cb, (void *)paddr, BUS_DMA_NOWAIT);
1348
1349         if (error) {
1350                 bus_dmamem_free(sh->ndis_stag, *vaddr, sh->ndis_smap);
1351                 bus_dma_tag_destroy(sh->ndis_stag);
1352                 kfree(sh, M_DEVBUF);
1353                 return;
1354         }
1355
1356         /*
1357          * Save the physical address along with the source address.
1358          * The AirGo MIMO driver will call NdisMFreeSharedMemory()
1359          * with a bogus virtual address sometimes, but with a valid
1360          * physical address. To keep this from causing trouble, we
1361          * use the physical address to as a sanity check in case
1362          * searching based on the virtual address fails.
1363          */
1364
1365         NDIS_LOCK(sc);
1366         sh->ndis_paddr.np_quad = paddr->np_quad;
1367         sh->ndis_saddr = *vaddr;
1368         InsertHeadList((&sc->ndis_shlist), (&sh->ndis_list));
1369         NDIS_UNLOCK(sc);
1370 }
1371
1372 struct ndis_allocwork {
1373         uint32_t                na_len;
1374         uint8_t                 na_cached;
1375         void                    *na_ctx;
1376         io_workitem             *na_iw;
1377 };
1378
1379 static void
1380 ndis_asyncmem_complete(device_object *dobj, void *arg)
1381 {
1382         ndis_miniport_block     *block;
1383         struct ndis_softc       *sc;
1384         struct ndis_allocwork   *w;
1385         void                    *vaddr;
1386         ndis_physaddr           paddr;
1387         ndis_allocdone_handler  donefunc;
1388
1389         w = arg;
1390         block = (ndis_miniport_block *)dobj->do_devext;
1391         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
1392
1393         vaddr = NULL;
1394         paddr.np_quad = 0;
1395
1396         donefunc = sc->ndis_chars->nmc_allocate_complete_func;
1397         NdisMAllocateSharedMemory(block, w->na_len,
1398             w->na_cached, &vaddr, &paddr);
1399         MSCALL5(donefunc, block, vaddr, &paddr, w->na_len, w->na_ctx);
1400
1401         IoFreeWorkItem(w->na_iw);
1402         kfree(w, M_DEVBUF);
1403 }
1404
1405 static ndis_status
1406 NdisMAllocateSharedMemoryAsync(ndis_handle adapter, uint32_t len,
1407     uint8_t cached, void *ctx)
1408 {
1409         ndis_miniport_block     *block;
1410         struct ndis_allocwork   *w;
1411         io_workitem             *iw;
1412         io_workitem_func        ifw;
1413
1414         if (adapter == NULL)
1415                 return (NDIS_STATUS_FAILURE);
1416
1417         block = adapter;
1418
1419         iw = IoAllocateWorkItem(block->nmb_deviceobj);
1420         if (iw == NULL)
1421                 return (NDIS_STATUS_FAILURE);
1422
1423         w = kmalloc(sizeof(struct ndis_allocwork), M_TEMP, M_NOWAIT);
1424
1425         if (w == NULL)
1426                 return (NDIS_STATUS_FAILURE);
1427
1428         w->na_cached = cached;
1429         w->na_len = len;
1430         w->na_ctx = ctx;
1431         w->na_iw = iw;
1432
1433         ifw = (io_workitem_func)ndis_findwrap((funcptr)ndis_asyncmem_complete);
1434         IoQueueWorkItem(iw, ifw, WORKQUEUE_DELAYED, w);
1435
1436         return (NDIS_STATUS_PENDING);
1437 }
1438
1439 static void
1440 NdisMFreeSharedMemory(ndis_handle adapter, uint32_t len, uint8_t cached,
1441     void *vaddr, ndis_physaddr paddr)
1442 {
1443         ndis_miniport_block     *block;
1444         struct ndis_softc       *sc;
1445         struct ndis_shmem       *sh = NULL;
1446         list_entry              *l;
1447
1448         if (vaddr == NULL || adapter == NULL)
1449                 return;
1450
1451         block = (ndis_miniport_block *)adapter;
1452         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
1453
1454         /* Sanity check: is list empty? */
1455
1456         if (IsListEmpty(&sc->ndis_shlist))
1457                 return;
1458
1459         NDIS_LOCK(sc);
1460         l = sc->ndis_shlist.nle_flink;
1461         while (l != &sc->ndis_shlist) {
1462                 sh = CONTAINING_RECORD(l, struct ndis_shmem, ndis_list);
1463                 if (sh->ndis_saddr == vaddr)
1464                         break;
1465                 /*
1466                  * Check the physaddr too, just in case the driver lied
1467                  * about the virtual address.
1468                  */
1469                 if (sh->ndis_paddr.np_quad == paddr.np_quad)
1470                         break;
1471                 l = l->nle_flink;
1472         }
1473
1474         if (sh == NULL) {
1475                 NDIS_UNLOCK(sc);
1476                 kprintf("NDIS: buggy driver tried to free "
1477                     "invalid shared memory: vaddr: %p paddr: 0x%jx\n",
1478                     vaddr, (uintmax_t)paddr.np_quad);
1479                 return;
1480         }
1481
1482         RemoveEntryList(&sh->ndis_list);
1483
1484         NDIS_UNLOCK(sc);
1485
1486         bus_dmamap_unload(sh->ndis_stag, sh->ndis_smap);
1487         bus_dmamem_free(sh->ndis_stag, sh->ndis_saddr, sh->ndis_smap);
1488         bus_dma_tag_destroy(sh->ndis_stag);
1489
1490         kfree(sh, M_DEVBUF);
1491 }
1492
1493 static ndis_status
1494 NdisMMapIoSpace(void **vaddr, ndis_handle adapter, ndis_physaddr paddr,
1495     uint32_t len)
1496 {
1497         if (adapter == NULL)
1498                 return (NDIS_STATUS_FAILURE);
1499
1500         *vaddr = MmMapIoSpace(paddr.np_quad, len, 0);
1501
1502         if (*vaddr == NULL)
1503                 return (NDIS_STATUS_FAILURE);
1504
1505         return (NDIS_STATUS_SUCCESS);
1506 }
1507
1508 static void
1509 NdisMUnmapIoSpace(ndis_handle adapter, void *vaddr, uint32_t len)
1510 {
1511         MmUnmapIoSpace(vaddr, len);
1512 }
1513
1514 static uint32_t
1515 NdisGetCacheFillSize(void)
1516 {
1517         return (128);
1518 }
1519
1520 static void *
1521 NdisGetRoutineAddress(unicode_string *ustr)
1522 {
1523         ansi_string             astr;
1524
1525         if (RtlUnicodeStringToAnsiString(&astr, ustr, TRUE))
1526                 return (NULL);
1527         return (ndis_get_routine_address(ndis_functbl, astr.as_buf));
1528 }
1529
1530 static uint32_t
1531 NdisMGetDmaAlignment(ndis_handle handle)
1532 {
1533         return (16);
1534 }
1535
1536 /*
1537  * NDIS has two methods for dealing with NICs that support DMA.
1538  * One is to just pass packets to the driver and let it call
1539  * NdisMStartBufferPhysicalMapping() to map each buffer in the packet
1540  * all by itself, and the other is to let the NDIS library handle the
1541  * buffer mapping internally, and hand the driver an already populated
1542  * scatter/gather fragment list. If the driver calls
1543  * NdisMInitializeScatterGatherDma(), it wants to use the latter
1544  * method.
1545  */
1546
1547 static ndis_status
1548 NdisMInitializeScatterGatherDma(ndis_handle adapter, uint8_t is64,
1549     uint32_t maxphysmap)
1550 {
1551         struct ndis_softc       *sc;
1552         ndis_miniport_block     *block;
1553         int                     error;
1554
1555         if (adapter == NULL)
1556                 return (NDIS_STATUS_FAILURE);
1557         block = (ndis_miniport_block *)adapter;
1558         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
1559
1560         /* Don't do this twice. */
1561         if (sc->ndis_sc == 1)
1562                 return (NDIS_STATUS_SUCCESS);
1563
1564         error = bus_dma_tag_create(sc->ndis_parent_tag, ETHER_ALIGN, 0,
1565             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
1566             MCLBYTES * NDIS_MAXSEG, NDIS_MAXSEG, MCLBYTES, BUS_DMA_ALLOCNOW,
1567             &sc->ndis_ttag);
1568
1569         sc->ndis_sc = 1;
1570
1571         return (NDIS_STATUS_SUCCESS);
1572 }
1573
1574 void
1575 NdisAllocatePacketPool(ndis_status *status, ndis_handle *pool,
1576     uint32_t descnum, uint32_t protrsvdlen)
1577 {
1578         ndis_packet_pool        *p;
1579         ndis_packet             *packets;
1580         int                     i;
1581
1582         p = ExAllocatePoolWithTag(NonPagedPool, sizeof(ndis_packet_pool), 0);
1583         if (p == NULL) {
1584                 *status = NDIS_STATUS_RESOURCES;
1585                 return;
1586         }
1587
1588         p->np_cnt = descnum + NDIS_POOL_EXTRA;
1589         p->np_protrsvd = protrsvdlen;
1590         p->np_len = sizeof(ndis_packet) + protrsvdlen;
1591
1592         packets = ExAllocatePoolWithTag(NonPagedPool, p->np_cnt *
1593             p->np_len, 0);
1594
1595
1596         if (packets == NULL) {
1597                 ExFreePool(p);
1598                 *status = NDIS_STATUS_RESOURCES;
1599                 return;
1600         }
1601
1602         p->np_pktmem = packets;
1603
1604         for (i = 0; i < p->np_cnt; i++)
1605                 InterlockedPushEntrySList(&p->np_head,
1606                     (struct slist_entry *)&packets[i]);
1607
1608 #ifdef NDIS_DEBUG_PACKETS
1609         p->np_dead = 0;
1610         KeInitializeSpinLock(&p->np_lock);
1611         KeInitializeEvent(&p->np_event, EVENT_TYPE_NOTIFY, TRUE);
1612 #endif
1613
1614         *pool = p;
1615         *status = NDIS_STATUS_SUCCESS;
1616 }
1617
1618 void
1619 NdisAllocatePacketPoolEx(ndis_status *status, ndis_handle *pool,
1620     uint32_t descnum, uint32_t oflowdescnum, uint32_t protrsvdlen)
1621 {
1622         NdisAllocatePacketPool(status, pool, descnum + oflowdescnum,
1623             protrsvdlen);
1624 }
1625
1626 uint32_t
1627 NdisPacketPoolUsage(ndis_handle pool)
1628 {
1629         ndis_packet_pool        *p;
1630
1631         p = (ndis_packet_pool *)pool;
1632         return (p->np_cnt - ExQueryDepthSList(&p->np_head));
1633 }
1634
1635 void
1636 NdisFreePacketPool(ndis_handle pool)
1637 {
1638         ndis_packet_pool        *p;
1639         int                     usage;
1640 #ifdef NDIS_DEBUG_PACKETS
1641         uint8_t                 irql;
1642 #endif
1643
1644         p = (ndis_packet_pool *)pool;
1645
1646 #ifdef NDIS_DEBUG_PACKETS
1647         KeAcquireSpinLock(&p->np_lock, &irql);
1648 #endif
1649
1650         usage = NdisPacketPoolUsage(pool);
1651
1652 #ifdef NDIS_DEBUG_PACKETS
1653         if (usage) {
1654                 p->np_dead = 1;
1655                 KeResetEvent(&p->np_event);
1656                 KeReleaseSpinLock(&p->np_lock, irql);
1657                 KeWaitForSingleObject(&p->np_event, 0, 0, FALSE, NULL);
1658         } else
1659                 KeReleaseSpinLock(&p->np_lock, irql);
1660 #endif
1661
1662         ExFreePool(p->np_pktmem);
1663         ExFreePool(p);
1664 }
1665
1666 void
1667 NdisAllocatePacket(ndis_status *status, ndis_packet **packet, ndis_handle pool)
1668 {
1669         ndis_packet_pool        *p;
1670         ndis_packet             *pkt;
1671 #ifdef NDIS_DEBUG_PACKETS
1672         uint8_t                 irql;
1673 #endif
1674
1675         p = (ndis_packet_pool *)pool;
1676
1677 #ifdef NDIS_DEBUG_PACKETS
1678         KeAcquireSpinLock(&p->np_lock, &irql);
1679         if (p->np_dead) {
1680                 KeReleaseSpinLock(&p->np_lock, irql);
1681                 kprintf("NDIS: tried to allocate packet from dead pool %p\n",
1682                     pool);
1683                 *status = NDIS_STATUS_RESOURCES;
1684                 return;
1685         }
1686 #endif
1687
1688         pkt = (ndis_packet *)InterlockedPopEntrySList(&p->np_head);
1689
1690 #ifdef NDIS_DEBUG_PACKETS
1691         KeReleaseSpinLock(&p->np_lock, irql);
1692 #endif
1693
1694         if (pkt == NULL) {
1695                 *status = NDIS_STATUS_RESOURCES;
1696                 return;
1697         }
1698
1699
1700         bzero((char *)pkt, sizeof(ndis_packet));
1701
1702         /* Save pointer to the pool. */
1703         pkt->np_private.npp_pool = pool;
1704
1705         /* Set the oob offset pointer. Lots of things expect this. */
1706         pkt->np_private.npp_packetooboffset = offsetof(ndis_packet, np_oob);
1707
1708         /*
1709          * We must initialize the packet flags correctly in order
1710          * for the NDIS_SET_PACKET_MEDIA_SPECIFIC_INFO() and
1711          * NDIS_GET_PACKET_MEDIA_SPECIFIC_INFO() macros to work
1712          * correctly.
1713          */
1714         pkt->np_private.npp_ndispktflags = NDIS_PACKET_ALLOCATED_BY_NDIS;
1715         pkt->np_private.npp_validcounts = FALSE;
1716
1717         *packet = pkt;
1718
1719         *status = NDIS_STATUS_SUCCESS;
1720 }
1721
1722 void
1723 NdisFreePacket(ndis_packet *packet)
1724 {
1725         ndis_packet_pool        *p;
1726 #ifdef NDIS_DEBUG_PACKETS
1727         uint8_t                 irql;
1728 #endif
1729
1730         p = (ndis_packet_pool *)packet->np_private.npp_pool;
1731
1732 #ifdef NDIS_DEBUG_PACKETS
1733         KeAcquireSpinLock(&p->np_lock, &irql);
1734 #endif
1735
1736         InterlockedPushEntrySList(&p->np_head, (slist_entry *)packet);
1737
1738 #ifdef NDIS_DEBUG_PACKETS
1739         if (p->np_dead) {
1740                 if (ExQueryDepthSList(&p->np_head) == p->np_cnt)
1741                         KeSetEvent(&p->np_event, IO_NO_INCREMENT, FALSE);
1742         }
1743         KeReleaseSpinLock(&p->np_lock, irql);
1744 #endif
1745 }
1746
1747 static void
1748 NdisUnchainBufferAtFront(ndis_packet *packet, ndis_buffer **buf)
1749 {
1750         ndis_packet_private     *priv;
1751
1752         if (packet == NULL || buf == NULL)
1753                 return;
1754
1755         priv = &packet->np_private;
1756
1757         priv->npp_validcounts = FALSE;
1758
1759         if (priv->npp_head == priv->npp_tail) {
1760                 *buf = priv->npp_head;
1761                 priv->npp_head = priv->npp_tail = NULL;
1762         } else {
1763                 *buf = priv->npp_head;
1764                 priv->npp_head = (*buf)->mdl_next;
1765         }
1766 }
1767
1768 static void
1769 NdisUnchainBufferAtBack(ndis_packet *packet, ndis_buffer **buf)
1770 {
1771         ndis_packet_private     *priv;
1772         ndis_buffer             *tmp;
1773
1774         if (packet == NULL || buf == NULL)
1775                 return;
1776
1777         priv = &packet->np_private;
1778
1779         priv->npp_validcounts = FALSE;
1780
1781         if (priv->npp_head == priv->npp_tail) {
1782                 *buf = priv->npp_head;
1783                 priv->npp_head = priv->npp_tail = NULL;
1784         } else {
1785                 *buf = priv->npp_tail;
1786                 tmp = priv->npp_head;
1787                 while (tmp->mdl_next != priv->npp_tail)
1788                         tmp = tmp->mdl_next;
1789                 priv->npp_tail = tmp;
1790                 tmp->mdl_next = NULL;
1791         }
1792 }
1793
1794 /*
1795  * The NDIS "buffer" is really an MDL (memory descriptor list)
1796  * which is used to describe a buffer in a way that allows it
1797  * to mapped into different contexts. We have to be careful how
1798  * we handle them: in some versions of Windows, the NdisFreeBuffer()
1799  * routine is an actual function in the NDIS API, but in others
1800  * it's just a macro wrapper around IoFreeMdl(). There's really
1801  * no way to use the 'descnum' parameter to count how many
1802  * "buffers" are allocated since in order to use IoFreeMdl() to
1803  * dispose of a buffer, we have to use IoAllocateMdl() to allocate
1804  * them, and IoAllocateMdl() just grabs them out of the heap.
1805  */
1806
1807 static void
1808 NdisAllocateBufferPool(ndis_status *status, ndis_handle *pool,
1809     uint32_t descnum)
1810 {
1811
1812         /*
1813          * The only thing we can really do here is verify that descnum
1814          * is a reasonable value, but I really don't know what to check
1815          * it against.
1816          */
1817
1818         *pool = NonPagedPool;
1819         *status = NDIS_STATUS_SUCCESS;
1820 }
1821
1822 static void
1823 NdisFreeBufferPool(ndis_handle pool)
1824 {
1825 }
1826
1827 static void
1828 NdisAllocateBuffer(ndis_status *status, ndis_buffer **buffer, ndis_handle pool,
1829     void *vaddr, uint32_t len)
1830 {
1831         ndis_buffer             *buf;
1832
1833         buf = IoAllocateMdl(vaddr, len, FALSE, FALSE, NULL);
1834         if (buf == NULL) {
1835                 *status = NDIS_STATUS_RESOURCES;
1836                 return;
1837         }
1838
1839         MmBuildMdlForNonPagedPool(buf);
1840
1841         *buffer = buf;
1842         *status = NDIS_STATUS_SUCCESS;
1843 }
1844
1845 static void
1846 NdisFreeBuffer(ndis_buffer *buf)
1847 {
1848         IoFreeMdl(buf);
1849 }
1850
1851 /* Aw c'mon. */
1852
1853 static uint32_t
1854 NdisBufferLength(ndis_buffer *buf)
1855 {
1856         return (MmGetMdlByteCount(buf));
1857 }
1858
1859 /*
1860  * Get the virtual address and length of a buffer.
1861  * Note: the vaddr argument is optional.
1862  */
1863
1864 static void
1865 NdisQueryBuffer(ndis_buffer *buf, void **vaddr, uint32_t *len)
1866 {
1867         if (vaddr != NULL)
1868                 *vaddr = MmGetMdlVirtualAddress(buf);
1869         *len = MmGetMdlByteCount(buf);
1870 }
1871
1872 /* Same as above -- we don't care about the priority. */
1873
1874 static void
1875 NdisQueryBufferSafe(ndis_buffer *buf, void **vaddr, uint32_t *len,
1876     uint32_t prio)
1877 {
1878         if (vaddr != NULL)
1879                 *vaddr = MmGetMdlVirtualAddress(buf);
1880         *len = MmGetMdlByteCount(buf);
1881 }
1882
1883 /* Damnit Microsoft!! How many ways can you do the same thing?! */
1884
1885 static void *
1886 NdisBufferVirtualAddress(ndis_buffer *buf)
1887 {
1888         return (MmGetMdlVirtualAddress(buf));
1889 }
1890
1891 static void *
1892 NdisBufferVirtualAddressSafe(ndis_buffer *buf, uint32_t prio)
1893 {
1894         return (MmGetMdlVirtualAddress(buf));
1895 }
1896
1897 static void
1898 NdisAdjustBufferLength(ndis_buffer *buf, int len)
1899 {
1900         MmGetMdlByteCount(buf) = len;
1901 }
1902
1903 static uint32_t
1904 NdisInterlockedIncrement(uint32_t *addend)
1905 {
1906         atomic_add_long((u_long *)addend, 1);
1907         return (*addend);
1908 }
1909
1910 static uint32_t
1911 NdisInterlockedDecrement(uint32_t *addend)
1912 {
1913         atomic_subtract_long((u_long *)addend, 1);
1914         return (*addend);
1915 }
1916
1917 static uint32_t
1918 NdisGetVersion(void)
1919 {
1920         return (0x00050001);
1921 }
1922
1923 static void
1924 NdisInitializeEvent(ndis_event *event)
1925 {
1926         /*
1927          * NDIS events are always notification
1928          * events, and should be initialized to the
1929          * not signaled state.
1930          */
1931         KeInitializeEvent(&event->ne_event, EVENT_TYPE_NOTIFY, FALSE);
1932 }
1933
1934 static void
1935 NdisSetEvent(ndis_event *event)
1936 {
1937         KeSetEvent(&event->ne_event, IO_NO_INCREMENT, FALSE);
1938 }
1939
1940 static void
1941 NdisResetEvent(ndis_event *event)
1942 {
1943         KeResetEvent(&event->ne_event);
1944 }
1945
1946 static uint8_t
1947 NdisWaitEvent(ndis_event *event, uint32_t msecs)
1948 {
1949         int64_t                 duetime;
1950         uint32_t                rval;
1951
1952         duetime = ((int64_t)msecs * -10000);
1953         rval = KeWaitForSingleObject(event,
1954             0, 0, TRUE, msecs ? & duetime : NULL);
1955
1956         if (rval == STATUS_TIMEOUT)
1957                 return (FALSE);
1958
1959         return (TRUE);
1960 }
1961
1962 static ndis_status
1963 NdisUnicodeStringToAnsiString(ansi_string *dstr, unicode_string *sstr)
1964 {
1965         uint32_t                rval;
1966
1967         rval = RtlUnicodeStringToAnsiString(dstr, sstr, FALSE);
1968
1969         if (rval == STATUS_INSUFFICIENT_RESOURCES)
1970                 return (NDIS_STATUS_RESOURCES);
1971         if (rval)
1972                 return (NDIS_STATUS_FAILURE);
1973
1974         return (NDIS_STATUS_SUCCESS);
1975 }
1976
1977 static ndis_status
1978 NdisAnsiStringToUnicodeString(unicode_string *dstr, ansi_string *sstr)
1979 {
1980         uint32_t                rval;
1981
1982         rval = RtlAnsiStringToUnicodeString(dstr, sstr, FALSE);
1983
1984         if (rval == STATUS_INSUFFICIENT_RESOURCES)
1985                 return (NDIS_STATUS_RESOURCES);
1986         if (rval)
1987                 return (NDIS_STATUS_FAILURE);
1988
1989         return (NDIS_STATUS_SUCCESS);
1990 }
1991
1992 static ndis_status
1993 NdisMPciAssignResources(ndis_handle adapter, uint32_t slot,
1994     ndis_resource_list **list)
1995 {
1996         ndis_miniport_block     *block;
1997
1998         if (adapter == NULL || list == NULL)
1999                 return (NDIS_STATUS_FAILURE);
2000
2001         block = (ndis_miniport_block *)adapter;
2002         *list = block->nmb_rlist;
2003
2004         return (NDIS_STATUS_SUCCESS);
2005 }
2006
2007 static uint8_t
2008 ndis_intr(kinterrupt *iobj, void *arg)
2009 {
2010         struct ndis_softc       *sc;
2011         uint8_t                 is_our_intr = FALSE;
2012         int                     call_isr = 0;
2013         ndis_miniport_interrupt *intr;
2014
2015         sc = arg;
2016         intr = sc->ndis_block->nmb_interrupt;
2017
2018         if (intr == NULL || sc->ndis_block->nmb_miniportadapterctx == NULL)
2019                 return (FALSE);
2020
2021         if (sc->ndis_block->nmb_interrupt->ni_isrreq == TRUE)
2022                 MSCALL3(intr->ni_isrfunc, &is_our_intr, &call_isr,
2023                     sc->ndis_block->nmb_miniportadapterctx);
2024         else {
2025                 MSCALL1(sc->ndis_chars->nmc_disable_interrupts_func,
2026                     sc->ndis_block->nmb_miniportadapterctx);
2027                 call_isr = 1;
2028         }
2029
2030         if (call_isr)
2031                 IoRequestDpc(sc->ndis_block->nmb_deviceobj, NULL, sc);
2032
2033         return (is_our_intr);
2034 }
2035
2036 static void
2037 ndis_intrhand(kdpc *dpc, ndis_miniport_interrupt *intr, void *sysarg1,
2038     void *sysarg2)
2039 {
2040         struct ndis_softc       *sc;
2041         ndis_miniport_block     *block;
2042         ndis_handle             adapter;
2043
2044         block = intr->ni_block;
2045         adapter = block->nmb_miniportadapterctx;
2046         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
2047
2048         if (NDIS_SERIALIZED(sc->ndis_block))
2049                 KeAcquireSpinLockAtDpcLevel(&block->nmb_lock);
2050
2051         MSCALL1(intr->ni_dpcfunc, adapter);
2052
2053         /* If there's a MiniportEnableInterrupt() routine, call it. */
2054
2055         if (sc->ndis_chars->nmc_enable_interrupts_func != NULL)
2056                 MSCALL1(sc->ndis_chars->nmc_enable_interrupts_func, adapter);
2057
2058         if (NDIS_SERIALIZED(sc->ndis_block))
2059                 KeReleaseSpinLockFromDpcLevel(&block->nmb_lock);
2060
2061         /*
2062          * Set the completion event if we've drained all
2063          * pending interrupts.
2064          */
2065
2066         KeAcquireSpinLockAtDpcLevel(&intr->ni_dpccountlock);
2067         intr->ni_dpccnt--;
2068         if (intr->ni_dpccnt == 0)
2069                 KeSetEvent(&intr->ni_dpcevt, IO_NO_INCREMENT, FALSE);
2070         KeReleaseSpinLockFromDpcLevel(&intr->ni_dpccountlock);
2071 }
2072
2073 static ndis_status
2074 NdisMRegisterInterrupt(ndis_miniport_interrupt *intr, ndis_handle adapter,
2075     uint32_t ivec, uint32_t ilevel, uint8_t reqisr, uint8_t shared,
2076     ndis_interrupt_mode imode)
2077 {
2078         ndis_miniport_block     *block;
2079         ndis_miniport_characteristics *ch;
2080         struct ndis_softc       *sc;
2081         int                     error;
2082
2083         block = adapter;
2084         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
2085         ch = IoGetDriverObjectExtension(block->nmb_deviceobj->do_drvobj,
2086             (void *)1);
2087
2088         intr->ni_rsvd = ExAllocatePoolWithTag(NonPagedPool,
2089             sizeof(struct mtx), 0);
2090         if (intr->ni_rsvd == NULL)
2091                 return (NDIS_STATUS_RESOURCES);
2092
2093         intr->ni_block = adapter;
2094         intr->ni_isrreq = reqisr;
2095         intr->ni_shared = shared;
2096         intr->ni_dpccnt = 0;
2097         intr->ni_isrfunc = ch->nmc_isr_func;
2098         intr->ni_dpcfunc = ch->nmc_interrupt_func;
2099
2100         KeInitializeEvent(&intr->ni_dpcevt, EVENT_TYPE_NOTIFY, TRUE);
2101         KeInitializeDpc(&intr->ni_dpc,
2102             ndis_findwrap((funcptr)ndis_intrhand), intr);
2103         KeSetImportanceDpc(&intr->ni_dpc, KDPC_IMPORTANCE_LOW);
2104
2105         error = IoConnectInterrupt(&intr->ni_introbj,
2106             ndis_findwrap((funcptr)ndis_intr), sc, NULL,
2107             ivec, ilevel, 0, imode, shared, 0, FALSE);
2108
2109         if (error != STATUS_SUCCESS)
2110                 return (NDIS_STATUS_FAILURE);
2111
2112         block->nmb_interrupt = intr;
2113
2114         return (NDIS_STATUS_SUCCESS);
2115 }
2116
2117 static void
2118 NdisMDeregisterInterrupt(ndis_miniport_interrupt *intr)
2119 {
2120         ndis_miniport_block     *block;
2121         uint8_t                 irql;
2122
2123         block = intr->ni_block;
2124
2125         /* Should really be KeSynchronizeExecution() */
2126
2127         KeAcquireSpinLock(intr->ni_introbj->ki_lock, &irql);
2128         block->nmb_interrupt = NULL;
2129         KeReleaseSpinLock(intr->ni_introbj->ki_lock, irql);
2130 /*
2131         KeFlushQueuedDpcs();
2132 */
2133         /* Disconnect our ISR */
2134
2135         IoDisconnectInterrupt(intr->ni_introbj);
2136
2137         KeWaitForSingleObject(&intr->ni_dpcevt, 0, 0, FALSE, NULL);
2138         KeResetEvent(&intr->ni_dpcevt);
2139 }
2140
2141 static void
2142 NdisMRegisterAdapterShutdownHandler(ndis_handle adapter, void *shutdownctx,
2143     ndis_shutdown_handler shutdownfunc)
2144 {
2145         ndis_miniport_block     *block;
2146         ndis_miniport_characteristics *chars;
2147         struct ndis_softc       *sc;
2148
2149         if (adapter == NULL)
2150                 return;
2151
2152         block = (ndis_miniport_block *)adapter;
2153         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
2154         chars = sc->ndis_chars;
2155
2156         chars->nmc_shutdown_handler = shutdownfunc;
2157         chars->nmc_rsvd0 = shutdownctx;
2158 }
2159
2160 static void
2161 NdisMDeregisterAdapterShutdownHandler(ndis_handle adapter)
2162 {
2163         ndis_miniport_block     *block;
2164         ndis_miniport_characteristics *chars;
2165         struct ndis_softc       *sc;
2166
2167         if (adapter == NULL)
2168                 return;
2169
2170         block = (ndis_miniport_block *)adapter;
2171         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
2172         chars = sc->ndis_chars;
2173
2174         chars->nmc_shutdown_handler = NULL;
2175         chars->nmc_rsvd0 = NULL;
2176 }
2177
2178 static uint32_t
2179 NDIS_BUFFER_TO_SPAN_PAGES(ndis_buffer *buf)
2180 {
2181         if (buf == NULL)
2182                 return (0);
2183         if (MmGetMdlByteCount(buf) == 0)
2184                 return (1);
2185         return (SPAN_PAGES(MmGetMdlVirtualAddress(buf),
2186             MmGetMdlByteCount(buf)));
2187 }
2188
2189 static void
2190 NdisGetBufferPhysicalArraySize(ndis_buffer *buf, uint32_t *pages)
2191 {
2192         if (buf == NULL)
2193                 return;
2194
2195         *pages = NDIS_BUFFER_TO_SPAN_PAGES(buf);
2196 }
2197
2198 static void
2199 NdisQueryBufferOffset(ndis_buffer *buf, uint32_t *off, uint32_t *len)
2200 {
2201         if (buf == NULL)
2202                 return;
2203
2204         *off = MmGetMdlByteOffset(buf);
2205         *len = MmGetMdlByteCount(buf);
2206 }
2207
2208 void
2209 NdisMSleep(uint32_t usecs)
2210 {
2211         ktimer                  timer;
2212
2213         /*
2214          * During system bootstrap, (i.e. cold == 1), we aren't
2215          * allowed to sleep, so we have to do a hard DELAY()
2216          * instead.
2217          */
2218
2219         if (cold)
2220                 DELAY(usecs);
2221         else {
2222                 KeInitializeTimer(&timer);
2223                 KeSetTimer(&timer, ((int64_t)usecs * -10), NULL);
2224                 KeWaitForSingleObject(&timer, 0, 0, FALSE, NULL);
2225         }
2226 }
2227
2228 static uint32_t
2229 NdisReadPcmciaAttributeMemory(ndis_handle handle, uint32_t offset, void *buf,
2230     uint32_t len)
2231 {
2232         struct ndis_softc       *sc;
2233         ndis_miniport_block     *block;
2234         bus_space_handle_t      bh;
2235         bus_space_tag_t         bt;
2236         char                    *dest;
2237         int                     i;
2238
2239         if (handle == NULL)
2240                 return (0);
2241
2242         block = (ndis_miniport_block *)handle;
2243         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
2244         dest = buf;
2245
2246         bh = rman_get_bushandle(sc->ndis_res_am);
2247         bt = rman_get_bustag(sc->ndis_res_am);
2248
2249         for (i = 0; i < len; i++)
2250                 dest[i] = bus_space_read_1(bt, bh, (offset + i) * 2);
2251
2252         return (i);
2253 }
2254
2255 static uint32_t
2256 NdisWritePcmciaAttributeMemory(ndis_handle handle, uint32_t offset, void *buf,
2257     uint32_t len)
2258 {
2259         struct ndis_softc       *sc;
2260         ndis_miniport_block     *block;
2261         bus_space_handle_t      bh;
2262         bus_space_tag_t         bt;
2263         char                    *src;
2264         int                     i;
2265
2266         if (handle == NULL)
2267                 return (0);
2268
2269         block = (ndis_miniport_block *)handle;
2270         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
2271         src = buf;
2272
2273         bh = rman_get_bushandle(sc->ndis_res_am);
2274         bt = rman_get_bustag(sc->ndis_res_am);
2275
2276         for (i = 0; i < len; i++)
2277                 bus_space_write_1(bt, bh, (offset + i) * 2, src[i]);
2278
2279         return (i);
2280 }
2281
2282 static list_entry *
2283 NdisInterlockedInsertHeadList(list_entry *head, list_entry *entry,
2284     ndis_spin_lock *lock)
2285 {
2286         list_entry              *flink;
2287
2288         KeAcquireSpinLock(&lock->nsl_spinlock, &lock->nsl_kirql);
2289         flink = head->nle_flink;
2290         entry->nle_flink = flink;
2291         entry->nle_blink = head;
2292         flink->nle_blink = entry;
2293         head->nle_flink = entry;
2294         KeReleaseSpinLock(&lock->nsl_spinlock, lock->nsl_kirql);
2295
2296         return (flink);
2297 }
2298
2299 static list_entry *
2300 NdisInterlockedRemoveHeadList(list_entry *head, ndis_spin_lock *lock)
2301 {
2302         list_entry              *flink;
2303         list_entry              *entry;
2304
2305         KeAcquireSpinLock(&lock->nsl_spinlock, &lock->nsl_kirql);
2306         entry = head->nle_flink;
2307         flink = entry->nle_flink;
2308         head->nle_flink = flink;
2309         flink->nle_blink = head;
2310         KeReleaseSpinLock(&lock->nsl_spinlock, lock->nsl_kirql);
2311
2312         return (entry);
2313 }
2314
2315 static list_entry *
2316 NdisInterlockedInsertTailList(list_entry *head, list_entry *entry,
2317     ndis_spin_lock *lock)
2318 {
2319         list_entry              *blink;
2320
2321         KeAcquireSpinLock(&lock->nsl_spinlock, &lock->nsl_kirql);
2322         blink = head->nle_blink;
2323         entry->nle_flink = head;
2324         entry->nle_blink = blink;
2325         blink->nle_flink = entry;
2326         head->nle_blink = entry;
2327         KeReleaseSpinLock(&lock->nsl_spinlock, lock->nsl_kirql);
2328
2329         return (blink);
2330 }
2331
2332 static uint8_t
2333 NdisMSynchronizeWithInterrupt(ndis_miniport_interrupt *intr, void *syncfunc,
2334     void *syncctx)
2335 {
2336         return (KeSynchronizeExecution(intr->ni_introbj, syncfunc, syncctx));
2337 }
2338
2339 static void
2340 NdisGetCurrentSystemTime(uint64_t *tval)
2341 {
2342         ntoskrnl_time(tval);
2343 }
2344
2345 /*
2346  * Return the number of milliseconds since the system booted.
2347  */
2348 static void
2349 NdisGetSystemUpTime(uint32_t *tval)
2350 {
2351         struct timespec         ts;
2352
2353         nanouptime(&ts);
2354         *tval = ts.tv_nsec / 1000000 + ts.tv_sec * 1000;
2355 }
2356
2357 static void
2358 NdisInitializeString(unicode_string *dst, char *src)
2359 {
2360         ansi_string             as;
2361         RtlInitAnsiString(&as, src);
2362         RtlAnsiStringToUnicodeString(dst, &as, TRUE);
2363 }
2364
2365 static void
2366 NdisFreeString(unicode_string *str)
2367 {
2368         RtlFreeUnicodeString(str);
2369 }
2370
2371 static ndis_status
2372 NdisMRemoveMiniport(ndis_handle *adapter)
2373 {
2374         return (NDIS_STATUS_SUCCESS);
2375 }
2376
2377 static void
2378 NdisInitAnsiString(ansi_string *dst, char *src)
2379 {
2380         RtlInitAnsiString(dst, src);
2381 }
2382
2383 static void
2384 NdisInitUnicodeString(unicode_string *dst, uint16_t *src)
2385 {
2386         RtlInitUnicodeString(dst, src);
2387 }
2388
2389 static void NdisMGetDeviceProperty(ndis_handle adapter,
2390     device_object **phydevobj, device_object **funcdevobj,
2391     device_object **nextdevobj, cm_resource_list *resources,
2392     cm_resource_list *transresources)
2393 {
2394         ndis_miniport_block     *block;
2395
2396         block = (ndis_miniport_block *)adapter;
2397
2398         if (phydevobj != NULL)
2399                 *phydevobj = block->nmb_physdeviceobj;
2400         if (funcdevobj != NULL)
2401                 *funcdevobj = block->nmb_deviceobj;
2402         if (nextdevobj != NULL)
2403                 *nextdevobj = block->nmb_nextdeviceobj;
2404 }
2405
2406 static void
2407 NdisGetFirstBufferFromPacket(ndis_packet *packet, ndis_buffer **buf,
2408     void **firstva, uint32_t *firstlen, uint32_t *totlen)
2409 {
2410         ndis_buffer             *tmp;
2411
2412         tmp = packet->np_private.npp_head;
2413         *buf = tmp;
2414         if (tmp == NULL) {
2415                 *firstva = NULL;
2416                 *firstlen = *totlen = 0;
2417         } else {
2418                 *firstva = MmGetMdlVirtualAddress(tmp);
2419                 *firstlen = *totlen = MmGetMdlByteCount(tmp);
2420                 for (tmp = tmp->mdl_next; tmp != NULL; tmp = tmp->mdl_next)
2421                         *totlen += MmGetMdlByteCount(tmp);
2422         }
2423 }
2424
2425 static void
2426 NdisGetFirstBufferFromPacketSafe(ndis_packet *packet, ndis_buffer **buf,
2427     void **firstva, uint32_t *firstlen, uint32_t *totlen, uint32_t prio)
2428 {
2429         NdisGetFirstBufferFromPacket(packet, buf, firstva, firstlen, totlen);
2430 }
2431
2432 static int
2433 ndis_find_sym(linker_file_t lf, char *filename, char *suffix, caddr_t *sym)
2434 {
2435         char                    *fullsym;
2436         char                    *suf;
2437         int                     i;
2438
2439         fullsym = ExAllocatePoolWithTag(NonPagedPool, MAXPATHLEN, 0);
2440         if (fullsym == NULL)
2441                 return (ENOMEM);
2442
2443         bzero(fullsym, MAXPATHLEN);
2444         strncpy(fullsym, filename, MAXPATHLEN);
2445         if (strlen(filename) < 4) {
2446                 ExFreePool(fullsym);
2447                 return (EINVAL);
2448         }
2449
2450         /* If the filename has a .ko suffix, strip if off. */
2451         suf = fullsym + (strlen(filename) - 3);
2452         if (strcmp(suf, ".ko") == 0)
2453                 *suf = '\0';
2454
2455         for (i = 0; i < strlen(fullsym); i++) {
2456                 if (fullsym[i] == '.')
2457                         fullsym[i] = '_';
2458                 else
2459                         fullsym[i] = tolower(fullsym[i]);
2460         }
2461         strcat(fullsym, suffix);
2462         linker_file_lookup_symbol(lf, fullsym, 0, sym);
2463         ExFreePool(fullsym);
2464         if (*sym == 0)
2465                 return (ENOENT);
2466
2467         return (0);
2468 }
2469
2470 struct ndis_checkmodule {
2471         char    *afilename;
2472         ndis_fh *fh;
2473 };
2474
2475 /*
2476  * See if a single module contains the symbols for a specified file.
2477  */
2478 static int
2479 NdisCheckModule(linker_file_t lf, void *context)
2480 {
2481         struct ndis_checkmodule *nc;
2482         caddr_t                 kldstart, kldend;
2483
2484         nc = (struct ndis_checkmodule *)context;
2485         if (ndis_find_sym(lf, nc->afilename, "_start", &kldstart))
2486                 return (0);
2487         if (ndis_find_sym(lf, nc->afilename, "_end", &kldend))
2488                 return (0);
2489         nc->fh->nf_vp = lf;
2490         nc->fh->nf_map = NULL;
2491         nc->fh->nf_type = NDIS_FH_TYPE_MODULE;
2492         nc->fh->nf_maplen = (kldend - kldstart) & 0xFFFFFFFF;
2493         return (1);
2494 }
2495
2496 /* can also return NDIS_STATUS_RESOURCES/NDIS_STATUS_ERROR_READING_FILE */
2497 static void
2498 NdisOpenFile(ndis_status *status, ndis_handle *filehandle,
2499     uint32_t *filelength, unicode_string *filename, ndis_physaddr highestaddr)
2500 {
2501         ansi_string             as;
2502         char                    *afilename = NULL;
2503         struct thread           *td = curthread;
2504         struct nlookupdata      nd;
2505         int                     error;
2506         struct vattr            vat;
2507         struct vattr            *vap = &vat;
2508         ndis_fh                 *fh;
2509         char                    *path;
2510         struct ndis_checkmodule nc;
2511         struct vnode            *vp;
2512
2513         if (RtlUnicodeStringToAnsiString(&as, filename, TRUE)) {
2514                 *status = NDIS_STATUS_RESOURCES;
2515                 return;
2516         }
2517
2518         afilename = kstrdup(as.as_buf, M_DEVBUF);
2519         RtlFreeAnsiString(&as);
2520
2521         fh = ExAllocatePoolWithTag(NonPagedPool, sizeof(ndis_fh), 0);
2522         if (fh == NULL) {
2523                 kfree(afilename, M_DEVBUF);
2524                 *status = NDIS_STATUS_RESOURCES;
2525                 return;
2526         }
2527
2528         fh->nf_name = afilename;
2529
2530         /*
2531          * During system bootstrap, it's impossible to load files
2532          * from the rootfs since it's not mounted yet. We therefore
2533          * offer the possibility of opening files that have been
2534          * preloaded as modules instead. Both choices will work
2535          * when kldloading a module from multiuser, but only the
2536          * module option will work during bootstrap. The module
2537          * loading option works by using the ndiscvt(8) utility
2538          * to convert the arbitrary file into a .ko using objcopy(1).
2539          * This file will contain two special symbols: filename_start
2540          * and filename_end. All we have to do is traverse the KLD
2541          * list in search of those symbols and we've found the file
2542          * data. As an added bonus, ndiscvt(8) will also generate
2543          * a normal .o file which can be linked statically with
2544          * the kernel. This means that the symbols will actual reside
2545          * in the kernel's symbol table, but that doesn't matter to
2546          * us since the kernel appears to us as just another module.
2547          */
2548
2549         nc.afilename = afilename;
2550         nc.fh = fh;
2551         if (linker_file_foreach(NdisCheckModule, &nc)) {
2552                 *filelength = fh->nf_maplen;
2553                 *filehandle = fh;
2554                 *status = NDIS_STATUS_SUCCESS;
2555                 return;
2556         }
2557
2558         if (mountlist_boot_getfirst() == NULL) {
2559                 ExFreePool(fh);
2560                 *status = NDIS_STATUS_FILE_NOT_FOUND;
2561                 kprintf("NDIS: could not find file %s in linker list\n",
2562                     afilename);
2563                 kprintf("NDIS: and no filesystems mounted yet, "
2564                     "aborting NdisOpenFile()\n");
2565                 kfree(afilename, M_DEVBUF);
2566                 return;
2567         }
2568
2569         path = ExAllocatePoolWithTag(NonPagedPool, MAXPATHLEN, 0);
2570         if (path == NULL) {
2571                 ExFreePool(fh);
2572                 kfree(afilename, M_DEVBUF);
2573                 *status = NDIS_STATUS_RESOURCES;
2574                 return;
2575         }
2576
2577         ksnprintf(path, MAXPATHLEN, "%s/%s", ndis_filepath, afilename);
2578
2579         /* Some threads don't have a current working directory. */
2580
2581         if (td->td_proc && td->td_proc->p_fd->fd_rdir == NULL)
2582                 td->td_proc->p_fd->fd_rdir = rootvnode;
2583         if (td->td_proc && td->td_proc->p_fd->fd_cdir == NULL)
2584                 td->td_proc->p_fd->fd_cdir = rootvnode;
2585
2586         error = nlookup_init(&nd, path, UIO_SYSSPACE, NLC_FOLLOW|NLC_LOCKVP);
2587         if (error)
2588                 goto init_fail;
2589         error = vn_open(&nd, NULL, FREAD, 0);
2590         if (error)
2591                 goto open_fail;
2592
2593         ExFreePool(path);
2594
2595         vp = nd.nl_open_vp;
2596         nd.nl_open_vp = NULL;
2597
2598         /* Get the file size. */
2599         VOP_GETATTR(vp, vap);
2600         vn_unlock(vp);
2601
2602         fh->nf_vp = nd.nl_open_vp;
2603         fh->nf_map = NULL;
2604         fh->nf_type = NDIS_FH_TYPE_VFS;
2605         *filehandle = fh;
2606         *filelength = fh->nf_maplen = vap->va_size & 0xFFFFFFFF;
2607         *status = NDIS_STATUS_SUCCESS;
2608
2609         return;
2610
2611 open_fail:
2612         nlookup_done(&nd);
2613 init_fail:
2614         *status = NDIS_STATUS_FILE_NOT_FOUND;
2615         ExFreePool(fh);
2616         kprintf("NDIS: open file %s failed: %d\n", path, error);
2617         ExFreePool(path);
2618         kfree(afilename, M_DEVBUF);
2619 }
2620
2621 static void
2622 NdisMapFile(ndis_status *status, void **mappedbuffer, ndis_handle filehandle)
2623 {
2624         ndis_fh                 *fh;
2625         struct thread           *td = curthread;
2626         linker_file_t           lf;
2627         caddr_t                 kldstart;
2628         int                     error, resid;
2629         struct vnode            *vp;
2630
2631         if (filehandle == NULL) {
2632                 *status = NDIS_STATUS_FAILURE;
2633                 return;
2634         }
2635
2636         fh = (ndis_fh *)filehandle;
2637
2638         if (fh->nf_vp == NULL) {
2639                 *status = NDIS_STATUS_FAILURE;
2640                 return;
2641         }
2642
2643         if (fh->nf_map != NULL) {
2644                 *status = NDIS_STATUS_ALREADY_MAPPED;
2645                 return;
2646         }
2647
2648         if (fh->nf_type == NDIS_FH_TYPE_MODULE) {
2649                 lf = fh->nf_vp;
2650                 if (ndis_find_sym(lf, fh->nf_name, "_start", &kldstart)) {
2651                         *status = NDIS_STATUS_FAILURE;
2652                         return;
2653                 }
2654                 fh->nf_map = kldstart;
2655                 *status = NDIS_STATUS_SUCCESS;
2656                 *mappedbuffer = fh->nf_map;
2657                 return;
2658         }
2659
2660         fh->nf_map = ExAllocatePoolWithTag(NonPagedPool, fh->nf_maplen, 0);
2661
2662         if (fh->nf_map == NULL) {
2663                 *status = NDIS_STATUS_RESOURCES;
2664                 return;
2665         }
2666
2667         vp = fh->nf_vp;
2668         error = vn_rdwr(UIO_READ, vp, fh->nf_map, fh->nf_maplen, 0,
2669             UIO_SYSSPACE, 0, td->td_ucred, &resid);
2670
2671         if (error)
2672                 *status = NDIS_STATUS_FAILURE;
2673         else {
2674                 *status = NDIS_STATUS_SUCCESS;
2675                 *mappedbuffer = fh->nf_map;
2676         }
2677 }
2678
2679 static void
2680 NdisUnmapFile(ndis_handle filehandle)
2681 {
2682         ndis_fh                 *fh;
2683         fh = (ndis_fh *)filehandle;
2684
2685         if (fh->nf_map == NULL)
2686                 return;
2687
2688         if (fh->nf_type == NDIS_FH_TYPE_VFS)
2689                 ExFreePool(fh->nf_map);
2690         fh->nf_map = NULL;
2691 }
2692
2693 static void
2694 NdisCloseFile(ndis_handle filehandle)
2695 {
2696         ndis_fh                 *fh;
2697         struct vnode            *vp;
2698
2699         if (filehandle == NULL)
2700                 return;
2701
2702         fh = (ndis_fh *)filehandle;
2703         if (fh->nf_map != NULL) {
2704                 if (fh->nf_type == NDIS_FH_TYPE_VFS)
2705                         ExFreePool(fh->nf_map);
2706                 fh->nf_map = NULL;
2707         }
2708
2709         if (fh->nf_vp == NULL)
2710                 return;
2711
2712         if (fh->nf_type == NDIS_FH_TYPE_VFS) {
2713                 vp = fh->nf_vp;
2714                 vn_close(vp, FREAD, NULL);
2715         }
2716
2717         fh->nf_vp = NULL;
2718         kfree(fh->nf_name, M_DEVBUF);
2719         ExFreePool(fh);
2720 }
2721
2722 static uint8_t
2723 NdisSystemProcessorCount(void)
2724 {
2725         return (ncpus);
2726 }
2727
2728 static void
2729 NdisGetCurrentProcessorCounts(uint32_t *idle_count, uint32_t *kernel_and_user,
2730     uint32_t *index)
2731 {
2732 #if 0 /* XXX swildner */
2733         struct pcpu             *pcpu;
2734
2735         pcpu = pcpu_find(curthread->td_oncpu);
2736         *index = pcpu->pc_cpuid;
2737         *idle_count = pcpu->pc_cp_time[CP_IDLE];
2738         *kernel_and_user = pcpu->pc_cp_time[CP_INTR];
2739 #else
2740         panic("%s", __func__);
2741 #endif
2742 }
2743
2744 typedef void (*ndis_statusdone_handler)(ndis_handle);
2745 typedef void (*ndis_status_handler)(ndis_handle, ndis_status,
2746         void *, uint32_t);
2747
2748 static void
2749 NdisMIndicateStatusComplete(ndis_handle adapter)
2750 {
2751         ndis_miniport_block     *block;
2752         ndis_statusdone_handler statusdonefunc;
2753
2754         block = (ndis_miniport_block *)adapter;
2755         statusdonefunc = block->nmb_statusdone_func;
2756
2757         MSCALL1(statusdonefunc, adapter);
2758 }
2759
2760 static void
2761 NdisMIndicateStatus(ndis_handle adapter, ndis_status status, void *sbuf,
2762     uint32_t slen)
2763 {
2764         ndis_miniport_block     *block;
2765         ndis_status_handler     statusfunc;
2766
2767         block = (ndis_miniport_block *)adapter;
2768         statusfunc = block->nmb_status_func;
2769
2770         MSCALL4(statusfunc, adapter, status, sbuf, slen);
2771 }
2772
2773 /*
2774  * The DDK documentation says that you should use IoQueueWorkItem()
2775  * instead of ExQueueWorkItem(). The problem is, IoQueueWorkItem()
2776  * is fundamentally incompatible with NdisScheduleWorkItem(), which
2777  * depends on the API semantics of ExQueueWorkItem(). In our world,
2778  * ExQueueWorkItem() is implemented on top of IoAllocateQueueItem()
2779  * anyway.
2780  *
2781  * There are actually three distinct APIs here. NdisScheduleWorkItem()
2782  * takes a pointer to an NDIS_WORK_ITEM. ExQueueWorkItem() takes a pointer
2783  * to a WORK_QUEUE_ITEM. And finally, IoQueueWorkItem() takes a pointer
2784  * to an opaque work item thingie which you get from IoAllocateWorkItem().
2785  * An NDIS_WORK_ITEM is not the same as a WORK_QUEUE_ITEM. However,
2786  * the NDIS_WORK_ITEM has some opaque storage at the end of it, and we
2787  * (ab)use this storage as a WORK_QUEUE_ITEM, which is what we submit
2788  * to ExQueueWorkItem().
2789  *
2790  * Got all that? (Sheesh.)
2791  */
2792
2793 ndis_status
2794 NdisScheduleWorkItem(ndis_work_item *work)
2795 {
2796         work_queue_item         *wqi;
2797
2798         wqi = (work_queue_item *)work->nwi_wraprsvd;
2799         ExInitializeWorkItem(wqi,
2800             (work_item_func)work->nwi_func, work->nwi_ctx);
2801         ExQueueWorkItem(wqi, WORKQUEUE_DELAYED);
2802
2803         return (NDIS_STATUS_SUCCESS);
2804 }
2805
2806 static void
2807 NdisCopyFromPacketToPacket(ndis_packet *dpkt, uint32_t doff, uint32_t reqlen,
2808     ndis_packet *spkt, uint32_t soff, uint32_t *cpylen)
2809 {
2810         ndis_buffer             *src, *dst;
2811         char                    *sptr, *dptr;
2812         int                     resid, copied, len, scnt, dcnt;
2813
2814         *cpylen = 0;
2815
2816         src = spkt->np_private.npp_head;
2817         dst = dpkt->np_private.npp_head;
2818
2819         sptr = MmGetMdlVirtualAddress(src);
2820         dptr = MmGetMdlVirtualAddress(dst);
2821         scnt = MmGetMdlByteCount(src);
2822         dcnt = MmGetMdlByteCount(dst);
2823
2824         while (soff) {
2825                 if (MmGetMdlByteCount(src) > soff) {
2826                         sptr += soff;
2827                         scnt = MmGetMdlByteCount(src)- soff;
2828                         break;
2829                 }
2830                 soff -= MmGetMdlByteCount(src);
2831                 src = src->mdl_next;
2832                 if (src == NULL)
2833                         return;
2834                 sptr = MmGetMdlVirtualAddress(src);
2835         }
2836
2837         while (doff) {
2838                 if (MmGetMdlByteCount(dst) > doff) {
2839                         dptr += doff;
2840                         dcnt = MmGetMdlByteCount(dst) - doff;
2841                         break;
2842                 }
2843                 doff -= MmGetMdlByteCount(dst);
2844                 dst = dst->mdl_next;
2845                 if (dst == NULL)
2846                         return;
2847                 dptr = MmGetMdlVirtualAddress(dst);
2848         }
2849
2850         resid = reqlen;
2851         copied = 0;
2852
2853         while(1) {
2854                 if (resid < scnt)
2855                         len = resid;
2856                 else
2857                         len = scnt;
2858                 if (dcnt < len)
2859                         len = dcnt;
2860
2861                 bcopy(sptr, dptr, len);
2862
2863                 copied += len;
2864                 resid -= len;
2865                 if (resid == 0)
2866                         break;
2867
2868                 dcnt -= len;
2869                 if (dcnt == 0) {
2870                         dst = dst->mdl_next;
2871                         if (dst == NULL)
2872                                 break;
2873                         dptr = MmGetMdlVirtualAddress(dst);
2874                         dcnt = MmGetMdlByteCount(dst);
2875                 }
2876
2877                 scnt -= len;
2878                 if (scnt == 0) {
2879                         src = src->mdl_next;
2880                         if (src == NULL)
2881                                 break;
2882                         sptr = MmGetMdlVirtualAddress(src);
2883                         scnt = MmGetMdlByteCount(src);
2884                 }
2885         }
2886
2887         *cpylen = copied;
2888 }
2889
2890 static void
2891 NdisCopyFromPacketToPacketSafe(ndis_packet *dpkt, uint32_t doff,
2892     uint32_t reqlen, ndis_packet *spkt, uint32_t soff, uint32_t *cpylen,
2893     uint32_t prio)
2894 {
2895         NdisCopyFromPacketToPacket(dpkt, doff, reqlen, spkt, soff, cpylen);
2896 }
2897
2898 static void
2899 NdisIMCopySendPerPacketInfo(ndis_packet *dpkt, ndis_packet *spkt)
2900 {
2901         memcpy(&dpkt->np_ext, &spkt->np_ext, sizeof(ndis_packet_extension));
2902 }
2903
2904 static ndis_status
2905 NdisMRegisterDevice(ndis_handle handle, unicode_string *devname,
2906     unicode_string *symname, driver_dispatch *majorfuncs[], void **devobj,
2907     ndis_handle *devhandle)
2908 {
2909         uint32_t                status;
2910         device_object           *dobj;
2911
2912         status = IoCreateDevice(handle, 0, devname,
2913             FILE_DEVICE_UNKNOWN, 0, FALSE, &dobj);
2914
2915         if (status == STATUS_SUCCESS) {
2916                 *devobj = dobj;
2917                 *devhandle = dobj;
2918         }
2919
2920         return (status);
2921 }
2922
2923 static ndis_status
2924 NdisMDeregisterDevice(ndis_handle handle)
2925 {
2926         IoDeleteDevice(handle);
2927         return (NDIS_STATUS_SUCCESS);
2928 }
2929
2930 static ndis_status
2931 NdisMQueryAdapterInstanceName(unicode_string *name, ndis_handle handle)
2932 {
2933         ndis_miniport_block     *block;
2934         device_t                dev;
2935         ansi_string             as;
2936
2937         block = (ndis_miniport_block *)handle;
2938         dev = block->nmb_physdeviceobj->do_devext;
2939
2940         RtlInitAnsiString(&as, __DECONST(char *, device_get_nameunit(dev)));
2941         if (RtlAnsiStringToUnicodeString(name, &as, TRUE))
2942                 return (NDIS_STATUS_RESOURCES);
2943
2944         return (NDIS_STATUS_SUCCESS);
2945 }
2946
2947 static void
2948 NdisMRegisterUnloadHandler(ndis_handle handle, void *func)
2949 {
2950 }
2951
2952 static void
2953 dummy(void)
2954 {
2955         kprintf("NDIS dummy called...\n");
2956 }
2957
2958 /*
2959  * Note: a couple of entries in this table specify the
2960  * number of arguments as "foo + 1". These are routines
2961  * that accept a 64-bit argument, passed by value. On
2962  * x86, these arguments consume two longwords on the stack,
2963  * so we lie and say there's one additional argument so
2964  * that the wrapping routines will do the right thing.
2965  */
2966
2967 image_patch_table ndis_functbl[] = {
2968         IMPORT_SFUNC(NdisCopyFromPacketToPacket, 6),
2969         IMPORT_SFUNC(NdisCopyFromPacketToPacketSafe, 7),
2970         IMPORT_SFUNC(NdisIMCopySendPerPacketInfo, 2),
2971         IMPORT_SFUNC(NdisScheduleWorkItem, 1),
2972         IMPORT_SFUNC(NdisMIndicateStatusComplete, 1),
2973         IMPORT_SFUNC(NdisMIndicateStatus, 4),
2974         IMPORT_SFUNC(NdisSystemProcessorCount, 0),
2975         IMPORT_SFUNC(NdisGetCurrentProcessorCounts, 3),
2976         IMPORT_SFUNC(NdisUnchainBufferAtBack, 2),
2977         IMPORT_SFUNC(NdisGetFirstBufferFromPacket, 5),
2978         IMPORT_SFUNC(NdisGetFirstBufferFromPacketSafe, 6),
2979         IMPORT_SFUNC(NdisGetBufferPhysicalArraySize, 2),
2980         IMPORT_SFUNC(NdisMGetDeviceProperty, 6),
2981         IMPORT_SFUNC(NdisInitAnsiString, 2),
2982         IMPORT_SFUNC(NdisInitUnicodeString, 2),
2983         IMPORT_SFUNC(NdisWriteConfiguration, 4),
2984         IMPORT_SFUNC(NdisAnsiStringToUnicodeString, 2),
2985         IMPORT_SFUNC(NdisTerminateWrapper, 2),
2986         IMPORT_SFUNC(NdisOpenConfigurationKeyByName, 4),
2987         IMPORT_SFUNC(NdisOpenConfigurationKeyByIndex, 5),
2988         IMPORT_SFUNC(NdisMRemoveMiniport, 1),
2989         IMPORT_SFUNC(NdisInitializeString, 2),
2990         IMPORT_SFUNC(NdisFreeString, 1),
2991         IMPORT_SFUNC(NdisGetCurrentSystemTime, 1),
2992         IMPORT_SFUNC(NdisGetRoutineAddress, 1),
2993         IMPORT_SFUNC(NdisGetSystemUpTime, 1),
2994         IMPORT_SFUNC(NdisGetVersion, 0),
2995         IMPORT_SFUNC(NdisMSynchronizeWithInterrupt, 3),
2996         IMPORT_SFUNC(NdisMAllocateSharedMemoryAsync, 4),
2997         IMPORT_SFUNC(NdisInterlockedInsertHeadList, 3),
2998         IMPORT_SFUNC(NdisInterlockedInsertTailList, 3),
2999         IMPORT_SFUNC(NdisInterlockedRemoveHeadList, 2),
3000         IMPORT_SFUNC(NdisInitializeWrapper, 4),
3001         IMPORT_SFUNC(NdisMRegisterMiniport, 3),
3002         IMPORT_SFUNC(NdisAllocateMemoryWithTag, 3),
3003         IMPORT_SFUNC(NdisAllocateMemory, 4 + 1),
3004         IMPORT_SFUNC(NdisMSetAttributesEx, 5),
3005         IMPORT_SFUNC(NdisCloseConfiguration, 1),
3006         IMPORT_SFUNC(NdisReadConfiguration, 5),
3007         IMPORT_SFUNC(NdisOpenConfiguration, 3),
3008         IMPORT_SFUNC(NdisAcquireSpinLock, 1),
3009         IMPORT_SFUNC(NdisReleaseSpinLock, 1),
3010         IMPORT_SFUNC(NdisDprAcquireSpinLock, 1),
3011         IMPORT_SFUNC(NdisDprReleaseSpinLock, 1),
3012         IMPORT_SFUNC(NdisAllocateSpinLock, 1),
3013         IMPORT_SFUNC(NdisInitializeReadWriteLock, 1),
3014         IMPORT_SFUNC(NdisAcquireReadWriteLock, 3),
3015         IMPORT_SFUNC(NdisReleaseReadWriteLock, 2),
3016         IMPORT_SFUNC(NdisFreeSpinLock, 1),
3017         IMPORT_SFUNC(NdisFreeMemory, 3),
3018         IMPORT_SFUNC(NdisReadPciSlotInformation, 5),
3019         IMPORT_SFUNC(NdisWritePciSlotInformation, 5),
3020         IMPORT_SFUNC_MAP(NdisImmediateReadPciSlotInformation,
3021             NdisReadPciSlotInformation, 5),
3022         IMPORT_SFUNC_MAP(NdisImmediateWritePciSlotInformation,
3023             NdisWritePciSlotInformation, 5),
3024         IMPORT_CFUNC(NdisWriteErrorLogEntry, 0),
3025         IMPORT_SFUNC(NdisMStartBufferPhysicalMapping, 6),
3026         IMPORT_SFUNC(NdisMCompleteBufferPhysicalMapping, 3),
3027         IMPORT_SFUNC(NdisMInitializeTimer, 4),
3028         IMPORT_SFUNC(NdisInitializeTimer, 3),
3029         IMPORT_SFUNC(NdisSetTimer, 2),
3030         IMPORT_SFUNC(NdisMCancelTimer, 2),
3031         IMPORT_SFUNC_MAP(NdisCancelTimer, NdisMCancelTimer, 2),
3032         IMPORT_SFUNC(NdisMSetPeriodicTimer, 2),
3033         IMPORT_SFUNC(NdisMQueryAdapterResources, 4),
3034         IMPORT_SFUNC(NdisMRegisterIoPortRange, 4),
3035         IMPORT_SFUNC(NdisMDeregisterIoPortRange, 4),
3036         IMPORT_SFUNC(NdisReadNetworkAddress, 4),
3037         IMPORT_SFUNC(NdisQueryMapRegisterCount, 2),
3038         IMPORT_SFUNC(NdisMAllocateMapRegisters, 5),
3039         IMPORT_SFUNC(NdisMFreeMapRegisters, 1),
3040         IMPORT_SFUNC(NdisMAllocateSharedMemory, 5),
3041         IMPORT_SFUNC(NdisMMapIoSpace, 4 + 1),
3042         IMPORT_SFUNC(NdisMUnmapIoSpace, 3),
3043         IMPORT_SFUNC(NdisGetCacheFillSize, 0),
3044         IMPORT_SFUNC(NdisMGetDmaAlignment, 1),
3045         IMPORT_SFUNC(NdisMInitializeScatterGatherDma, 3),
3046         IMPORT_SFUNC(NdisAllocatePacketPool, 4),
3047         IMPORT_SFUNC(NdisAllocatePacketPoolEx, 5),
3048         IMPORT_SFUNC(NdisAllocatePacket, 3),
3049         IMPORT_SFUNC(NdisFreePacket, 1),
3050         IMPORT_SFUNC(NdisFreePacketPool, 1),
3051         IMPORT_SFUNC_MAP(NdisDprAllocatePacket, NdisAllocatePacket, 3),
3052         IMPORT_SFUNC_MAP(NdisDprFreePacket, NdisFreePacket, 1),
3053         IMPORT_SFUNC(NdisAllocateBufferPool, 3),
3054         IMPORT_SFUNC(NdisAllocateBuffer, 5),
3055         IMPORT_SFUNC(NdisQueryBuffer, 3),
3056         IMPORT_SFUNC(NdisQueryBufferSafe, 4),
3057         IMPORT_SFUNC(NdisBufferVirtualAddress, 1),
3058         IMPORT_SFUNC(NdisBufferVirtualAddressSafe, 2),
3059         IMPORT_SFUNC(NdisBufferLength, 1),
3060         IMPORT_SFUNC(NdisFreeBuffer, 1),
3061         IMPORT_SFUNC(NdisFreeBufferPool, 1),
3062         IMPORT_SFUNC(NdisInterlockedIncrement, 1),
3063         IMPORT_SFUNC(NdisInterlockedDecrement, 1),
3064         IMPORT_SFUNC(NdisInitializeEvent, 1),
3065         IMPORT_SFUNC(NdisSetEvent, 1),
3066         IMPORT_SFUNC(NdisResetEvent, 1),
3067         IMPORT_SFUNC(NdisWaitEvent, 2),
3068         IMPORT_SFUNC(NdisUnicodeStringToAnsiString, 2),
3069         IMPORT_SFUNC(NdisMPciAssignResources, 3),
3070         IMPORT_SFUNC(NdisMFreeSharedMemory, 5 + 1),
3071         IMPORT_SFUNC(NdisMRegisterInterrupt, 7),
3072         IMPORT_SFUNC(NdisMDeregisterInterrupt, 1),
3073         IMPORT_SFUNC(NdisMRegisterAdapterShutdownHandler, 3),
3074         IMPORT_SFUNC(NdisMDeregisterAdapterShutdownHandler, 1),
3075         IMPORT_SFUNC(NDIS_BUFFER_TO_SPAN_PAGES, 1),
3076         IMPORT_SFUNC(NdisQueryBufferOffset, 3),
3077         IMPORT_SFUNC(NdisAdjustBufferLength, 2),
3078         IMPORT_SFUNC(NdisPacketPoolUsage, 1),
3079         IMPORT_SFUNC(NdisMSleep, 1),
3080         IMPORT_SFUNC(NdisUnchainBufferAtFront, 2),
3081         IMPORT_SFUNC(NdisReadPcmciaAttributeMemory, 4),
3082         IMPORT_SFUNC(NdisWritePcmciaAttributeMemory, 4),
3083         IMPORT_SFUNC(NdisOpenFile, 5 + 1),
3084         IMPORT_SFUNC(NdisMapFile, 3),
3085         IMPORT_SFUNC(NdisUnmapFile, 1),
3086         IMPORT_SFUNC(NdisCloseFile, 1),
3087         IMPORT_SFUNC(NdisMRegisterDevice, 6),
3088         IMPORT_SFUNC(NdisMDeregisterDevice, 1),
3089         IMPORT_SFUNC(NdisMQueryAdapterInstanceName, 2),
3090         IMPORT_SFUNC(NdisMRegisterUnloadHandler, 2),
3091         IMPORT_SFUNC(ndis_timercall, 4),
3092         IMPORT_SFUNC(ndis_asyncmem_complete, 2),
3093         IMPORT_SFUNC(ndis_intr, 2),
3094         IMPORT_SFUNC(ndis_intrhand, 4),
3095
3096         /*
3097          * This last entry is a catch-all for any function we haven't
3098          * implemented yet. The PE import list patching routine will
3099          * use it for any function that doesn't have an explicit match
3100          * in this table.
3101          */
3102
3103         { NULL, (FUNC)dummy, NULL, 0, WINDRV_WRAP_STDCALL },
3104
3105         /* End of list. */
3106
3107         { NULL, NULL, NULL }
3108 };