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