POC non-blocking chelper, bg thread step generation

On my printer host (opi 3 lts), with input shaper enabled, during printing a steppersyncmgr_gen_steps() call from motion_queuing._advance_flush_time() regularly takes tens of milliseconds and at peaks exceeds 100 ms. The call is synchronous, so the reactor is blocked for that time. No timers fire, no other greenlet runs, etc..

E.g. from log:

Reactor 22154.778 busy for 0.082 with:
- 'PrinterMotionQueuing._flush_handler (motion_queuing.py:206)' 

Extra logging for the call to ensure that it’s specifically the stepgen, rather than flush callbacks.

_advance_flush_time 22154.7 busy all=0.0812 step_gen_t=0.081 

In practice this does not turn into TTC or a motion stall, because steps are generated well ahead of the MCU. The toolhead keeps up to BUFFER_TIME_HIGH=1.0 of moves queued ahead of the estimated print time. The motion_queuing flush timer wakes up once the generated steps are only BGFLUSH_SG_LOW_TIME=0.450 ahead and generates up to BGFLUSH_SG_HIGH_TIME=0.700 ahead, so each batch covers about 250 ms of motion. Even a 100 ms batch leaves roughly 350 ms of margin before the MCU would run out of queued steps.

Still, those 100 ms could be spent on other work. The Gcode greenlet could be parsing and planning the next moves (arcs in particular cost more to process than plain G1 moves), sensor batches could be processed and API clients could be served. So this is not a fix for a specific failure on my hardware I can point at. It is an attempt to make the host more productive and the reactor latency more predictable, which should also leave more headroom on slower SBCs.

A proof of concept is at GitHub - MRX8024/klipper at work-nonblock-chelper-20261024 · GitHub . It is Python only and touches no C code. CFFI already releases the GIL around C calls, so the C step generation can run in parallel with the reactor as long as it is called from another thread and nothing else touches the same C state at the same time. The changes are split into small commits in chelper, toolhead.py and motion_queuing.py.

motion_queuing gets a single worker thread. _advance_flush_time() still does all the Python bookkeeping it did before, flush callbacks, the trapq free and history times, and so on. It also publishes the new last_flush_time and last_step_gen_time up front, so any new moves are queued after this flush. Then it hands steppersyncmgr_gen_steps() to the thread and returns. A reactor completion tracks the batch. When the thread finishes, it returns to the reactor through register_async_callback(), where the result is checked and trapq_finalize_moves() runs.

The harder part is everything else that calls into C while a batch is running, trapq_append() from the toolhead, itersolve position queries, stepcompress queries from motion_report and angle, manual_stepper, and so on. Rather than adding locking to around 20 call sites, chelper.get_ffi() now returns a thin FFISyncLib wrapper around the CFFI lib. Before most C calls it invokes a callback registered by motion_queuing, wait_step_gen(), which pauses the calling greenlet on the completion until the active batch finishes. Greenlets never switch in the middle of a C call, so once a greenlet passes this barrier and enters C, no new batch can start until that greenlet yields again, and one barrier at the FFI boundary is enough.

A few functions are excluded from the barrier. serialqueue_* and trdispatch_* have their own locking. *_alloc, *_free and free must stay callable from destructors at arbitrary points. steppersyncmgr_gen_steps is what the worker thread itself calls. trapq_extract_old only reads history that the thread does not modify. The wrapper also raises an error if a synced call comes from a thread other than the reactor thread, which catches accidental misuse early.

Clock calibration in stats() is split in two. mcu.calibrate_clock() still runs on every stats call without waiting for step generation, so e.g. the ‘mcu lost communication’ check is never delayed. The resulting steppersync_set_time() is applied only right before the next step generation batch.

Klippy tests pass both as is and with a local patch that enables the background thread in batch mode, and the generated steps match master in both cases. On the real printer I ran prints and homing with debug logging, together with motan, whose dump timers constantly query C to stress the barrier, and it seems to work as intended. For now I haven’t tested more thoroughly with manual_stepper or something else “exclusive”.

Any feedback on the approach, or on C call paths I may have missed, is welcome. Thanks!

1 Like

