ovn-controller: Drop unknown datapath log message.
[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                          OvsPendPacketCmdHandler,
93                          OvsSubscribeEventCmdHandler,
94                          OvsSubscribePacketCmdHandler,
95                          OvsReadEventCmdHandler,
96                          OvsReadPacketCmdHandler,
97                          OvsNewDpCmdHandler,
98                          OvsGetDpCmdHandler,
99                          OvsSetDpCmdHandler;
100
101 NetlinkCmdHandler        OvsGetNetdevCmdHandler,
102                          OvsGetVportCmdHandler,
103                          OvsSetVportCmdHandler,
104                          OvsNewVportCmdHandler,
105                          OvsDeleteVportCmdHandler;
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     OvsFreeMemoryWithTag(instance, OVS_DATAPATH_POOL_TAG);
592 }
593
594 NTSTATUS
595 OvsCompleteIrpRequest(PIRP irp,
596                       ULONG_PTR infoPtr,
597                       NTSTATUS status)
598 {
599     irp->IoStatus.Information = infoPtr;
600     irp->IoStatus.Status = status;
601     IoCompleteRequest(irp, IO_NO_INCREMENT);
602     return status;
603 }
604
605
606 NTSTATUS
607 OvsOpenCloseDevice(PDEVICE_OBJECT deviceObject,
608                    PIRP irp)
609 {
610     PIO_STACK_LOCATION irpSp;
611     NTSTATUS status = STATUS_SUCCESS;
612     PFILE_OBJECT fileObject;
613     POVS_DEVICE_EXTENSION ovsExt =
614         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
615
616     ASSERT(deviceObject == gOvsDeviceObject);
617     ASSERT(ovsExt != NULL);
618
619     irpSp = IoGetCurrentIrpStackLocation(irp);
620     fileObject = irpSp->FileObject;
621     OVS_LOG_TRACE("DeviceObject: %p, fileObject:%p, instance: %u",
622                   deviceObject, fileObject,
623                   ovsExt->numberOpenInstance);
624
625     switch (irpSp->MajorFunction) {
626     case IRP_MJ_CREATE:
627         status = OvsAddOpenInstance(ovsExt, fileObject);
628         if (STATUS_SUCCESS == status) {
629             InterlockedIncrement((LONG volatile *)&ovsExt->numberOpenInstance);
630         }
631         break;
632     case IRP_MJ_CLOSE:
633         ASSERT(ovsExt->numberOpenInstance > 0);
634         OvsRemoveOpenInstance(fileObject);
635         InterlockedDecrement((LONG volatile *)&ovsExt->numberOpenInstance);
636         break;
637     default:
638         ASSERT(0);
639     }
640     return OvsCompleteIrpRequest(irp, (ULONG_PTR)0, status);
641 }
642
643 _Use_decl_annotations_
644 NTSTATUS
645 OvsCleanupDevice(PDEVICE_OBJECT deviceObject,
646                  PIRP irp)
647 {
648
649     PIO_STACK_LOCATION irpSp;
650     PFILE_OBJECT fileObject;
651
652     NTSTATUS status = STATUS_SUCCESS;
653 #ifdef DBG
654     POVS_DEVICE_EXTENSION ovsExt =
655         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
656     if (ovsExt) {
657         ASSERT(ovsExt->numberOpenInstance > 0);
658     }
659 #else
660     UNREFERENCED_PARAMETER(deviceObject);
661 #endif
662     ASSERT(deviceObject == gOvsDeviceObject);
663     irpSp = IoGetCurrentIrpStackLocation(irp);
664     fileObject = irpSp->FileObject;
665
666     ASSERT(irpSp->MajorFunction == IRP_MJ_CLEANUP);
667
668     OvsCleanupOpenInstance(fileObject);
669
670     return OvsCompleteIrpRequest(irp, (ULONG_PTR)0, status);
671 }
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     /* Concurrent netlink operations are not supported. */
731     if (InterlockedCompareExchange((LONG volatile *)&instance->inUse, 1, 0)) {
732         status = STATUS_RESOURCE_IN_USE;
733         goto done;
734     }
735
736     /*
737      * Validate the input/output buffer arguments depending on the type of the
738      * operation.
739      */
740     switch (code) {
741     case OVS_IOCTL_GET_PID:
742         /* Both input buffer and output buffer use the same location. */
743         outputBuffer = irp->AssociatedIrp.SystemBuffer;
744         if (outputBufferLen != 0) {
745             InitUserParamsCtx(irp, instance, 0, NULL,
746                               inputBuffer, inputBufferLen,
747                               outputBuffer, outputBufferLen,
748                               &usrParamsCtx);
749
750             ASSERT(outputBuffer);
751         } else {
752             status = STATUS_NDIS_INVALID_LENGTH;
753             goto done;
754         }
755
756         status = OvsGetPidHandler(&usrParamsCtx, &replyLen);
757         goto done;
758
759     case OVS_IOCTL_TRANSACT:
760         /* Both input buffer and output buffer are mandatory. */
761         if (outputBufferLen != 0) {
762             status = MapIrpOutputBuffer(irp, outputBufferLen,
763                                         sizeof *ovsMsg, &outputBuffer);
764             if (status != STATUS_SUCCESS) {
765                 goto done;
766             }
767             ASSERT(outputBuffer);
768         } else {
769             status = STATUS_NDIS_INVALID_LENGTH;
770             goto done;
771         }
772
773         if (inputBufferLen < sizeof (*ovsMsg)) {
774             status = STATUS_NDIS_INVALID_LENGTH;
775             goto done;
776         }
777
778         ovsMsg = inputBuffer;
779         devOp = OVS_TRANSACTION_DEV_OP;
780         break;
781
782     case OVS_IOCTL_READ_EVENT:
783     case OVS_IOCTL_READ_PACKET:
784         /*
785          * Output buffer is mandatory. These IOCTLs are used to read events and
786          * packets respectively. It is convenient to have separate ioctls.
787          */
788         if (outputBufferLen != 0) {
789             status = MapIrpOutputBuffer(irp, outputBufferLen,
790                                         sizeof *ovsMsg, &outputBuffer);
791             if (status != STATUS_SUCCESS) {
792                 goto done;
793             }
794             ASSERT(outputBuffer);
795         } else {
796             status = STATUS_NDIS_INVALID_LENGTH;
797             goto done;
798         }
799         inputBuffer = NULL;
800         inputBufferLen = 0;
801
802         ovsMsg = &ovsMsgReadOp;
803         RtlZeroMemory(ovsMsg, sizeof *ovsMsg);
804         ovsMsg->nlMsg.nlmsgLen = sizeof *ovsMsg;
805         ovsMsg->nlMsg.nlmsgType = nlControlFamilyOps.id;
806         ovsMsg->nlMsg.nlmsgPid = instance->pid;
807
808         /* An "artificial" command so we can use NL family function table*/
809         ovsMsg->genlMsg.cmd = (code == OVS_IOCTL_READ_EVENT) ?
810                               OVS_CTRL_CMD_EVENT_NOTIFY :
811                               OVS_CTRL_CMD_READ_NOTIFY;
812         ovsMsg->genlMsg.version = nlControlFamilyOps.version;
813
814         devOp = OVS_READ_DEV_OP;
815         break;
816
817     case OVS_IOCTL_READ:
818         /* Output buffer is mandatory. */
819         if (outputBufferLen != 0) {
820             status = MapIrpOutputBuffer(irp, outputBufferLen,
821                                         sizeof *ovsMsg, &outputBuffer);
822             if (status != STATUS_SUCCESS) {
823                 goto done;
824             }
825             ASSERT(outputBuffer);
826         } else {
827             status = STATUS_NDIS_INVALID_LENGTH;
828             goto done;
829         }
830
831         /*
832          * Operate in the mode that read ioctl is similar to ReadFile(). This
833          * might change as the userspace code gets implemented.
834          */
835         inputBuffer = NULL;
836         inputBufferLen = 0;
837
838         /*
839          * For implementing read (ioctl or otherwise), we need to store some
840          * state in the instance to indicate the command that started the dump
841          * operation. The state can setup 'ovsMsgReadOp' appropriately. Note
842          * that 'ovsMsgReadOp' is needed only in this function to call into the
843          * appropriate handler. The handler itself can access the state in the
844          * instance.
845          *
846          * In the absence of a dump start, return 0 bytes.
847          */
848         if (instance->dumpState.ovsMsg == NULL) {
849             replyLen = 0;
850             status = STATUS_SUCCESS;
851             goto done;
852         }
853         RtlCopyMemory(&ovsMsgReadOp, instance->dumpState.ovsMsg,
854                       sizeof (ovsMsgReadOp));
855
856         /* Create an NL message for consumption. */
857         ovsMsg = &ovsMsgReadOp;
858         devOp = OVS_READ_DEV_OP;
859
860         break;
861
862     case OVS_IOCTL_WRITE:
863         /* Input buffer is mandatory. */
864         if (inputBufferLen < sizeof (*ovsMsg)) {
865             status = STATUS_NDIS_INVALID_LENGTH;
866             goto done;
867         }
868
869         ovsMsg = inputBuffer;
870         devOp = OVS_WRITE_DEV_OP;
871         break;
872
873     default:
874         status = STATUS_INVALID_DEVICE_REQUEST;
875         goto done;
876     }
877
878     ASSERT(ovsMsg);
879     switch (ovsMsg->nlMsg.nlmsgType) {
880     case OVS_WIN_NL_CTRL_FAMILY_ID:
881         nlFamilyOps = &nlControlFamilyOps;
882         break;
883     case OVS_WIN_NL_DATAPATH_FAMILY_ID:
884         nlFamilyOps = &nlDatapathFamilyOps;
885         break;
886     case OVS_WIN_NL_FLOW_FAMILY_ID:
887          nlFamilyOps = &nlFLowFamilyOps;
888          break;
889     case OVS_WIN_NL_PACKET_FAMILY_ID:
890          nlFamilyOps = &nlPacketFamilyOps;
891          break;
892     case OVS_WIN_NL_VPORT_FAMILY_ID:
893         nlFamilyOps = &nlVportFamilyOps;
894         break;
895     case OVS_WIN_NL_NETDEV_FAMILY_ID:
896         nlFamilyOps = &nlNetdevFamilyOps;
897         break;
898     default:
899         status = STATUS_INVALID_PARAMETER;
900         goto done;
901     }
902
903     /*
904      * For read operation, avoid duplicate validation since 'ovsMsg' is either
905      * "artificial" or was copied from a previously validated 'ovsMsg'.
906      */
907     if (devOp != OVS_READ_DEV_OP) {
908         status = ValidateNetlinkCmd(devOp, instance, ovsMsg, nlFamilyOps);
909         if (status != STATUS_SUCCESS) {
910             goto done;
911         }
912     }
913
914     InitUserParamsCtx(irp, instance, devOp, ovsMsg,
915                       inputBuffer, inputBufferLen,
916                       outputBuffer, outputBufferLen,
917                       &usrParamsCtx);
918
919     status = InvokeNetlinkCmdHandler(&usrParamsCtx, nlFamilyOps, &replyLen);
920
921 done:
922     OvsReleaseSwitchContext(gOvsSwitchContext);
923
924 exit:
925     KeMemoryBarrier();
926     instance->inUse = 0;
927
928     /* Should not complete a pending IRP unless proceesing is completed */
929     if (status == STATUS_PENDING) {
930         return status;
931     }
932     return OvsCompleteIrpRequest(irp, (ULONG_PTR)replyLen, status);
933 }
934
935
936 /*
937  * --------------------------------------------------------------------------
938  * Function to validate a netlink command. Only certain combinations of
939  * (device operation, netlink family, command) are valid.
940  * --------------------------------------------------------------------------
941  */
942 static NTSTATUS
943 ValidateNetlinkCmd(UINT32 devOp,
944                    POVS_OPEN_INSTANCE instance,
945                    POVS_MESSAGE ovsMsg,
946                    NETLINK_FAMILY *nlFamilyOps)
947 {
948     NTSTATUS status = STATUS_INVALID_PARAMETER;
949     UINT16 i;
950
951     for (i = 0; i < nlFamilyOps->opsCount; i++) {
952         if (nlFamilyOps->cmds[i].cmd == ovsMsg->genlMsg.cmd) {
953             /* Validate if the command is valid for the device operation. */
954             if ((devOp & nlFamilyOps->cmds[i].supportedDevOp) == 0) {
955                 status = STATUS_INVALID_PARAMETER;
956                 goto done;
957             }
958
959             /* Validate the version. */
960             if (nlFamilyOps->version > ovsMsg->genlMsg.version) {
961                 status = STATUS_INVALID_PARAMETER;
962                 goto done;
963             }
964
965             /* Validate the DP for commands that require a DP. */
966             if (nlFamilyOps->cmds[i].validateDpIndex == TRUE) {
967                 if (ovsMsg->ovsHdr.dp_ifindex !=
968                                           (INT)gOvsSwitchContext->dpNo) {
969                     status = STATUS_INVALID_PARAMETER;
970                     goto done;
971                 }
972             }
973
974             /* Validate the PID. */
975             if (ovsMsg->nlMsg.nlmsgPid != instance->pid) {
976                 status = STATUS_INVALID_PARAMETER;
977                 goto done;
978             }
979
980             status = STATUS_SUCCESS;
981             break;
982         }
983     }
984
985 done:
986     return status;
987 }
988
989 /*
990  * --------------------------------------------------------------------------
991  * Function to invoke the netlink command handler. The function also stores
992  * the return value of the handler function to construct a 'NL_ERROR' message,
993  * and in turn returns success to the caller.
994  * --------------------------------------------------------------------------
995  */
996 static NTSTATUS
997 InvokeNetlinkCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
998                         NETLINK_FAMILY *nlFamilyOps,
999                         UINT32 *replyLen)
1000 {
1001     NTSTATUS status = STATUS_INVALID_PARAMETER;
1002     UINT16 i;
1003
1004     for (i = 0; i < nlFamilyOps->opsCount; i++) {
1005         if (nlFamilyOps->cmds[i].cmd == usrParamsCtx->ovsMsg->genlMsg.cmd) {
1006             NetlinkCmdHandler *handler = nlFamilyOps->cmds[i].handler;
1007             ASSERT(handler);
1008             if (handler) {
1009                 status = handler(usrParamsCtx, replyLen);
1010             }
1011             break;
1012         }
1013     }
1014
1015     /*
1016      * Netlink socket semantics dictate that the return value of the netlink
1017      * function should be an error ONLY under fatal conditions. If the message
1018      * made it all the way to the handler function, it is not a fatal condition.
1019      * Absorb the error returned by the handler function into a 'struct
1020      * NL_ERROR' and populate the 'output buffer' to return to userspace.
1021      *
1022      * This behavior is obviously applicable only to netlink commands that
1023      * specify an 'output buffer'. For other commands, we return the error as
1024      * is.
1025      *
1026      * 'STATUS_PENDING' is a special return value and userspace is equipped to
1027      * handle it.
1028      */
1029     if (status != STATUS_SUCCESS && status != STATUS_PENDING) {
1030         if (usrParamsCtx->devOp != OVS_WRITE_DEV_OP && *replyLen == 0) {
1031             NL_ERROR nlError = NlMapStatusToNlErr(status);
1032             POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1033             POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR)
1034                 usrParamsCtx->outputBuffer;
1035
1036             ASSERT(msgError);
1037             NlBuildErrorMsg(msgIn, msgError, nlError);
1038             *replyLen = msgError->nlMsg.nlmsgLen;
1039         }
1040
1041         if (*replyLen != 0) {
1042             status = STATUS_SUCCESS;
1043         }
1044     }
1045
1046 #ifdef DBG
1047     if (usrParamsCtx->devOp != OVS_WRITE_DEV_OP) {
1048         ASSERT(status == STATUS_PENDING || *replyLen != 0 || status == STATUS_SUCCESS);
1049     }
1050 #endif
1051
1052     return status;
1053 }
1054
1055 /*
1056  * --------------------------------------------------------------------------
1057  *  Handler for 'OVS_IOCTL_GET_PID'.
1058  *
1059  *  Each handle on the device is assigned a unique PID when the handle is
1060  *  created. This function passes the PID to userspace using METHOD_BUFFERED
1061  *  method.
1062  * --------------------------------------------------------------------------
1063  */
1064 static NTSTATUS
1065 OvsGetPidHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1066                  UINT32 *replyLen)
1067 {
1068     NTSTATUS status = STATUS_SUCCESS;
1069     PUINT32 msgOut = (PUINT32)usrParamsCtx->outputBuffer;
1070
1071     if (usrParamsCtx->outputLength >= sizeof *msgOut) {
1072         POVS_OPEN_INSTANCE instance =
1073             (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1074
1075         RtlZeroMemory(msgOut, sizeof *msgOut);
1076         RtlCopyMemory(msgOut, &instance->pid, sizeof(*msgOut));
1077         *replyLen = sizeof *msgOut;
1078     } else {
1079         *replyLen = sizeof *msgOut;
1080         status = STATUS_NDIS_INVALID_LENGTH;
1081     }
1082
1083     return status;
1084 }
1085
1086 /*
1087  * --------------------------------------------------------------------------
1088  * Utility function to fill up information about the datapath in a reply to
1089  * userspace.
1090  * --------------------------------------------------------------------------
1091  */
1092 static NTSTATUS
1093 OvsDpFillInfo(POVS_SWITCH_CONTEXT ovsSwitchContext,
1094               POVS_MESSAGE msgIn,
1095               PNL_BUFFER nlBuf)
1096 {
1097     BOOLEAN writeOk;
1098     OVS_MESSAGE msgOutTmp;
1099     OVS_DATAPATH *datapath = &ovsSwitchContext->datapath;
1100     PNL_MSG_HDR nlMsg;
1101
1102     ASSERT(NlBufAt(nlBuf, 0, 0) != 0 && NlBufRemLen(nlBuf) >= sizeof *msgIn);
1103
1104     msgOutTmp.nlMsg.nlmsgType = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1105     msgOutTmp.nlMsg.nlmsgFlags = 0;  /* XXX: ? */
1106     msgOutTmp.nlMsg.nlmsgSeq = msgIn->nlMsg.nlmsgSeq;
1107     msgOutTmp.nlMsg.nlmsgPid = msgIn->nlMsg.nlmsgPid;
1108
1109     msgOutTmp.genlMsg.cmd = OVS_DP_CMD_GET;
1110     msgOutTmp.genlMsg.version = nlDatapathFamilyOps.version;
1111     msgOutTmp.genlMsg.reserved = 0;
1112
1113     msgOutTmp.ovsHdr.dp_ifindex = ovsSwitchContext->dpNo;
1114
1115     writeOk = NlMsgPutHead(nlBuf, (PCHAR)&msgOutTmp, sizeof msgOutTmp);
1116     if (writeOk) {
1117         writeOk = NlMsgPutTailString(nlBuf, OVS_DP_ATTR_NAME,
1118                                      OVS_SYSTEM_DP_NAME);
1119     }
1120     if (writeOk) {
1121         OVS_DP_STATS dpStats;
1122
1123         dpStats.n_hit = datapath->hits;
1124         dpStats.n_missed = datapath->misses;
1125         dpStats.n_lost = datapath->lost;
1126         dpStats.n_flows = datapath->nFlows;
1127         writeOk = NlMsgPutTailUnspec(nlBuf, OVS_DP_ATTR_STATS,
1128                                      (PCHAR)&dpStats, sizeof dpStats);
1129     }
1130     nlMsg = (PNL_MSG_HDR)NlBufAt(nlBuf, 0, 0);
1131     nlMsg->nlmsgLen = NlBufSize(nlBuf);
1132
1133     return writeOk ? STATUS_SUCCESS : STATUS_INVALID_BUFFER_SIZE;
1134 }
1135
1136 /*
1137  * --------------------------------------------------------------------------
1138  * Handler for queueing an IRP used for event notification. The IRP is
1139  * completed when a port state changes. STATUS_PENDING is returned on
1140  * success. User mode keep a pending IRP at all times.
1141  * --------------------------------------------------------------------------
1142  */
1143 static NTSTATUS
1144 OvsPendEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1145                        UINT32 *replyLen)
1146 {
1147     NDIS_STATUS status;
1148
1149     UNREFERENCED_PARAMETER(replyLen);
1150
1151     POVS_OPEN_INSTANCE instance =
1152         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1153     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1154     OVS_EVENT_POLL poll;
1155
1156     poll.dpNo = msgIn->ovsHdr.dp_ifindex;
1157     status = OvsWaitEventIoctl(usrParamsCtx->irp, instance->fileObject,
1158                                &poll, sizeof poll);
1159     return status;
1160 }
1161
1162 /*
1163  * --------------------------------------------------------------------------
1164  *  Handler for the subscription for the event queue
1165  * --------------------------------------------------------------------------
1166  */
1167 static NTSTATUS
1168 OvsSubscribeEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1169                             UINT32 *replyLen)
1170 {
1171     NDIS_STATUS status;
1172     OVS_EVENT_SUBSCRIBE request;
1173     BOOLEAN rc;
1174     UINT8 join;
1175     PNL_ATTR attrs[2];
1176     const NL_POLICY policy[] =  {
1177         [OVS_NL_ATTR_MCAST_GRP] = {.type = NL_A_U32 },
1178         [OVS_NL_ATTR_MCAST_JOIN] = {.type = NL_A_U8 },
1179         };
1180
1181     UNREFERENCED_PARAMETER(replyLen);
1182
1183     POVS_OPEN_INSTANCE instance =
1184         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1185     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1186
1187     rc = NlAttrParse(&msgIn->nlMsg, sizeof (*msgIn),
1188          NlMsgAttrsLen((PNL_MSG_HDR)msgIn), policy, attrs, ARRAY_SIZE(attrs));
1189     if (!rc) {
1190         status = STATUS_INVALID_PARAMETER;
1191         goto done;
1192     }
1193
1194     /* XXX Ignore the MC group for now */
1195     join = NlAttrGetU8(attrs[OVS_NL_ATTR_MCAST_JOIN]);
1196     request.dpNo = msgIn->ovsHdr.dp_ifindex;
1197     request.subscribe = join;
1198     request.mask = OVS_EVENT_MASK_ALL;
1199
1200     status = OvsSubscribeEventIoctl(instance->fileObject, &request,
1201                                     sizeof request);
1202 done:
1203     return status;
1204 }
1205
1206 /*
1207  * --------------------------------------------------------------------------
1208  *  Command Handler for 'OVS_DP_CMD_NEW'.
1209  * --------------------------------------------------------------------------
1210  */
1211 static NTSTATUS
1212 OvsNewDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1213                    UINT32 *replyLen)
1214 {
1215     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1216 }
1217
1218 /*
1219  * --------------------------------------------------------------------------
1220  *  Command Handler for 'OVS_DP_CMD_GET'.
1221  *
1222  *  The function handles both the dump based as well as the transaction based
1223  *  'OVS_DP_CMD_GET' command. In the dump command, it handles the initial
1224  *  call to setup dump state, as well as subsequent calls to continue dumping
1225  *  data.
1226  * --------------------------------------------------------------------------
1227  */
1228 static NTSTATUS
1229 OvsGetDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1230                    UINT32 *replyLen)
1231 {
1232     if (usrParamsCtx->devOp == OVS_TRANSACTION_DEV_OP) {
1233         return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1234     } else {
1235         return HandleGetDpDump(usrParamsCtx, replyLen);
1236     }
1237 }
1238
1239 /*
1240  * --------------------------------------------------------------------------
1241  *  Function for handling the transaction based 'OVS_DP_CMD_GET' command.
1242  * --------------------------------------------------------------------------
1243  */
1244 static NTSTATUS
1245 HandleGetDpTransaction(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1246                        UINT32 *replyLen)
1247 {
1248     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1249 }
1250
1251
1252 /*
1253  * --------------------------------------------------------------------------
1254  *  Function for handling the dump-based 'OVS_DP_CMD_GET' command.
1255  * --------------------------------------------------------------------------
1256  */
1257 static NTSTATUS
1258 HandleGetDpDump(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1259                 UINT32 *replyLen)
1260 {
1261     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1262     POVS_OPEN_INSTANCE instance =
1263         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1264
1265     if (usrParamsCtx->devOp == OVS_WRITE_DEV_OP) {
1266         *replyLen = 0;
1267         OvsSetupDumpStart(usrParamsCtx);
1268     } else {
1269         NL_BUFFER nlBuf;
1270         NTSTATUS status;
1271         POVS_MESSAGE msgIn = instance->dumpState.ovsMsg;
1272
1273         ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP);
1274
1275         if (instance->dumpState.ovsMsg == NULL) {
1276             ASSERT(FALSE);
1277             return STATUS_INVALID_DEVICE_STATE;
1278         }
1279
1280         /* Dump state must have been deleted after previous dump operation. */
1281         ASSERT(instance->dumpState.index[0] == 0);
1282
1283         /* Output buffer has been validated while validating read dev op. */
1284         ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1285
1286         NlBufInit(&nlBuf, usrParamsCtx->outputBuffer,
1287                   usrParamsCtx->outputLength);
1288
1289         status = OvsDpFillInfo(gOvsSwitchContext, msgIn, &nlBuf);
1290
1291         if (status != STATUS_SUCCESS) {
1292             *replyLen = 0;
1293             FreeUserDumpState(instance);
1294             return status;
1295         }
1296
1297         /* Increment the dump index. */
1298         instance->dumpState.index[0] = 1;
1299         *replyLen = msgOut->nlMsg.nlmsgLen;
1300
1301         /* Free up the dump state, since there's no more data to continue. */
1302         FreeUserDumpState(instance);
1303     }
1304
1305     return STATUS_SUCCESS;
1306 }
1307
1308
1309 /*
1310  * --------------------------------------------------------------------------
1311  *  Command Handler for 'OVS_DP_CMD_SET'.
1312  * --------------------------------------------------------------------------
1313  */
1314 static NTSTATUS
1315 OvsSetDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1316                    UINT32 *replyLen)
1317 {
1318     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1319 }
1320
1321 /*
1322  * --------------------------------------------------------------------------
1323  *  Function for handling transaction based 'OVS_DP_CMD_NEW', 'OVS_DP_CMD_GET'
1324  *  and 'OVS_DP_CMD_SET' commands.
1325  *
1326  * 'OVS_DP_CMD_NEW' is implemented to keep userspace code happy. Creation of a
1327  * new datapath is not supported currently.
1328  * --------------------------------------------------------------------------
1329  */
1330 static NTSTATUS
1331 HandleDpTransactionCommon(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1332                           UINT32 *replyLen)
1333 {
1334     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1335     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1336     NTSTATUS status = STATUS_SUCCESS;
1337     NL_BUFFER nlBuf;
1338     NL_ERROR nlError = NL_ERROR_SUCCESS;
1339     static const NL_POLICY ovsDatapathSetPolicy[] = {
1340         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .maxLen = IFNAMSIZ },
1341         [OVS_DP_ATTR_UPCALL_PID] = { .type = NL_A_U32, .optional = TRUE },
1342         [OVS_DP_ATTR_USER_FEATURES] = { .type = NL_A_U32, .optional = TRUE },
1343     };
1344     PNL_ATTR dpAttrs[ARRAY_SIZE(ovsDatapathSetPolicy)];
1345
1346     UNREFERENCED_PARAMETER(msgOut);
1347
1348     /* input buffer has been validated while validating write dev op. */
1349     ASSERT(msgIn != NULL && usrParamsCtx->inputLength >= sizeof *msgIn);
1350
1351     /* Parse any attributes in the request. */
1352     if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_SET ||
1353         usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_NEW) {
1354         if (!NlAttrParse((PNL_MSG_HDR)msgIn,
1355                         NLMSG_HDRLEN + GENL_HDRLEN + OVS_HDRLEN,
1356                         NlMsgAttrsLen((PNL_MSG_HDR)msgIn),
1357                         ovsDatapathSetPolicy, dpAttrs, ARRAY_SIZE(dpAttrs))) {
1358             return STATUS_INVALID_PARAMETER;
1359         }
1360
1361         /*
1362         * XXX: Not clear at this stage if there's any role for the
1363         * OVS_DP_ATTR_UPCALL_PID and OVS_DP_ATTR_USER_FEATURES attributes passed
1364         * from userspace.
1365         */
1366
1367     } else {
1368         RtlZeroMemory(dpAttrs, sizeof dpAttrs);
1369     }
1370
1371     /* Output buffer has been validated while validating transact dev op. */
1372     ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1373
1374     NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength);
1375
1376     if (dpAttrs[OVS_DP_ATTR_NAME] != NULL) {
1377         if (!OvsCompareString(NlAttrGet(dpAttrs[OVS_DP_ATTR_NAME]),
1378                               OVS_SYSTEM_DP_NAME)) {
1379
1380             /* Creation of new datapaths is not supported. */
1381             if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_SET) {
1382                 nlError = NL_ERROR_NOTSUPP;
1383                 goto cleanup;
1384             }
1385
1386             nlError = NL_ERROR_NODEV;
1387             goto cleanup;
1388         }
1389     } else if ((UINT32)msgIn->ovsHdr.dp_ifindex != gOvsSwitchContext->dpNo) {
1390         nlError = NL_ERROR_NODEV;
1391         goto cleanup;
1392     }
1393
1394     if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_NEW) {
1395         nlError = NL_ERROR_EXIST;
1396         goto cleanup;
1397     }
1398
1399     status = OvsDpFillInfo(gOvsSwitchContext, msgIn, &nlBuf);
1400
1401     *replyLen = NlBufSize(&nlBuf);
1402
1403 cleanup:
1404     if (nlError != NL_ERROR_SUCCESS) {
1405         POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR)
1406             usrParamsCtx->outputBuffer;
1407
1408         NlBuildErrorMsg(msgIn, msgError, nlError);
1409         *replyLen = msgError->nlMsg.nlmsgLen;
1410     }
1411
1412     return STATUS_SUCCESS;
1413 }
1414
1415
1416 NTSTATUS
1417 OvsSetupDumpStart(POVS_USER_PARAMS_CONTEXT usrParamsCtx)
1418 {
1419     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1420     POVS_OPEN_INSTANCE instance =
1421         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1422
1423     /* input buffer has been validated while validating write dev op. */
1424     ASSERT(msgIn != NULL && usrParamsCtx->inputLength >= sizeof *msgIn);
1425
1426     /* A write operation that does not indicate dump start is invalid. */
1427     if ((msgIn->nlMsg.nlmsgFlags & NLM_F_DUMP) != NLM_F_DUMP) {
1428         return STATUS_INVALID_PARAMETER;
1429     }
1430     /* XXX: Handle other NLM_F_* flags in the future. */
1431
1432     /*
1433      * This operation should be setting up the dump state. If there's any
1434      * previous state, clear it up so as to set it up afresh.
1435      */
1436     FreeUserDumpState(instance);
1437
1438     return InitUserDumpState(instance, msgIn);
1439 }
1440
1441
1442 /*
1443  * --------------------------------------------------------------------------
1444  *  Utility function to map the output buffer in an IRP. The buffer is assumed
1445  *  to have been passed down using METHOD_OUT_DIRECT (Direct I/O).
1446  * --------------------------------------------------------------------------
1447  */
1448 static NTSTATUS
1449 MapIrpOutputBuffer(PIRP irp,
1450                    UINT32 bufferLength,
1451                    UINT32 requiredLength,
1452                    PVOID *buffer)
1453 {
1454     ASSERT(irp);
1455     ASSERT(buffer);
1456     ASSERT(bufferLength);
1457     ASSERT(requiredLength);
1458     if (!buffer || !irp || bufferLength == 0 || requiredLength == 0) {
1459         return STATUS_INVALID_PARAMETER;
1460     }
1461
1462     if (bufferLength < requiredLength) {
1463         return STATUS_NDIS_INVALID_LENGTH;
1464     }
1465     if (irp->MdlAddress == NULL) {
1466         return STATUS_INVALID_PARAMETER;
1467     }
1468     *buffer = MmGetSystemAddressForMdlSafe(irp->MdlAddress,
1469                                            NormalPagePriority);
1470     if (*buffer == NULL) {
1471         return STATUS_INSUFFICIENT_RESOURCES;
1472     }
1473
1474     return STATUS_SUCCESS;
1475 }
1476
1477 /*
1478  * --------------------------------------------------------------------------
1479  * Utility function to fill up information about the state of a port in a reply
1480  * to* userspace.
1481  * --------------------------------------------------------------------------
1482  */
1483 static NTSTATUS
1484 OvsPortFillInfo(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1485                 POVS_EVENT_ENTRY eventEntry,
1486                 PNL_BUFFER nlBuf)
1487 {
1488     NTSTATUS status;
1489     BOOLEAN ok;
1490     OVS_MESSAGE msgOutTmp;
1491     PNL_MSG_HDR nlMsg;
1492     POVS_VPORT_ENTRY vport;
1493
1494     ASSERT(NlBufAt(nlBuf, 0, 0) != 0 && nlBuf->bufRemLen >= sizeof msgOutTmp);
1495
1496     msgOutTmp.nlMsg.nlmsgType = OVS_WIN_NL_VPORT_FAMILY_ID;
1497     msgOutTmp.nlMsg.nlmsgFlags = 0;  /* XXX: ? */
1498
1499     /* driver intiated messages should have zerp seq number*/
1500     msgOutTmp.nlMsg.nlmsgSeq = 0;
1501     msgOutTmp.nlMsg.nlmsgPid = usrParamsCtx->ovsInstance->pid;
1502
1503     msgOutTmp.genlMsg.version = nlVportFamilyOps.version;
1504     msgOutTmp.genlMsg.reserved = 0;
1505
1506     /* we don't have netdev yet, treat link up/down a adding/removing a port*/
1507     if (eventEntry->status & (OVS_EVENT_LINK_UP | OVS_EVENT_CONNECT)) {
1508         msgOutTmp.genlMsg.cmd = OVS_VPORT_CMD_NEW;
1509     } else if (eventEntry->status &
1510              (OVS_EVENT_LINK_DOWN | OVS_EVENT_DISCONNECT)) {
1511         msgOutTmp.genlMsg.cmd = OVS_VPORT_CMD_DEL;
1512     } else {
1513         ASSERT(FALSE);
1514         return STATUS_UNSUCCESSFUL;
1515     }
1516     msgOutTmp.ovsHdr.dp_ifindex = gOvsSwitchContext->dpNo;
1517
1518     ok = NlMsgPutHead(nlBuf, (PCHAR)&msgOutTmp, sizeof msgOutTmp);
1519     if (!ok) {
1520         status = STATUS_INVALID_BUFFER_SIZE;
1521         goto cleanup;
1522     }
1523
1524     vport = OvsFindVportByPortNo(gOvsSwitchContext, eventEntry->portNo);
1525     if (!vport) {
1526         status = STATUS_DEVICE_DOES_NOT_EXIST;
1527         goto cleanup;
1528     }
1529
1530     ok = NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_PORT_NO, eventEntry->portNo) &&
1531          NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_TYPE, vport->ovsType) &&
1532          NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_UPCALL_PID,
1533                          vport->upcallPid) &&
1534          NlMsgPutTailString(nlBuf, OVS_VPORT_ATTR_NAME, vport->ovsName);
1535     if (!ok) {
1536         status = STATUS_INVALID_BUFFER_SIZE;
1537         goto cleanup;
1538     }
1539
1540     /* XXXX Should we add the port stats attributes?*/
1541     nlMsg = (PNL_MSG_HDR)NlBufAt(nlBuf, 0, 0);
1542     nlMsg->nlmsgLen = NlBufSize(nlBuf);
1543     status = STATUS_SUCCESS;
1544
1545 cleanup:
1546     return status;
1547 }
1548
1549
1550 /*
1551  * --------------------------------------------------------------------------
1552  * Handler for reading events from the driver event queue. This handler is
1553  * executed when user modes issues a socket receive on a socket assocaited
1554  * with the MC group for events.
1555  * XXX user mode should read multiple events in one system call
1556  * --------------------------------------------------------------------------
1557  */
1558 static NTSTATUS
1559 OvsReadEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1560                        UINT32 *replyLen)
1561 {
1562 #ifdef DBG
1563     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1564     POVS_OPEN_INSTANCE instance =
1565         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1566 #endif
1567     NL_BUFFER nlBuf;
1568     NTSTATUS status;
1569     OVS_EVENT_ENTRY eventEntry;
1570
1571     ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP);
1572
1573     /* Should never read events with a dump socket */
1574     ASSERT(instance->dumpState.ovsMsg == NULL);
1575
1576     /* Must have an event queue */
1577     ASSERT(instance->eventQueue != NULL);
1578
1579     /* Output buffer has been validated while validating read dev op. */
1580     ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1581
1582     NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength);
1583
1584     /* remove an event entry from the event queue */
1585     status = OvsRemoveEventEntry(usrParamsCtx->ovsInstance, &eventEntry);
1586     if (status != STATUS_SUCCESS) {
1587         /* If there were not elements, read should return no data. */
1588         status = STATUS_SUCCESS;
1589         *replyLen = 0;
1590         goto cleanup;
1591     }
1592
1593     status = OvsPortFillInfo(usrParamsCtx, &eventEntry, &nlBuf);
1594     if (status == NDIS_STATUS_SUCCESS) {
1595         *replyLen = NlBufSize(&nlBuf);
1596     }
1597
1598 cleanup:
1599     return status;
1600 }
1601
1602 /*
1603  * --------------------------------------------------------------------------
1604  * Handler for reading missed pacckets from the driver event queue. This
1605  * handler is executed when user modes issues a socket receive on a socket
1606  * --------------------------------------------------------------------------
1607  */
1608 static NTSTATUS
1609 OvsReadPacketCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1610                        UINT32 *replyLen)
1611 {
1612 #ifdef DBG
1613     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1614 #endif
1615     POVS_OPEN_INSTANCE instance =
1616         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1617     NTSTATUS status;
1618
1619     ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP);
1620
1621     /* Should never read events with a dump socket */
1622     ASSERT(instance->dumpState.ovsMsg == NULL);
1623
1624     /* Must have an packet queue */
1625     ASSERT(instance->packetQueue != NULL);
1626
1627     /* Output buffer has been validated while validating read dev op. */
1628     ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1629
1630     /* Read a packet from the instance queue */
1631     status = OvsReadDpIoctl(instance->fileObject, usrParamsCtx->outputBuffer,
1632                             usrParamsCtx->outputLength, replyLen);
1633     return status;
1634 }
1635
1636 /*
1637  * --------------------------------------------------------------------------
1638  *  Handler for the subscription for a packet queue
1639  * --------------------------------------------------------------------------
1640  */
1641 static NTSTATUS
1642 OvsSubscribePacketCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1643                             UINT32 *replyLen)
1644 {
1645     NDIS_STATUS status;
1646     BOOLEAN rc;
1647     UINT8 join;
1648     UINT32 pid;
1649     const NL_POLICY policy[] =  {
1650         [OVS_NL_ATTR_PACKET_PID] = {.type = NL_A_U32 },
1651         [OVS_NL_ATTR_PACKET_SUBSCRIBE] = {.type = NL_A_U8 }
1652         };
1653     PNL_ATTR attrs[ARRAY_SIZE(policy)];
1654
1655     UNREFERENCED_PARAMETER(replyLen);
1656
1657     POVS_OPEN_INSTANCE instance =
1658         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1659     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1660
1661     rc = NlAttrParse(&msgIn->nlMsg, sizeof (*msgIn),
1662          NlMsgAttrsLen((PNL_MSG_HDR)msgIn), policy, attrs, ARRAY_SIZE(attrs));
1663     if (!rc) {
1664         status = STATUS_INVALID_PARAMETER;
1665         goto done;
1666     }
1667
1668     join = NlAttrGetU8(attrs[OVS_NL_ATTR_PACKET_PID]);
1669     pid = NlAttrGetU32(attrs[OVS_NL_ATTR_PACKET_PID]);
1670
1671     /* The socket subscribed with must be the same socket we perform receive*/
1672     ASSERT(pid == instance->pid);
1673
1674     status = OvsSubscribeDpIoctl(instance, pid, join);
1675
1676     /*
1677      * XXX Need to add this instance to a global data structure
1678      * which hold all packet based instances. The data structure (hash)
1679      * should be searched through the pid field of the instance for
1680      * placing the missed packet into the correct queue
1681      */
1682 done:
1683     return status;
1684 }
1685
1686 /*
1687  * --------------------------------------------------------------------------
1688  * Handler for queueing an IRP used for missed packet notification. The IRP is
1689  * completed when a packet received and mismatched. STATUS_PENDING is returned
1690  * on success. User mode keep a pending IRP at all times.
1691  * --------------------------------------------------------------------------
1692  */
1693 static NTSTATUS
1694 OvsPendPacketCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1695                        UINT32 *replyLen)
1696 {
1697     UNREFERENCED_PARAMETER(replyLen);
1698
1699     POVS_OPEN_INSTANCE instance =
1700         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1701
1702     /*
1703      * XXX access to packet queue must be through acquiring a lock as user mode
1704      * could unsubscribe and the instnace will be freed.
1705      */
1706     return OvsWaitDpIoctl(usrParamsCtx->irp, instance->fileObject);
1707 }