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