Interesting. I have some very high-level thoughts, but please don’t take these comments too seriously.

  • I agree it should be possible to thread the code so that the python reactor can run in parallel with step generation. I gave this some thought as well when we were implementing the multi-threaded step generation last year.
  • I suspect a threaded implementation would increase the code complexity. For what it is worth, I suspect that would only be worthwhile if there were a large number of machines that can’t keep up with the current implementation. To wit, I’d avoid complex optimizations just for the sake of optimizing.
  • I’d try to avoid threads in the python code. In my experience, Python developers tend to not think about threads at all - even developers that also regularly work in C/C++ and understand the nuances of threads. For example, if I could go back in time, I’m not sure I would have used a python thread for the mcu message receiving code (eg, the heater/temperature control loop), as it regularly causes issues. If possible, I’d try to implement threading entirely in the C code, or if Python threads are needed then try to encapsulate the parallelized logic entirely within a single Python class so that nothing external needed to know that threads are utilized.
  • When threading code, I’d recommend using standard locking methods. For what it is worth, “clever locking” like chelper wrappers aren’t worth it in my opinion. That is, it may be a little more work to add locks to trapq.c, itersolve.c, and stepcompress.c, but the resulting code will be a lot easier for developers to understand/review.
  • For what it is worth, when I last looked at this, one challenge I identified is that calls to toolhead.flush_step_generation() are expecting all the steps to be fully generated once the call completes. I didn’t look closely at your code, but it’s not immediately clear to me if this was addressed. I guess there may be an expectation that all callers will also call into the chelper code and thus block anyway, but it is not immediately clear to me if that is valid.

Again, just some high-level thoughts. I haven’t looked at this close enough to give any solid advice.

Cheers,
-Kevin

When I implemented reactor slow callback detection, it was done with the assumption that the flush advances every 50ms. Which it clearly does not do.
Basically, I’ve expected that 50ms blocking in flush time is 100% CPU usage, whereas with a 250ms flush interval it is actually about 20%.

The only known time-sensitive thing to me in the reactor is an output pin queue.
Where it seems to be normally flushed every 200- 250 ms, about 400 ms ahead.

@@ -30,6 +33,10 @@ class GCodeRequestQueue:
         rqueue = self.rqueue
         while rqueue:
             next_time = max(rqueue[0][0], self.next_min_flush_time)
+            now = self.printer.get_reactor().monotonic()
+            logging.info("Ept now %.3f, Next time %.3f, flush_time %.3f" % (
+                self.mcu.estimated_print_time(now), next_time,
+                must_flush_time))
             if next_time > must_flush_time:
                 return
             # Skip requests that have been overridden with a following request

With the following G-Code:

G4 P1000
M106 S1
G4 P300
M106 S2
G4 P300
M106 S3
G4 P300
M106 S0

Where, in the worst-case scenario, I guess, it can be flushed +199ms from “next_time”, so with only 400ms:

# Some lines are removed
Ept now 1.146, Next time 2.145, flush_time 1.546
Ept now 1.347, Next time 2.145, flush_time 1.747
Ept now 1.746, Next time 2.145, flush_time 2.146
Ept now 2.045, Next time 2.445, flush_time 2.445
Ept now 2.046, Next time 2.745, flush_time 2.445
# flush at +400ms from now, and next_time is +300ms from now 
Ept now 2.447, Next time 2.745, flush_time 2.847
Ept now 2.648, Next time 3.045, flush_time 3.048

So, with the current step generation, it can cause some issues.
If anything “blocks” for 300ms or so (step generation can basically block for 250ms at 100% CPU load).

So, from my PoV, it is cheaper for now to simply ensure that print time advances at smaller intervals, for example, at most by 125ms at one call, and if we are behind BGFLUSH_SG_HIGH_TIME, then simply do another flush of +125ms to catch up.

That should generally relieve the pressure and reduce the need for BG step generation threads.

Regards,
-Timofey

*Or, well, duct tape the next_time with something like:

max(next_time, self.mcu.estimated_print_time(now) + 0.300)

But it can desynchronize the queue from the motion, which seems to be unwanted behaviour.

**It seems that during the actual stepping, the timings are slightly different because the flush handler goes further in time from now, closer to BGFLUSH_SG_LOW_TIME = 0.450, so maybe it is fine actually

Thanks Kevin.

