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