MP_STATE_PORT macro

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
astrorafael
Posts: 6
Joined: Mon Feb 15, 2021 10:09 am

MP_STATE_PORT macro

Post by astrorafael » Wed Feb 17, 2021 12:52 pm

I was examining the machine_pin.c file. and have seen tons of references in the code the MP_STATE_PORT(x) macro which seems to be associated with "irq objects". i.e.:

Code: Select all

machine_pin_irq_obj_t *irq = MP_STATE_PORT(machine_pin_irq_obj[self->id]);
I would like to know what its purpose is. I've tried to imitate its use it, bit it gives me compilation errors.

Other question related to machine_pin_irq_obj is that apparently this is an array, declared with

Code: Select all

STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_pin_irq_obj, 1, machine_pin_irq);
zeroed with

Code: Select all

memset(MP_STATE_PORT(machine_pin_irq_obj), 0, sizeof(MP_STATE_PORT(machine_pin_irq_obj)));
but I can't see its size, which I suppose is NUM_BANK0_GPIOS

I have a working version of machine_rtc.c without interrupts. It could be used with busy loops or asyncio using polling with RTC.alarm_left(). If you find it useful as is, I could issue a pull request.

User avatar
jimmo
Posts: 2244
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: MP_STATE_PORT macro

Post by jimmo » Thu Feb 18, 2021 12:41 am

astrorafael wrote:
Wed Feb 17, 2021 12:52 pm
I was examining the machine_pin.c file. and have seen tons of references in the code the MP_STATE_PORT(x) macro which seems to be associated with "irq objects". i.e.:
I think in all cases, MP_STATE_PORT(x) is an alias for MP_STATE_VM(x)

So really the question is, what is MP_STATE_VM.

The answer to that is that it's a convenient way of accessing the members of the global mp_state_vm_t struct (which is the entire VM state).

Essentially, MicroPython has a global variable "mp_state_ctx" (defined in py/mpstate.c) which contains the mp_state_vm_t instance.

So you will see this all through the codebase to access various objects that are part of the VM state.

But in this particular case, another thing that's part of the VM state is any "root pointers" that are defined by the port (defined in MICROPY_PORT_ROOT_POINTERS). These are important because the port may have additional objects that need to be tracked by the garbage collector.

So typically, MP_STATE_PORT is used to access port-specific root pointers (i.e. things that are both global state, but also GC root pointers).

In this case, the irq objects need to be root pointers because they contain pointers to python functions.

astrorafael
Posts: 6
Joined: Mon Feb 15, 2021 10:09 am

Re: MP_STATE_PORT macro

Post by astrorafael » Thu Feb 18, 2021 2:55 pm

Ok, thanks ! Very helpful explanation.

Post Reply