On whether it’s worth it, i think the lack of reports may not mean the problem is rare. On weaker hosts, users commonly lower microsteps up front to avoid any issues, or people building new machines pick a more powerful host than needed for the same reason. That said, I agree with you that significantly complicating the code without a clear, specific objective is not a good practice. But as I’ve already mentioned, the user can tailor the configuration to the power of their host, so we cannot have clear-cut statistics. In my defense, I should say that I am trying to implement this solution with minimal changes.

On flush_step_generation(), this is handled explicitly rather than by relying on callers to hit the C barrier. flush_all_steps() starts the batch and waits on the step generation completion. The reactor side of the batch, trapq_finalize_moves(), runs without pausing before the waiting greenlet is woken, so it is also done by the time flush_step_generation() returns.

On threads, the thread lives only in motion_queuing, but the design does leak a bit out of it. The toolhead has to wait for the batch before its with assert_no_pause() block, the reactor got a can_pause() helper, and chelper users depends on the wrapper.

On the wrapper, I agree it’s implicit and debatable. But with explicit locks at each Python call site, it’s just as easy to miss one, and that fails silently by corrupting state. So, in general, yes, without a Python wrapper it would be preferable to implement the locks directly in C, next to the state they protect. The C implementation looked more complex, I’m still not entirely sure how to approach it, so I started with the Python side first.

I’ve started thinking about how this could be done in C. steppersync.c already runs a thread per syncemitter and steppersyncmgr_gen_steps() just starts them and waits. That call could be split into start and finish, with Python waiting on a reactor completion signaled from C, and trapq, itersolve and stepcompress getting regular mutexes held only around their state changes. A query during a batch would then see the state as of that moment, which is fine for history queries into the past, and anything needing the final state already calls flush_step_generation(). I might have missed something, these are just some preliminary thoughts.

Thanks for the feedback.
-Maksim

Hi Maksim,

I think we’re “on the same page”.

I haven’t looked at it closely, but I’d probably try something like:

  • Add mutexes to struct trapq, struct stepcompress, and struct stepper_kinematics. Update the trapq_xxx(), stepcompress_xxx(), itersolve_xxx(), and similar C exported functions (those with a __visible tag) to take and release the appropriate mutex on each call.
  • Have itersolve_generate_steps() take the stepcompress, trapq, and stepper_kinematics locks at the start/end to reduce the amount of locking needed during bulk step generation.
  • Use a rwlock for struct trapq so that stepper step generation is parallelized.
  • Split steppersyncmgr_gen_steps() into two start/finalize calls as you suggested. I suspect it’s not necessary to wake the reactor on completion as the code could wait until the next flush to finalize the previous flush.

I suspect it’d be a lot of bulk changes, but none of the changes would be complicated. Ideally, the Python code wouldn’t need to know about the threads as any C calls would seamlessly take the appropriate locks. Unclear if it would all be worthwhile though.

Again, don’t take anything I say here too seriously; I haven’t looked at this closely.

Cheers,
-Kevin

EDIT: To be clear, the above wouldn’t improve worst case reactor latency, as nothing would stop a user from issuing a command (eg, GET_POSITION) that calls into C code which blocks on a mutex until step generation completes. At best, the changes would only improve typical core utilization on low-end multi-core CPUs. In general, “people building new machines pick a more powerful host than needed” is probably a safer option.. YMMV.

Thanks Kevin.

On the batch-wide locks, I looked at which C calls would hit them during a regular print, and I think they would help little with reactor latency. It’s not only manual commands like GET_POSITION. trapq_append() is called from the toolhead lookahead flush several times per second, steppersync_set_time() from stats() every second touches every stepcompress, and e.g. during printing there’s also extruder_set_pressure_advance() from lookahead callbacks (e.g. per feature PA), extruder.find_past_position() from filament_motion_sensor on its timer. These calls are effectively random relative to the batches, so with a batch taking a noticeable part of the flush interval, a good share of them would block the reactor until the batch ends.

Fine-grained locks held only around state changes would avoid that, and the CPU cost of the extra locking should be small. But the implementation gets more complex, trapq_append() has to work on the tail while generation iterates the list, readers see the state as of the moment of the call, parameter changes like pressure advance need either short locks on each read or deferral to the next batch, and finalize has to signal the reactor so flush_step_generation() can wait without blocking.

