Re: C++ in kernel (was Re: exception in a device driver)

Chip Salzenberg (chip@perlsupport.com)
Sat, 16 Jan 1999 03:21:19 -0500


According to Alexander Viro:
> Example I gave was pretty typical for fs/inode.c, BTW. Would you
> care to show me how to rearrange the code in it so that lexical
> scopes would become compatible with the lock-holding ones?

Sure. BTW, the first line of your example:

if (!wee) unlock(&hop);

doesn't require any translation -- it's not cleanup, it's
initialization.

This template takes care of semaphores that may or may not require
release at cleanup time:

template<semaphore_t *SEM>
class cond_hold {
public:
cond_hold() : _have(false) { take(); }
cond_hold(bool now =true) : _have(false) { if (now) take(); }
~cond_hold() { release(); }

take() { if (!_have) { down(SEM); _have = true; }
release() { if (_have) { up(SEM); _have = false; }

private:
bool _have;
};

This template takes care of conditional release of a template
that we did not acquire in the same block of code:

template<semaphore_t *SEM, const bool &COND>
class pending_release_if {
public:
~pending_release_if() { if (COND) up(SEM); }
};

Now, on to the code:

cond_hold<&foo> fooh; // lock(&foo);
while(bar()) {
if (baz()<0) {
pending_release_if<&hop, wee> hoppy; // assuming wee is a bool
// if (wee) unlock(&hop);
barf();
return;
}
fooh.release(); // unlock(&foo);
quux();
fooh.take(); // lock(&foo);
fred();
}
barf();

The pattern is simple to follow: Just make sure that every time you
_commit_ to something happening ("in the if, I *commit* to release &hop
if wee is true before returning"), I create an object whose destruction
will fulfill that commitment.

> Moreover, I'd like to the *code* (for ELF, say it on x86) that would
> result of said thing. Preferably with exception-related pieces
> marked as such in the listing. Do it for the example you've snipped, OK?

IIRC, the details of the ELF exception support aren't all that magic;
they're just tables of which objects are in scope during which basic
blocks in each function. Exception code uses those tables. (The
tables are heavily compressed, as a quality of implementation issue.)

ELF the object format is involved because it makes possible the
creation of a readonly section just for exception info; applications
benefit by preserving locality of reference for non-exception code.
At least, that's how I remember it.

Given this explanation, if you still want me to dig deeper, I will.

-- 
Chip Salzenberg      - a.k.a. -      <chip@perlsupport.com>
      "When do you work?"   "Whenever I'm not busy."

- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.rutgers.edu Please read the FAQ at http://www.tux.org/lkml/