win-pvdrivers

view xennet/xennet.c @ 102:a1db6a819d41

xennet: fix off by 1 bug; start implementing shutdown code; redo task offload code in QueryInformation
author Andy Grover <andy.grover@oracle.com>
date Mon Jan 07 19:31:14 2008 -0800 (2008-01-07)
parents ca121c57a360
children a96426482216
line source
1 /*
2 PV Net Driver for Windows Xen HVM Domains
3 Copyright (C) 2007 James Harper
4 Copyright (C) 2007 Andrew Grover <andy.grover@oracle.com>
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 */
21 #include <stdlib.h>
22 #include <io/xenbus.h>
23 #include "xennet.h"
25 /* Xen macros use these, so they need to be redefined to Win equivs */
26 #define wmb() KeMemoryBarrier()
27 #define mb() KeMemoryBarrier()
29 #if !defined (NDIS51_MINIPORT)
30 #error requires NDIS 5.1 compilation environment
31 #endif
33 #define GRANT_INVALID_REF 0
35 /* couldn't get regular xen ring macros to work...*/
36 #define __NET_RING_SIZE(type, _sz) \
37 (__RD32( \
38 (_sz - sizeof(struct type##_sring) + sizeof(union type##_sring_entry)) \
39 / sizeof(union type##_sring_entry)))
41 #define NET_TX_RING_SIZE __NET_RING_SIZE(netif_tx, PAGE_SIZE)
42 #define NET_RX_RING_SIZE __NET_RING_SIZE(netif_rx, PAGE_SIZE)
44 #pragma warning(disable: 4127) // conditional expression is constant
46 struct xennet_info
47 {
48 PDEVICE_OBJECT pdo;
49 PDEVICE_OBJECT fdo;
50 PDEVICE_OBJECT lower_do;
51 WDFDEVICE wdf_device;
52 PXENPCI_XEN_DEVICE_DATA pdoData;
54 WCHAR name[NAME_SIZE];
55 NDIS_HANDLE adapter_handle;
56 ULONG packet_filter;
57 int connected;
58 UINT8 perm_mac_addr[ETH_ALEN];
59 UINT8 curr_mac_addr[ETH_ALEN];
61 // char Path[128];
62 char BackendPath[128];
63 XEN_IFACE XenInterface;
65 /* ring control structures */
66 struct netif_tx_front_ring tx;
67 struct netif_rx_front_ring rx;
69 /* ptrs to the actual rings themselvves */
70 struct netif_tx_sring *tx_pgs;
71 struct netif_rx_sring *rx_pgs;
73 /* MDLs for the above */
74 PMDL tx_mdl;
75 PMDL rx_mdl;
77 /* Outstanding packets. The first entry in tx_pkts
78 * is an index into a chain of free entries. */
79 PNDIS_PACKET tx_pkts[NET_TX_RING_SIZE+1];
80 PNDIS_PACKET rx_pkts[NET_RX_RING_SIZE];
82 grant_ref_t gref_tx_head;
83 grant_ref_t grant_tx_ref[NET_TX_RING_SIZE];
84 grant_ref_t gref_rx_head;
85 grant_ref_t grant_rx_ref[NET_TX_RING_SIZE];
87 UINT irq;
88 evtchn_port_t event_channel;
90 grant_ref_t tx_ring_ref;
91 grant_ref_t rx_ring_ref;
93 /* Receive-ring batched refills. */
94 #define RX_MIN_TARGET 8
95 #define RX_DFL_MIN_TARGET 64
96 #define RX_MAX_TARGET min(NET_RX_RING_SIZE, 256)
97 ULONG rx_target;
98 ULONG rx_max_target;
99 ULONG rx_min_target;
101 NDIS_HANDLE packet_pool;
102 NDIS_HANDLE buffer_pool;
104 /* stats */
105 ULONG64 stat_tx_ok;
106 ULONG64 stat_rx_ok;
107 ULONG64 stat_tx_error;
108 ULONG64 stat_rx_error;
109 ULONG64 stat_rx_no_buffer;
111 // KEVENT backend_ready_event;
112 KEVENT backend_state_change_event;
114 ULONG state;
115 ULONG backend_state;
117 KSPIN_LOCK RxLock;
118 KSPIN_LOCK TxLock;
119 };
121 /* This function copied from linux's lib/vsprintf.c, see it for attribution */
122 static unsigned long
123 simple_strtoul(const char *cp,char **endp,unsigned int base)
124 {
125 unsigned long result = 0,value;
127 if (!base) {
128 base = 10;
129 if (*cp == '0') {
130 base = 8;
131 cp++;
132 if ((toupper(*cp) == 'X') && isxdigit(cp[1])) {
133 cp++;
134 base = 16;
135 }
136 }
137 } else if (base == 16) {
138 if (cp[0] == '0' && toupper(cp[1]) == 'X')
139 cp += 2;
140 }
141 while (isxdigit(*cp) &&
142 (value = isdigit(*cp) ? *cp-'0' : toupper(*cp)-'A'+10) < base) {
143 result = result*base + value;
144 cp++;
145 }
146 if (endp)
147 *endp = (char *)cp;
148 return result;
149 }
151 static void
152 add_id_to_freelist(NDIS_PACKET **list, unsigned short id)
153 {
154 list[id] = list[0];
155 list[0] = (void *)(unsigned long)id;
156 }
158 static unsigned short
159 get_id_from_freelist(NDIS_PACKET **list)
160 {
161 unsigned short id = (unsigned short)(unsigned long)list[0];
162 list[0] = list[id];
163 return id;
164 }
166 // Called at DISPATCH_LEVEL
167 static NDIS_STATUS
168 XenNet_TxBufferGC(struct xennet_info *xi)
169 {
170 RING_IDX cons, prod;
171 unsigned short id;
172 PNDIS_PACKET pkt;
173 PMDL pmdl;
174 KIRQL OldIrql;
176 ASSERT(xi->connected);
178 // KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
180 KeAcquireSpinLock(&xi->TxLock, &OldIrql);
182 do {
183 prod = xi->tx.sring->rsp_prod;
184 KeMemoryBarrier(); /* Ensure we see responses up to 'rp'. */
186 for (cons = xi->tx.rsp_cons; cons != prod; cons++) {
187 struct netif_tx_response *txrsp;
189 txrsp = RING_GET_RESPONSE(&xi->tx, cons);
190 if (txrsp->status == NETIF_RSP_NULL)
191 continue;
193 id = txrsp->id;
194 pkt = xi->tx_pkts[id];
195 xi->XenInterface.GntTbl_EndAccess(xi->XenInterface.InterfaceHeader.Context,
196 xi->grant_tx_ref[id]);
197 xi->grant_tx_ref[id] = GRANT_INVALID_REF;
198 add_id_to_freelist(xi->tx_pkts, id);
200 /* free linearized data page */
201 pmdl = *(PMDL *)pkt->MiniportReservedEx;
202 NdisFreeMemory(MmGetMdlVirtualAddress(pmdl), 0, 0); // <= DISPATCH_LEVEL
203 IoFreeMdl(pmdl);
205 xi->stat_tx_ok++;
206 NdisMSendComplete(xi->adapter_handle, pkt, NDIS_STATUS_SUCCESS);
207 }
209 xi->tx.rsp_cons = prod;
211 /*
212 * Set a new event, then check for race with update of tx_cons.
213 * Note that it is essential to schedule a callback, no matter
214 * how few buffers are pending. Even if there is space in the
215 * transmit ring, higher layers may be blocked because too much
216 * data is outstanding: in such cases notification from Xen is
217 * likely to be the only kick that we'll get.
218 */
219 xi->tx.sring->rsp_event =
220 prod + ((xi->tx.sring->req_prod - prod) >> 1) + 1;
221 KeMemoryBarrier();
222 } while ((cons == prod) && (prod != xi->tx.sring->rsp_prod));
224 /* if queued packets, send them now?
225 network_maybe_wake_tx(dev); */
227 KeReleaseSpinLock(&xi->TxLock, OldIrql);
229 // KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
231 return NDIS_STATUS_SUCCESS;
232 }
234 // Called at DISPATCH_LEVEL with RxLock held
235 static NDIS_STATUS
236 XenNet_AllocRXBuffers(struct xennet_info *xi)
237 {
238 unsigned short id;
239 PNDIS_PACKET packet;
240 PNDIS_BUFFER buffer;
241 int i, batch_target, notify;
242 RING_IDX req_prod = xi->rx.req_prod_pvt;
243 grant_ref_t ref;
244 netif_rx_request_t *req;
245 NDIS_STATUS status;
246 PVOID start;
248 // KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
250 batch_target = xi->rx_target - (req_prod - xi->rx.rsp_cons);
251 for (i = 0; i < batch_target; i++)
252 {
253 /*
254 * Allocate a packet, page, and buffer. Hook them up.
255 */
256 status = NdisAllocateMemoryWithTag(&start, PAGE_SIZE, XENNET_POOL_TAG);
257 if (status != NDIS_STATUS_SUCCESS)
258 {
259 KdPrint(("NdisAllocateMemoryWithTag Failed! status = 0x%x\n", status));
260 break;
261 }
262 NdisAllocateBuffer(&status, &buffer, xi->buffer_pool, start, PAGE_SIZE);
263 if (status != NDIS_STATUS_SUCCESS)
264 {
265 KdPrint(("NdisAllocateBuffer Failed! status = 0x%x\n", status));
266 NdisFreeMemory(start, 0, 0);
267 break;
268 }
269 NdisAllocatePacket(&status, &packet, xi->packet_pool);
270 if (status != NDIS_STATUS_SUCCESS)
271 {
272 KdPrint(("NdisAllocatePacket Failed! status = 0x%x\n", status));
273 NdisFreeMemory(start, 0, 0);
274 NdisFreeBuffer(buffer);
275 break;
276 }
277 NdisChainBufferAtBack(packet, buffer);
278 NDIS_SET_PACKET_HEADER_SIZE(packet, XN_HDR_SIZE);
280 /* Give to netback */
281 id = (unsigned short)(req_prod + i) & (NET_RX_RING_SIZE - 1);
282 ASSERT(!xi->rx_pkts[id]);
283 xi->rx_pkts[id] = packet;
284 req = RING_GET_REQUEST(&xi->rx, req_prod + i);
285 /* an NDIS_BUFFER is just a MDL, so we can get its pfn array */
286 ref = xi->XenInterface.GntTbl_GrantAccess(
287 xi->XenInterface.InterfaceHeader.Context, 0,
288 *MmGetMdlPfnArray(buffer), FALSE);
289 ASSERT((signed short)ref >= 0);
290 xi->grant_rx_ref[id] = ref;
292 req->id = id;
293 req->gref = ref;
294 }
296 xi->rx.req_prod_pvt = req_prod + i;
297 RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&xi->rx, notify);
298 if (notify)
299 {
300 xi->XenInterface.EvtChn_Notify(xi->XenInterface.InterfaceHeader.Context,
301 xi->event_channel);
302 }
304 // KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
306 return NDIS_STATUS_SUCCESS;
307 }
309 /* free rx buffers */
310 static void
311 XenNet_FreeRXBuffers(struct xennet_info *xi)
312 {
313 int i;
314 PNDIS_PACKET packet;
315 PNDIS_BUFFER buffer;
316 PVOID buff_va;
317 UINT buff_len;
318 UINT tot_buff_len;
319 KIRQL OldIrql;
321 ASSERT(!xi->connected);
323 KeAcquireSpinLock(&xi->RxLock, &OldIrql);
325 for (i = 0; i < NET_RX_RING_SIZE; i++)
326 {
327 if (xi->rx_pkts[i])
328 {
329 packet = xi->rx_pkts[i];
330 NdisGetFirstBufferFromPacketSafe(packet, &buffer, &buff_va, &buff_len,
331 &tot_buff_len, NormalPagePriority);
332 ASSERT(buff_len == tot_buff_len);
334 NdisFreeMemory(buff_va, 0, 0);
335 NdisFreeBuffer(buffer);
336 NdisFreePacket(packet);
337 }
338 }
340 KeReleaseSpinLock(&xi->RxLock, OldIrql);
341 }
343 // Called at DISPATCH_LEVEL
344 static NDIS_STATUS
345 XenNet_RxBufferCheck(struct xennet_info *xi)
346 {
347 RING_IDX cons, prod;
349 PNDIS_PACKET pkt;
350 PNDIS_BUFFER buffer;
351 PVOID buff_va;
352 UINT buff_len;
353 UINT tot_buff_len;
354 int moretodo;
355 KIRQL OldIrql;
356 PNDIS_TCP_IP_CHECKSUM_PACKET_INFO csum_info;
358 // KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
360 ASSERT(xi->connected);
362 KeAcquireSpinLock(&xi->RxLock, &OldIrql);
364 do {
365 prod = xi->rx.sring->rsp_prod;
366 KeMemoryBarrier(); /* Ensure we see responses up to 'rp'. */
368 for (cons = xi->rx.rsp_cons; cons != prod; cons++) {
369 struct netif_rx_response *rxrsp;
371 rxrsp = RING_GET_RESPONSE(&xi->rx, cons);
372 if (rxrsp->status == NETIF_RSP_NULL)
373 continue;
375 // KdPrint((__DRIVER_NAME " Got a packet\n"));
377 pkt = xi->rx_pkts[rxrsp->id];
378 xi->rx_pkts[rxrsp->id] = NULL;
379 xi->XenInterface.GntTbl_EndAccess(xi->XenInterface.InterfaceHeader.Context,
380 xi->grant_rx_ref[rxrsp->id]);
381 xi->grant_rx_ref[rxrsp->id] = GRANT_INVALID_REF;
383 NdisGetFirstBufferFromPacketSafe(pkt, &buffer, &buff_va, &buff_len,
384 &tot_buff_len, NormalPagePriority);
385 ASSERT(rxrsp->offset == 0);
386 ASSERT(rxrsp->status > 0);
387 NdisAdjustBufferLength(buffer, rxrsp->status);
389 #if 0
390 KdPrint((__DRIVER_NAME " Flags = %sNETRXF_data_validated|%sNETRXF_csum_blank|%sNETRXF_more_data|%sNETRXF_extra_info\n",
391 (rxrsp->flags|NETRXF_data_validated)?"":"!",
392 (rxrsp->flags|NETRXF_csum_blank)?"":"!",
393 (rxrsp->flags|NETRXF_more_data)?"":"!",
394 (rxrsp->flags|NETRXF_extra_info)?"":"!"));
395 #endif
396 // maybe use NDIS_GET_PACKET_PROTOCOL_TYPE(Packet) here and check for == NDIS_PROTOCOL_ID_TCP_IP etc
398 csum_info = (PNDIS_TCP_IP_CHECKSUM_PACKET_INFO)&NDIS_PER_PACKET_INFO_FROM_PACKET(pkt, TcpIpChecksumPacketInfo);
399 csum_info->Receive.NdisPacketTcpChecksumSucceeded = 1;
400 csum_info->Receive.NdisPacketUdpChecksumSucceeded = 1;
401 csum_info->Receive.NdisPacketIpChecksumSucceeded = 1;
403 xi->stat_rx_ok++;
404 NDIS_SET_PACKET_STATUS(pkt, NDIS_STATUS_SUCCESS);
406 /* just indicate 1 packet for now */
407 // KdPrint((__DRIVER_NAME " Indicating Received\n"));
408 NdisMIndicateReceivePacket(xi->adapter_handle, &pkt, 1);
409 // KdPrint((__DRIVER_NAME " Done Indicating Received\n"));
410 }
412 xi->rx.rsp_cons = prod;
414 RING_FINAL_CHECK_FOR_RESPONSES(&xi->rx, moretodo);
415 } while (moretodo);
417 /* Give netback more buffers */
418 XenNet_AllocRXBuffers(xi);
420 KeReleaseSpinLock(&xi->RxLock, OldIrql);
422 //xi->rx.sring->rsp_event = xi->rx.rsp_cons + 1;
424 // KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
426 return NDIS_STATUS_SUCCESS;
427 }
429 // Called at DISPATCH_LEVEL
430 static BOOLEAN
431 XenNet_Interrupt(
432 PKINTERRUPT Interrupt,
433 PVOID ServiceContext
434 )
435 {
436 struct xennet_info *xi = ServiceContext;
438 UNREFERENCED_PARAMETER(Interrupt);
440 // KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
442 if (xi->connected)
443 {
444 XenNet_TxBufferGC(xi);
445 XenNet_RxBufferCheck(xi);
446 }
448 // KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
450 return TRUE;
451 }
453 // Called at <= DISPATCH_LEVEL
455 static VOID
456 XenNet_BackEndStateHandler(char *Path, PVOID Data)
457 {
458 struct xennet_info *xi = Data;
459 char *Value;
460 char TmpPath[128];
461 xenbus_transaction_t xbt = 0;
462 int retry = 0;
463 char *err;
464 int i;
465 ULONG new_backend_state;
467 struct set_params {
468 char *name;
469 int value;
470 } params[] = {
471 {"tx-ring-ref", 0},
472 {"rx-ring-ref", 0},
473 {"event-channel", 0},
474 {"request-rx-copy", 1},
475 {"feature-rx-notify", 1},
476 {"feature-no-csum-offload", 1},
477 {"feature-sg", 1},
478 {"feature-gso-tcpv4", 0},
479 {NULL, 0},
480 };
482 KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
483 KdPrint((__DRIVER_NAME " IRQL = %d\n", KeGetCurrentIrql()));
485 xi->XenInterface.XenBus_Read(xi->XenInterface.InterfaceHeader.Context,
486 XBT_NIL, Path, &Value);
487 new_backend_state = atoi(Value);
488 xi->XenInterface.FreeMem(Value);
490 if (xi->backend_state == new_backend_state)
491 {
492 KdPrint((__DRIVER_NAME " state unchanged\n"));
493 KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
494 return;
495 }
497 xi->backend_state = new_backend_state;
499 switch (xi->backend_state)
500 {
501 case XenbusStateUnknown:
502 KdPrint((__DRIVER_NAME " Backend State Changed to Unknown\n"));
503 break;
505 case XenbusStateInitialising:
506 KdPrint((__DRIVER_NAME " Backend State Changed to Initialising\n"));
507 break;
509 case XenbusStateInitWait:
510 KdPrint((__DRIVER_NAME " Backend State Changed to InitWait\n"));
512 xi->event_channel = xi->XenInterface.EvtChn_AllocUnbound(
513 xi->XenInterface.InterfaceHeader.Context, 0);
514 xi->XenInterface.EvtChn_BindDpc(xi->XenInterface.InterfaceHeader.Context,
515 xi->event_channel, XenNet_Interrupt, xi);
517 /* TODO: must free pages in MDL as well as MDL using MmFreePagesFromMdl and ExFreePool */
518 // or, allocate mem and then get mdl, then free mdl
519 xi->tx_mdl = AllocatePage();
520 xi->tx_pgs = MmGetMdlVirtualAddress(xi->tx_mdl); //MmMapLockedPagesSpecifyCache(xi->tx_mdl, KernelMode, MmNonCached, NULL, FALSE, NormalPagePriority);
521 SHARED_RING_INIT(xi->tx_pgs);
522 FRONT_RING_INIT(&xi->tx, xi->tx_pgs, PAGE_SIZE);
523 xi->tx_ring_ref = xi->XenInterface.GntTbl_GrantAccess(
524 xi->XenInterface.InterfaceHeader.Context, 0,
525 *MmGetMdlPfnArray(xi->tx_mdl), FALSE);
527 xi->rx_mdl = AllocatePage();
528 xi->rx_pgs = MmGetMdlVirtualAddress(xi->rx_mdl); //MmMapLockedPagesSpecifyCache(xi->rx_mdl, KernelMode, MmNonCached, NULL, FALSE, NormalPagePriority);
529 SHARED_RING_INIT(xi->rx_pgs);
530 FRONT_RING_INIT(&xi->rx, xi->rx_pgs, PAGE_SIZE);
531 xi->rx_ring_ref = xi->XenInterface.GntTbl_GrantAccess(
532 xi->XenInterface.InterfaceHeader.Context, 0,
533 *MmGetMdlPfnArray(xi->rx_mdl), FALSE);
535 /* fixup array for dynamic values */
536 params[0].value = xi->tx_ring_ref;
537 params[1].value = xi->rx_ring_ref;
538 params[2].value = xi->event_channel;
540 xi->XenInterface.XenBus_StartTransaction(
541 xi->XenInterface.InterfaceHeader.Context, &xbt);
543 for (i = 0; params[i].name; i++)
544 {
545 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath), "%s/%s",
546 xi->pdoData->Path, params[i].name);
547 err = xi->XenInterface.XenBus_Printf(xi->XenInterface.InterfaceHeader.Context,
548 XBT_NIL, TmpPath, "%d", params[i].value);
549 if (err)
550 {
551 KdPrint(("setting %s failed, err = %s\n", params[i].name, err));
552 goto trouble;
553 }
554 }
556 /* commit transaction */
557 xi->XenInterface.XenBus_EndTransaction(xi->XenInterface.InterfaceHeader.Context,
558 xbt, 0, &retry);
560 XenNet_AllocRXBuffers(xi);
562 xi->state = XenbusStateConnected;
563 KdPrint((__DRIVER_NAME " Set Frontend state to Connected\n"));
564 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath), "%s/state", xi->pdoData->Path);
565 xi->XenInterface.XenBus_Printf(xi->XenInterface.InterfaceHeader.Context,
566 XBT_NIL, TmpPath, "%d", xi->state);
568 /* send fake arp? */
570 xi->connected = TRUE;
572 break;
574 case XenbusStateInitialised:
575 KdPrint((__DRIVER_NAME " Backend State Changed to Initialised\n"));
576 break;
578 case XenbusStateConnected:
579 KdPrint((__DRIVER_NAME " Backend State Changed to Connected\n"));
580 break;
582 case XenbusStateClosing:
583 KdPrint((__DRIVER_NAME " Backend State Changed to Closing\n"));
584 break;
586 case XenbusStateClosed:
587 KdPrint((__DRIVER_NAME " Backend State Changed to Closed\n"));
588 break;
590 default:
591 KdPrint((__DRIVER_NAME " Backend State Changed to Undefined = %d\n", xi->backend_state));
592 break;
593 }
595 KeSetEvent(&xi->backend_state_change_event, 1, FALSE);
597 KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
599 return;
601 trouble:
602 KdPrint((__DRIVER_NAME __FUNCTION__ ": Should never happen!\n"));
603 xi->XenInterface.XenBus_EndTransaction(xi->XenInterface.InterfaceHeader.Context,
604 xbt, 1, &retry);
605 KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
606 }
608 VOID
609 XenNet_Halt(
610 IN NDIS_HANDLE MiniportAdapterContext
611 )
612 {
613 struct xennet_info *xi = MiniportAdapterContext;
614 CHAR TmpPath[128];
616 KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
617 KdPrint((__DRIVER_NAME " IRQL = %d\n", KeGetCurrentIrql()));
619 // set frontend state to 'closing'
620 xi->state = XenbusStateClosing;
621 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath), "%s/state", xi->pdoData->Path);
622 xi->XenInterface.XenBus_Printf(xi->XenInterface.InterfaceHeader.Context,
623 XBT_NIL, TmpPath, "%d", xi->state);
625 // wait for backend to set 'Closing' state
627 while (xi->backend_state != XenbusStateClosing)
628 KeWaitForSingleObject(&xi->backend_state_change_event, Executive, KernelMode, FALSE, NULL);
630 // set frontend state to 'closed'
631 xi->state = XenbusStateClosed;
632 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath), "%s/state", xi->pdoData->Path);
633 xi->XenInterface.XenBus_Printf(xi->XenInterface.InterfaceHeader.Context,
634 XBT_NIL, TmpPath, "%d", xi->state);
636 // wait for backend to set 'Closed' state
637 while (xi->backend_state != XenbusStateClosed)
638 KeWaitForSingleObject(&xi->backend_state_change_event, Executive, KernelMode, FALSE, NULL);
640 // remove event channel xenbus entry
641 // unbind event channel
642 // remove tx/rx ring entries
643 // clean up all grant table entries
644 // free all memory
646 KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
647 }
649 static NDIS_STATUS
650 XenNet_Init(
651 OUT PNDIS_STATUS OpenErrorStatus,
652 OUT PUINT SelectedMediumIndex,
653 IN PNDIS_MEDIUM MediumArray,
654 IN UINT MediumArraySize,
655 IN NDIS_HANDLE MiniportAdapterHandle,
656 IN NDIS_HANDLE WrapperConfigurationContext
657 )
658 {
659 NDIS_STATUS status;
660 UINT i;
661 BOOLEAN medium_found = FALSE;
662 struct xennet_info *xi = NULL;
663 ULONG length;
664 WDF_OBJECT_ATTRIBUTES wdf_attrs;
665 char *res;
666 char *Value;
667 char TmpPath[128];
669 UNREFERENCED_PARAMETER(OpenErrorStatus);
670 UNREFERENCED_PARAMETER(WrapperConfigurationContext);
672 KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
673 KdPrint((__DRIVER_NAME " IRQL = %d\n", KeGetCurrentIrql()));
675 /* deal with medium stuff */
676 for (i = 0; i < MediumArraySize; i++)
677 {
678 if (MediumArray[i] == NdisMedium802_3)
679 {
680 medium_found = TRUE;
681 break;
682 }
683 }
684 if (!medium_found)
685 {
686 KdPrint(("NIC_MEDIA_TYPE not in MediumArray\n"));
687 return NDIS_STATUS_UNSUPPORTED_MEDIA;
688 }
689 *SelectedMediumIndex = i;
691 /* Alloc memory for adapter private info */
692 status = NdisAllocateMemoryWithTag(&xi, sizeof(*xi), XENNET_POOL_TAG);
693 if (!NT_SUCCESS(status))
694 {
695 KdPrint(("NdisAllocateMemoryWithTag failed with 0x%x\n", status));
696 status = NDIS_STATUS_RESOURCES;
697 goto err;
698 }
699 RtlZeroMemory(xi, sizeof(*xi));
701 /* init xennet_info */
702 xi->adapter_handle = MiniportAdapterHandle;
703 xi->rx_target = RX_DFL_MIN_TARGET;
704 xi->rx_min_target = RX_DFL_MIN_TARGET;
705 xi->rx_max_target = RX_MAX_TARGET;
707 xi->state = XenbusStateUnknown;
708 xi->backend_state = XenbusStateUnknown;
710 KeInitializeSpinLock(&xi->TxLock);
711 KeInitializeSpinLock(&xi->RxLock);
713 NdisAllocatePacketPool(&status, &xi->packet_pool, NET_RX_RING_SIZE,
714 PROTOCOL_RESERVED_SIZE_IN_PACKET);
715 if (status != NDIS_STATUS_SUCCESS)
716 {
717 KdPrint(("NdisAllocatePacketPool failed with 0x%x\n", status));
718 status = NDIS_STATUS_RESOURCES;
719 goto err;
720 }
722 NdisAllocateBufferPool(&status, &xi->buffer_pool, NET_RX_RING_SIZE);
723 if (status != NDIS_STATUS_SUCCESS)
724 {
725 KdPrint(("NdisAllocateBufferPool failed with 0x%x\n", status));
726 status = NDIS_STATUS_RESOURCES;
727 goto err;
728 }
730 NdisMGetDeviceProperty(MiniportAdapterHandle, &xi->pdo, &xi->fdo,
731 &xi->lower_do, NULL, NULL);
732 xi->pdoData = (PXENPCI_XEN_DEVICE_DATA)xi->pdo->DeviceExtension;
734 /* Initialize tx_pkts as a free chain containing every entry. */
735 for (i = 0; i < NET_TX_RING_SIZE+1; i++) {
736 xi->tx_pkts[i] = (void *)((unsigned long) i+1);
737 }
738 for (i = 0; i < NET_TX_RING_SIZE; i++) {
739 xi->grant_tx_ref[i] = GRANT_INVALID_REF;
740 }
742 for (i = 0; i < NET_RX_RING_SIZE; i++) {
743 xi->rx_pkts[i] = NULL;
744 xi->grant_rx_ref[i] = GRANT_INVALID_REF;
745 }
747 xi->packet_filter = NDIS_PACKET_TYPE_PROMISCUOUS;
749 status = IoGetDeviceProperty(xi->pdo, DevicePropertyDeviceDescription,
750 NAME_SIZE, xi->name, &length);
751 if (!NT_SUCCESS(status))
752 {
753 KdPrint(("IoGetDeviceProperty failed with 0x%x\n", status));
754 status = NDIS_STATUS_FAILURE;
755 goto err;
756 }
758 NdisMSetAttributesEx(xi->adapter_handle, (NDIS_HANDLE) xi,
759 0, (NDIS_ATTRIBUTE_DESERIALIZE /*| NDIS_ATTRIBUTE_BUS_MASTER*/),
760 NdisInterfaceInternal);
762 WDF_OBJECT_ATTRIBUTES_INIT(&wdf_attrs);
764 status = WdfDeviceMiniportCreate(WdfGetDriver(), &wdf_attrs, xi->fdo,
765 xi->lower_do, xi->pdo, &xi->wdf_device);
766 if (!NT_SUCCESS(status))
767 {
768 KdPrint(("WdfDeviceMiniportCreate failed with 0x%x\n", status));
769 status = NDIS_STATUS_FAILURE;
770 goto err;
771 }
773 /* get lower (Xen) interfaces */
775 status = WdfFdoQueryForInterface(xi->wdf_device, &GUID_XEN_IFACE,
776 (PINTERFACE) &xi->XenInterface, sizeof(XEN_IFACE), 1, NULL);
777 if(!NT_SUCCESS(status))
778 {
779 KdPrint(("WdfFdoQueryForInterface failed with status 0x%08x\n", status));
780 status = NDIS_STATUS_FAILURE;
781 goto err;
782 }
784 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath),
785 "%s/backend", xi->pdoData->Path);
786 KdPrint(("About to read %s to get backend path\n", TmpPath));
787 res = xi->XenInterface.XenBus_Read(xi->XenInterface.InterfaceHeader.Context,
788 XBT_NIL, TmpPath, &Value);
789 if (res)
790 {
791 KdPrint((__DRIVER_NAME " Failed to read backend path\n"));
792 xi->XenInterface.FreeMem(res);
793 status = NDIS_STATUS_FAILURE;
794 goto err;
795 }
796 RtlStringCbCopyA(xi->BackendPath, ARRAY_SIZE(xi->BackendPath), Value);
797 KdPrint((__DRIVER_NAME "backend path = %s\n", xi->BackendPath));
799 KeInitializeEvent(&xi->backend_state_change_event, SynchronizationEvent, FALSE);
801 /* Add watch on backend state */
802 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath), "%s/state", xi->BackendPath);
803 xi->XenInterface.XenBus_AddWatch(xi->XenInterface.InterfaceHeader.Context,
804 XBT_NIL, TmpPath, XenNet_BackEndStateHandler, xi);
806 // Fire backend state handler here, as we may have missed it
807 // XenNet_BackEndStateHandler(TmpPath, xi);
809 KdPrint((__DRIVER_NAME " Waiting for backend to connect\n"));
811 // wait here for signal that we are all set up
812 while (xi->backend_state != XenbusStateConnected)
813 KeWaitForSingleObject(&xi->backend_state_change_event, Executive, KernelMode, FALSE, NULL);
815 KdPrint((__DRIVER_NAME " Connected\n"));
817 /* get mac address */
818 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath), "%s/mac", xi->BackendPath);
819 xi->XenInterface.XenBus_Read(xi->XenInterface.InterfaceHeader.Context,
820 XBT_NIL, TmpPath, &Value);
821 if (!Value)
822 {
823 KdPrint((__DRIVER_NAME " mac Read Failed\n"));
824 status = NDIS_STATUS_FAILURE;
825 goto err;
826 }
827 else
828 {
829 char *s, *e;
830 s = Value;
831 for (i = 0; i < ETH_ALEN; i++) {
832 xi->perm_mac_addr[i] = (UINT8)simple_strtoul(s, &e, 16);
833 if ((s == e) || (*e != ((i == ETH_ALEN-1) ? '\0' : ':'))) {
834 KdPrint((__DRIVER_NAME "Error parsing MAC address\n"));
835 xi->XenInterface.FreeMem(Value);
836 status = NDIS_STATUS_FAILURE;
837 goto err;
838 }
839 s = e + 1;
840 }
841 memcpy(xi->curr_mac_addr, xi->perm_mac_addr, ETH_ALEN);
842 xi->XenInterface.FreeMem(Value);
843 }
845 KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
847 return NDIS_STATUS_SUCCESS;
849 err:
850 NdisFreeMemory(xi, 0, 0);
851 KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
852 return status;
853 }
855 // Q = Query Mandatory, S = Set Mandatory
856 NDIS_OID supported_oids[] =
857 {
858 /* general OIDs */
859 OID_GEN_SUPPORTED_LIST, // Q
860 OID_GEN_HARDWARE_STATUS, // Q
861 OID_GEN_MEDIA_SUPPORTED, // Q
862 OID_GEN_MEDIA_IN_USE, // Q
863 OID_GEN_MAXIMUM_LOOKAHEAD, // Q
864 OID_GEN_MAXIMUM_FRAME_SIZE, // Q
865 OID_GEN_LINK_SPEED, // Q
866 OID_GEN_TRANSMIT_BUFFER_SPACE, // Q
867 OID_GEN_RECEIVE_BUFFER_SPACE, // Q
868 OID_GEN_TRANSMIT_BLOCK_SIZE, // Q
869 OID_GEN_RECEIVE_BLOCK_SIZE, // Q
870 OID_GEN_VENDOR_ID, // Q
871 OID_GEN_VENDOR_DESCRIPTION, // Q
872 OID_GEN_CURRENT_PACKET_FILTER, // QS
873 OID_GEN_CURRENT_LOOKAHEAD, // QS
874 OID_GEN_DRIVER_VERSION, // Q
875 OID_GEN_MAXIMUM_TOTAL_SIZE, // Q
876 OID_GEN_PROTOCOL_OPTIONS, // S
877 OID_GEN_MAC_OPTIONS, // Q
878 OID_GEN_MEDIA_CONNECT_STATUS, // Q
879 OID_GEN_MAXIMUM_SEND_PACKETS, // Q
880 /* stats */
881 OID_GEN_XMIT_OK, // Q
882 OID_GEN_RCV_OK, // Q
883 OID_GEN_XMIT_ERROR, // Q
884 OID_GEN_RCV_ERROR, // Q
885 OID_GEN_RCV_NO_BUFFER, // Q
886 /* media-specific OIDs */
887 OID_802_3_PERMANENT_ADDRESS,
888 OID_802_3_CURRENT_ADDRESS,
889 OID_802_3_MULTICAST_LIST,
890 OID_802_3_MAXIMUM_LIST_SIZE,
891 /* tcp offload */
892 OID_TCP_TASK_OFFLOAD,
893 };
895 /* return 4 or 8 depending on size of buffer */
896 #define HANDLE_STAT_RETURN \
897 {if (InformationBufferLength == 4) { \
898 len = 4; *BytesNeeded = 8; \
899 } else { \
900 len = 8; \
901 } }
903 //#define LARGE_SEND
905 NDIS_STATUS
906 XenNet_QueryInformation(
907 IN NDIS_HANDLE MiniportAdapterContext,
908 IN NDIS_OID Oid,
909 IN PVOID InformationBuffer,
910 IN ULONG InformationBufferLength,
911 OUT PULONG BytesWritten,
912 OUT PULONG BytesNeeded)
913 {
914 struct xennet_info *xi = MiniportAdapterContext;
915 UCHAR vendor_desc[] = XN_VENDOR_DESC;
916 ULONG64 temp_data;
917 PVOID data = &temp_data;
918 ULONG offset = 0;
919 UINT len = 4;
920 BOOLEAN used_temp_buffer = TRUE;
921 NDIS_STATUS status = NDIS_STATUS_SUCCESS;
922 PNDIS_TASK_OFFLOAD_HEADER ntoh;
923 PNDIS_TASK_OFFLOAD nto;
924 PNDIS_TASK_TCP_IP_CHECKSUM nttic;
925 #ifdef LARGE_SEND
926 PNDIS_TASK_TCP_LARGE_SEND nttls;
927 #endif
929 // KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
931 switch(Oid)
932 {
933 case OID_GEN_SUPPORTED_LIST:
934 data = supported_oids;
935 len = sizeof(supported_oids);
936 break;
937 case OID_GEN_HARDWARE_STATUS:
938 if (!xi->connected)
939 temp_data = NdisHardwareStatusInitializing;
940 else
941 temp_data = NdisHardwareStatusReady;
942 break;
943 case OID_GEN_MEDIA_SUPPORTED:
944 temp_data = NdisMedium802_3;
945 break;
946 case OID_GEN_MEDIA_IN_USE:
947 temp_data = NdisMedium802_3;
948 break;
949 case OID_GEN_MAXIMUM_LOOKAHEAD:
950 temp_data = XN_DATA_SIZE;
951 break;
952 case OID_GEN_MAXIMUM_FRAME_SIZE:
953 // According to the specs, OID_GEN_MAXIMUM_FRAME_SIZE does not include the header, so
954 // it is XN_DATA_SIZE not XN_MAX_PKT_SIZE
955 temp_data = XN_DATA_SIZE; // XN_MAX_PKT_SIZE;
956 break;
957 case OID_GEN_LINK_SPEED:
958 temp_data = 10000000; /* 1Gb */
959 break;
960 case OID_GEN_TRANSMIT_BUFFER_SPACE:
961 /* pkts times sizeof ring, maybe? */
962 temp_data = XN_MAX_PKT_SIZE * NET_TX_RING_SIZE;
963 break;
964 case OID_GEN_RECEIVE_BUFFER_SPACE:
965 /* pkts times sizeof ring, maybe? */
966 temp_data = XN_MAX_PKT_SIZE * NET_RX_RING_SIZE;
967 break;
968 case OID_GEN_TRANSMIT_BLOCK_SIZE:
969 temp_data = XN_MAX_PKT_SIZE;
970 break;
971 case OID_GEN_RECEIVE_BLOCK_SIZE:
972 temp_data = XN_MAX_PKT_SIZE;
973 break;
974 case OID_GEN_VENDOR_ID:
975 temp_data = 0xFFFFFF; // Not guaranteed to be XENSOURCE_MAC_HDR;
976 break;
977 case OID_GEN_VENDOR_DESCRIPTION:
978 data = vendor_desc;
979 len = sizeof(vendor_desc);
980 break;
981 case OID_GEN_CURRENT_PACKET_FILTER:
982 temp_data = xi->packet_filter;
983 break;
984 case OID_GEN_CURRENT_LOOKAHEAD:
985 // TODO: we should store this...
986 temp_data = XN_MAX_PKT_SIZE;
987 break;
988 case OID_GEN_DRIVER_VERSION:
989 temp_data = (NDIS_MAJOR_VER << 8) | NDIS_MINOR_VER;
990 len = 2;
991 break;
992 case OID_GEN_MAXIMUM_TOTAL_SIZE:
993 temp_data = XN_MAX_PKT_SIZE;
994 break;
995 case OID_GEN_MAC_OPTIONS:
996 temp_data = NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA |
997 NDIS_MAC_OPTION_TRANSFERS_NOT_PEND |
998 NDIS_MAC_OPTION_NO_LOOPBACK;
999 break;
1000 case OID_GEN_MEDIA_CONNECT_STATUS:
1001 if (xi->connected)
1002 temp_data = NdisMediaStateConnected;
1003 else
1004 temp_data = NdisMediaStateDisconnected;
1005 break;
1006 case OID_GEN_MAXIMUM_SEND_PACKETS:
1007 temp_data = XN_MAX_SEND_PKTS;
1008 break;
1009 case OID_GEN_XMIT_OK:
1010 temp_data = xi->stat_tx_ok;
1011 HANDLE_STAT_RETURN;
1012 break;
1013 case OID_GEN_RCV_OK:
1014 temp_data = xi->stat_rx_ok;
1015 HANDLE_STAT_RETURN;
1016 break;
1017 case OID_GEN_XMIT_ERROR:
1018 temp_data = xi->stat_tx_error;
1019 HANDLE_STAT_RETURN;
1020 break;
1021 case OID_GEN_RCV_ERROR:
1022 temp_data = xi->stat_rx_error;
1023 HANDLE_STAT_RETURN;
1024 break;
1025 case OID_GEN_RCV_NO_BUFFER:
1026 temp_data = xi->stat_rx_no_buffer;
1027 HANDLE_STAT_RETURN;
1028 break;
1029 case OID_802_3_PERMANENT_ADDRESS:
1030 data = xi->perm_mac_addr;
1031 len = ETH_ALEN;
1032 break;
1033 case OID_802_3_CURRENT_ADDRESS:
1034 data = xi->curr_mac_addr;
1035 len = ETH_ALEN;
1036 break;
1037 case OID_802_3_MULTICAST_LIST:
1038 data = NULL;
1039 len = 0;
1040 case OID_802_3_MAXIMUM_LIST_SIZE:
1041 temp_data = 0; /* no mcast support */
1042 break;
1043 case OID_TCP_TASK_OFFLOAD:
1044 KdPrint(("Get OID_TCP_TASK_OFFLOAD\n"));
1045 /* it's times like this that C really sucks */
1046 len = sizeof(NDIS_TASK_OFFLOAD_HEADER)
1047 + FIELD_OFFSET(NDIS_TASK_OFFLOAD, TaskBuffer)
1048 + sizeof(NDIS_TASK_TCP_IP_CHECKSUM);
1049 #ifdef LARGE_SEND
1050 len += FIELD_OFFSET(NDIS_TASK_OFFLOAD, TaskBuffer)
1051 + sizeof(NDIS_TASK_TCP_LARGE_SEND);
1052 #endif
1054 if (len > InformationBufferLength)
1056 break;
1059 ntoh = InformationBuffer;
1060 ASSERT(ntoh->Version == NDIS_TASK_OFFLOAD_VERSION);
1061 ASSERT(ntoh->Size == sizeof(*ntoh));
1062 ASSERT(ntoh->EncapsulationFormat.Encapsulation == IEEE_802_3_Encapsulation);
1063 ntoh->OffsetFirstTask = ntoh->Size;
1065 /* fill in first nto */
1066 nto = (PNDIS_TASK_OFFLOAD)((PCHAR)(ntoh) + ntoh->OffsetFirstTask);
1067 nto->Version = NDIS_TASK_OFFLOAD_VERSION;
1068 nto->Size = sizeof(NDIS_TASK_OFFLOAD);
1069 nto->Task = TcpIpChecksumNdisTask;
1070 nto->TaskBufferLength = sizeof(NDIS_TASK_TCP_IP_CHECKSUM);
1072 /* fill in checksum offload struct */
1073 nttic = (PNDIS_TASK_TCP_IP_CHECKSUM)&nto->TaskBuffer;
1074 nttic->V4Transmit.IpOptionsSupported = 0;
1075 nttic->V4Transmit.TcpOptionsSupported = 0;
1076 nttic->V4Transmit.TcpChecksum = 0;
1077 nttic->V4Transmit.UdpChecksum = 0;
1078 nttic->V4Transmit.IpChecksum = 0;
1079 nttic->V4Receive.IpOptionsSupported = 0;
1080 nttic->V4Receive.TcpOptionsSupported = 0;
1081 nttic->V4Receive.TcpChecksum = 0;
1082 nttic->V4Receive.UdpChecksum = 0;
1083 nttic->V4Receive.IpChecksum = 1;
1084 nttic->V6Transmit.IpOptionsSupported = 0;
1085 nttic->V6Transmit.TcpOptionsSupported = 0;
1086 nttic->V6Transmit.TcpChecksum = 0;
1087 nttic->V6Transmit.UdpChecksum = 0;
1088 nttic->V6Receive.IpOptionsSupported = 0;
1089 nttic->V6Receive.TcpOptionsSupported = 0;
1090 nttic->V6Receive.TcpChecksum = 0;
1091 nttic->V6Receive.UdpChecksum = 0;
1092 #ifdef LARGE_SEND
1093 nto->OffsetNextTask = sizeof(NDIS_TASK_OFFLOAD_HEADER)
1094 + FIELD_OFFSET(NDIS_TASK_OFFLOAD, TaskBuffer)
1095 + sizeof(NDIS_TASK_TCP_IP_CHECKSUM);
1097 /* fill in second nto */
1098 nto = (PNDIS_TASK_OFFLOAD)((PCHAR)(ntoh) + nto->OffsetNextTask);
1099 nto->Version = NDIS_TASK_OFFLOAD_VERSION;
1100 nto->Size = sizeof(NDIS_TASK_OFFLOAD);
1101 nto->Task = TcpLargeSendNdisTask;
1102 nto->TaskBufferLength = sizeof(NDIS_TASK_TCP_LARGE_SEND);
1104 /* fill in large send struct */
1105 nttls = (PNDIS_TASK_TCP_LARGE_SEND)&nto->TaskBuffer;
1106 nttls->Version = 0;
1107 nttls->MaxOffLoadSize = 1024*64; /* made up, fixme */
1108 nttls->MinSegmentCount = 4; /* also made up */
1109 nttls->TcpOptions = FALSE;
1110 nttls->IpOptions = FALSE;
1111 #endif
1112 nto->OffsetNextTask = 0; /* last one */
1114 used_temp_buffer = FALSE;
1115 break;
1116 default:
1117 KdPrint(("Get Unknown OID 0x%x\n", Oid));
1118 status = NDIS_STATUS_NOT_SUPPORTED;
1121 if (!NT_SUCCESS(status))
1123 // KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ " (returned error)\n"));
1124 return status;
1127 if (len > InformationBufferLength)
1129 *BytesNeeded = len;
1130 KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ " (BUFFER_TOO_SHORT)\n"));
1131 return NDIS_STATUS_BUFFER_TOO_SHORT;
1134 *BytesWritten = len;
1135 if (len && used_temp_buffer)
1137 NdisMoveMemory(((PUCHAR)InformationBuffer) + offset, data, len - offset);
1140 //KdPrint(("Got OID 0x%x\n", Oid));
1141 // KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
1143 return status;
1146 NDIS_STATUS
1147 XenNet_SetInformation(
1148 IN NDIS_HANDLE MiniportAdapterContext,
1149 IN NDIS_OID Oid,
1150 IN PVOID InformationBuffer,
1151 IN ULONG InformationBufferLength,
1152 OUT PULONG BytesRead,
1153 OUT PULONG BytesNeeded
1156 NTSTATUS status;
1157 struct xennet_info *xi = MiniportAdapterContext;
1158 PULONG64 data = InformationBuffer;
1160 KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
1162 UNREFERENCED_PARAMETER(MiniportAdapterContext);
1163 UNREFERENCED_PARAMETER(InformationBufferLength);
1164 UNREFERENCED_PARAMETER(BytesRead);
1165 UNREFERENCED_PARAMETER(BytesNeeded);
1167 switch(Oid)
1169 case OID_GEN_SUPPORTED_LIST:
1170 status = NDIS_STATUS_NOT_SUPPORTED;
1171 KdPrint(("Unsupported set OID_GEN_SUPPORTED_LIST\n"));
1172 break;
1173 case OID_GEN_HARDWARE_STATUS:
1174 status = NDIS_STATUS_NOT_SUPPORTED;
1175 KdPrint(("Unsupported set OID_GEN_HARDWARE_STATUS\n"));
1176 break;
1177 case OID_GEN_MEDIA_SUPPORTED:
1178 status = NDIS_STATUS_NOT_SUPPORTED;
1179 KdPrint(("Unsupported set OID_GEN_MEDIA_SUPPORTED\n"));
1180 break;
1181 case OID_GEN_MEDIA_IN_USE:
1182 status = NDIS_STATUS_NOT_SUPPORTED;
1183 KdPrint(("Unsupported set OID_GEN_MEDIA_IN_USE\n"));
1184 break;
1185 case OID_GEN_MAXIMUM_LOOKAHEAD:
1186 status = NDIS_STATUS_NOT_SUPPORTED;
1187 KdPrint(("Unsupported set OID_GEN_MAXIMUM_LOOKAHEAD\n"));
1188 break;
1189 case OID_GEN_MAXIMUM_FRAME_SIZE:
1190 status = NDIS_STATUS_NOT_SUPPORTED;
1191 KdPrint(("Unsupported set OID_GEN_MAXIMUM_FRAME_SIZE\n"));
1192 break;
1193 case OID_GEN_LINK_SPEED:
1194 status = NDIS_STATUS_NOT_SUPPORTED;
1195 KdPrint(("Unsupported set OID_GEN_LINK_SPEED\n"));
1196 break;
1197 case OID_GEN_TRANSMIT_BUFFER_SPACE:
1198 status = NDIS_STATUS_NOT_SUPPORTED;
1199 KdPrint(("Unsupported set OID_GEN_TRANSMIT_BUFFER_SPACE\n"));
1200 break;
1201 case OID_GEN_RECEIVE_BUFFER_SPACE:
1202 status = NDIS_STATUS_NOT_SUPPORTED;
1203 KdPrint(("Unsupported set OID_GEN_RECEIVE_BUFFER_SPACE\n"));
1204 break;
1205 case OID_GEN_TRANSMIT_BLOCK_SIZE:
1206 status = NDIS_STATUS_NOT_SUPPORTED;
1207 KdPrint(("Unsupported set OID_GEN_TRANSMIT_BLOCK_SIZE\n"));
1208 break;
1209 case OID_GEN_RECEIVE_BLOCK_SIZE:
1210 status = NDIS_STATUS_NOT_SUPPORTED;
1211 KdPrint(("Unsupported set OID_GEN_RECEIVE_BLOCK_SIZE\n"));
1212 break;
1213 case OID_GEN_VENDOR_ID:
1214 status = NDIS_STATUS_NOT_SUPPORTED;
1215 KdPrint(("Unsupported set OID_GEN_VENDOR_ID\n"));
1216 break;
1217 case OID_GEN_VENDOR_DESCRIPTION:
1218 status = NDIS_STATUS_NOT_SUPPORTED;
1219 KdPrint(("Unsupported set OID_GEN_VENDOR_DESCRIPTION\n"));
1220 break;
1221 case OID_GEN_CURRENT_PACKET_FILTER:
1222 KdPrint(("Set OID_GEN_CURRENT_PACKET_FILTER\n"));
1223 xi->packet_filter = *(ULONG *)data;
1224 status = NDIS_STATUS_SUCCESS;
1225 break;
1226 case OID_GEN_CURRENT_LOOKAHEAD:
1227 KdPrint(("Set OID_GEN_CURRENT_LOOKAHEAD %d\n", *(int *)data));
1228 // TODO: We should do this...
1229 status = NDIS_STATUS_SUCCESS;
1230 break;
1231 case OID_GEN_DRIVER_VERSION:
1232 status = NDIS_STATUS_NOT_SUPPORTED;
1233 KdPrint(("Unsupported set OID_GEN_DRIVER_VERSION\n"));
1234 break;
1235 case OID_GEN_MAXIMUM_TOTAL_SIZE:
1236 status = NDIS_STATUS_NOT_SUPPORTED;
1237 KdPrint(("Unsupported set OID_GEN_MAXIMUM_TOTAL_SIZE\n"));
1238 break;
1239 case OID_GEN_PROTOCOL_OPTIONS:
1240 KdPrint(("Unsupported set OID_GEN_PROTOCOL_OPTIONS\n"));
1241 // TODO - actually do this...
1242 status = NDIS_STATUS_SUCCESS;
1243 break;
1244 case OID_GEN_MAC_OPTIONS:
1245 status = NDIS_STATUS_NOT_SUPPORTED;
1246 KdPrint(("Unsupported set OID_GEN_MAC_OPTIONS\n"));
1247 break;
1248 case OID_GEN_MEDIA_CONNECT_STATUS:
1249 status = NDIS_STATUS_NOT_SUPPORTED;
1250 KdPrint(("Unsupported set OID_GEN_MEDIA_CONNECT_STATUS\n"));
1251 break;
1252 case OID_GEN_MAXIMUM_SEND_PACKETS:
1253 status = NDIS_STATUS_NOT_SUPPORTED;
1254 KdPrint(("Unsupported set OID_GEN_MAXIMUM_SEND_PACKETS\n"));
1255 break;
1256 case OID_GEN_XMIT_OK:
1257 status = NDIS_STATUS_NOT_SUPPORTED;
1258 KdPrint(("Unsupported set OID_GEN_XMIT_OK\n"));
1259 break;
1260 case OID_GEN_RCV_OK:
1261 status = NDIS_STATUS_NOT_SUPPORTED;
1262 KdPrint(("Unsupported set OID_GEN_RCV_OK\n"));
1263 break;
1264 case OID_GEN_XMIT_ERROR:
1265 status = NDIS_STATUS_NOT_SUPPORTED;
1266 KdPrint(("Unsupported set OID_GEN_XMIT_ERROR\n"));
1267 break;
1268 case OID_GEN_RCV_ERROR:
1269 status = NDIS_STATUS_NOT_SUPPORTED;
1270 KdPrint(("Unsupported set OID_GEN_RCV_ERROR\n"));
1271 break;
1272 case OID_GEN_RCV_NO_BUFFER:
1273 status = NDIS_STATUS_NOT_SUPPORTED;
1274 KdPrint(("Unsupported set OID_GEN_RCV_NO_BUFFER\n"));
1275 break;
1276 case OID_802_3_PERMANENT_ADDRESS:
1277 status = NDIS_STATUS_NOT_SUPPORTED;
1278 KdPrint(("Unsupported set OID_802_3_PERMANENT_ADDRESS\n"));
1279 break;
1280 case OID_802_3_CURRENT_ADDRESS:
1281 status = NDIS_STATUS_NOT_SUPPORTED;
1282 KdPrint(("Unsupported set OID_802_3_CURRENT_ADDRESS\n"));
1283 break;
1284 case OID_802_3_MULTICAST_LIST:
1285 status = NDIS_STATUS_NOT_SUPPORTED;
1286 KdPrint(("Unsupported set OID_802_3_MULTICAST_LIST\n"));
1287 break;
1288 case OID_802_3_MAXIMUM_LIST_SIZE:
1289 status = NDIS_STATUS_NOT_SUPPORTED;
1290 KdPrint(("Unsupported set OID_802_3_MAXIMUM_LIST_SIZE\n"));
1291 break;
1292 case OID_TCP_TASK_OFFLOAD:
1293 // Just fake this for now... not sure if we will do anything different as a result...
1294 KdPrint(("Set OID_TCP_TASK_OFFLOAD\n"));
1295 status = NDIS_STATUS_SUCCESS;
1296 break;
1297 default:
1298 KdPrint(("Set Unknown OID 0x%x\n", Oid));
1299 status = NDIS_STATUS_NOT_SUPPORTED;
1300 break;
1302 KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
1303 return status;
1306 VOID
1307 XenNet_ReturnPacket(
1308 IN NDIS_HANDLE MiniportAdapterContext,
1309 IN PNDIS_PACKET Packet
1312 PNDIS_BUFFER buffer;
1313 PVOID buff_va;
1314 UINT buff_len;
1315 UINT tot_buff_len;
1317 // KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
1319 UNREFERENCED_PARAMETER(MiniportAdapterContext);
1321 NdisGetFirstBufferFromPacketSafe(Packet, &buffer, &buff_va, &buff_len,
1322 &tot_buff_len, NormalPagePriority);
1323 ASSERT(buff_len == tot_buff_len);
1325 /* TODO: reuse returned packets */
1327 NdisFreeMemory(buff_va, 0, 0);
1328 NdisFreeBuffer(buffer);
1329 NdisFreePacket(Packet);
1331 //KdPrint((__FUNCTION__ " called\n"));
1332 // KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
1335 PMDL
1336 XenNet_Linearize(PNDIS_PACKET Packet)
1338 NDIS_STATUS status;
1339 PMDL pmdl;
1340 char *start;
1341 PNDIS_BUFFER buffer;
1342 PVOID buff_va;
1343 UINT buff_len;
1344 UINT tot_buff_len;
1346 // KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
1348 NdisGetFirstBufferFromPacketSafe(Packet, &buffer, &buff_va, &buff_len,
1349 &tot_buff_len, NormalPagePriority);
1350 ASSERT(tot_buff_len <= XN_MAX_PKT_SIZE);
1352 status = NdisAllocateMemoryWithTag(&start, tot_buff_len, XENNET_POOL_TAG);
1353 if (!NT_SUCCESS(status))
1355 KdPrint(("Could not allocate memory for linearization\n"));
1356 return NULL;
1358 pmdl = IoAllocateMdl(start, tot_buff_len, FALSE, FALSE, FALSE);
1359 if (!pmdl)
1361 KdPrint(("Could not allocate MDL for linearization\n"));
1362 NdisFreeMemory(start, 0, 0);
1363 return NULL;
1365 MmBuildMdlForNonPagedPool(pmdl);
1367 while (buffer)
1369 NdisQueryBufferSafe(buffer, &buff_va, &buff_len, NormalPagePriority);
1370 RtlCopyMemory(start, buff_va, buff_len);
1371 start += buff_len;
1372 NdisGetNextBuffer(buffer, &buffer);
1375 // KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
1376 return pmdl;
1379 VOID
1380 XenNet_SendPackets(
1381 IN NDIS_HANDLE MiniportAdapterContext,
1382 IN PPNDIS_PACKET PacketArray,
1383 IN UINT NumberOfPackets
1386 struct xennet_info *xi = MiniportAdapterContext;
1387 PNDIS_PACKET curr_packet;
1388 UINT i;
1389 struct netif_tx_request *tx;
1390 unsigned short id;
1391 int notify;
1392 PMDL pmdl;
1393 UINT pkt_size;
1394 KIRQL OldIrql;
1396 // KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
1398 KeAcquireSpinLock(&xi->TxLock, &OldIrql);
1400 for (i = 0; i < NumberOfPackets; i++)
1402 curr_packet = PacketArray[i];
1403 ASSERT(curr_packet);
1405 NdisQueryPacket(curr_packet, NULL, NULL, NULL, &pkt_size);
1407 //KdPrint(("sending pkt, len %d\n", pkt_size));
1409 pmdl = XenNet_Linearize(curr_packet);
1410 if (!pmdl)
1412 KdPrint((__DRIVER_NAME "Couldn't linearize packet!\n"));
1413 NdisMSendComplete(xi, curr_packet, NDIS_STATUS_FAILURE);
1414 break;
1416 *((PMDL *)curr_packet->MiniportReservedEx) = pmdl;
1418 id = get_id_from_freelist(xi->tx_pkts);
1419 xi->tx_pkts[id] = curr_packet;
1421 tx = RING_GET_REQUEST(&xi->tx, xi->tx.req_prod_pvt);
1422 tx->id = id;
1423 tx->gref = xi->XenInterface.GntTbl_GrantAccess(
1424 xi->XenInterface.InterfaceHeader.Context,
1425 0,
1426 *MmGetMdlPfnArray(pmdl),
1427 TRUE);
1428 xi->grant_tx_ref[id] = tx->gref;
1429 tx->offset = (uint16_t)MmGetMdlByteOffset(pmdl);
1430 tx->size = (UINT16)pkt_size;
1431 // NETTXF_csum_blank should only be used for tcp and udp packets...
1432 tx->flags = 0; //NETTXF_csum_blank;
1434 xi->tx.req_prod_pvt++;
1436 // NDIS_SET_PACKET_STATUS(curr_packet, NDIS_STATUS_SUCCESS);
1437 // NdisMSendComplete(xi, curr_packet, NDIS_STATUS_SUCCESS);
1440 RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&xi->tx, notify);
1441 if (notify)
1443 xi->XenInterface.EvtChn_Notify(xi->XenInterface.InterfaceHeader.Context,
1444 xi->event_channel);
1447 KeReleaseSpinLock(&xi->TxLock, OldIrql);
1449 // KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ "\n"));
1452 VOID
1453 XenNet_PnPEventNotify(
1454 IN NDIS_HANDLE MiniportAdapterContext,
1455 IN NDIS_DEVICE_PNP_EVENT PnPEvent,
1456 IN PVOID InformationBuffer,
1457 IN ULONG InformationBufferLength
1460 UNREFERENCED_PARAMETER(MiniportAdapterContext);
1461 UNREFERENCED_PARAMETER(PnPEvent);
1462 UNREFERENCED_PARAMETER(InformationBuffer);
1463 UNREFERENCED_PARAMETER(InformationBufferLength);
1465 KdPrint((__FUNCTION__ " called\n"));
1468 VOID
1469 XenNet_Shutdown(
1470 IN NDIS_HANDLE MiniportAdapterContext
1473 struct xennet_info *xi = MiniportAdapterContext;
1475 xi->connected = FALSE;
1477 /* Free xen resources */
1478 /* TODO: disconnect from backend */
1480 /* Free ndis resources */
1481 XenNet_FreeRXBuffers(MiniportAdapterContext);
1482 /* TODO: clean TX ring */
1484 KdPrint((__FUNCTION__ " called\n"));
1487 NTSTATUS
1488 DriverEntry(
1489 PDRIVER_OBJECT DriverObject,
1490 PUNICODE_STRING RegistryPath
1493 NTSTATUS status;
1494 WDF_DRIVER_CONFIG config;
1495 NDIS_HANDLE ndis_wrapper_handle;
1496 NDIS_MINIPORT_CHARACTERISTICS mini_chars;
1498 RtlZeroMemory(&mini_chars, sizeof(mini_chars));
1500 WDF_DRIVER_CONFIG_INIT(&config, WDF_NO_EVENT_CALLBACK);
1501 config.DriverInitFlags |= WdfDriverInitNoDispatchOverride;
1503 status = WdfDriverCreate(DriverObject, RegistryPath, WDF_NO_OBJECT_ATTRIBUTES,
1504 &config, WDF_NO_HANDLE);
1505 if (!NT_SUCCESS(status))
1507 KdPrint(("WdfDriverCreate failed err = 0x%x\n", status));
1508 return status;
1511 NdisMInitializeWrapper(&ndis_wrapper_handle, DriverObject, RegistryPath, NULL);
1512 if (!ndis_wrapper_handle)
1514 KdPrint(("NdisMInitializeWrapper failed\n"));
1515 return NDIS_STATUS_FAILURE;
1518 /* NDIS 5.1 driver */
1519 mini_chars.MajorNdisVersion = NDIS_MAJOR_VER;
1520 mini_chars.MinorNdisVersion = NDIS_MINOR_VER;
1522 mini_chars.HaltHandler = XenNet_Halt;
1523 mini_chars.InitializeHandler = XenNet_Init;
1524 mini_chars.ISRHandler = NULL; // needed if we register interrupt?
1525 mini_chars.QueryInformationHandler = XenNet_QueryInformation;
1526 mini_chars.ResetHandler = NULL; //TODO: fill in
1527 mini_chars.SetInformationHandler = XenNet_SetInformation;
1528 /* added in v.4 -- use multiple pkts interface */
1529 mini_chars.ReturnPacketHandler = XenNet_ReturnPacket;
1530 mini_chars.SendPacketsHandler = XenNet_SendPackets;
1531 /* added in v.5.1 */
1532 mini_chars.PnPEventNotifyHandler = XenNet_PnPEventNotify;
1533 mini_chars.AdapterShutdownHandler = XenNet_Shutdown;
1535 /* TODO: we don't have hardware, but we have "resources", so do we need to implement fns to handle this? */
1537 /* set up upper-edge interface */
1538 status = NdisMRegisterMiniport(ndis_wrapper_handle, &mini_chars, sizeof(mini_chars));
1539 if (!NT_SUCCESS(status))
1541 KdPrint(("NdisMRegisterMiniport failed, status = 0x%x\n", status));
1542 NdisTerminateWrapper(ndis_wrapper_handle, NULL);
1543 return status;
1546 return status;