So my question is, would you support going in the direction of fine-grained locks, with the more complex implementation that comes with it, or should we stop here?

-Maksim

What are your thoughts on that trade-off? Do you have a better way to implement it that is less complex (and/or easier to understand)?

I’m not sure what the real-world benefits of further optimizing the host threads would be. In contrast, more complex code seems to have a more tangible cost. So, I guess all else being equal, I’d probably lean towards not complicating the code unless there was a well defined use case for it. To be sure though, I’m open to improvements in this area of the code.

Also, out of curiosity, is your main goal increasing processing capability on low-end cpus or is it reduced reactor latency?

Good points. FWIW, I’d be leery about adding nested locks to itersolve_generate_steps() - the inner loop of that code is invoked a lot - adding locks to it could risk increasing overall load.

An alternative might be: trapq_append() could append to a new upcoming list and trapq_check_sentinels() could be reworked to move the upcoming list into the main moves list; steppersync_set_time() could be called as part of batch flushing (as you indicated in your original post); extruder_set_pressure_advance() could also use an upcoming_pa_list vs regular pa_list; find_past_position could be parallelized by using reader-writer locks (only taking a write lock when the lists are modified in some way)..

None of these address the main performance/complexity trade-off. I’m just throwing out some high-level ideas - maybe they’ll inspire a new approach.

Maybe that helps a little,
-Kevin

Thinking about this further, I think this might be possible to do without fine grained locks.

Here’s what I was thinking:

  • Add simple coarse grained locking to struct itersolve:
    • Add a regular pthread_mutex_t lock to struct iterseolve and take the lock at the start of all exported functions, including ones exported from the kin_xxx.c code.
    • To avoid blocking on itersolve_get_commanded_pos(), avoid exporting that call to the python code and instead export a new syncemitter_get_last_commanded_pos(). The syncemitter code can store the last position after every flush and return that value - with no need to take the itersolve lock.
    • To avoid blocking in extruder_set_pressure_advance() the extruder.py code can register a motion_queuing flush callback and batch up PA changes to that callback. (Thus, the itersolve lock gets taken but only after each step generation pass is complete.)
    • To avoid confusion, remove struct trapq *tq from struct itersolve and have syncemitter pass the tq->moves list directly to itersolve_generate_steps().
  • Split out message generation and history tracking from struct stepcompress and avoid locking in struct stepcompress:
    • Rename struct history_steps to struct steps and change the main stepcompress add_move() to generate a list of struct steps instead of a list of struct queue_message. On each flush, the syncemitter code can generate the list of struct queue_message from the list of struct steps. Similarly, the syncemitter code can add that list to its own history list stored in struct syncemitter. The syncemitter lock can thus be used to protect the step history list and message generation variables (eg, oid, queue_step_msgtag, set_next_step_dir_msgtag, invert_sdir).
    • After these changes, it shouldn’t be necessary for the stepcompress code to directly export any python functions. Any remaining calls (eg, stepcompress_reset()) can be invoked via syncemitter (eg, syncemitter_step_reset()). These calls can then be protected with the syncemitter locking.

Thoughts?
-Kevin

Mainly reduced reactor latency. Better core utilization on low-end CPUs is a nice side effect, but the original issue was the reactor being stalled for the duration of each batch.

Fine-grained locks are hard to get right and to review, but stalling the reactor for the whole batch isn’t great either. Your approach in the next post looks like a good middle ground, since state is handed over at batch boundaries instead of being locked. Being less familiar with this code, I was mostly looking at it from the locking side.

I like this direction, it removes most of the calls I listed from the batch path. A few things I noticed.

I think this should be part of it too. Both the append and the move into the main list at batch start happen in the reactor thread, so this wouldn’t need a lock at all. Generation and trapq_extract_old() only read the main list, and trapq_finalize_moves() runs after the batch.

Currently se_background_thread() holds se->lock for the whole se_generate_steps(), so find_past_position() would still wait for the batch. If the history list is only updated during finalize in the reactor thread, readers wouldn’t need a lock, otherwise it would need a separate lock. This also moves message generation into the reactor thread, though that should be cheap. Not sure.

