Sync ndis(4) and tools with FreeBSD and hook it all back into the build.
[dragonfly.git] / sys / emulation / ndis / kern_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/kern_ndis.c,v 1.111 2011/02/23 21:45:28 brucec Exp $
33  */
34
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/unistd.h>
38 #include <sys/types.h>
39 #include <sys/errno.h>
40 #include <sys/callout.h>
41 #include <sys/socket.h>
42 #include <sys/queue.h>
43 #include <sys/sysctl.h>
44 #include <sys/proc.h>
45 #include <sys/malloc.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/conf.h>
49
50 #include <sys/kernel.h>
51 #include <sys/module.h>
52 #include <sys/kthread.h>
53 #include <sys/bus.h>
54 #include <sys/rman.h>
55 #include <sys/mplock2.h>
56
57 #include <net/if.h>
58 #include <net/if_arp.h>
59 #include <net/ethernet.h>
60 #include <net/if_dl.h>
61 #include <net/if_media.h>
62
63 #include <netproto/802_11/ieee80211_var.h>
64 #include <netproto/802_11/ieee80211_ioctl.h>
65
66 #include <bus/usb/usb.h>
67 #include <bus/usb/usbdi.h>
68
69 #include <emulation/ndis/pe_var.h>
70 #include <emulation/ndis/cfg_var.h>
71 #include <emulation/ndis/resource_var.h>
72 #include <emulation/ndis/ntoskrnl_var.h>
73 #include <emulation/ndis/ndis_var.h>
74 #include <emulation/ndis/hal_var.h>
75 #include <emulation/ndis/usbd_var.h>
76 #include <dev/netif/ndis/if_ndisvar.h>
77
78 #define NDIS_DUMMY_PATH "\\\\some\\bogus\\path"
79
80 static void ndis_status_func(ndis_handle, ndis_status, void *, uint32_t);
81 static void ndis_statusdone_func(ndis_handle);
82 static void ndis_setdone_func(ndis_handle, ndis_status);
83 static void ndis_getdone_func(ndis_handle, ndis_status);
84 static void ndis_resetdone_func(ndis_handle, ndis_status, uint8_t);
85 static void ndis_sendrsrcavail_func(ndis_handle);
86 static void ndis_intrsetup(kdpc *, device_object *,
87         irp *, struct ndis_softc *);
88 static void ndis_return(device_object *, void *);
89
90 static image_patch_table kernndis_functbl[] = {
91         IMPORT_SFUNC(ndis_status_func, 4),
92         IMPORT_SFUNC(ndis_statusdone_func, 1),
93         IMPORT_SFUNC(ndis_setdone_func, 2),
94         IMPORT_SFUNC(ndis_getdone_func, 2),
95         IMPORT_SFUNC(ndis_resetdone_func, 3),
96         IMPORT_SFUNC(ndis_sendrsrcavail_func, 1),
97         IMPORT_SFUNC(ndis_intrsetup, 4),
98         IMPORT_SFUNC(ndis_return, 1),
99
100         { NULL, NULL, NULL }
101 };
102
103 static struct nd_head ndis_devhead;
104
105 /*
106  * This allows us to export our symbols to other modules.
107  * Note that we call ourselves 'ndisapi' to avoid a namespace
108  * collision with if_ndis.ko, which internally calls itself
109  * 'ndis.'
110  *
111  * Note: some of the subsystems depend on each other, so the
112  * order in which they're started is important. The order of
113  * importance is:
114  *
115  * HAL - spinlocks and IRQL manipulation
116  * ntoskrnl - DPC and workitem threads, object waiting
117  * windrv - driver/device registration
118  *
119  * The HAL should also be the last thing shut down, since
120  * the ntoskrnl subsystem will use spinlocks right up until
121  * the DPC and workitem threads are terminated.
122  */
123
124 static int
125 ndis_modevent(module_t mod, int cmd, void *arg)
126 {
127         int                     error = 0;
128         image_patch_table       *patch;
129
130         switch (cmd) {
131         case MOD_LOAD:
132                 /* Initialize subsystems */
133                 hal_libinit();
134                 ntoskrnl_libinit();
135                 windrv_libinit();
136                 ndis_libinit();
137                 usbd_libinit();
138
139                 patch = kernndis_functbl;
140                 while (patch->ipt_func != NULL) {
141                         windrv_wrap((funcptr)patch->ipt_func,
142                             (funcptr *)&patch->ipt_wrap,
143                             patch->ipt_argcnt, patch->ipt_ftype);
144                         patch++;
145                 }
146
147                 TAILQ_INIT(&ndis_devhead);
148                 break;
149         case MOD_SHUTDOWN:
150                 if (TAILQ_FIRST(&ndis_devhead) == NULL) {
151                         /* Shut down subsystems */
152                         ndis_libfini();
153                         usbd_libfini();
154                         windrv_libfini();
155                         ntoskrnl_libfini();
156                         hal_libfini();
157
158                         patch = kernndis_functbl;
159                         while (patch->ipt_func != NULL) {
160                                 windrv_unwrap(patch->ipt_wrap);
161                                 patch++;
162                         }
163                 }
164                 break;
165         case MOD_UNLOAD:
166                 /* Shut down subsystems */
167                 ndis_libfini();
168                 usbd_libfini();
169                 windrv_libfini();
170                 ntoskrnl_libfini();
171                 hal_libfini();
172
173                 patch = kernndis_functbl;
174                 while (patch->ipt_func != NULL) {
175                         windrv_unwrap(patch->ipt_wrap);
176                         patch++;
177                 }
178
179                 break;
180         default:
181                 error = EINVAL;
182                 break;
183         }
184
185         return (error);
186 }
187 DEV_MODULE(ndis, ndis_modevent, NULL);
188 MODULE_VERSION(ndis, 1);
189
190 static void
191 ndis_sendrsrcavail_func(ndis_handle adapter)
192 {
193 }
194
195 static void
196 ndis_status_func(ndis_handle adapter, ndis_status status, void *sbuf,
197     uint32_t slen)
198 {
199         ndis_miniport_block     *block;
200         struct ndis_softc       *sc;
201         struct ifnet            *ifp;
202
203         block = adapter;
204         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
205         ifp = sc->ifp;
206         if (ifp->if_flags & IFF_DEBUG)
207                 device_printf(sc->ndis_dev, "status: %x\n", status);
208 }
209
210 static void
211 ndis_statusdone_func(ndis_handle adapter)
212 {
213         ndis_miniport_block     *block;
214         struct ndis_softc       *sc;
215         struct ifnet            *ifp;
216
217         block = adapter;
218         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
219         ifp = sc->ifp;
220         if (ifp->if_flags & IFF_DEBUG)
221                 device_printf(sc->ndis_dev, "status complete\n");
222 }
223
224 static void
225 ndis_setdone_func(ndis_handle adapter, ndis_status status)
226 {
227         ndis_miniport_block     *block;
228         block = adapter;
229
230         block->nmb_setstat = status;
231         KeSetEvent(&block->nmb_setevent, IO_NO_INCREMENT, FALSE);
232 }
233
234 static void
235 ndis_getdone_func(ndis_handle adapter, ndis_status status)
236 {
237         ndis_miniport_block     *block;
238         block = adapter;
239
240         block->nmb_getstat = status;
241         KeSetEvent(&block->nmb_getevent, IO_NO_INCREMENT, FALSE);
242 }
243
244 static void
245 ndis_resetdone_func(ndis_handle adapter, ndis_status status,
246         uint8_t addressingreset)
247 {
248         ndis_miniport_block     *block;
249         struct ndis_softc       *sc;
250         struct ifnet            *ifp;
251
252         block = adapter;
253         sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
254         ifp = sc->ifp;
255
256         if (ifp->if_flags & IFF_DEBUG)
257                 device_printf(sc->ndis_dev, "reset done...\n");
258         KeSetEvent(&block->nmb_resetevent, IO_NO_INCREMENT, FALSE);
259 }
260
261 int
262 ndis_create_sysctls(void *arg)
263 {
264         struct ndis_softc       *sc;
265         ndis_cfg                *vals;
266         char                    buf[256];
267         struct sysctl_oid       *oidp;
268         struct sysctl_ctx_entry *e;
269
270         if (arg == NULL)
271                 return (EINVAL);
272
273         sc = arg;
274         vals = sc->ndis_regvals;
275
276         TAILQ_INIT(&sc->ndis_cfglist_head);
277
278         /* Create the sysctl tree. */
279
280         sc->ndis_tree = SYSCTL_ADD_NODE(&sc->ndis_ctx,
281             SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
282             device_get_nameunit(sc->ndis_dev), CTLFLAG_RD, 0,
283             device_get_desc(sc->ndis_dev));
284
285         /* Add the driver-specific registry keys. */
286
287         while(1) {
288                 if (vals->nc_cfgkey == NULL)
289                         break;
290
291                 if (vals->nc_idx != sc->ndis_devidx) {
292                         vals++;
293                         continue;
294                 }
295
296                 /* See if we already have a sysctl with this name */
297
298                 oidp = NULL;
299                 TAILQ_FOREACH(e, &sc->ndis_ctx, link) {
300                         oidp = e->entry;
301                         if (strcasecmp(oidp->oid_name, vals->nc_cfgkey) == 0)
302                                 break;
303                         oidp = NULL;
304                 }
305
306                 if (oidp != NULL) {
307                         vals++;
308                         continue;
309                 }
310
311                 ndis_add_sysctl(sc, vals->nc_cfgkey, vals->nc_cfgdesc,
312                     vals->nc_val, CTLFLAG_RW);
313                 vals++;
314         }
315
316         /* Now add a couple of builtin keys. */
317
318         /*
319          * Environment can be either Windows (0) or WindowsNT (1).
320          * We qualify as the latter.
321          */
322         ndis_add_sysctl(sc, "Environment",
323             "Windows environment", "1", CTLFLAG_RD);
324
325         /* NDIS version should be 5.1. */
326         ndis_add_sysctl(sc, "NdisVersion",
327             "NDIS API Version", "0x00050001", CTLFLAG_RD);
328
329         /*
330          * Some miniport drivers rely on the existence of the SlotNumber,
331          * NetCfgInstanceId and DriverDesc keys.
332          */
333         ndis_add_sysctl(sc, "SlotNumber", "Slot Numer", "01", CTLFLAG_RD);
334         ndis_add_sysctl(sc, "NetCfgInstanceId", "NetCfgInstanceId",
335             "{12345678-1234-5678-CAFE0-123456789ABC}", CTLFLAG_RD);
336         ndis_add_sysctl(sc, "DriverDesc", "Driver Description",
337             "NDIS Network Adapter", CTLFLAG_RD);
338
339         /* Bus type (PCI, PCMCIA, etc...) */
340         ksprintf(buf, "%d", (int)sc->ndis_iftype);
341         ndis_add_sysctl(sc, "BusType", "Bus Type", buf, CTLFLAG_RD);
342
343         if (sc->ndis_res_io != NULL) {
344                 ksprintf(buf, "0x%lx", rman_get_start(sc->ndis_res_io));
345                 ndis_add_sysctl(sc, "IOBaseAddress",
346                     "Base I/O Address", buf, CTLFLAG_RD);
347         }
348
349         if (sc->ndis_irq != NULL) {
350                 ksprintf(buf, "%lu", rman_get_start(sc->ndis_irq));
351                 ndis_add_sysctl(sc, "InterruptNumber",
352                     "Interrupt Number", buf, CTLFLAG_RD);
353         }
354
355         return (0);
356 }
357
358 int
359 ndis_add_sysctl(void *arg, char *key, char *desc, char *val, int flag)
360 {
361         struct ndis_softc       *sc;
362         struct ndis_cfglist     *cfg;
363         char                    descstr[256];
364
365         sc = arg;
366
367         cfg = kmalloc(sizeof(struct ndis_cfglist), M_DEVBUF, M_WAITOK|M_ZERO);
368         cfg->ndis_cfg.nc_cfgkey = kstrdup(key, M_DEVBUF);
369         if (desc == NULL) {
370                 ksnprintf(descstr, sizeof(descstr), "%s (dynamic)", key);
371                 cfg->ndis_cfg.nc_cfgdesc = kstrdup(descstr, M_DEVBUF);
372         } else
373                 cfg->ndis_cfg.nc_cfgdesc = kstrdup(desc, M_DEVBUF);
374         strcpy(cfg->ndis_cfg.nc_val, val);
375
376         TAILQ_INSERT_TAIL(&sc->ndis_cfglist_head, cfg, link);
377
378         cfg->ndis_oid =
379         SYSCTL_ADD_STRING(&sc->ndis_ctx, SYSCTL_CHILDREN(sc->ndis_tree),
380             OID_AUTO, cfg->ndis_cfg.nc_cfgkey, flag,
381             cfg->ndis_cfg.nc_val, sizeof(cfg->ndis_cfg.nc_val),
382             cfg->ndis_cfg.nc_cfgdesc);
383
384         return (0);
385 }
386
387 /*
388  * Somewhere, somebody decided "hey, let's automatically create
389  * a sysctl tree for each device instance as it's created -- it'll
390  * make life so much easier!" Lies. Why must they turn the kernel
391  * into a house of lies?
392  */
393
394 int
395 ndis_flush_sysctls(void *arg)
396 {
397         struct ndis_softc       *sc;
398         struct ndis_cfglist     *cfg;
399         struct sysctl_ctx_list  *clist;
400
401         sc = arg;
402
403         clist = &sc->ndis_ctx;
404
405         while (!TAILQ_EMPTY(&sc->ndis_cfglist_head)) {
406                 cfg = TAILQ_FIRST(&sc->ndis_cfglist_head);
407                 TAILQ_REMOVE(&sc->ndis_cfglist_head, cfg, link);
408                 sysctl_ctx_entry_del(clist, cfg->ndis_oid);
409                 sysctl_remove_oid(cfg->ndis_oid, 1, 0);
410                 kfree(cfg->ndis_cfg.nc_cfgkey, M_DEVBUF);
411                 kfree(cfg->ndis_cfg.nc_cfgdesc, M_DEVBUF);
412                 kfree(cfg, M_DEVBUF);
413         }
414
415         return (0);
416 }
417
418 void *
419 ndis_get_routine_address(struct image_patch_table *functbl, char *name)
420 {
421         int                     i;
422
423         for (i = 0; functbl[i].ipt_name != NULL; i++)
424                 if (strcmp(name, functbl[i].ipt_name) == 0)
425                         return (functbl[i].ipt_wrap);
426         return (NULL);
427 }
428
429 static void
430 ndis_return(device_object *dobj, void *arg)
431 {
432         ndis_miniport_block     *block;
433         ndis_miniport_characteristics   *ch;
434         ndis_return_handler     returnfunc;
435         ndis_handle             adapter;
436         ndis_packet             *p;
437         uint8_t                 irql;
438         list_entry              *l;
439
440         block = arg;
441         ch = IoGetDriverObjectExtension(dobj->do_drvobj, (void *)1);
442
443         p = arg;
444         adapter = block->nmb_miniportadapterctx;
445
446         if (adapter == NULL)
447                 return;
448
449         returnfunc = ch->nmc_return_packet_func;
450
451         KeAcquireSpinLock(&block->nmb_returnlock, &irql);
452         while (!IsListEmpty(&block->nmb_returnlist)) {
453                 l = RemoveHeadList((&block->nmb_returnlist));
454                 p = CONTAINING_RECORD(l, ndis_packet, np_list);
455                 InitializeListHead((&p->np_list));
456                 KeReleaseSpinLock(&block->nmb_returnlock, irql);
457                 MSCALL2(returnfunc, adapter, p);
458                 KeAcquireSpinLock(&block->nmb_returnlock, &irql);
459         }
460         KeReleaseSpinLock(&block->nmb_returnlock, irql);
461 }
462
463 static void
464 ndis_reference_packet(void *arg)
465 {
466         ndis_packet             *p;
467
468         if (arg == NULL)
469                 return;
470
471         p = arg;
472
473         /* Increment refcount. */
474         atomic_add_int(&p->np_refcnt, 1);
475 }
476
477 void
478 ndis_return_packet(void *arg)
479 {
480         ndis_packet             *p;
481         ndis_miniport_block     *block;
482
483         if (arg == NULL)
484                 return;
485
486         p = arg;
487
488         /* Release packet when refcount hits zero, otherwise return. */
489         if (atomic_fetchadd_int(&p->np_refcnt, -1) > 1)
490                 return;
491
492         block = ((struct ndis_softc *)p->np_softc)->ndis_block;
493
494         KeAcquireSpinLockAtDpcLevel(&block->nmb_returnlock);
495         InitializeListHead((&p->np_list));
496         InsertHeadList((&block->nmb_returnlist), (&p->np_list));
497         KeReleaseSpinLockFromDpcLevel(&block->nmb_returnlock);
498
499         IoQueueWorkItem(block->nmb_returnitem,
500             (io_workitem_func)kernndis_functbl[7].ipt_wrap,
501             WORKQUEUE_CRITICAL, block);
502 }
503
504 void
505 ndis_free_bufs(ndis_buffer *b0)
506 {
507         ndis_buffer             *next;
508
509         if (b0 == NULL)
510                 return;
511
512         while(b0 != NULL) {
513                 next = b0->mdl_next;
514                 IoFreeMdl(b0);
515                 b0 = next;
516         }
517 }
518
519 void
520 ndis_free_packet(ndis_packet *p)
521 {
522         if (p == NULL)
523                 return;
524
525         ndis_free_bufs(p->np_private.npp_head);
526         NdisFreePacket(p);
527 }
528
529 int
530 ndis_convert_res(void *arg)
531 {
532         struct ndis_softc       *sc;
533         ndis_resource_list      *rl = NULL;
534         cm_partial_resource_desc        *prd = NULL;
535         ndis_miniport_block     *block;
536         device_t                dev;
537         struct resource_list    *brl;
538         struct resource_list_entry      *brle;
539         struct resource_list    brl_rev;
540         struct resource_list_entry      *n;
541         int                     error = 0;
542
543         sc = arg;
544         block = sc->ndis_block;
545         dev = sc->ndis_dev;
546
547         SLIST_INIT(&brl_rev);
548
549         rl = kmalloc(sizeof(ndis_resource_list) +
550             (sizeof(cm_partial_resource_desc) * (sc->ndis_rescnt - 1)),
551             M_DEVBUF, M_WAITOK|M_NULLOK|M_ZERO);
552
553         if (rl == NULL)
554                 return (ENOMEM);
555
556         rl->cprl_version = 5;
557         rl->cprl_version = 1;
558         rl->cprl_count = sc->ndis_rescnt;
559         prd = rl->cprl_partial_descs;
560
561         brl = BUS_GET_RESOURCE_LIST(dev, dev);
562
563         if (brl != NULL) {
564
565                 /*
566                  * We have a small problem. Some PCI devices have
567                  * multiple I/O ranges. Windows orders them starting
568                  * from lowest numbered BAR to highest. We discover
569                  * them in that order too, but insert them into a singly
570                  * linked list head first, which means when time comes
571                  * to traverse the list, we enumerate them in reverse
572                  * order. This screws up some drivers which expect the
573                  * BARs to be in ascending order so that they can choose
574                  * the "first" one as their register space. Unfortunately,
575                  * in order to fix this, we have to create our own
576                  * temporary list with the entries in reverse order.
577                  */
578
579                 SLIST_FOREACH(brle, brl, link) {
580                         n = kmalloc(sizeof(struct resource_list_entry),
581                             M_TEMP, M_WAITOK|M_NULLOK);
582                         if (n == NULL) {
583                                 error = ENOMEM;
584                                 goto bad;
585                         }
586                         bcopy((char *)brle, (char *)n,
587                             sizeof(struct resource_list_entry));
588                         SLIST_INSERT_HEAD(&brl_rev, n, link);
589                 }
590
591                 SLIST_FOREACH(brle, &brl_rev, link) {
592                         switch (brle->type) {
593                         case SYS_RES_IOPORT:
594                                 prd->cprd_type = CmResourceTypePort;
595                                 prd->cprd_flags = CM_RESOURCE_PORT_IO;
596                                 prd->cprd_sharedisp =
597                                     CmResourceShareDeviceExclusive;
598                                 prd->u.cprd_port.cprd_start.np_quad =
599                                     brle->start;
600                                 prd->u.cprd_port.cprd_len = brle->count;
601                                 break;
602                         case SYS_RES_MEMORY:
603                                 prd->cprd_type = CmResourceTypeMemory;
604                                 prd->cprd_flags =
605                                     CM_RESOURCE_MEMORY_READ_WRITE;
606                                 prd->cprd_sharedisp =
607                                     CmResourceShareDeviceExclusive;
608                                 prd->u.cprd_mem.cprd_start.np_quad =
609                                     brle->start;
610                                 prd->u.cprd_mem.cprd_len = brle->count;
611                                 break;
612                         case SYS_RES_IRQ:
613                                 prd->cprd_type = CmResourceTypeInterrupt;
614                                 prd->cprd_flags = 0;
615                                 /*
616                                  * Always mark interrupt resources as
617                                  * shared, since in our implementation,
618                                  * they will be.
619                                  */
620                                 prd->cprd_sharedisp =
621                                     CmResourceShareShared;
622                                 prd->u.cprd_intr.cprd_level = brle->start;
623                                 prd->u.cprd_intr.cprd_vector = brle->start;
624                                 prd->u.cprd_intr.cprd_affinity = 0;
625                                 break;
626                         default:
627                                 break;
628                         }
629                         prd++;
630                 }
631         }
632
633         block->nmb_rlist = rl;
634
635 bad:
636
637         while (!SLIST_EMPTY(&brl_rev)) {
638                 n = SLIST_FIRST(&brl_rev);
639                 SLIST_REMOVE_HEAD(&brl_rev, link);
640                 kfree (n, M_TEMP);
641         }
642
643         return (error);
644 }
645
646 /*
647  * Map an NDIS packet to an mbuf list. When an NDIS driver receives a
648  * packet, it will hand it to us in the form of an ndis_packet,
649  * which we need to convert to an mbuf that is then handed off
650  * to the stack. Note: we configure the mbuf list so that it uses
651  * the memory regions specified by the ndis_buffer structures in
652  * the ndis_packet as external storage. In most cases, this will
653  * point to a memory region allocated by the driver (either by
654  * ndis_malloc_withtag() or ndis_alloc_sharedmem()). We expect
655  * the driver to handle kfree()ing this region for is, so we set up
656  * a dummy no-op free handler for it.
657  */
658
659 int
660 ndis_ptom(struct mbuf **m0, ndis_packet *p)
661 {
662         struct mbuf             *m = NULL, *prev = NULL;
663         ndis_buffer             *buf;
664         ndis_packet_private     *priv;
665         uint32_t                totlen = 0;
666         struct ifnet            *ifp;
667         struct ether_header     *eh;
668         int                     diff;
669
670         if (p == NULL || m0 == NULL)
671                 return (EINVAL);
672
673         priv = &p->np_private;
674         buf = priv->npp_head;
675         p->np_refcnt = 0;
676
677         for (buf = priv->npp_head; buf != NULL; buf = buf->mdl_next) {
678                 if (buf == priv->npp_head) {
679                         /* XXX swildner: why not MT_HEADER? (see FreeBSD) */
680                         MGETHDR(m, MB_DONTWAIT, MT_DATA);
681                 } else {
682                         MGET(m, MB_DONTWAIT, MT_DATA);
683                 }
684                 if (m == NULL) {
685                         m_freem(*m0);
686                         *m0 = NULL;
687                         return (ENOBUFS);
688                 }
689                 m->m_len = MmGetMdlByteCount(buf);
690                 m->m_data = MmGetMdlVirtualAddress(buf);
691                 m_extadd(m, m->m_data, m->m_len, ndis_reference_packet,
692                     ndis_return_packet, p);
693 //              p->np_refcnt++;
694
695                 totlen += m->m_len;
696                 if (m->m_flags & M_PKTHDR)
697                         *m0 = m;
698                 else
699                         prev->m_next = m;
700                 prev = m;
701         }
702
703         /*
704          * This is a hack to deal with the Marvell 8335 driver
705          * which, when associated with an AP in WPA-PSK mode,
706          * seems to overpad its frames by 8 bytes. I don't know
707          * that the extra 8 bytes are for, and they're not there
708          * in open mode, so for now clamp the frame size at 1514
709          * until I can figure out how to deal with this properly,
710          * otherwise if_ethersubr() will spank us by discarding
711          * the 'oversize' frames.
712          */
713
714         eh = mtod((*m0), struct ether_header *);
715         ifp = ((struct ndis_softc *)p->np_softc)->ifp;
716         if (totlen > ETHER_MAX_FRAME(ifp, eh->ether_type, FALSE)) {
717                 diff = totlen - ETHER_MAX_FRAME(ifp, eh->ether_type, FALSE);
718                 totlen -= diff;
719                 m->m_len -= diff;
720         }
721         (*m0)->m_pkthdr.len = totlen;
722
723         return (0);
724 }
725
726 /*
727  * Create an NDIS packet from an mbuf chain.
728  * This is used mainly when transmitting packets, where we need
729  * to turn an mbuf off an interface's send queue and transform it
730  * into an NDIS packet which will be fed into the NDIS driver's
731  * send routine.
732  *
733  * NDIS packets consist of two parts: an ndis_packet structure,
734  * which is vaguely analagous to the pkthdr portion of an mbuf,
735  * and one or more ndis_buffer structures, which define the
736  * actual memory segments in which the packet data resides.
737  * We need to allocate one ndis_buffer for each mbuf in a chain,
738  * plus one ndis_packet as the header.
739  */
740
741 int
742 ndis_mtop(struct mbuf *m0, ndis_packet **p)
743 {
744         struct mbuf             *m;
745         ndis_buffer             *buf = NULL, *prev = NULL;
746         ndis_packet_private     *priv;
747
748         if (p == NULL || *p == NULL || m0 == NULL)
749                 return (EINVAL);
750
751         priv = &(*p)->np_private;
752         priv->npp_totlen = m0->m_pkthdr.len;
753
754         for (m = m0; m != NULL; m = m->m_next) {
755                 if (m->m_len == 0)
756                         continue;
757                 buf = IoAllocateMdl(m->m_data, m->m_len, FALSE, FALSE, NULL);
758                 if (buf == NULL) {
759                         ndis_free_packet(*p);
760                         *p = NULL;
761                         return (ENOMEM);
762                 }
763                 MmBuildMdlForNonPagedPool(buf);
764
765                 if (priv->npp_head == NULL)
766                         priv->npp_head = buf;
767                 else
768                         prev->mdl_next = buf;
769                 prev = buf;
770         }
771
772         priv->npp_tail = buf;
773
774         return (0);
775 }
776
777 int
778 ndis_get_supported_oids(void *arg, ndis_oid **oids, int *oidcnt)
779 {
780         int                     len, rval;
781         ndis_oid                *o;
782
783         if (arg == NULL || oids == NULL || oidcnt == NULL)
784                 return (EINVAL);
785         len = 0;
786         ndis_get_info(arg, OID_GEN_SUPPORTED_LIST, NULL, &len);
787
788         o = kmalloc(len, M_DEVBUF, M_WAITOK);
789
790         rval = ndis_get_info(arg, OID_GEN_SUPPORTED_LIST, o, &len);
791
792         if (rval) {
793                 kfree(o, M_DEVBUF);
794                 return (rval);
795         }
796
797         *oids = o;
798         *oidcnt = len / 4;
799
800         return (0);
801 }
802
803 int
804 ndis_set_info(void *arg, ndis_oid oid, void *buf, int *buflen)
805 {
806         struct ndis_softc       *sc;
807         ndis_status             rval;
808         ndis_handle             adapter;
809         ndis_setinfo_handler    setfunc;
810         uint32_t                byteswritten = 0, bytesneeded = 0;
811         uint8_t                 irql;
812         uint64_t                duetime;
813
814         /*
815          * According to the NDIS spec, MiniportQueryInformation()
816          * and MiniportSetInformation() requests are handled serially:
817          * once one request has been issued, we must wait for it to
818          * finish before allowing another request to proceed.
819          */
820
821         sc = arg;
822
823         KeResetEvent(&sc->ndis_block->nmb_setevent);
824
825         KeAcquireSpinLock(&sc->ndis_block->nmb_lock, &irql);
826
827         if (sc->ndis_block->nmb_pendingreq != NULL) {
828                 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
829                 panic("ndis_set_info() called while other request pending");
830         } else
831                 sc->ndis_block->nmb_pendingreq = (ndis_request *)sc;
832
833         setfunc = sc->ndis_chars->nmc_setinfo_func;
834         adapter = sc->ndis_block->nmb_miniportadapterctx;
835
836         if (adapter == NULL || setfunc == NULL ||
837             sc->ndis_block->nmb_devicectx == NULL) {
838                 sc->ndis_block->nmb_pendingreq = NULL;
839                 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
840                 return (ENXIO);
841         }
842
843         rval = MSCALL6(setfunc, adapter, oid, buf, *buflen,
844             &byteswritten, &bytesneeded);
845
846         sc->ndis_block->nmb_pendingreq = NULL;
847
848         KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
849
850         if (rval == NDIS_STATUS_PENDING) {
851                 /* Wait up to 5 seconds. */
852                 duetime = (5 * 1000000) * -10;
853                 KeWaitForSingleObject(&sc->ndis_block->nmb_setevent,
854                     0, 0, FALSE, &duetime);
855                 rval = sc->ndis_block->nmb_setstat;
856         }
857
858         if (byteswritten)
859                 *buflen = byteswritten;
860         if (bytesneeded)
861                 *buflen = bytesneeded;
862
863         if (rval == NDIS_STATUS_INVALID_LENGTH)
864                 return (ENOSPC);
865
866         if (rval == NDIS_STATUS_INVALID_OID)
867                 return (EINVAL);
868
869         if (rval == NDIS_STATUS_NOT_SUPPORTED ||
870             rval == NDIS_STATUS_NOT_ACCEPTED)
871                 return (ENOTSUP);
872
873         if (rval != NDIS_STATUS_SUCCESS)
874                 return (ENODEV);
875
876         return (0);
877 }
878
879 typedef void (*ndis_senddone_func)(ndis_handle, ndis_packet *, ndis_status);
880
881 int
882 ndis_send_packets(void *arg, ndis_packet **packets, int cnt)
883 {
884         struct ndis_softc       *sc;
885         ndis_handle             adapter;
886         ndis_sendmulti_handler  sendfunc;
887         ndis_senddone_func              senddonefunc;
888         int                     i;
889         ndis_packet             *p;
890         uint8_t                 irql = 0;
891
892         sc = arg;
893         adapter = sc->ndis_block->nmb_miniportadapterctx;
894         if (adapter == NULL)
895                 return (ENXIO);
896         sendfunc = sc->ndis_chars->nmc_sendmulti_func;
897         senddonefunc = sc->ndis_block->nmb_senddone_func;
898
899         if (NDIS_SERIALIZED(sc->ndis_block))
900                 KeAcquireSpinLock(&sc->ndis_block->nmb_lock, &irql);
901
902         MSCALL3(sendfunc, adapter, packets, cnt);
903
904         for (i = 0; i < cnt; i++) {
905                 p = packets[i];
906                 /*
907                  * Either the driver already handed the packet to
908                  * ndis_txeof() due to a failure, or it wants to keep
909                  * it and release it asynchronously later. Skip to the
910                  * next one.
911                  */
912                 if (p == NULL || p->np_oob.npo_status == NDIS_STATUS_PENDING)
913                         continue;
914                 MSCALL3(senddonefunc, sc->ndis_block, p, p->np_oob.npo_status);
915         }
916
917         if (NDIS_SERIALIZED(sc->ndis_block))
918                 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
919
920         return(0);
921 }
922
923 int
924 ndis_send_packet(void *arg, ndis_packet *packet)
925 {
926         struct ndis_softc       *sc;
927         ndis_handle             adapter;
928         ndis_status             status;
929         ndis_sendsingle_handler sendfunc;
930         ndis_senddone_func              senddonefunc;
931         uint8_t                 irql = 0;
932
933         sc = arg;
934         adapter = sc->ndis_block->nmb_miniportadapterctx;
935         if (adapter == NULL)
936                 return (ENXIO);
937         sendfunc = sc->ndis_chars->nmc_sendsingle_func;
938         senddonefunc = sc->ndis_block->nmb_senddone_func;
939
940         if (NDIS_SERIALIZED(sc->ndis_block))
941                 KeAcquireSpinLock(&sc->ndis_block->nmb_lock, &irql);
942         status = MSCALL3(sendfunc, adapter, packet,
943             packet->np_private.npp_flags);
944
945         if (status == NDIS_STATUS_PENDING) {
946                 if (NDIS_SERIALIZED(sc->ndis_block))
947                         KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
948                 return (0);
949         }
950
951         MSCALL3(senddonefunc, sc->ndis_block, packet, status);
952
953         if (NDIS_SERIALIZED(sc->ndis_block))
954                 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
955
956         return (0);
957 }
958
959 int
960 ndis_init_dma(void *arg)
961 {
962         struct ndis_softc       *sc;
963         int                     i, error;
964
965         sc = arg;
966
967         sc->ndis_tmaps = kmalloc(sizeof(bus_dmamap_t) * sc->ndis_maxpkts,
968             M_DEVBUF, M_WAITOK|M_ZERO);
969
970         for (i = 0; i < sc->ndis_maxpkts; i++) {
971                 error = bus_dmamap_create(sc->ndis_ttag, 0,
972                     &sc->ndis_tmaps[i]);
973                 if (error) {
974                         kfree(sc->ndis_tmaps, M_DEVBUF);
975                         return (ENODEV);
976                 }
977         }
978
979         return (0);
980 }
981
982 int
983 ndis_destroy_dma(void *arg)
984 {
985         struct ndis_softc       *sc;
986         struct mbuf             *m;
987         ndis_packet             *p = NULL;
988         int                     i;
989
990         sc = arg;
991
992         for (i = 0; i < sc->ndis_maxpkts; i++) {
993                 if (sc->ndis_txarray[i] != NULL) {
994                         p = sc->ndis_txarray[i];
995                         m = (struct mbuf *)p->np_rsvd[1];
996                         if (m != NULL)
997                                 m_freem(m);
998                         ndis_free_packet(sc->ndis_txarray[i]);
999                 }
1000                 bus_dmamap_destroy(sc->ndis_ttag, sc->ndis_tmaps[i]);
1001         }
1002
1003         kfree(sc->ndis_tmaps, M_DEVBUF);
1004
1005         bus_dma_tag_destroy(sc->ndis_ttag);
1006
1007         return (0);
1008 }
1009
1010 int
1011 ndis_reset_nic(void *arg)
1012 {
1013         struct ndis_softc       *sc;
1014         ndis_handle             adapter;
1015         ndis_reset_handler      resetfunc;
1016         uint8_t                 addressing_reset;
1017         int                     rval;
1018         uint8_t                 irql = 0;
1019
1020         sc = arg;
1021
1022         NDIS_LOCK(sc);
1023         adapter = sc->ndis_block->nmb_miniportadapterctx;
1024         resetfunc = sc->ndis_chars->nmc_reset_func;
1025
1026         if (adapter == NULL || resetfunc == NULL ||
1027             sc->ndis_block->nmb_devicectx == NULL) {
1028                 NDIS_UNLOCK(sc);
1029                 return(EIO);
1030         }
1031
1032         NDIS_UNLOCK(sc);
1033
1034         KeResetEvent(&sc->ndis_block->nmb_resetevent);
1035
1036         if (NDIS_SERIALIZED(sc->ndis_block))
1037                 KeAcquireSpinLock(&sc->ndis_block->nmb_lock, &irql);
1038
1039         rval = MSCALL2(resetfunc, &addressing_reset, adapter);
1040
1041         if (NDIS_SERIALIZED(sc->ndis_block))
1042                 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
1043
1044         if (rval == NDIS_STATUS_PENDING)
1045                 KeWaitForSingleObject(&sc->ndis_block->nmb_resetevent,
1046                     0, 0, FALSE, NULL);
1047
1048         return (0);
1049 }
1050
1051 int
1052 ndis_halt_nic(void *arg)
1053 {
1054         struct ndis_softc       *sc;
1055         ndis_handle             adapter;
1056         ndis_halt_handler       haltfunc;
1057         ndis_miniport_block     *block;
1058         int                     empty = 0;
1059         uint8_t                 irql;
1060
1061         sc = arg;
1062         block = sc->ndis_block;
1063
1064         if (!cold)
1065                 KeFlushQueuedDpcs();
1066
1067         /*
1068          * Wait for all packets to be returned.
1069          */
1070
1071         while (1) {
1072                 KeAcquireSpinLock(&block->nmb_returnlock, &irql);
1073                 empty = IsListEmpty(&block->nmb_returnlist);
1074                 KeReleaseSpinLock(&block->nmb_returnlock, irql);
1075                 if (empty)
1076                         break;
1077                 NdisMSleep(1000);
1078         }
1079
1080         NDIS_LOCK(sc);
1081         adapter = sc->ndis_block->nmb_miniportadapterctx;
1082         if (adapter == NULL) {
1083                 NDIS_UNLOCK(sc);
1084                 return (EIO);
1085         }
1086
1087         sc->ndis_block->nmb_devicectx = NULL;
1088
1089         /*
1090          * The adapter context is only valid after the init
1091          * handler has been called, and is invalid once the
1092          * halt handler has been called.
1093          */
1094
1095         haltfunc = sc->ndis_chars->nmc_halt_func;
1096         NDIS_UNLOCK(sc);
1097
1098         MSCALL1(haltfunc, adapter);
1099
1100         NDIS_LOCK(sc);
1101         sc->ndis_block->nmb_miniportadapterctx = NULL;
1102         NDIS_UNLOCK(sc);
1103
1104         return (0);
1105 }
1106
1107 int
1108 ndis_shutdown_nic(void *arg)
1109 {
1110         struct ndis_softc       *sc;
1111         ndis_handle             adapter;
1112         ndis_shutdown_handler   shutdownfunc;
1113
1114         sc = arg;
1115         NDIS_LOCK(sc);
1116         adapter = sc->ndis_block->nmb_miniportadapterctx;
1117         shutdownfunc = sc->ndis_chars->nmc_shutdown_handler;
1118         NDIS_UNLOCK(sc);
1119         if (adapter == NULL || shutdownfunc == NULL)
1120                 return (EIO);
1121
1122         if (sc->ndis_chars->nmc_rsvd0 == NULL)
1123                 MSCALL1(shutdownfunc, adapter);
1124         else
1125                 MSCALL1(shutdownfunc, sc->ndis_chars->nmc_rsvd0);
1126
1127         TAILQ_REMOVE(&ndis_devhead, sc->ndis_block, link);
1128
1129         return(0);
1130 }
1131
1132 int
1133 ndis_pnpevent_nic(void *arg, int type)
1134 {
1135         device_t                dev;
1136         struct ndis_softc       *sc;
1137         ndis_handle             adapter;
1138         ndis_pnpevent_handler   pnpeventfunc;
1139
1140         dev = arg;
1141         sc = device_get_softc(arg);
1142         NDIS_LOCK(sc);
1143         adapter = sc->ndis_block->nmb_miniportadapterctx;
1144         pnpeventfunc = sc->ndis_chars->nmc_pnpevent_handler;
1145         NDIS_UNLOCK(sc);
1146         if (adapter == NULL || pnpeventfunc == NULL)
1147                 return (EIO);
1148
1149         if (sc->ndis_chars->nmc_rsvd0 == NULL)
1150                 MSCALL4(pnpeventfunc, adapter, type, NULL, 0);
1151         else
1152                 MSCALL4(pnpeventfunc, sc->ndis_chars->nmc_rsvd0, type, NULL, 0);
1153
1154         return (0);
1155 }
1156
1157 int
1158 ndis_init_nic(void *arg)
1159 {
1160         struct ndis_softc       *sc;
1161         ndis_miniport_block     *block;
1162         ndis_init_handler       initfunc;
1163         ndis_status             status, openstatus = 0;
1164         ndis_medium             mediumarray[NdisMediumMax];
1165         uint32_t                chosenmedium, i;
1166
1167         if (arg == NULL)
1168                 return (EINVAL);
1169
1170         sc = arg;
1171         NDIS_LOCK(sc);
1172         block = sc->ndis_block;
1173         initfunc = sc->ndis_chars->nmc_init_func;
1174         NDIS_UNLOCK(sc);
1175
1176         sc->ndis_block->nmb_timerlist = NULL;
1177
1178         for (i = 0; i < NdisMediumMax; i++)
1179                 mediumarray[i] = i;
1180
1181         status = MSCALL6(initfunc, &openstatus, &chosenmedium,
1182             mediumarray, NdisMediumMax, block, block);
1183
1184         /*
1185          * If the init fails, blow away the other exported routines
1186          * we obtained from the driver so we can't call them later.
1187          * If the init failed, none of these will work.
1188          */
1189         if (status != NDIS_STATUS_SUCCESS) {
1190                 NDIS_LOCK(sc);
1191                 sc->ndis_block->nmb_miniportadapterctx = NULL;
1192                 NDIS_UNLOCK(sc);
1193                 return (ENXIO);
1194         }
1195
1196         /*
1197          * This may look really goofy, but apparently it is possible
1198          * to halt a miniport too soon after it's been initialized.
1199          * After MiniportInitialize() finishes, pause for 1 second
1200          * to give the chip a chance to handle any short-lived timers
1201          * that were set in motion. If we call MiniportHalt() too soon,
1202          * some of the timers may not be cancelled, because the driver
1203          * expects them to fire before the halt is called.
1204          */
1205
1206         tsleep(arg, 0, "ndwait", hz);
1207
1208         NDIS_LOCK(sc);
1209         sc->ndis_block->nmb_devicectx = sc;
1210         NDIS_UNLOCK(sc);
1211
1212         return (0);
1213 }
1214
1215 static void
1216 ndis_intrsetup(kdpc *dpc, device_object *dobj, irp *ip, struct ndis_softc *sc)
1217 {
1218         ndis_miniport_interrupt *intr;
1219
1220         intr = sc->ndis_block->nmb_interrupt;
1221
1222         /* Sanity check. */
1223
1224         if (intr == NULL)
1225                 return;
1226
1227         KeAcquireSpinLockAtDpcLevel(&intr->ni_dpccountlock);
1228         KeResetEvent(&intr->ni_dpcevt);
1229         if (KeInsertQueueDpc(&intr->ni_dpc, NULL, NULL) == TRUE)
1230                 intr->ni_dpccnt++;
1231         KeReleaseSpinLockFromDpcLevel(&intr->ni_dpccountlock);
1232 }
1233
1234 int
1235 ndis_get_info(void *arg, ndis_oid oid, void *buf, int *buflen)
1236 {
1237         struct ndis_softc       *sc;
1238         ndis_status             rval;
1239         ndis_handle             adapter;
1240         ndis_queryinfo_handler  queryfunc;
1241         uint32_t                byteswritten = 0, bytesneeded = 0;
1242         uint8_t                 irql;
1243         uint64_t                duetime;
1244
1245         sc = arg;
1246
1247         KeResetEvent(&sc->ndis_block->nmb_getevent);
1248
1249         KeAcquireSpinLock(&sc->ndis_block->nmb_lock, &irql);
1250
1251         if (sc->ndis_block->nmb_pendingreq != NULL) {
1252                 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
1253                 panic("ndis_get_info() called while other request pending");
1254         } else
1255                 sc->ndis_block->nmb_pendingreq = (ndis_request *)sc;
1256
1257         queryfunc = sc->ndis_chars->nmc_queryinfo_func;
1258         adapter = sc->ndis_block->nmb_miniportadapterctx;
1259
1260         if (adapter == NULL || queryfunc == NULL ||
1261             sc->ndis_block->nmb_devicectx == NULL) {
1262                 sc->ndis_block->nmb_pendingreq = NULL;
1263                 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
1264                 return (ENXIO);
1265         }
1266
1267         rval = MSCALL6(queryfunc, adapter, oid, buf, *buflen,
1268             &byteswritten, &bytesneeded);
1269
1270         sc->ndis_block->nmb_pendingreq = NULL;
1271
1272         KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
1273
1274         /* Wait for requests that block. */
1275
1276         if (rval == NDIS_STATUS_PENDING) {
1277                 /* Wait up to 5 seconds. */
1278                 duetime = (5 * 1000000) * -10;
1279                 KeWaitForSingleObject(&sc->ndis_block->nmb_getevent,
1280                     0, 0, FALSE, &duetime);
1281                 rval = sc->ndis_block->nmb_getstat;
1282         }
1283
1284         if (byteswritten)
1285                 *buflen = byteswritten;
1286         if (bytesneeded)
1287                 *buflen = bytesneeded;
1288
1289         if (rval == NDIS_STATUS_INVALID_LENGTH ||
1290             rval == NDIS_STATUS_BUFFER_TOO_SHORT)
1291                 return (ENOSPC);
1292
1293         if (rval == NDIS_STATUS_INVALID_OID)
1294                 return (EINVAL);
1295
1296         if (rval == NDIS_STATUS_NOT_SUPPORTED ||
1297             rval == NDIS_STATUS_NOT_ACCEPTED)
1298                 return (ENOTSUP);
1299
1300         if (rval != NDIS_STATUS_SUCCESS)
1301                 return (ENODEV);
1302
1303         return (0);
1304 }
1305
1306 uint32_t
1307 NdisAddDevice(driver_object *drv, device_object *pdo)
1308 {
1309         device_object           *fdo;
1310         ndis_miniport_block     *block;
1311         struct ndis_softc       *sc;
1312         uint32_t                status;
1313         int                     error;
1314
1315         sc = device_get_softc(pdo->do_devext);
1316
1317         if (sc->ndis_iftype == PCMCIABus || sc->ndis_iftype == PCIBus) {
1318                 error = bus_setup_intr(sc->ndis_dev, sc->ndis_irq,
1319                     INTR_MPSAFE,
1320                     ntoskrnl_intr, sc, &sc->ndis_intrhand, NULL);
1321                 if (error)
1322                         return (NDIS_STATUS_FAILURE);
1323         }
1324
1325         status = IoCreateDevice(drv, sizeof(ndis_miniport_block), NULL,
1326             FILE_DEVICE_UNKNOWN, 0, FALSE, &fdo);
1327
1328         if (status != STATUS_SUCCESS)
1329                 return (status);
1330
1331         block = fdo->do_devext;
1332
1333         block->nmb_filterdbs.nf_ethdb = block;
1334         block->nmb_deviceobj = fdo;
1335         block->nmb_physdeviceobj = pdo;
1336         block->nmb_nextdeviceobj = IoAttachDeviceToDeviceStack(fdo, pdo);
1337         KeInitializeSpinLock(&block->nmb_lock);
1338         KeInitializeSpinLock(&block->nmb_returnlock);
1339         KeInitializeEvent(&block->nmb_getevent, EVENT_TYPE_NOTIFY, TRUE);
1340         KeInitializeEvent(&block->nmb_setevent, EVENT_TYPE_NOTIFY, TRUE);
1341         KeInitializeEvent(&block->nmb_resetevent, EVENT_TYPE_NOTIFY, TRUE);
1342         InitializeListHead(&block->nmb_parmlist);
1343         InitializeListHead(&block->nmb_returnlist);
1344         block->nmb_returnitem = IoAllocateWorkItem(fdo);
1345
1346         /*
1347          * Stash pointers to the miniport block and miniport
1348          * characteristics info in the if_ndis softc so the
1349          * UNIX wrapper driver can get to them later.
1350          */
1351         sc->ndis_block = block;
1352         sc->ndis_chars = IoGetDriverObjectExtension(drv, (void *)1);
1353
1354         /*
1355          * If the driver has a MiniportTransferData() function,
1356          * we should allocate a private RX packet pool.
1357          */
1358
1359         if (sc->ndis_chars->nmc_transferdata_func != NULL) {
1360                 NdisAllocatePacketPool(&status, &block->nmb_rxpool,
1361                     32, PROTOCOL_RESERVED_SIZE_IN_PACKET);
1362                 if (status != NDIS_STATUS_SUCCESS) {
1363                         IoDetachDevice(block->nmb_nextdeviceobj);
1364                         IoDeleteDevice(fdo);
1365                         return (status);
1366                 }
1367                 InitializeListHead((&block->nmb_packetlist));
1368         }
1369
1370         /* Give interrupt handling priority over timers. */
1371         IoInitializeDpcRequest(fdo, kernndis_functbl[6].ipt_wrap);
1372         KeSetImportanceDpc(&fdo->do_dpc, KDPC_IMPORTANCE_HIGH);
1373
1374         /* Finish up BSD-specific setup. */
1375
1376         block->nmb_signature = (void *)0xcafebabe;
1377         block->nmb_status_func = kernndis_functbl[0].ipt_wrap;
1378         block->nmb_statusdone_func = kernndis_functbl[1].ipt_wrap;
1379         block->nmb_setdone_func = kernndis_functbl[2].ipt_wrap;
1380         block->nmb_querydone_func = kernndis_functbl[3].ipt_wrap;
1381         block->nmb_resetdone_func = kernndis_functbl[4].ipt_wrap;
1382         block->nmb_sendrsrc_func = kernndis_functbl[5].ipt_wrap;
1383         block->nmb_pendingreq = NULL;
1384
1385         TAILQ_INSERT_TAIL(&ndis_devhead, block, link);
1386
1387         return (STATUS_SUCCESS);
1388 }
1389
1390 int
1391 ndis_unload_driver(void *arg)
1392 {
1393         struct ndis_softc       *sc;
1394         device_object           *fdo;
1395
1396         sc = arg;
1397
1398         if (sc->ndis_intrhand)
1399                 bus_teardown_intr(sc->ndis_dev,
1400                     sc->ndis_irq, sc->ndis_intrhand);
1401
1402         if (sc->ndis_block->nmb_rlist != NULL)
1403                 kfree(sc->ndis_block->nmb_rlist, M_DEVBUF);
1404
1405         ndis_flush_sysctls(sc);
1406
1407         TAILQ_REMOVE(&ndis_devhead, sc->ndis_block, link);
1408
1409         if (sc->ndis_chars->nmc_transferdata_func != NULL)
1410                 NdisFreePacketPool(sc->ndis_block->nmb_rxpool);
1411         fdo = sc->ndis_block->nmb_deviceobj;
1412         IoFreeWorkItem(sc->ndis_block->nmb_returnitem);
1413         IoDetachDevice(sc->ndis_block->nmb_nextdeviceobj);
1414         IoDeleteDevice(fdo);
1415
1416         return (0);
1417 }