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