- The CPU (the actual hardware) interrupts the current process based on an internal timer, switches into kernel mode, and hands control back to the kernel.
Most task switches are caused by tasks blocking (because they have to wait for a mutex, disk IO, user IO, end-user action, etc).
It's better (more accurate) to say that "something" (IRQ, system call) causes a switch to the kernel's code before the kernel decides it wants to do a task switch, and that this "something" is not part of the task switch itself.
- The kernel records the current state of the CPU and memory, which will be essential to resuming the process that was just interrupted.
Sort of. Because "something" (IRQ, system call) causes a switch to the kernel's code before the kernel decides it wants to do a task switch; all task switches only every happen between kernel's code (for one task) and kernel's code (for another task). Because task switches only ever switch from kernel's code to kernel's code; the task switch itself doesn't need to care about user-space memory (which isn't so important for kernel's code) or kernel's memory (which is global/shared by all CPUs and all virtual address spaces). More; because some registers are "callee preserved" (by C calling conventions) and some are "constant as far as kernel is concerned" (e.g. segment registers) the task switch code doesn't need to care about various parts of the CPU state either.
- The kernel performs any tasks that might have come up during the preceding time slice (such as collecting data from input and output, or I/O, operations).
Also not part of the task switch (more "things that happen before or after kernel decides to do a task switch").
- The kernel is now ready to let another process run. The kernel analyzes the list of processes that are ready to run and chooses one.
Sort of; but it's no as simple as a list, and sometimes (e.g. high-priority real time thread unblocks and preempts a less important task) the kernel knows which task it needs to switch to without doing anything extra.
- The kernel prepares the memory for this new process, and then prepares the CPU.
For memory; kernel mostly just loads a new "reference for new task's virtual address space" (e.g. a single mov cr3, ...
instruction on 80x86). For CPU state, it's the reverse of "2. The kernel records the current state of the CPU ...
" above (loading what was previously saved, where some CPU state isn't loaded and isn't saved).
- The kernel tells the CPU how long the time slice for the new process will last.
Yes.
- The kernel switches the CPU into user mode and hands control of the CPU to the process.
Not really. It's better (more accurate) to say after the kernel has finished doing a task switch, the kernel code for the new task does whatever it wants (and eventually may return to user-space); and that "things that happen after task switch finished" are not part of the task switch.