When a per-stream context that is associated with a file stream is no longer needed, it should be deleted. Stream contexts are deleted in one of two ways:
Manually, when the filter driver calls FsRtlRemovePerStreamContext.
When the Filter Deletes the Per-Stream Context
When a filter driver needs to delete its per-stream context for a file stream while the file stream is still open, it first calls FsRtlRemovePerStreamContext to remove the context from the global list of contexts associated with the given file. After calling FsRtlRemovePerStreamContext, the filter usually frees the context structure.
Note After your filter driver has called FsRtlInsertPerStreamContext to associate a per-stream context structure with a file stream, it must call FsRtlRemovePerStreamContext for the context before freeing it. Otherwise, the system will crash when the file stream is closed.
When the Per-Stream Context's FreeCallback Is Called
When the file stream is being closed or deleted, the file system frees its own stream context for the file stream. At this time, the file system also calls FsRtlTeardownPerStreamContexts, which in turn calls the FreeCallback routines registered for all of the per-stream contexts contained in the global list of contexts for that file stream. (A FreeCallback routine is registered when the filter driver calls FsRtlInitPerStreamContext to initialize a per-stream context structure. For more information, see FSRTL_PER_STREAM_CONTEXT.)
Note After your filter driver has called FsRtlInsertPerStreamContext to associate a per-stream context structure with a file stream, the file system is responsible for ensuring that the FreeCallback routine for the filter's per-stream context is called when there are no longer any open references to the stream.