I didn’t explain this very clearly in my previous post, so I’ll repeat. For the background flush that works, but an explicit flush_step_generation() during a batch, e.g. PA smooth time change, ACTIVATE_EXTRUDER, etc., would block on finalize. A completion signaled from C (eventfd registered with the reactor, or a short poll) would let it wait without blocking.

I’ll try to work on an test implementation this week, more issues will probably come up along the way.

-Maksim

Agreed.

Wiring up a signal to the reactor for the completion notice seems complicated to me. An alternative would be to introduce a steppersyncmgr_try_finalize() and have motion_queuing.flush_all_steps() call this in a loop with a pause(curtime+0.001) on each busy notification. That is, full flushes are rare, so it’s not necessary to optimize them.

That said, I did gloss over a notable issue - it’s fine to wait until the next batch to “finalize” the previous batch, but it is not okay to wait before sorting the messages and sending them to the C serialqueue code. A reactor notification could help with this, as a notification could be used to wake the python code so it can call back into the C code to invoke the message sorting/transmit. However, I don’t think that’s a great solution because we really want the messages to be sent to the serialqueue code without further help from the Python code. An alternative would be for a new thread in steppersync.c that can wait for a batch to complete, generate all the messages, sort them, and transmit them. Alas, more complexity.

Cheers,
-Kevin

I slightly underestimated the amount of work, but in the end, it’s finished. I put together a new test implementation based on outline from the last posts GitHub - MRX8024/klipper at work-nonblock-stepgen-20261127 · GitHub . Most of it follows the “plan”, but a few things came out differently, so I’ll go through those.

Instead of a separate thread I tried another option that seemed more interesting to me, and implemented that for now. Each steppersync counts its pending syncemitters, and the last syncemitter thread to finish on an mcu sorts and sends the messages for that mcu. There is no extra thread or wakeup, and each mcu is sent as soon as its own steppers are done. What do you think about this compared to a dedicated thread? Python uses steppersyncmgr_start_gen_steps(), steppersyncmgr_is_busy() and steppersyncmgr_finalize(). The previous pass is finalized at the next flush, in flush_all_steps(), and also in wipe_trapq(), since a drip move wipes the trapq while its last pass can still be running.

Since tq moved to the syncemitter, set_trapq, get_trapq and check_active became syncemitter_xxx(). I also added syncemitter_set_position(), so the stored commanded position is updated on set_position(), not only after the next flush (otherwise get_commanded_position() would return a stale value until the next pass). steppersync_set_time() is applied from python at the start of each flush, as suggested. The syncemitter tracks the direction as sent to the mcu (dir ^ invert_sdir), so set_next_step_dir is now queued together with the next queue_step and can go out one flush later than before (the order relative to the same stepper’s queue_step unchanged).

There are some things I’m not sure about. flush_all_steps() can run under assert_no_pause(), via klippy:ready → idex apply_transform → input_shaper → flush_step_generation(). So I added reactor.can_pause() and block there instead of pausing. Is that ok, or is there a better way?

The mcu disconnect handler also frees the serialqueue before motion_queuing gets to wait for the last pass. For now motion_queuing holds a reference to the serialqueues until its own disconnect. Maybe mcu._disconnect() should instead detach the movequeue first, mirroring setup_mcu_movequeue()?

Since finalize moved to the next flush, a stepcompress error is noticed later than before. The thread that fails logs the error right away and skips sending the messages for its mcu, but the shutdown only happens on the next finalize. For the last pass after the motion stops there may be no next flush for a long time, so the end of the move would be silently dropped without a shutdown. I think the flush timer can finalize the pending pass before it goes idle, which would cover this case, throughts?

Another question is kin_shaper and kin_idex, generation only takes the outer sk lock, so changes to orig_sk rely on a full flush before them, which is how all callers work today. Should the wrappers share the lock instead?

I ran various tests in the klippy test suite and on my printer, and the step output per oid matches master. Flush now blocks the reactor for about 1-1.5ms on average.

I only described the changes briefly here, so if you have questions about any specific decisions I’ll be happy to answer them.

-Maksim

EDIT: I split your suggested steppersyncmgr_try_finalize() into steppersyncmgr_is_busy() and steppersyncmgr_finalize(). A single call would have to return both the busy state and the failed syncemitter, which needs an out parameter through cffi, and a blocking wait is needed anyway where pausing isn’t allowed and on disconnect. So python polls is_busy() with a short pause, and finalize() waits for the pass and returns the failed syncemitter, if any.

