1e166041dcc5d094b7455087ca26630ab3f82872
[cascardo/ovs.git] / datapath-windows / ovsext / Datapath.c
1 /*
2  * Copyright (c) 2014 VMware, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * XXX: OVS_USE_NL_INTERFACE is being used to keep the legacy DPIF interface
19  * alive while we transition over to the netlink based interface.
20  * OVS_USE_NL_INTERFACE = 0 => legacy inteface to use with dpif-windows.c
21  * OVS_USE_NL_INTERFACE = 1 => netlink inteface to use with ported dpif-linux.c
22  */
23
24 #include "precomp.h"
25 #include "Switch.h"
26 #include "User.h"
27 #include "Datapath.h"
28 #include "Jhash.h"
29 #include "Vport.h"
30 #include "Event.h"
31 #include "User.h"
32 #include "PacketIO.h"
33 #include "NetProto.h"
34 #include "Flow.h"
35 #include "User.h"
36 #include "Vxlan.h"
37
38 #ifdef OVS_DBG_MOD
39 #undef OVS_DBG_MOD
40 #endif
41 #define OVS_DBG_MOD OVS_DBG_DATAPATH
42 #include "Debug.h"
43
44 #define NETLINK_FAMILY_NAME_LEN 48
45
46
47 /*
48  * Netlink messages are grouped by family (aka type), and each family supports
49  * a set of commands, and can be passed both from kernel -> userspace or
50  * vice-versa. To call into the kernel, userspace uses a device operation which
51  * is outside of a netlink message.
52  *
53  * Each command results in the invocation of a handler function to implement the
54  * request functionality.
55  *
56  * Expectedly, only certain combinations of (device operation, netlink family,
57  * command) are valid.
58  *
59  * Here, we implement the basic infrastructure to perform validation on the
60  * incoming message, version checking, and also to invoke the corresponding
61  * handler to do the heavy-lifting.
62  */
63
64 /*
65  * Handler for a given netlink command. Not all the parameters are used by all
66  * the handlers.
67  */
68 typedef NTSTATUS(NetlinkCmdHandler)(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
69                                     UINT32 *replyLen);
70
71 typedef struct _NETLINK_CMD {
72     UINT16 cmd;
73     NetlinkCmdHandler *handler;
74     UINT32 supportedDevOp;      /* Supported device operations. */
75     BOOLEAN validateDpIndex;    /* Does command require a valid DP argument. */
76 } NETLINK_CMD, *PNETLINK_CMD;
77
78 /* A netlink family is a group of commands. */
79 typedef struct _NETLINK_FAMILY {
80     CHAR *name;
81     UINT16 id;
82     UINT8 version;
83     UINT8 pad1;
84     UINT16 maxAttr;
85     UINT16 pad2;
86     NETLINK_CMD *cmds;          /* Array of netlink commands and handlers. */
87     UINT16 opsCount;
88 } NETLINK_FAMILY, *PNETLINK_FAMILY;
89
90 /* Handlers for the various netlink commands. */
91 static NetlinkCmdHandler OvsPendEventCmdHandler,
92                          OvsSubscribeEventCmdHandler,
93                          OvsReadEventCmdHandler,
94                          OvsNewDpCmdHandler,
95                          OvsGetDpCmdHandler,
96                          OvsSetDpCmdHandler;
97
98 NetlinkCmdHandler        OvsGetNetdevCmdHandler,
99                          OvsGetVportCmdHandler,
100                          OvsSetVportCmdHandler,
101                          OvsNewVportCmdHandler,
102                          OvsDeleteVportCmdHandler,
103                          OvsPendPacketCmdHandler,
104                          OvsSubscribePacketCmdHandler,
105                          OvsReadPacketCmdHandler;
106
107 static NTSTATUS HandleGetDpTransaction(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
108                                        UINT32 *replyLen);
109 static NTSTATUS HandleGetDpDump(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
110                                 UINT32 *replyLen);
111 static NTSTATUS HandleDpTransactionCommon(
112                     POVS_USER_PARAMS_CONTEXT usrParamsCtx, UINT32 *replyLen);
113 static NTSTATUS OvsGetPidHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
114                                     UINT32 *replyLen);
115
116 /*
117  * The various netlink families, along with the supported commands. Most of
118  * these families and commands are part of the openvswitch specification for a
119  * netlink datapath. In addition, each platform can implement a few families
120  * and commands as extensions.
121  */
122
123 /* Netlink control family: this is a Windows specific family. */
124 NETLINK_CMD nlControlFamilyCmdOps[] = {
125     { .cmd = OVS_CTRL_CMD_WIN_PEND_REQ,
126       .handler = OvsPendEventCmdHandler,
127       .supportedDevOp = OVS_WRITE_DEV_OP,
128       .validateDpIndex = TRUE,
129     },
130     { .cmd = OVS_CTRL_CMD_WIN_PEND_PACKET_REQ,
131       .handler = OvsPendPacketCmdHandler,
132       .supportedDevOp = OVS_WRITE_DEV_OP,
133       .validateDpIndex = TRUE,
134     },
135     { .cmd = OVS_CTRL_CMD_MC_SUBSCRIBE_REQ,
136       .handler = OvsSubscribeEventCmdHandler,
137       .supportedDevOp = OVS_WRITE_DEV_OP,
138       .validateDpIndex = TRUE,
139     },
140     { .cmd = OVS_CTRL_CMD_PACKET_SUBSCRIBE_REQ,
141       .handler = OvsSubscribePacketCmdHandler,
142       .supportedDevOp = OVS_WRITE_DEV_OP,
143       .validateDpIndex = TRUE,
144     },
145     { .cmd = OVS_CTRL_CMD_EVENT_NOTIFY,
146       .handler = OvsReadEventCmdHandler,
147       .supportedDevOp = OVS_READ_DEV_OP,
148       .validateDpIndex = FALSE,
149     },
150     { .cmd = OVS_CTRL_CMD_READ_NOTIFY,
151       .handler = OvsReadPacketCmdHandler,
152       .supportedDevOp = OVS_READ_DEV_OP,
153       .validateDpIndex = FALSE,
154     }
155 };
156
157 NETLINK_FAMILY nlControlFamilyOps = {
158     .name     = OVS_WIN_CONTROL_FAMILY,
159     .id       = OVS_WIN_NL_CTRL_FAMILY_ID,
160     .version  = OVS_WIN_CONTROL_VERSION,
161     .maxAttr  = OVS_WIN_CONTROL_ATTR_MAX,
162     .cmds     = nlControlFamilyCmdOps,
163     .opsCount = ARRAY_SIZE(nlControlFamilyCmdOps)
164 };
165
166 /* Netlink datapath family. */
167 NETLINK_CMD nlDatapathFamilyCmdOps[] = {
168     { .cmd             = OVS_DP_CMD_NEW,
169       .handler         = OvsNewDpCmdHandler,
170       .supportedDevOp  = OVS_TRANSACTION_DEV_OP,
171       .validateDpIndex = FALSE
172     },
173     { .cmd             = OVS_DP_CMD_GET,
174       .handler         = OvsGetDpCmdHandler,
175       .supportedDevOp  = OVS_WRITE_DEV_OP | OVS_READ_DEV_OP |
176                          OVS_TRANSACTION_DEV_OP,
177       .validateDpIndex = FALSE
178     },
179     { .cmd             = OVS_DP_CMD_SET,
180       .handler         = OvsSetDpCmdHandler,
181       .supportedDevOp  = OVS_WRITE_DEV_OP | OVS_READ_DEV_OP |
182                          OVS_TRANSACTION_DEV_OP,
183       .validateDpIndex = TRUE
184     }
185 };
186
187 NETLINK_FAMILY nlDatapathFamilyOps = {
188     .name     = OVS_DATAPATH_FAMILY,
189     .id       = OVS_WIN_NL_DATAPATH_FAMILY_ID,
190     .version  = OVS_DATAPATH_VERSION,
191     .maxAttr  = OVS_DP_ATTR_MAX,
192     .cmds     = nlDatapathFamilyCmdOps,
193     .opsCount = ARRAY_SIZE(nlDatapathFamilyCmdOps)
194 };
195
196 /* Netlink packet family. */
197
198 NETLINK_CMD nlPacketFamilyCmdOps[] = {
199     { .cmd             = OVS_PACKET_CMD_EXECUTE,
200       .handler         = OvsNlExecuteCmdHandler,
201       .supportedDevOp  = OVS_TRANSACTION_DEV_OP,
202       .validateDpIndex = TRUE
203     }
204 };
205
206 NETLINK_FAMILY nlPacketFamilyOps = {
207     .name     = OVS_PACKET_FAMILY,
208     .id       = OVS_WIN_NL_PACKET_FAMILY_ID,
209     .version  = OVS_PACKET_VERSION,
210     .maxAttr  = OVS_PACKET_ATTR_MAX,
211     .cmds     = nlPacketFamilyCmdOps,
212     .opsCount = ARRAY_SIZE(nlPacketFamilyCmdOps)
213 };
214
215 /* Netlink vport family. */
216 NETLINK_CMD nlVportFamilyCmdOps[] = {
217     { .cmd = OVS_VPORT_CMD_GET,
218       .handler = OvsGetVportCmdHandler,
219       .supportedDevOp = OVS_WRITE_DEV_OP | OVS_READ_DEV_OP |
220                         OVS_TRANSACTION_DEV_OP,
221       .validateDpIndex = TRUE
222     },
223     { .cmd = OVS_VPORT_CMD_NEW,
224       .handler = OvsNewVportCmdHandler,
225       .supportedDevOp = OVS_TRANSACTION_DEV_OP,
226       .validateDpIndex = TRUE
227     },
228     { .cmd = OVS_VPORT_CMD_SET,
229       .handler = OvsSetVportCmdHandler,
230       .supportedDevOp = OVS_TRANSACTION_DEV_OP,
231       .validateDpIndex = TRUE
232     },
233     { .cmd = OVS_VPORT_CMD_DEL,
234       .handler = OvsDeleteVportCmdHandler,
235       .supportedDevOp = OVS_TRANSACTION_DEV_OP,
236       .validateDpIndex = TRUE
237     },
238 };
239
240 NETLINK_FAMILY nlVportFamilyOps = {
241     .name     = OVS_VPORT_FAMILY,
242     .id       = OVS_WIN_NL_VPORT_FAMILY_ID,
243     .version  = OVS_VPORT_VERSION,
244     .maxAttr  = OVS_VPORT_ATTR_MAX,
245     .cmds     = nlVportFamilyCmdOps,
246     .opsCount = ARRAY_SIZE(nlVportFamilyCmdOps)
247 };
248
249 /* Netlink flow family. */
250
251 NETLINK_CMD nlFlowFamilyCmdOps[] = {
252     { .cmd              = OVS_FLOW_CMD_NEW,
253       .handler          = OvsFlowNlCmdHandler,
254       .supportedDevOp   = OVS_TRANSACTION_DEV_OP,
255       .validateDpIndex  = TRUE
256     },
257     { .cmd              = OVS_FLOW_CMD_SET,
258       .handler          = OvsFlowNlCmdHandler,
259       .supportedDevOp   = OVS_TRANSACTION_DEV_OP,
260       .validateDpIndex  = TRUE
261     },
262     { .cmd              = OVS_FLOW_CMD_DEL,
263       .handler          = OvsFlowNlCmdHandler,
264       .supportedDevOp   = OVS_TRANSACTION_DEV_OP,
265       .validateDpIndex  = TRUE
266     },
267     { .cmd              = OVS_FLOW_CMD_GET,
268       .handler          = OvsFlowNlGetCmdHandler,
269       .supportedDevOp   = OVS_TRANSACTION_DEV_OP |
270                           OVS_WRITE_DEV_OP | OVS_READ_DEV_OP,
271       .validateDpIndex  = TRUE
272     },
273 };
274
275 NETLINK_FAMILY nlFLowFamilyOps = {
276     .name     = OVS_FLOW_FAMILY,
277     .id       = OVS_WIN_NL_FLOW_FAMILY_ID,
278     .version  = OVS_FLOW_VERSION,
279     .maxAttr  = OVS_FLOW_ATTR_MAX,
280     .cmds     = nlFlowFamilyCmdOps,
281     .opsCount = ARRAY_SIZE(nlFlowFamilyCmdOps)
282 };
283
284 /* Netlink netdev family. */
285 NETLINK_CMD nlNetdevFamilyCmdOps[] = {
286     { .cmd = OVS_WIN_NETDEV_CMD_GET,
287       .handler = OvsGetNetdevCmdHandler,
288       .supportedDevOp = OVS_TRANSACTION_DEV_OP,
289       .validateDpIndex = FALSE
290     },
291 };
292
293 NETLINK_FAMILY nlNetdevFamilyOps = {
294     .name     = OVS_WIN_NETDEV_FAMILY,
295     .id       = OVS_WIN_NL_NETDEV_FAMILY_ID,
296     .version  = OVS_WIN_NETDEV_VERSION,
297     .maxAttr  = OVS_WIN_NETDEV_ATTR_MAX,
298     .cmds     = nlNetdevFamilyCmdOps,
299     .opsCount = ARRAY_SIZE(nlNetdevFamilyCmdOps)
300 };
301
302 static NTSTATUS MapIrpOutputBuffer(PIRP irp,
303                                    UINT32 bufferLength,
304                                    UINT32 requiredLength,
305                                    PVOID *buffer);
306 static NTSTATUS ValidateNetlinkCmd(UINT32 devOp,
307                                    POVS_OPEN_INSTANCE instance,
308                                    POVS_MESSAGE ovsMsg,
309                                    NETLINK_FAMILY *nlFamilyOps);
310 static NTSTATUS InvokeNetlinkCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
311                                         NETLINK_FAMILY *nlFamilyOps,
312                                         UINT32 *replyLen);
313
314 /* Handles to the device object for communication with userspace. */
315 NDIS_HANDLE gOvsDeviceHandle;
316 PDEVICE_OBJECT gOvsDeviceObject;
317
318 _Dispatch_type_(IRP_MJ_CREATE)
319 _Dispatch_type_(IRP_MJ_CLOSE)
320 DRIVER_DISPATCH OvsOpenCloseDevice;
321
322 _Dispatch_type_(IRP_MJ_CLEANUP)
323 DRIVER_DISPATCH OvsCleanupDevice;
324
325 _Dispatch_type_(IRP_MJ_DEVICE_CONTROL)
326 DRIVER_DISPATCH OvsDeviceControl;
327
328 #ifdef ALLOC_PRAGMA
329 #pragma alloc_text(INIT, OvsCreateDeviceObject)
330 #pragma alloc_text(PAGE, OvsOpenCloseDevice)
331 #pragma alloc_text(PAGE, OvsCleanupDevice)
332 #pragma alloc_text(PAGE, OvsDeviceControl)
333 #endif // ALLOC_PRAGMA
334
335 /*
336  * We might hit this limit easily since userspace opens a netlink descriptor for
337  * each thread, and at least one descriptor per vport. Revisit this later.
338  */
339 #define OVS_MAX_OPEN_INSTANCES 512
340 #define OVS_SYSTEM_DP_NAME     "ovs-system"
341
342 POVS_OPEN_INSTANCE ovsOpenInstanceArray[OVS_MAX_OPEN_INSTANCES];
343 UINT32 ovsNumberOfOpenInstances;
344 extern POVS_SWITCH_CONTEXT gOvsSwitchContext;
345
346 NDIS_SPIN_LOCK ovsCtrlLockObj;
347 PNDIS_SPIN_LOCK gOvsCtrlLock;
348
349 NTSTATUS
350 InitUserDumpState(POVS_OPEN_INSTANCE instance,
351                   POVS_MESSAGE ovsMsg)
352 {
353     /* Clear the dumpState from a previous dump sequence. */
354     ASSERT(instance->dumpState.ovsMsg == NULL);
355     ASSERT(ovsMsg);
356
357     instance->dumpState.ovsMsg =
358         (POVS_MESSAGE)OvsAllocateMemoryWithTag(sizeof(OVS_MESSAGE),
359                                                OVS_DATAPATH_POOL_TAG);
360     if (instance->dumpState.ovsMsg == NULL) {
361         return STATUS_NO_MEMORY;
362     }
363     RtlCopyMemory(instance->dumpState.ovsMsg, ovsMsg,
364                   sizeof *instance->dumpState.ovsMsg);
365     RtlZeroMemory(instance->dumpState.index,
366                   sizeof instance->dumpState.index);
367
368     return STATUS_SUCCESS;
369 }
370
371 VOID
372 FreeUserDumpState(POVS_OPEN_INSTANCE instance)
373 {
374     if (instance->dumpState.ovsMsg != NULL) {
375         OvsFreeMemoryWithTag(instance->dumpState.ovsMsg,
376                              OVS_DATAPATH_POOL_TAG);
377         RtlZeroMemory(&instance->dumpState, sizeof instance->dumpState);
378     }
379 }
380
381 VOID
382 OvsInit()
383 {
384     gOvsCtrlLock = &ovsCtrlLockObj;
385     NdisAllocateSpinLock(gOvsCtrlLock);
386     OvsInitEventQueue();
387 }
388
389 VOID
390 OvsCleanup()
391 {
392     OvsCleanupEventQueue();
393     if (gOvsCtrlLock) {
394         NdisFreeSpinLock(gOvsCtrlLock);
395         gOvsCtrlLock = NULL;
396     }
397 }
398
399 VOID
400 OvsAcquireCtrlLock()
401 {
402     NdisAcquireSpinLock(gOvsCtrlLock);
403 }
404
405 VOID
406 OvsReleaseCtrlLock()
407 {
408     NdisReleaseSpinLock(gOvsCtrlLock);
409 }
410
411
412 /*
413  * --------------------------------------------------------------------------
414  * Creates the communication device between user and kernel, and also
415  * initializes the data associated data structures.
416  * --------------------------------------------------------------------------
417  */
418 NDIS_STATUS
419 OvsCreateDeviceObject(NDIS_HANDLE ovsExtDriverHandle)
420 {
421     NDIS_STATUS status = NDIS_STATUS_SUCCESS;
422     UNICODE_STRING deviceName;
423     UNICODE_STRING symbolicDeviceName;
424     PDRIVER_DISPATCH dispatchTable[IRP_MJ_MAXIMUM_FUNCTION+1];
425     NDIS_DEVICE_OBJECT_ATTRIBUTES deviceAttributes;
426     OVS_LOG_TRACE("ovsExtDriverHandle: %p", ovsExtDriverHandle);
427
428     RtlZeroMemory(dispatchTable,
429                   (IRP_MJ_MAXIMUM_FUNCTION + 1) * sizeof (PDRIVER_DISPATCH));
430     dispatchTable[IRP_MJ_CREATE] = OvsOpenCloseDevice;
431     dispatchTable[IRP_MJ_CLOSE] = OvsOpenCloseDevice;
432     dispatchTable[IRP_MJ_CLEANUP] = OvsCleanupDevice;
433     dispatchTable[IRP_MJ_DEVICE_CONTROL] = OvsDeviceControl;
434
435     NdisInitUnicodeString(&deviceName, OVS_DEVICE_NAME_NT);
436     NdisInitUnicodeString(&symbolicDeviceName, OVS_DEVICE_NAME_DOS);
437
438     RtlZeroMemory(&deviceAttributes, sizeof (NDIS_DEVICE_OBJECT_ATTRIBUTES));
439
440     OVS_INIT_OBJECT_HEADER(&deviceAttributes.Header,
441                            NDIS_OBJECT_TYPE_DEVICE_OBJECT_ATTRIBUTES,
442                            NDIS_DEVICE_OBJECT_ATTRIBUTES_REVISION_1,
443                            sizeof (NDIS_DEVICE_OBJECT_ATTRIBUTES));
444
445     deviceAttributes.DeviceName = &deviceName;
446     deviceAttributes.SymbolicName = &symbolicDeviceName;
447     deviceAttributes.MajorFunctions = dispatchTable;
448     deviceAttributes.ExtensionSize = sizeof (OVS_DEVICE_EXTENSION);
449
450     status = NdisRegisterDeviceEx(ovsExtDriverHandle,
451                                   &deviceAttributes,
452                                   &gOvsDeviceObject,
453                                   &gOvsDeviceHandle);
454     if (status != NDIS_STATUS_SUCCESS) {
455         POVS_DEVICE_EXTENSION ovsExt =
456             (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(gOvsDeviceObject);
457         ASSERT(gOvsDeviceObject != NULL);
458         ASSERT(gOvsDeviceHandle != NULL);
459
460         if (ovsExt) {
461             ovsExt->numberOpenInstance = 0;
462         }
463     } else {
464         OvsRegisterSystemProvider((PVOID)gOvsDeviceObject);
465     }
466
467     OVS_LOG_TRACE("DeviceObject: %p", gOvsDeviceObject);
468     return status;
469 }
470
471
472 VOID
473 OvsDeleteDeviceObject()
474 {
475     if (gOvsDeviceHandle) {
476 #ifdef DBG
477         POVS_DEVICE_EXTENSION ovsExt = (POVS_DEVICE_EXTENSION)
478                     NdisGetDeviceReservedExtension(gOvsDeviceObject);
479         if (ovsExt) {
480             ASSERT(ovsExt->numberOpenInstance == 0);
481         }
482 #endif
483
484         ASSERT(gOvsDeviceObject);
485         NdisDeregisterDeviceEx(gOvsDeviceHandle);
486         gOvsDeviceHandle = NULL;
487         gOvsDeviceObject = NULL;
488
489         OvsUnregisterSystemProvider();
490     }
491 }
492
493 POVS_OPEN_INSTANCE
494 OvsGetOpenInstance(PFILE_OBJECT fileObject,
495                    UINT32 dpNo)
496 {
497     POVS_OPEN_INSTANCE instance = (POVS_OPEN_INSTANCE)fileObject->FsContext;
498     ASSERT(instance);
499     ASSERT(instance->fileObject == fileObject);
500     if (gOvsSwitchContext->dpNo != dpNo) {
501         return NULL;
502     }
503     return instance;
504 }
505
506
507 POVS_OPEN_INSTANCE
508 OvsFindOpenInstance(PFILE_OBJECT fileObject)
509 {
510     UINT32 i, j;
511     for (i = 0, j = 0; i < OVS_MAX_OPEN_INSTANCES &&
512                        j < ovsNumberOfOpenInstances; i++) {
513         if (ovsOpenInstanceArray[i]) {
514             if (ovsOpenInstanceArray[i]->fileObject == fileObject) {
515                 return ovsOpenInstanceArray[i];
516             }
517             j++;
518         }
519     }
520     return NULL;
521 }
522
523 NTSTATUS
524 OvsAddOpenInstance(POVS_DEVICE_EXTENSION ovsExt,
525                    PFILE_OBJECT fileObject)
526 {
527     POVS_OPEN_INSTANCE instance =
528         (POVS_OPEN_INSTANCE)OvsAllocateMemoryWithTag(sizeof(OVS_OPEN_INSTANCE),
529                                                      OVS_DATAPATH_POOL_TAG);
530     UINT32 i;
531
532     if (instance == NULL) {
533         return STATUS_NO_MEMORY;
534     }
535     OvsAcquireCtrlLock();
536     ASSERT(OvsFindOpenInstance(fileObject) == NULL);
537
538     if (ovsNumberOfOpenInstances >= OVS_MAX_OPEN_INSTANCES) {
539         OvsReleaseCtrlLock();
540         OvsFreeMemoryWithTag(instance, OVS_DATAPATH_POOL_TAG);
541         return STATUS_INSUFFICIENT_RESOURCES;
542     }
543     RtlZeroMemory(instance, sizeof (OVS_OPEN_INSTANCE));
544
545     for (i = 0; i < OVS_MAX_OPEN_INSTANCES; i++) {
546         if (ovsOpenInstanceArray[i] == NULL) {
547             ovsOpenInstanceArray[i] = instance;
548             ovsNumberOfOpenInstances++;
549             instance->cookie = i;
550             break;
551         }
552     }
553     ASSERT(i < OVS_MAX_OPEN_INSTANCES);
554     instance->fileObject = fileObject;
555     ASSERT(fileObject->FsContext == NULL);
556     instance->pid = (UINT32)InterlockedIncrement((LONG volatile *)&ovsExt->pidCount);
557     if (instance->pid == 0) {
558         /* XXX: check for rollover. */
559     }
560     fileObject->FsContext = instance;
561     OvsReleaseCtrlLock();
562     return STATUS_SUCCESS;
563 }
564
565 static VOID
566 OvsCleanupOpenInstance(PFILE_OBJECT fileObject)
567 {
568     POVS_OPEN_INSTANCE instance = (POVS_OPEN_INSTANCE)fileObject->FsContext;
569     ASSERT(instance);
570     ASSERT(fileObject == instance->fileObject);
571     OvsCleanupEvent(instance);
572     OvsCleanupPacketQueue(instance);
573 }
574
575 VOID
576 OvsRemoveOpenInstance(PFILE_OBJECT fileObject)
577 {
578     POVS_OPEN_INSTANCE instance;
579     ASSERT(fileObject->FsContext);
580     instance = (POVS_OPEN_INSTANCE)fileObject->FsContext;
581     ASSERT(instance->cookie < OVS_MAX_OPEN_INSTANCES);
582
583     OvsAcquireCtrlLock();
584     fileObject->FsContext = NULL;
585     ASSERT(ovsOpenInstanceArray[instance->cookie] == instance);
586     ovsOpenInstanceArray[instance->cookie] = NULL;
587     ovsNumberOfOpenInstances--;
588     OvsReleaseCtrlLock();
589     ASSERT(instance->eventQueue == NULL);
590     ASSERT (instance->packetQueue == NULL);
591     FreeUserDumpState(instance);
592     OvsFreeMemoryWithTag(instance, OVS_DATAPATH_POOL_TAG);
593 }
594
595 NTSTATUS
596 OvsCompleteIrpRequest(PIRP irp,
597                       ULONG_PTR infoPtr,
598                       NTSTATUS status)
599 {
600     irp->IoStatus.Information = infoPtr;
601     irp->IoStatus.Status = status;
602     IoCompleteRequest(irp, IO_NO_INCREMENT);
603     return status;
604 }
605
606
607 NTSTATUS
608 OvsOpenCloseDevice(PDEVICE_OBJECT deviceObject,
609                    PIRP irp)
610 {
611     PIO_STACK_LOCATION irpSp;
612     NTSTATUS status = STATUS_SUCCESS;
613     PFILE_OBJECT fileObject;
614     POVS_DEVICE_EXTENSION ovsExt =
615         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
616
617     ASSERT(deviceObject == gOvsDeviceObject);
618     ASSERT(ovsExt != NULL);
619
620     irpSp = IoGetCurrentIrpStackLocation(irp);
621     fileObject = irpSp->FileObject;
622     OVS_LOG_TRACE("DeviceObject: %p, fileObject:%p, instance: %u",
623                   deviceObject, fileObject,
624                   ovsExt->numberOpenInstance);
625
626     switch (irpSp->MajorFunction) {
627     case IRP_MJ_CREATE:
628         status = OvsAddOpenInstance(ovsExt, fileObject);
629         if (STATUS_SUCCESS == status) {
630             InterlockedIncrement((LONG volatile *)&ovsExt->numberOpenInstance);
631         }
632         break;
633     case IRP_MJ_CLOSE:
634         ASSERT(ovsExt->numberOpenInstance > 0);
635         OvsRemoveOpenInstance(fileObject);
636         InterlockedDecrement((LONG volatile *)&ovsExt->numberOpenInstance);
637         break;
638     default:
639         ASSERT(0);
640     }
641     return OvsCompleteIrpRequest(irp, (ULONG_PTR)0, status);
642 }
643
644 _Use_decl_annotations_
645 NTSTATUS
646 OvsCleanupDevice(PDEVICE_OBJECT deviceObject,
647                  PIRP irp)
648 {
649
650     PIO_STACK_LOCATION irpSp;
651     PFILE_OBJECT fileObject;
652
653     NTSTATUS status = STATUS_SUCCESS;
654 #ifdef DBG
655     POVS_DEVICE_EXTENSION ovsExt =
656         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
657     if (ovsExt) {
658         ASSERT(ovsExt->numberOpenInstance > 0);
659     }
660 #else
661     UNREFERENCED_PARAMETER(deviceObject);
662 #endif
663     ASSERT(deviceObject == gOvsDeviceObject);
664     irpSp = IoGetCurrentIrpStackLocation(irp);
665     fileObject = irpSp->FileObject;
666
667     ASSERT(irpSp->MajorFunction == IRP_MJ_CLEANUP);
668
669     OvsCleanupOpenInstance(fileObject);
670
671     return OvsCompleteIrpRequest(irp, (ULONG_PTR)0, status);
672 }
673
674 /*
675  * --------------------------------------------------------------------------
676  * IOCTL function handler for the device.
677  * --------------------------------------------------------------------------
678  */
679 NTSTATUS
680 OvsDeviceControl(PDEVICE_OBJECT deviceObject,
681                  PIRP irp)
682 {
683     PIO_STACK_LOCATION irpSp;
684     NTSTATUS status = STATUS_SUCCESS;
685     PFILE_OBJECT fileObject;
686     PVOID inputBuffer = NULL;
687     PVOID outputBuffer = NULL;
688     UINT32 inputBufferLen, outputBufferLen;
689     UINT32 code, replyLen = 0;
690     POVS_OPEN_INSTANCE instance;
691     UINT32 devOp;
692     OVS_MESSAGE ovsMsgReadOp;
693     POVS_MESSAGE ovsMsg;
694     NETLINK_FAMILY *nlFamilyOps;
695     OVS_USER_PARAMS_CONTEXT usrParamsCtx;
696
697 #ifdef DBG
698     POVS_DEVICE_EXTENSION ovsExt =
699         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
700     ASSERT(deviceObject == gOvsDeviceObject);
701     ASSERT(ovsExt);
702     ASSERT(ovsExt->numberOpenInstance > 0);
703 #else
704     UNREFERENCED_PARAMETER(deviceObject);
705 #endif
706
707     irpSp = IoGetCurrentIrpStackLocation(irp);
708
709     ASSERT(irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL);
710     ASSERT(irpSp->FileObject != NULL);
711
712     fileObject = irpSp->FileObject;
713     instance = (POVS_OPEN_INSTANCE)fileObject->FsContext;
714     code = irpSp->Parameters.DeviceIoControl.IoControlCode;
715     inputBufferLen = irpSp->Parameters.DeviceIoControl.InputBufferLength;
716     outputBufferLen = irpSp->Parameters.DeviceIoControl.OutputBufferLength;
717     inputBuffer = irp->AssociatedIrp.SystemBuffer;
718
719     /* Check if the extension is enabled. */
720     if (NULL == gOvsSwitchContext) {
721         status = STATUS_NOT_FOUND;
722         goto exit;
723     }
724
725     if (!OvsAcquireSwitchContext()) {
726         status = STATUS_NOT_FOUND;
727         goto exit;
728     }
729
730     /*
731      * Validate the input/output buffer arguments depending on the type of the
732      * operation.
733      */
734     switch (code) {
735     case OVS_IOCTL_GET_PID:
736         /* Both input buffer and output buffer use the same location. */
737         outputBuffer = irp->AssociatedIrp.SystemBuffer;
738         if (outputBufferLen != 0) {
739             InitUserParamsCtx(irp, instance, 0, NULL,
740                               inputBuffer, inputBufferLen,
741                               outputBuffer, outputBufferLen,
742                               &usrParamsCtx);
743
744             ASSERT(outputBuffer);
745         } else {
746             status = STATUS_NDIS_INVALID_LENGTH;
747             goto done;
748         }
749
750         status = OvsGetPidHandler(&usrParamsCtx, &replyLen);
751         goto done;
752
753     case OVS_IOCTL_TRANSACT:
754         /* Both input buffer and output buffer are mandatory. */
755         if (outputBufferLen != 0) {
756             status = MapIrpOutputBuffer(irp, outputBufferLen,
757                                         sizeof *ovsMsg, &outputBuffer);
758             if (status != STATUS_SUCCESS) {
759                 goto done;
760             }
761             ASSERT(outputBuffer);
762         } else {
763             status = STATUS_NDIS_INVALID_LENGTH;
764             goto done;
765         }
766
767         if (inputBufferLen < sizeof (*ovsMsg)) {
768             status = STATUS_NDIS_INVALID_LENGTH;
769             goto done;
770         }
771
772         ovsMsg = inputBuffer;
773         devOp = OVS_TRANSACTION_DEV_OP;
774         break;
775
776     case OVS_IOCTL_READ_EVENT:
777     case OVS_IOCTL_READ_PACKET:
778         /*
779          * Output buffer is mandatory. These IOCTLs are used to read events and
780          * packets respectively. It is convenient to have separate ioctls.
781          */
782         if (outputBufferLen != 0) {
783             status = MapIrpOutputBuffer(irp, outputBufferLen,
784                                         sizeof *ovsMsg, &outputBuffer);
785             if (status != STATUS_SUCCESS) {
786                 goto done;
787             }
788             ASSERT(outputBuffer);
789         } else {
790             status = STATUS_NDIS_INVALID_LENGTH;
791             goto done;
792         }
793         inputBuffer = NULL;
794         inputBufferLen = 0;
795
796         ovsMsg = &ovsMsgReadOp;
797         RtlZeroMemory(ovsMsg, sizeof *ovsMsg);
798         ovsMsg->nlMsg.nlmsgLen = sizeof *ovsMsg;
799         ovsMsg->nlMsg.nlmsgType = nlControlFamilyOps.id;
800         ovsMsg->nlMsg.nlmsgPid = instance->pid;
801
802         /* An "artificial" command so we can use NL family function table*/
803         ovsMsg->genlMsg.cmd = (code == OVS_IOCTL_READ_EVENT) ?
804                               OVS_CTRL_CMD_EVENT_NOTIFY :
805                               OVS_CTRL_CMD_READ_NOTIFY;
806         ovsMsg->genlMsg.version = nlControlFamilyOps.version;
807
808         devOp = OVS_READ_DEV_OP;
809         break;
810
811     case OVS_IOCTL_READ:
812         /* Output buffer is mandatory. */
813         if (outputBufferLen != 0) {
814             status = MapIrpOutputBuffer(irp, outputBufferLen,
815                                         sizeof *ovsMsg, &outputBuffer);
816             if (status != STATUS_SUCCESS) {
817                 goto done;
818             }
819             ASSERT(outputBuffer);
820         } else {
821             status = STATUS_NDIS_INVALID_LENGTH;
822             goto done;
823         }
824
825         /*
826          * Operate in the mode that read ioctl is similar to ReadFile(). This
827          * might change as the userspace code gets implemented.
828          */
829         inputBuffer = NULL;
830         inputBufferLen = 0;
831
832         /*
833          * For implementing read (ioctl or otherwise), we need to store some
834          * state in the instance to indicate the command that started the dump
835          * operation. The state can setup 'ovsMsgReadOp' appropriately. Note
836          * that 'ovsMsgReadOp' is needed only in this function to call into the
837          * appropriate handler. The handler itself can access the state in the
838          * instance.
839          *
840          * In the absence of a dump start, return 0 bytes.
841          */
842         if (instance->dumpState.ovsMsg == NULL) {
843             replyLen = 0;
844             status = STATUS_SUCCESS;
845             goto done;
846         }
847         RtlCopyMemory(&ovsMsgReadOp, instance->dumpState.ovsMsg,
848                       sizeof (ovsMsgReadOp));
849
850         /* Create an NL message for consumption. */
851         ovsMsg = &ovsMsgReadOp;
852         devOp = OVS_READ_DEV_OP;
853
854         break;
855
856     case OVS_IOCTL_WRITE:
857         /* Input buffer is mandatory. */
858         if (inputBufferLen < sizeof (*ovsMsg)) {
859             status = STATUS_NDIS_INVALID_LENGTH;
860             goto done;
861         }
862
863         ovsMsg = inputBuffer;
864         devOp = OVS_WRITE_DEV_OP;
865         break;
866
867     default:
868         status = STATUS_INVALID_DEVICE_REQUEST;
869         goto done;
870     }
871
872     ASSERT(ovsMsg);
873     switch (ovsMsg->nlMsg.nlmsgType) {
874     case OVS_WIN_NL_CTRL_FAMILY_ID:
875         nlFamilyOps = &nlControlFamilyOps;
876         break;
877     case OVS_WIN_NL_DATAPATH_FAMILY_ID:
878         nlFamilyOps = &nlDatapathFamilyOps;
879         break;
880     case OVS_WIN_NL_FLOW_FAMILY_ID:
881          nlFamilyOps = &nlFLowFamilyOps;
882          break;
883     case OVS_WIN_NL_PACKET_FAMILY_ID:
884          nlFamilyOps = &nlPacketFamilyOps;
885          break;
886     case OVS_WIN_NL_VPORT_FAMILY_ID:
887         nlFamilyOps = &nlVportFamilyOps;
888         break;
889     case OVS_WIN_NL_NETDEV_FAMILY_ID:
890         nlFamilyOps = &nlNetdevFamilyOps;
891         break;
892     default:
893         status = STATUS_INVALID_PARAMETER;
894         goto done;
895     }
896
897     /*
898      * For read operation, avoid duplicate validation since 'ovsMsg' is either
899      * "artificial" or was copied from a previously validated 'ovsMsg'.
900      */
901     if (devOp != OVS_READ_DEV_OP) {
902         status = ValidateNetlinkCmd(devOp, instance, ovsMsg, nlFamilyOps);
903         if (status != STATUS_SUCCESS) {
904             goto done;
905         }
906     }
907
908     InitUserParamsCtx(irp, instance, devOp, ovsMsg,
909                       inputBuffer, inputBufferLen,
910                       outputBuffer, outputBufferLen,
911                       &usrParamsCtx);
912
913     status = InvokeNetlinkCmdHandler(&usrParamsCtx, nlFamilyOps, &replyLen);
914
915 done:
916     OvsReleaseSwitchContext(gOvsSwitchContext);
917
918 exit:
919     /* Should not complete a pending IRP unless proceesing is completed. */
920     if (status == STATUS_PENDING) {
921         return status;
922     }
923     return OvsCompleteIrpRequest(irp, (ULONG_PTR)replyLen, status);
924 }
925
926
927 /*
928  * --------------------------------------------------------------------------
929  * Function to validate a netlink command. Only certain combinations of
930  * (device operation, netlink family, command) are valid.
931  * --------------------------------------------------------------------------
932  */
933 static NTSTATUS
934 ValidateNetlinkCmd(UINT32 devOp,
935                    POVS_OPEN_INSTANCE instance,
936                    POVS_MESSAGE ovsMsg,
937                    NETLINK_FAMILY *nlFamilyOps)
938 {
939     NTSTATUS status = STATUS_INVALID_PARAMETER;
940     UINT16 i;
941
942     for (i = 0; i < nlFamilyOps->opsCount; i++) {
943         if (nlFamilyOps->cmds[i].cmd == ovsMsg->genlMsg.cmd) {
944             /* Validate if the command is valid for the device operation. */
945             if ((devOp & nlFamilyOps->cmds[i].supportedDevOp) == 0) {
946                 status = STATUS_INVALID_PARAMETER;
947                 goto done;
948             }
949
950             /* Validate the version. */
951             if (nlFamilyOps->version > ovsMsg->genlMsg.version) {
952                 status = STATUS_INVALID_PARAMETER;
953                 goto done;
954             }
955
956             /* Validate the DP for commands that require a DP. */
957             if (nlFamilyOps->cmds[i].validateDpIndex == TRUE) {
958                 if (ovsMsg->ovsHdr.dp_ifindex !=
959                                           (INT)gOvsSwitchContext->dpNo) {
960                     status = STATUS_INVALID_PARAMETER;
961                     goto done;
962                 }
963             }
964
965             /* Validate the PID. */
966             if (ovsMsg->nlMsg.nlmsgPid != instance->pid) {
967                 status = STATUS_INVALID_PARAMETER;
968                 goto done;
969             }
970
971             status = STATUS_SUCCESS;
972             break;
973         }
974     }
975
976 done:
977     return status;
978 }
979
980 /*
981  * --------------------------------------------------------------------------
982  * Function to invoke the netlink command handler. The function also stores
983  * the return value of the handler function to construct a 'NL_ERROR' message,
984  * and in turn returns success to the caller.
985  * --------------------------------------------------------------------------
986  */
987 static NTSTATUS
988 InvokeNetlinkCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
989                         NETLINK_FAMILY *nlFamilyOps,
990                         UINT32 *replyLen)
991 {
992     NTSTATUS status = STATUS_INVALID_PARAMETER;
993     UINT16 i;
994
995     for (i = 0; i < nlFamilyOps->opsCount; i++) {
996         if (nlFamilyOps->cmds[i].cmd == usrParamsCtx->ovsMsg->genlMsg.cmd) {
997             NetlinkCmdHandler *handler = nlFamilyOps->cmds[i].handler;
998             ASSERT(handler);
999             if (handler) {
1000                 status = handler(usrParamsCtx, replyLen);
1001             }
1002             break;
1003         }
1004     }
1005
1006     /*
1007      * Netlink socket semantics dictate that the return value of the netlink
1008      * function should be an error ONLY under fatal conditions. If the message
1009      * made it all the way to the handler function, it is not a fatal condition.
1010      * Absorb the error returned by the handler function into a 'struct
1011      * NL_ERROR' and populate the 'output buffer' to return to userspace.
1012      *
1013      * This behavior is obviously applicable only to netlink commands that
1014      * specify an 'output buffer'. For other commands, we return the error as
1015      * is.
1016      *
1017      * 'STATUS_PENDING' is a special return value and userspace is equipped to
1018      * handle it.
1019      */
1020     if (status != STATUS_SUCCESS && status != STATUS_PENDING) {
1021         if (usrParamsCtx->devOp != OVS_WRITE_DEV_OP && *replyLen == 0) {
1022             NL_ERROR nlError = NlMapStatusToNlErr(status);
1023             POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1024             POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR)
1025                 usrParamsCtx->outputBuffer;
1026
1027             ASSERT(msgError);
1028             NlBuildErrorMsg(msgIn, msgError, nlError);
1029             *replyLen = msgError->nlMsg.nlmsgLen;
1030         }
1031
1032         if (*replyLen != 0) {
1033             status = STATUS_SUCCESS;
1034         }
1035     }
1036
1037 #ifdef DBG
1038     if (usrParamsCtx->devOp != OVS_WRITE_DEV_OP) {
1039         ASSERT(status == STATUS_PENDING || *replyLen != 0 || status == STATUS_SUCCESS);
1040     }
1041 #endif
1042
1043     return status;
1044 }
1045
1046 /*
1047  * --------------------------------------------------------------------------
1048  *  Handler for 'OVS_IOCTL_GET_PID'.
1049  *
1050  *  Each handle on the device is assigned a unique PID when the handle is
1051  *  created. This function passes the PID to userspace using METHOD_BUFFERED
1052  *  method.
1053  * --------------------------------------------------------------------------
1054  */
1055 static NTSTATUS
1056 OvsGetPidHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1057                  UINT32 *replyLen)
1058 {
1059     NTSTATUS status = STATUS_SUCCESS;
1060     PUINT32 msgOut = (PUINT32)usrParamsCtx->outputBuffer;
1061
1062     if (usrParamsCtx->outputLength >= sizeof *msgOut) {
1063         POVS_OPEN_INSTANCE instance =
1064             (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1065
1066         RtlZeroMemory(msgOut, sizeof *msgOut);
1067         RtlCopyMemory(msgOut, &instance->pid, sizeof(*msgOut));
1068         *replyLen = sizeof *msgOut;
1069     } else {
1070         *replyLen = sizeof *msgOut;
1071         status = STATUS_NDIS_INVALID_LENGTH;
1072     }
1073
1074     return status;
1075 }
1076
1077 /*
1078  * --------------------------------------------------------------------------
1079  * Utility function to fill up information about the datapath in a reply to
1080  * userspace.
1081  * --------------------------------------------------------------------------
1082  */
1083 static NTSTATUS
1084 OvsDpFillInfo(POVS_SWITCH_CONTEXT ovsSwitchContext,
1085               POVS_MESSAGE msgIn,
1086               PNL_BUFFER nlBuf)
1087 {
1088     BOOLEAN writeOk;
1089     OVS_MESSAGE msgOutTmp;
1090     OVS_DATAPATH *datapath = &ovsSwitchContext->datapath;
1091     PNL_MSG_HDR nlMsg;
1092
1093     ASSERT(NlBufAt(nlBuf, 0, 0) != 0 && NlBufRemLen(nlBuf) >= sizeof *msgIn);
1094
1095     msgOutTmp.nlMsg.nlmsgType = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1096     msgOutTmp.nlMsg.nlmsgFlags = 0;  /* XXX: ? */
1097     msgOutTmp.nlMsg.nlmsgSeq = msgIn->nlMsg.nlmsgSeq;
1098     msgOutTmp.nlMsg.nlmsgPid = msgIn->nlMsg.nlmsgPid;
1099
1100     msgOutTmp.genlMsg.cmd = OVS_DP_CMD_GET;
1101     msgOutTmp.genlMsg.version = nlDatapathFamilyOps.version;
1102     msgOutTmp.genlMsg.reserved = 0;
1103
1104     msgOutTmp.ovsHdr.dp_ifindex = ovsSwitchContext->dpNo;
1105
1106     writeOk = NlMsgPutHead(nlBuf, (PCHAR)&msgOutTmp, sizeof msgOutTmp);
1107     if (writeOk) {
1108         writeOk = NlMsgPutTailString(nlBuf, OVS_DP_ATTR_NAME,
1109                                      OVS_SYSTEM_DP_NAME);
1110     }
1111     if (writeOk) {
1112         OVS_DP_STATS dpStats;
1113
1114         dpStats.n_hit = datapath->hits;
1115         dpStats.n_missed = datapath->misses;
1116         dpStats.n_lost = datapath->lost;
1117         dpStats.n_flows = datapath->nFlows;
1118         writeOk = NlMsgPutTailUnspec(nlBuf, OVS_DP_ATTR_STATS,
1119                                      (PCHAR)&dpStats, sizeof dpStats);
1120     }
1121     nlMsg = (PNL_MSG_HDR)NlBufAt(nlBuf, 0, 0);
1122     nlMsg->nlmsgLen = NlBufSize(nlBuf);
1123
1124     return writeOk ? STATUS_SUCCESS : STATUS_INVALID_BUFFER_SIZE;
1125 }
1126
1127 /*
1128  * --------------------------------------------------------------------------
1129  * Handler for queueing an IRP used for event notification. The IRP is
1130  * completed when a port state changes. STATUS_PENDING is returned on
1131  * success. User mode keep a pending IRP at all times.
1132  * --------------------------------------------------------------------------
1133  */
1134 static NTSTATUS
1135 OvsPendEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1136                        UINT32 *replyLen)
1137 {
1138     NDIS_STATUS status;
1139
1140     UNREFERENCED_PARAMETER(replyLen);
1141
1142     POVS_OPEN_INSTANCE instance =
1143         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1144     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1145     OVS_EVENT_POLL poll;
1146
1147     poll.dpNo = msgIn->ovsHdr.dp_ifindex;
1148     status = OvsWaitEventIoctl(usrParamsCtx->irp, instance->fileObject,
1149                                &poll, sizeof poll);
1150     return status;
1151 }
1152
1153 /*
1154  * --------------------------------------------------------------------------
1155  *  Handler for the subscription for the event queue
1156  * --------------------------------------------------------------------------
1157  */
1158 static NTSTATUS
1159 OvsSubscribeEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1160                             UINT32 *replyLen)
1161 {
1162     NDIS_STATUS status;
1163     OVS_EVENT_SUBSCRIBE request;
1164     BOOLEAN rc;
1165     UINT8 join;
1166     PNL_ATTR attrs[2];
1167     const NL_POLICY policy[] =  {
1168         [OVS_NL_ATTR_MCAST_GRP] = {.type = NL_A_U32 },
1169         [OVS_NL_ATTR_MCAST_JOIN] = {.type = NL_A_U8 },
1170         };
1171
1172     UNREFERENCED_PARAMETER(replyLen);
1173
1174     POVS_OPEN_INSTANCE instance =
1175         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1176     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1177
1178     rc = NlAttrParse(&msgIn->nlMsg, sizeof (*msgIn),
1179          NlMsgAttrsLen((PNL_MSG_HDR)msgIn), policy, ARRAY_SIZE(policy),
1180                        attrs, ARRAY_SIZE(attrs));
1181     if (!rc) {
1182         status = STATUS_INVALID_PARAMETER;
1183         goto done;
1184     }
1185
1186     /* XXX Ignore the MC group for now */
1187     join = NlAttrGetU8(attrs[OVS_NL_ATTR_MCAST_JOIN]);
1188     request.dpNo = msgIn->ovsHdr.dp_ifindex;
1189     request.subscribe = join;
1190     request.mask = OVS_EVENT_MASK_ALL;
1191
1192     status = OvsSubscribeEventIoctl(instance->fileObject, &request,
1193                                     sizeof request);
1194 done:
1195     return status;
1196 }
1197
1198 /*
1199  * --------------------------------------------------------------------------
1200  *  Command Handler for 'OVS_DP_CMD_NEW'.
1201  * --------------------------------------------------------------------------
1202  */
1203 static NTSTATUS
1204 OvsNewDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1205                    UINT32 *replyLen)
1206 {
1207     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1208 }
1209
1210 /*
1211  * --------------------------------------------------------------------------
1212  *  Command Handler for 'OVS_DP_CMD_GET'.
1213  *
1214  *  The function handles both the dump based as well as the transaction based
1215  *  'OVS_DP_CMD_GET' command. In the dump command, it handles the initial
1216  *  call to setup dump state, as well as subsequent calls to continue dumping
1217  *  data.
1218  * --------------------------------------------------------------------------
1219  */
1220 static NTSTATUS
1221 OvsGetDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1222                    UINT32 *replyLen)
1223 {
1224     if (usrParamsCtx->devOp == OVS_TRANSACTION_DEV_OP) {
1225         return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1226     } else {
1227         return HandleGetDpDump(usrParamsCtx, replyLen);
1228     }
1229 }
1230
1231 /*
1232  * --------------------------------------------------------------------------
1233  *  Function for handling the transaction based 'OVS_DP_CMD_GET' command.
1234  * --------------------------------------------------------------------------
1235  */
1236 static NTSTATUS
1237 HandleGetDpTransaction(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1238                        UINT32 *replyLen)
1239 {
1240     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1241 }
1242
1243
1244 /*
1245  * --------------------------------------------------------------------------
1246  *  Function for handling the dump-based 'OVS_DP_CMD_GET' command.
1247  * --------------------------------------------------------------------------
1248  */
1249 static NTSTATUS
1250 HandleGetDpDump(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1251                 UINT32 *replyLen)
1252 {
1253     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1254     POVS_OPEN_INSTANCE instance =
1255         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1256
1257     if (usrParamsCtx->devOp == OVS_WRITE_DEV_OP) {
1258         *replyLen = 0;
1259         OvsSetupDumpStart(usrParamsCtx);
1260     } else {
1261         NL_BUFFER nlBuf;
1262         NTSTATUS status;
1263         POVS_MESSAGE msgIn = instance->dumpState.ovsMsg;
1264
1265         ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP);
1266
1267         if (instance->dumpState.ovsMsg == NULL) {
1268             ASSERT(FALSE);
1269             return STATUS_INVALID_DEVICE_STATE;
1270         }
1271
1272         /* Dump state must have been deleted after previous dump operation. */
1273         ASSERT(instance->dumpState.index[0] == 0);
1274
1275         /* Output buffer has been validated while validating read dev op. */
1276         ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1277
1278         NlBufInit(&nlBuf, usrParamsCtx->outputBuffer,
1279                   usrParamsCtx->outputLength);
1280
1281         status = OvsDpFillInfo(gOvsSwitchContext, msgIn, &nlBuf);
1282
1283         if (status != STATUS_SUCCESS) {
1284             *replyLen = 0;
1285             FreeUserDumpState(instance);
1286             return status;
1287         }
1288
1289         /* Increment the dump index. */
1290         instance->dumpState.index[0] = 1;
1291         *replyLen = msgOut->nlMsg.nlmsgLen;
1292
1293         /* Free up the dump state, since there's no more data to continue. */
1294         FreeUserDumpState(instance);
1295     }
1296
1297     return STATUS_SUCCESS;
1298 }
1299
1300
1301 /*
1302  * --------------------------------------------------------------------------
1303  *  Command Handler for 'OVS_DP_CMD_SET'.
1304  * --------------------------------------------------------------------------
1305  */
1306 static NTSTATUS
1307 OvsSetDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1308                    UINT32 *replyLen)
1309 {
1310     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1311 }
1312
1313 /*
1314  * --------------------------------------------------------------------------
1315  *  Function for handling transaction based 'OVS_DP_CMD_NEW', 'OVS_DP_CMD_GET'
1316  *  and 'OVS_DP_CMD_SET' commands.
1317  *
1318  * 'OVS_DP_CMD_NEW' is implemented to keep userspace code happy. Creation of a
1319  * new datapath is not supported currently.
1320  * --------------------------------------------------------------------------
1321  */
1322 static NTSTATUS
1323 HandleDpTransactionCommon(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1324                           UINT32 *replyLen)
1325 {
1326     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1327     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1328     NTSTATUS status = STATUS_SUCCESS;
1329     NL_BUFFER nlBuf;
1330     NL_ERROR nlError = NL_ERROR_SUCCESS;
1331     static const NL_POLICY ovsDatapathSetPolicy[] = {
1332         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .maxLen = IFNAMSIZ },
1333         [OVS_DP_ATTR_UPCALL_PID] = { .type = NL_A_U32, .optional = TRUE },
1334         [OVS_DP_ATTR_USER_FEATURES] = { .type = NL_A_U32, .optional = TRUE },
1335     };
1336     PNL_ATTR dpAttrs[ARRAY_SIZE(ovsDatapathSetPolicy)];
1337
1338     UNREFERENCED_PARAMETER(msgOut);
1339
1340     /* input buffer has been validated while validating write dev op. */
1341     ASSERT(msgIn != NULL && usrParamsCtx->inputLength >= sizeof *msgIn);
1342
1343     /* Parse any attributes in the request. */
1344     if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_SET ||
1345         usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_NEW) {
1346         if (!NlAttrParse((PNL_MSG_HDR)msgIn,
1347                         NLMSG_HDRLEN + GENL_HDRLEN + OVS_HDRLEN,
1348                         NlMsgAttrsLen((PNL_MSG_HDR)msgIn),
1349                         ovsDatapathSetPolicy,
1350                         ARRAY_SIZE(ovsDatapathSetPolicy),
1351                         dpAttrs, ARRAY_SIZE(dpAttrs))) {
1352             return STATUS_INVALID_PARAMETER;
1353         }
1354
1355         /*
1356         * XXX: Not clear at this stage if there's any role for the
1357         * OVS_DP_ATTR_UPCALL_PID and OVS_DP_ATTR_USER_FEATURES attributes passed
1358         * from userspace.
1359         */
1360
1361     } else {
1362         RtlZeroMemory(dpAttrs, sizeof dpAttrs);
1363     }
1364
1365     /* Output buffer has been validated while validating transact dev op. */
1366     ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1367
1368     NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength);
1369
1370     if (dpAttrs[OVS_DP_ATTR_NAME] != NULL) {
1371         if (!OvsCompareString(NlAttrGet(dpAttrs[OVS_DP_ATTR_NAME]),
1372                               OVS_SYSTEM_DP_NAME)) {
1373
1374             /* Creation of new datapaths is not supported. */
1375             if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_SET) {
1376                 nlError = NL_ERROR_NOTSUPP;
1377                 goto cleanup;
1378             }
1379
1380             nlError = NL_ERROR_NODEV;
1381             goto cleanup;
1382         }
1383     } else if ((UINT32)msgIn->ovsHdr.dp_ifindex != gOvsSwitchContext->dpNo) {
1384         nlError = NL_ERROR_NODEV;
1385         goto cleanup;
1386     }
1387
1388     if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_NEW) {
1389         nlError = NL_ERROR_EXIST;
1390         goto cleanup;
1391     }
1392
1393     status = OvsDpFillInfo(gOvsSwitchContext, msgIn, &nlBuf);
1394
1395     *replyLen = NlBufSize(&nlBuf);
1396
1397 cleanup:
1398     if (nlError != NL_ERROR_SUCCESS) {
1399         POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR)
1400             usrParamsCtx->outputBuffer;
1401
1402         NlBuildErrorMsg(msgIn, msgError, nlError);
1403         *replyLen = msgError->nlMsg.nlmsgLen;
1404     }
1405
1406     return STATUS_SUCCESS;
1407 }
1408
1409
1410 NTSTATUS
1411 OvsSetupDumpStart(POVS_USER_PARAMS_CONTEXT usrParamsCtx)
1412 {
1413     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1414     POVS_OPEN_INSTANCE instance =
1415         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1416
1417     /* input buffer has been validated while validating write dev op. */
1418     ASSERT(msgIn != NULL && usrParamsCtx->inputLength >= sizeof *msgIn);
1419
1420     /* A write operation that does not indicate dump start is invalid. */
1421     if ((msgIn->nlMsg.nlmsgFlags & NLM_F_DUMP) != NLM_F_DUMP) {
1422         return STATUS_INVALID_PARAMETER;
1423     }
1424     /* XXX: Handle other NLM_F_* flags in the future. */
1425
1426     /*
1427      * This operation should be setting up the dump state. If there's any
1428      * previous state, clear it up so as to set it up afresh.
1429      */
1430     FreeUserDumpState(instance);
1431
1432     return InitUserDumpState(instance, msgIn);
1433 }
1434
1435
1436 /*
1437  * --------------------------------------------------------------------------
1438  *  Utility function to map the output buffer in an IRP. The buffer is assumed
1439  *  to have been passed down using METHOD_OUT_DIRECT (Direct I/O).
1440  * --------------------------------------------------------------------------
1441  */
1442 static NTSTATUS
1443 MapIrpOutputBuffer(PIRP irp,
1444                    UINT32 bufferLength,
1445                    UINT32 requiredLength,
1446                    PVOID *buffer)
1447 {
1448     ASSERT(irp);
1449     ASSERT(buffer);
1450     ASSERT(bufferLength);
1451     ASSERT(requiredLength);
1452     if (!buffer || !irp || bufferLength == 0 || requiredLength == 0) {
1453         return STATUS_INVALID_PARAMETER;
1454     }
1455
1456     if (bufferLength < requiredLength) {
1457         return STATUS_NDIS_INVALID_LENGTH;
1458     }
1459     if (irp->MdlAddress == NULL) {
1460         return STATUS_INVALID_PARAMETER;
1461     }
1462     *buffer = MmGetSystemAddressForMdlSafe(irp->MdlAddress,
1463                                            NormalPagePriority);
1464     if (*buffer == NULL) {
1465         return STATUS_INSUFFICIENT_RESOURCES;
1466     }
1467
1468     return STATUS_SUCCESS;
1469 }
1470
1471 /*
1472  * --------------------------------------------------------------------------
1473  * Utility function to fill up information about the state of a port in a reply
1474  * to* userspace.
1475  * --------------------------------------------------------------------------
1476  */
1477 static NTSTATUS
1478 OvsPortFillInfo(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1479                 POVS_EVENT_ENTRY eventEntry,
1480                 PNL_BUFFER nlBuf)
1481 {
1482     NTSTATUS status;
1483     BOOLEAN ok;
1484     OVS_MESSAGE msgOutTmp;
1485     PNL_MSG_HDR nlMsg;
1486     POVS_VPORT_ENTRY vport;
1487
1488     ASSERT(NlBufAt(nlBuf, 0, 0) != 0 && nlBuf->bufRemLen >= sizeof msgOutTmp);
1489
1490     msgOutTmp.nlMsg.nlmsgType = OVS_WIN_NL_VPORT_FAMILY_ID;
1491     msgOutTmp.nlMsg.nlmsgFlags = 0;  /* XXX: ? */
1492
1493     /* driver intiated messages should have zerp seq number*/
1494     msgOutTmp.nlMsg.nlmsgSeq = 0;
1495     msgOutTmp.nlMsg.nlmsgPid = usrParamsCtx->ovsInstance->pid;
1496
1497     msgOutTmp.genlMsg.version = nlVportFamilyOps.version;
1498     msgOutTmp.genlMsg.reserved = 0;
1499
1500     /* we don't have netdev yet, treat link up/down a adding/removing a port*/
1501     if (eventEntry->status & (OVS_EVENT_LINK_UP | OVS_EVENT_CONNECT)) {
1502         msgOutTmp.genlMsg.cmd = OVS_VPORT_CMD_NEW;
1503     } else if (eventEntry->status &
1504              (OVS_EVENT_LINK_DOWN | OVS_EVENT_DISCONNECT)) {
1505         msgOutTmp.genlMsg.cmd = OVS_VPORT_CMD_DEL;
1506     } else {
1507         ASSERT(FALSE);
1508         return STATUS_UNSUCCESSFUL;
1509     }
1510     msgOutTmp.ovsHdr.dp_ifindex = gOvsSwitchContext->dpNo;
1511
1512     ok = NlMsgPutHead(nlBuf, (PCHAR)&msgOutTmp, sizeof msgOutTmp);
1513     if (!ok) {
1514         status = STATUS_INVALID_BUFFER_SIZE;
1515         goto cleanup;
1516     }
1517
1518     vport = OvsFindVportByPortNo(gOvsSwitchContext, eventEntry->portNo);
1519     if (!vport) {
1520         status = STATUS_DEVICE_DOES_NOT_EXIST;
1521         goto cleanup;
1522     }
1523
1524     ok = NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_PORT_NO, eventEntry->portNo) &&
1525          NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_TYPE, vport->ovsType) &&
1526          NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_UPCALL_PID,
1527                          vport->upcallPid) &&
1528          NlMsgPutTailString(nlBuf, OVS_VPORT_ATTR_NAME, vport->ovsName);
1529     if (!ok) {
1530         status = STATUS_INVALID_BUFFER_SIZE;
1531         goto cleanup;
1532     }
1533
1534     /* XXXX Should we add the port stats attributes?*/
1535     nlMsg = (PNL_MSG_HDR)NlBufAt(nlBuf, 0, 0);
1536     nlMsg->nlmsgLen = NlBufSize(nlBuf);
1537     status = STATUS_SUCCESS;
1538
1539 cleanup:
1540     return status;
1541 }
1542
1543
1544 /*
1545  * --------------------------------------------------------------------------
1546  * Handler for reading events from the driver event queue. This handler is
1547  * executed when user modes issues a socket receive on a socket assocaited
1548  * with the MC group for events.
1549  * XXX user mode should read multiple events in one system call
1550  * --------------------------------------------------------------------------
1551  */
1552 static NTSTATUS
1553 OvsReadEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1554                        UINT32 *replyLen)
1555 {
1556 #ifdef DBG
1557     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1558     POVS_OPEN_INSTANCE instance =
1559         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1560 #endif
1561     NL_BUFFER nlBuf;
1562     NTSTATUS status;
1563     OVS_EVENT_ENTRY eventEntry;
1564
1565     ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP);
1566
1567     /* Should never read events with a dump socket */
1568     ASSERT(instance->dumpState.ovsMsg == NULL);
1569
1570     /* Must have an event queue */
1571     ASSERT(instance->eventQueue != NULL);
1572
1573     /* Output buffer has been validated while validating read dev op. */
1574     ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1575
1576     NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength);
1577
1578     /* remove an event entry from the event queue */
1579     status = OvsRemoveEventEntry(usrParamsCtx->ovsInstance, &eventEntry);
1580     if (status != STATUS_SUCCESS) {
1581         /* If there were not elements, read should return no data. */
1582         status = STATUS_SUCCESS;
1583         *replyLen = 0;
1584         goto cleanup;
1585     }
1586
1587     status = OvsPortFillInfo(usrParamsCtx, &eventEntry, &nlBuf);
1588     if (status == NDIS_STATUS_SUCCESS) {
1589         *replyLen = NlBufSize(&nlBuf);
1590     }
1591
1592 cleanup:
1593     return status;
1594 }
1595