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