Thanks for working on this.

I took a brief look through your code. I also tried a few different approaches on my side. (I tried moving syncemitter out of steppersync.c; I tried splitting itersolve code from the stepper kinematics code; and similar.) In my attempts, I wasn’t confident that the resulting code would be worthwhile.

I guess my high-level feedback from my brief review of your code is that I’m not sure about the maintenance costs. There does seem to be a measurable improvement in the latency, but it also seems like there is a notable increase in complexity.

There were a few things I noticed looking at the code. I have a few notes below. Don’t take these comments too seriously though, as I’m not sure they would alter the high-level trade-offs.

What prevents trapq_set_position() from being called (and altering the trapq->moves list) while step generation is occurring? Granted, that shouldn’t occur in practice, but sporadic segfaults would be difficult to diagnose if someone did make that python coding error.

I’m no longer confident that the extruder can push off pressure advance updates to a flush callback because the toolhead.register_lookahead_callback() itself may have been invoked from a flush callback and there’d be no assured ordering between the toolhead flush callback and the extruder flush callback. Sorry for suggesting that approach.

That’s fine in general, however I’m not sure how that would handle the pwm_tool case (as pwm_tool doesn’t allocate a step generation thread). I also wonder if creating a thread would be simpler, as it is only a few lines of code to create a thread.

That sounds like idex_modes.py should be using a reactor callback so apply_transform() can pause. (The “klippy:ready” event is only intended as an “atomic notification” of startup - none of the individual callbacks should be doing any significant work.)

FWIW, I’d be leery of adding a reactor.can_pause() because I fear it may encourage “papering over real bugs”.

I’m not understanding what you are suggesting here. I agree that order of free’ing can be an issue and we would need to make sure it is stable.

That makes sense to me.

That’s an interesting point I had not considered. I’m not sure how to handle that one. In a local branch I tried separating out the itersolve code from the stepper_kinematics code, however that turned out to be a little challenging because kin_polar wants access to commanded_pos and that variable is tied to the iterative solver.

So, I guess I’m not sure what to do for kin_shaper and kin_idex.

Anyway, in conclusion, I think your work is interesting, but I guess I’m still not sure about the trade-offs. Maybe give a few days to see if any alternative “locking” ideas arise or if there are further ideas on how the code can be structured. I’ll also try to see if I can mock up some possibilities.

Thanks again,
-Kevin

Ah, I truly overlooked that. Yes, this could lead to problems if someone were to make an incorrect call in Python.

I think the ordering is covered by can_add_trapq. The toolhead registers its flush callback with can_add_trapq=True, which puts it at the front of the list, so a lookahead flush and the lookahead callbacks it triggers always run before the extruder callback in the same pass. If a lookahead callback fires outside a flush, its PA update is applied at the next pass together with the moves it belongs to. Unless I’m missing some path, the order is assured.

On mcus without step generation the messages are sent directly from steppersyncmgr_start_gen_steps(), and on mcus with steppers the pwm_tool messages are sorted together with the steps by the last finishing thread. A dedicated thread is about the same size by my estimate, but needs no special case, so perhaps that would have been a bit simpler option.

Agreed.

I meant that mcu._disconnect() could detach the steppersync from its serialqueue before freeing it, e.g. steppersync_setup_movequeue(ss, NULL, 0), which would first wait for an in-flight pass. Then motion_queuing wouldn’t need to hold references to the serialqueues, and the free order is fixed in one place.

About the complexity, I’ve given some thought to how the code might be reduced, though that might not significantly decrease its overall complexity. I think most of the locking can be replaced based on one observation. Everything that changes the C state is called from the reactor thread, and a pass is also only started from the reactor thread. So if each exported function that modifies state used by step generation first waits for the in-flight pass to complete (e.g. stepgen_wait_idle()), no new pass can start until it returns, which is equivalent to holding all the sk, sc and trapq locks at once. In normal operation these calls already happen after flush_step_generation() and the wait returns immediately, while a python error like trapq_set_position() during a pass would wait instead of corrupting the lists. The wrapped orig_sk (kin_shaper, kin_idex) is covered as well, since the barrier isn’t tied to an object.

Only a few calls have to work during a pass without waiting. trapq_append() uses the upcoming list, steppersync_set_time() is applied at the start of a flush, PA changes go through the flush callback, find_past_position() and extract_old() would take a small lock on the stepcompress history list (taken once per queue_step in add_move(), not in the itersolve loop), and syncemitter_queue_msg() would take se->lock. Everything else, like GET_POSITION, homing or kinematic setters, may block until the pass completes.

With a dedicated sender thread, stepcompress, itersolve and the kinematics could then stay as in master apart from the barrier call and the history lock, and the sk lock, the trapq move and the message generation split would be dropped.

The main difference from your outline is that the barrier is global (a static in steppersync.c, as there is a single steppersyncmgr) rather than a lock per object.

Thoughts?

Thanks for the quick review,
-Maksim

Ah, okay. I was thinking there could be an issue if the flush callback itself was registered from the PA request, but I see now that you are registering the flush callback in advance. Thanks for clarifying.

I don’t have a preference (or at least not one right now) - motion_queing can hold a reference to the serialqueue objects, or mcu can call a new motion_queuing.finalize_mcu_movequeue() before it drops its reference to the serialqueue.

I think I understand what you are proposing. However, the result seems surprisingly similar to a mutex. I think it would be more apparent to use a standard mutex than to create a custom kind of mutex. That is, instead of stepgen_wait_idle() one could wrap the exported functions in pthread_mutex_lock(&my_global_step_gen_lock) and the latter may be more recognizable to other developers.

I guess a single static global mutex could work, but it might not be ideal during software RESTART commands.

Along the same lines though, as a thought experiment, what about something like the following as a series of independent commits (relative to current master):

  1. Add xxx_start_stepgen() and xxx_finalize_stepgen() to trapq, stepper_kinematics, and stepcompress objects. Have steppersyncmgr call all the xxx_start_stepgen() from the main thread, prior to launching any background threads. Arrange for xxx_finalize_stepgen() to be called after the step generation is fully complete on all mcus. The stepper_kinematics would use function pointers so notification can be propagated to embedded instances.
  2. Add a pthread_rwlock_t to trapq and implement the invariant that anything that reads/modifies data in the trapq takes the appropriate lock. The trapq_start_stepgen() call would take a read lock and subsequent itersolve calls wouldnn’t need to take the lock.
  3. Add a pthread_mutex_t to stepcompress and implement the invariant that any code that accesses the struct would take the lock first. The stepcompress_start_stepgen() would take the lock and susequent iterative solver code would not need to take the lock.
  4. Similarly, add a mutex and invariant to the stepper_kinematics code.
  5. Modify steppersyncmgr to start the step generation threads, but not wait for them to complete. A background thread (existing or new) will run the full set of xxx_finalize_stepgen() calls after all step generation is fully complete. Update motion_queing.flush_all_steps() to call a new C function to ensure steps are finished before it completes (eg, steppersyncmgr_wait_busy()). So, the goal is for the python code to be able to run in parallel, but anything calling the C functions will block until the step generation is fully complete on all mcus (and toolhead.flush_step_generation() similarly blocks).
  6. Modify the trapq to support a new “upcoming” list that would not be covered by its rwlock. Change trapq_start_stepgen() to move that “upcoming” list to the main moves list. The goal would be to allow trapq adds without blocking.
  7. Modify the extruder code to avoid blocking on pressure advance updates (as previously discussed).
  8. Modify the stepcompress object to move its sc->history_list outside of its main lock - stepcompress.c:add_move() would instead add to a new “upcoming_history_list” which would be moved to the main “history_list” upon stepcompress_finalize_stepgen().
  9. Identify python code that calls stepper.get_commanded_position() (eg, GET_POSITION, motion_report) and convert them to use stepper.get_past_position() and/or call some kind of new motion_queuing.wait_step_generation() first.

Again, this is just a “thought experiment”. I wouldn’t spend time on it other than to consider the approach. Basically, add a bunch of locking calls, but keep those locks “boilerplate” and simple to validate. Ideally, commit in a way that first adds very simple locking and then go one-by-one to identify places that need more advanced locking.

Thoughts? I’m very likely missing something, but maybe it will raise some new ideas.
-Kevin