Home | History | Annotate | Line # | Download | only in dev
midictl.c revision 1.6.32.2
      1 /* $NetBSD: midictl.c,v 1.6.32.2 2011/11/22 06:11:12 mrg Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 2006, 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Chapman Flack, and by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 #include <sys/cdefs.h>
     32 __KERNEL_RCSID(0, "$NetBSD: midictl.c,v 1.6.32.2 2011/11/22 06:11:12 mrg Exp $");
     33 
     34 /*
     35  * See midictl.h for an overview of the purpose and use of this module.
     36  */
     37 
     38 #include <sys/systm.h>
     39 #include <sys/types.h>
     40 #include <sys/param.h>
     41 #include <sys/kernel.h>
     42 #include <sys/kthread.h>
     43 #include <sys/kmem.h>
     44 
     45 #include "midictl.h"
     46 
     47 /*
     48  * The upper part of this file is MIDI-aware, and deals with things like
     49  * decoding MIDI Control Change messages, dealing with the ones that require
     50  * special handling as mode messages or parameter updates, and so on.
     51  *
     52  * It relies on a "store" layer (implemented in the lower part of this file)
     53  * that only must be able to stash away 2-, 8-, or 16-bit quantities (which
     54  * it may pack into larger units as it sees fit) and find them again given
     55  * a class, channel, and key (controller/parameter number).
     56  *
     57  * The MIDI controllers can have 1-, 7-, or 14-bit values; the parameters are
     58  * also 14-bit. The 14-bit values have to be set in two MIDI messages, 7 bits
     59  * at a time. The MIDI layer uses store-managed 2- or 8-bit slots for the
     60  * smaller types, and uses the free high bit to indicate that it has explicitly
     61  * set the value. (Because the store is allowed to pack things, it may 'find'
     62  * a zero entry for a value we never set, because it shares a word with a
     63  * different value that has been set. We know it is not a real value because
     64  * the high bit is clear.)
     65  *
     66  * The 14-bit values are handled similarly: 16-bit store slots are used to hold
     67  * them, with the two free high bits indicating independently whether the MSB
     68  * and the LSB have been explicitly set--as two separate MIDI messages are
     69  * required. If such a control is queried when only one half has been explicitly
     70  * set, the result is as if it had been set to the specified default value
     71  * before the explicit set.
     72  */
     73 
     74 typedef enum { CTL1, CTL7, CTL14, RPN, NRPN } class;
     75 
     76 /*
     77  * assert(does_not_apply(KNFNamespaceArgumentAgainstNamesInPrototypes,
     78  *    PrototypesOfStaticFunctionsWithinNonIncludedFile));
     79  */
     80 static void reset_all_controllers(midictl *mc, uint_fast8_t chan);
     81 static void enter14(midictl *mc, uint_fast8_t chan, class c,
     82                     uint_fast16_t key, _Bool islsb, uint8_t val);
     83 static uint_fast16_t read14(midictl *mc, uint_fast8_t chan, class c,
     84                             uint_fast16_t key, uint_fast16_t dflt);
     85 static class classify(uint_fast16_t *key, _Bool *islsb);
     86 static midictl_notify notify_no_one;
     87 
     88 static _Bool store_locate(midictl_store *s, class c,
     89                             uint_fast8_t chan, uint_fast16_t key);
     90 /*
     91  * store_extract and store_update operate on the bucket most recently found
     92  * by store_locate on this store. That works because reentrancy of midictl
     93  * functions is limited: they /can/ be reentered during midictl_notify
     94  * callbacks, but not at other arbitrary times. We never call notify /during/
     95  * a locate/extract/update transaction.
     96  */
     97 static uint16_t store_extract(midictl_store *s, class c,
     98                               uint_fast8_t chan, uint_fast16_t key);
     99 static void store_update(midictl_store *s, class c,
    100                          uint_fast8_t chan, uint_fast16_t key, uint16_t value);
    101 
    102 #define PN_SET 0x8000  /* a parameter number has been explicitly set */
    103 #define C14MSET 0x8000 /* MSB of a 14-bit val has been set */
    104 #define C14LSET 0x4000 /* LSB of a 14-bit val has been set */
    105 #define C7_SET 0x80    /* a 7-bit ctl has been set */
    106 #define C1_SET 2       /* a 1-bit ctl has been set */
    107 
    108 /*
    109  *   I M P L E M E N T A T I O N     O F     T H E     S T O R E :
    110  *
    111  * MIDI defines a metric plethora of possible controllers, registered
    112  * parameters, and nonregistered parameters: a bit more than 32k possible words
    113  * to store. The saving grace is that only a handful are likely to appear in
    114  * typical MIDI data, and only a handful are likely implemented by or
    115  * interesting to a typical client. So the store implementation needs to be
    116  * suited to a largish but quite sparse data set.
    117  *
    118  * A double-hashed, open address table is used here. Each slot is a uint64
    119  * that contains the match key (control class|channel|ctl-or-PN-number) as
    120  * well as the values for two or more channels. CTL14s, RPNs, and NRPNs can
    121  * be packed two channels to the slot; CTL7s, six channels; and CTL1s get all
    122  * 16 channels into one slot. The channel value used in the key is the lowest
    123  * channel stored in the slot. Open addressing is appropriate here because the
    124  * link fields in a chained approach would be at least 100% overhead, and also,
    125  * we don't delete (MIDICTL_RESET is the only event that logically deletes
    126  * things, and at the moment it does not remove anything from the table, but
    127  * zeroes the stored value). If wanted, the deletion algorithm for open
    128  * addressing could be used, with shrinking/rehashing when the load factor
    129  * drops below 3/8 (1/2 is the current threshold for expansion), and the
    130  * rehashing would relieve the fills-with-DELETED problem in most cases. But
    131  * for now the table never shrinks while the device is open.
    132  */
    133 
    134 struct midictl_store {
    135 	uint64_t *table;
    136 	uint64_t key;
    137 	uint32_t idx;
    138 	uint32_t lgcapacity;
    139 	uint32_t used;
    140 	kcondvar_t cv;
    141 	kmutex_t *lock;
    142 	bool destroy;
    143 };
    144 
    145 #define INITIALLGCAPACITY 6 /* initial capacity 1<<6 */
    146 #define IS_USED 1<<15
    147 #define IS_CTL7 1<<14
    148 
    149 #define CTL1SHIFT(chan) (23+((chan)<<1))
    150 #define CTL7SHIFT(chan) (16+((chan)<<3))
    151 #define CTLESHIFT(chan) (23+((chan)<<4))
    152 
    153 #define	NEED_REHASH(s)	((s)->used * 2 >= 1 << (s)->lgcapacity)
    154 
    155 static uint_fast8_t const packing[] = {
    156 	[CTL1 ] = 16, /* 16 * 2 bits ==> 32 bits, all chns in one bucket */
    157 	[CTL7 ] =  6, /*  6 * 8 bits ==> 48 bits, 6 chns in one bucket */
    158 	[CTL14] =  2, /*  2 *16 bits ==> 32 bits, 2 chns in one bucket */
    159 	[RPN  ] =  2,
    160 	[NRPN ] =  2
    161 };
    162 
    163 static uint32_t store_idx(uint32_t lgcapacity,
    164 			  uint64_t *table,
    165                           uint64_t key, uint64_t mask);
    166 static void store_rehash(midictl_store *s);
    167 static void store_thread(void *);
    168 
    169 int
    170 midictl_open(midictl *mc)
    171 {
    172 	midictl_store *s;
    173 	int error;
    174 
    175 	if (mc->lock == NULL)
    176 		panic("midictl_open: no lock");
    177 	if (NULL == mc->notify)
    178 		mc->notify = notify_no_one;
    179 	s = kmem_zalloc(sizeof(*s), KM_SLEEP);
    180 	if (s == NULL) {
    181 		return ENOMEM;
    182 	}
    183 	s->lgcapacity = INITIALLGCAPACITY;
    184 	s->table = kmem_zalloc(sizeof(*s->table)<<s->lgcapacity, KM_SLEEP);
    185 	if (s->table == NULL) {
    186 		kmem_free(s->table, sizeof(*s->table)<<s->lgcapacity);
    187 		kmem_free(s, sizeof(*s));
    188 		return ENOMEM;
    189 	}
    190 	s->lock = mc->lock;
    191 	cv_init(&s->cv, "midictl");
    192 	error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL, store_thread,
    193 	    s, NULL, "midictl");
    194 	if (error != 0) {
    195 		printf("midictl: cannot create kthread, error = %d\n", error);
    196 		cv_destroy(&s->cv);
    197 		kmem_free(s->table, sizeof(*s->table)<<s->lgcapacity);
    198 		kmem_free(s, sizeof(*s));
    199 		return error;
    200 	}
    201 	mc->store = s;
    202 	return 0;
    203 }
    204 
    205 void
    206 midictl_close(midictl *mc)
    207 {
    208 	midictl_store *s;
    209 	kmutex_t *lock;
    210 
    211 	s = mc->store;
    212 	lock = s->lock;
    213 
    214 	mutex_enter(lock);
    215 	s->destroy = true;
    216 	cv_broadcast(&s->cv);
    217 	mutex_exit(lock);
    218 }
    219 
    220 void
    221 midictl_change(midictl *mc, uint_fast8_t chan, uint8_t *ctlval)
    222 {
    223 	class c;
    224 	uint_fast16_t key, val;
    225 	_Bool islsb, present;
    226 
    227 	KASSERT(mutex_owned(mc->lock));
    228 
    229 	switch ( ctlval[0] ) {
    230 	/*
    231 	 * Channel mode messages:
    232 	 */
    233 	case MIDI_CTRL_OMNI_OFF:
    234 	case MIDI_CTRL_OMNI_ON:
    235 	case MIDI_CTRL_POLY_OFF:
    236 	case MIDI_CTRL_POLY_ON:
    237 		if ( chan != mc->base_channel )
    238 			return; /* ignored - not on base channel */
    239 		else
    240 			return; /* XXX ignored anyway - not implemented yet */
    241 	case MIDI_CTRL_NOTES_OFF:
    242 		mc->notify(mc->cookie, MIDICTL_NOTES_OFF, chan, 0);
    243 		return;
    244 	case MIDI_CTRL_LOCAL:
    245 		mc->notify(mc->cookie, MIDICTL_LOCAL, chan, ctlval[1]);
    246 		return;
    247 	case MIDI_CTRL_SOUND_OFF:
    248 		mc->notify(mc->cookie, MIDICTL_SOUND_OFF, chan, 0);
    249 		return;
    250 	case MIDI_CTRL_RESET:
    251 		reset_all_controllers(mc, chan);
    252 		return;
    253 	/*
    254 	 * Control changes to be handled specially:
    255 	 */
    256 	case MIDI_CTRL_RPN_LSB:
    257 		mc-> rpn &= ~0x7f;
    258 		mc-> rpn |=  PN_SET | (0x7f & ctlval[1]);
    259 		mc->nrpn &= ~PN_SET;
    260 		return;
    261 	case MIDI_CTRL_RPN_MSB:
    262 		mc-> rpn &= ~0x7f<<7;
    263 		mc-> rpn |=  PN_SET | (0x7f & ctlval[1])<<7;
    264 		mc->nrpn &= ~PN_SET;
    265 		return;
    266 	case MIDI_CTRL_NRPN_LSB:
    267 		mc->nrpn &= ~0x7f;
    268 		mc->nrpn |=  PN_SET | (0x7f & ctlval[1]);
    269 		mc-> rpn &= ~PN_SET;
    270 		return;
    271 	case MIDI_CTRL_NRPN_MSB:
    272 		mc->nrpn &= ~0x7f<<7;
    273 		mc->nrpn |=  PN_SET | (0x7f & ctlval[1])<<7;
    274 		mc-> rpn &= ~PN_SET;
    275 		return;
    276 	case MIDI_CTRL_DATA_ENTRY_LSB:
    277 		islsb = 1;
    278 		goto whichparm;
    279 	case MIDI_CTRL_DATA_ENTRY_MSB:
    280 		islsb = 0;
    281 	whichparm:
    282 		if ( 0 == ( (mc->rpn ^ mc->nrpn) & PN_SET ) )
    283 			return; /* exactly one must be current */
    284 		if ( mc->rpn & PN_SET ) {
    285 			key = mc->rpn;
    286 			c = RPN;
    287 		} else {
    288 			key = mc->nrpn;
    289 			c = NRPN;
    290 		}
    291 		key &= 0x3fff;
    292 		if ( 0x3fff == key ) /* 'null' parm# to lock out changes */
    293 			return;
    294 		enter14(mc, chan, c, key, islsb, ctlval[1]);
    295 		return;
    296 	case MIDI_CTRL_RPN_INCREMENT: /* XXX for later - these are a PITA to */
    297 	case MIDI_CTRL_RPN_DECREMENT: /* get right - 'right' varies by param */
    298 			/* see http://www.midi.org/about-midi/rp18.shtml */
    299 		return;
    300 	}
    301 
    302 	/*
    303 	 * Channel mode, RPN, and NRPN operations have been ruled out.
    304 	 * This is an ordinary control change.
    305 	 */
    306 
    307 	key = ctlval[0];
    308 	c = classify(&key, &islsb);
    309 
    310 	switch ( c ) {
    311 	case CTL14:
    312 		enter14(mc, chan, c, key, islsb, ctlval[1]);
    313 		return;
    314 	case CTL7:
    315 		present = store_locate(mc->store, c, chan, key);
    316 		if ( !mc->accept_any_ctl_rpn ) {
    317 			if ( !present )
    318 				break;
    319 			val = store_extract(mc->store, c, chan, key);
    320 			if ( !(val&C7_SET) )
    321 				break;
    322 		}
    323 		store_update(mc->store, c, chan, key,
    324 		    C7_SET | (0x7f & ctlval[1]));
    325 		mc->notify(mc->cookie, MIDICTL_CTLR, chan, key);
    326 		return;
    327 	case CTL1:
    328 		present = store_locate(mc->store, c, chan, key);
    329 		if ( !mc->accept_any_ctl_rpn ) {
    330 			if ( !present )
    331 				break;
    332 			val = store_extract(mc->store, c, chan, key);
    333 			if ( !(val&C1_SET) )
    334 				break;
    335 		}
    336 		store_update(mc->store, c, chan, key,
    337 		    C1_SET | (ctlval[1]>63));
    338 		mc->notify(mc->cookie, MIDICTL_CTLR, chan, key);
    339 		return;
    340 	case RPN:
    341 	case NRPN:
    342 		return; /* won't see these - sop for gcc */
    343 	}
    344 }
    345 
    346 uint_fast16_t
    347 midictl_read(midictl *mc, uint_fast8_t chan, uint_fast8_t ctlr,
    348              uint_fast16_t dflt)
    349 {
    350 	uint_fast16_t key, val;
    351 	class c;
    352 	_Bool islsb, present;
    353 
    354 	KASSERT(mutex_owned(mc->lock));
    355 
    356 	key = ctlr;
    357 	c = classify(&key, &islsb);
    358 	switch ( c ) {
    359 	case CTL1:
    360 		present = store_locate(mc->store, c, chan, key);
    361 		if ( !present ||
    362 		    !(C1_SET&(val = store_extract(mc->store, c, chan, key))) ) {
    363 			val = C1_SET | (dflt > 63); /* convert to boolean */
    364 			store_update(mc->store, c, chan, key, val);
    365 		}
    366 		return (val & 1) ? 127 : 0;
    367 	case CTL7:
    368 		present = store_locate(mc->store, c, chan, key);
    369 		if ( !present ||
    370 		    !(C7_SET&(val = store_extract(mc->store, c, chan, key))) ) {
    371 			val = C7_SET | (dflt & 0x7f);
    372 			store_update(mc->store, c, chan, key, val);
    373 		}
    374 		return val & 0x7f;
    375 	case CTL14:
    376 		KASSERT(!islsb);
    377 		return read14(mc, chan, c, key, dflt);
    378 	case RPN:
    379 	case NRPN:
    380 		break; /* sop for gcc */
    381 	}
    382 	return 0; /* sop for gcc */
    383 }
    384 
    385 uint_fast16_t
    386 midictl_rpn_read(midictl *mc, uint_fast8_t chan, uint_fast16_t ctlr,
    387                  uint_fast16_t dflt)
    388 {
    389 
    390 	KASSERT(mutex_owned(mc->lock));
    391 
    392 	return read14(mc, chan, RPN, ctlr, dflt);
    393 }
    394 
    395 uint_fast16_t
    396 midictl_nrpn_read(midictl *mc, uint_fast8_t chan, uint_fast16_t ctlr,
    397                   uint_fast16_t dflt)
    398 {
    399 
    400 	KASSERT(mutex_owned(mc->lock));
    401 
    402 	return read14(mc, chan, NRPN, ctlr, dflt);
    403 }
    404 
    405 static void
    406 reset_all_controllers(midictl *mc, uint_fast8_t chan)
    407 {
    408 	uint_fast16_t ctlr, key;
    409 	class c;
    410 	_Bool islsb, present;
    411 
    412 	KASSERT(mutex_owned(mc->lock));
    413 
    414 	for ( ctlr = 0 ; ; ++ ctlr ) {
    415 		switch ( ctlr ) {
    416 		/*
    417 		 * exempt by http://www.midi.org/about-midi/rp15.shtml:
    418 		 */
    419 		case MIDI_CTRL_BANK_SELECT_MSB:		/* 0 */
    420 		case MIDI_CTRL_CHANNEL_VOLUME_MSB:	/* 7 */
    421 		case MIDI_CTRL_PAN_MSB:			/* 10 */
    422 			continue;
    423 		case MIDI_CTRL_BANK_SELECT_LSB:		/* 32 */
    424 			ctlr += 31; /* skip all these LSBs anyway */
    425 			continue;
    426 		case MIDI_CTRL_SOUND_VARIATION:		/* 70 */
    427 			ctlr += 9; /* skip all Sound Controllers */
    428 			continue;
    429 		case MIDI_CTRL_EFFECT_DEPTH_1:		/* 91 */
    430 			goto loop_exit; /* nothing more gets reset */
    431 		/*
    432 		 * exempt for our own personal reasons:
    433 		 */
    434 		case MIDI_CTRL_DATA_ENTRY_MSB:		/* 6 */
    435 			continue; /* doesn't go to the store */
    436 		}
    437 
    438 		key = ctlr;
    439 		c = classify(&key, &islsb);
    440 
    441 		present = store_locate(mc->store, c, chan, key);
    442 		if ( !present )
    443 			continue;
    444 		store_update(mc->store, c, chan, key, 0); /* no C*SET */
    445 	}
    446 loop_exit:
    447 	mc->notify(mc->cookie, MIDICTL_RESET, chan, 0);
    448 }
    449 
    450 static void
    451 enter14(midictl *mc, uint_fast8_t chan, class c, uint_fast16_t key,
    452         _Bool islsb, uint8_t val)
    453 {
    454 	uint16_t stval;
    455 	_Bool present;
    456 
    457 	KASSERT(mutex_owned(mc->lock));
    458 
    459 	present = store_locate(mc->store, c, chan, key);
    460 	stval = (present) ? store_extract(mc->store, c, chan, key) : 0;
    461 	if ( !( stval & (C14MSET|C14LSET) ) ) {
    462 		if ( !((NRPN==c)? mc->accept_any_nrpn: mc->accept_any_ctl_rpn) )
    463 			return;
    464 	}
    465 	if ( islsb )
    466 		stval = C14LSET | val | ( stval & ~0x7f );
    467 	else
    468 		stval = C14MSET | ( val << 7 ) | ( stval & ~0x3f80 );
    469 	store_update(mc->store, c, chan, key, stval);
    470 	mc->notify(mc->cookie, CTL14 == c ? MIDICTL_CTLR
    471 		             : RPN   == c ? MIDICTL_RPN
    472 			     : MIDICTL_NRPN, chan, key);
    473 }
    474 
    475 static uint_fast16_t
    476 read14(midictl *mc, uint_fast8_t chan, class c, uint_fast16_t key,
    477        uint_fast16_t dflt)
    478 {
    479 	uint16_t val;
    480 	_Bool present;
    481 
    482 	KASSERT(mutex_owned(mc->lock));
    483 
    484 	present = store_locate(mc->store, c, chan, key);
    485 	if ( !present )
    486 		goto neitherset;
    487 
    488 	val = store_extract(mc->store, c, chan, key);
    489 	switch ( val & (C14MSET|C14LSET) ) {
    490 	case C14MSET|C14LSET:
    491 		return val & 0x3fff;
    492 	case C14MSET:
    493 		val = C14LSET | (val & ~0x7f) | (dflt & 0x7f);
    494 		break;
    495 	case C14LSET:
    496 		val = C14MSET | (val & ~0x3f8) | (dflt & 0x3f8);
    497 		break;
    498 neitherset:
    499 	case 0:
    500 		val = C14MSET|C14LSET | (dflt & 0x3fff);
    501 	}
    502 	store_update(mc->store, c, chan, key, val);
    503 	return val & 0x3fff;
    504 }
    505 
    506 /*
    507  * Determine the controller class; ranges based on
    508  * http://www.midi.org/about-midi/table3.shtml dated 1995/1999/2002
    509  * and viewed 2 June 2006.
    510  */
    511 static class
    512 classify(uint_fast16_t *key, _Bool *islsb) {
    513 	if ( *key < 32 ) {
    514 		*islsb = 0;
    515 		return CTL14;
    516 	} else if ( *key < 64 ) {
    517 		*islsb = 1;
    518 		*key -= 32;
    519 		return CTL14;
    520 	} else if ( *key < 70 ) {
    521 		return CTL1;
    522 	}	  	/* 70-84 defined, 85-90 undef'd, 91-95 def'd */
    523 	return CTL7;	/* 96-101,120- handled above, 102-119 all undef'd */
    524 		  	/* treat them all as CTL7 */
    525 }
    526 
    527 static void
    528 notify_no_one(void *cookie, midictl_evt evt,
    529     uint_fast8_t chan, uint_fast16_t k)
    530 {
    531 }
    532 
    533 #undef PN_SET
    534 #undef C14MSET
    535 #undef C14LSET
    536 #undef C7_SET
    537 #undef C1_SET
    538 
    539 static void
    540 store_thread(void *arg)
    541 {
    542 	midictl_store *s;
    543 
    544 	s = arg;
    545 
    546 	mutex_enter(s->lock);
    547 	for (;;) {
    548 		if (s->destroy) {
    549 			mutex_exit(s->lock);
    550 			cv_destroy(&s->cv);
    551 			kmem_free(s->table, sizeof(*s->table)<<s->lgcapacity);
    552 			kmem_free(s, sizeof(*s));
    553 			return;
    554 		} else if (NEED_REHASH(s)) {
    555 			store_rehash(s);
    556 		} else {
    557 			cv_wait(&s->cv, s->lock);
    558 		}
    559 	}
    560 }
    561 
    562 static _Bool
    563 store_locate(midictl_store *s, class c, uint_fast8_t chan, uint_fast16_t key)
    564 {
    565 	uint64_t mask;
    566 
    567 	KASSERT(mutex_owned(s->lock));
    568 
    569 	if ( s->used >= 1 << s->lgcapacity )
    570 		panic("%s: repeated attempts to expand table failed", __func__);
    571 
    572 	chan = packing[c] * (chan/packing[c]);
    573 
    574 	if ( CTL7 == c ) {	/* only 16 bits here (key's only 7) */
    575 		s->key = IS_USED | IS_CTL7 | (chan << 7) | key;
    576 		mask = 0xffff;
    577 	} else {		/* use 23 bits (key could be 14) */
    578 		s->key = (c << 20) | (chan << 16) | IS_USED | key;
    579 		mask = 0x7fffff;
    580 	}
    581 
    582 	s->idx = store_idx(s->lgcapacity, s->table, s->key, mask);
    583 
    584 	if ( !(s->table[s->idx] & IS_USED) )
    585 		return 0;
    586 
    587 	return 1;
    588 }
    589 
    590 static uint16_t
    591 store_extract(midictl_store *s, class c, uint_fast8_t chan,
    592     uint_fast16_t key)
    593 {
    594 
    595 	KASSERT(mutex_owned(s->lock));
    596 
    597 	chan %= packing[c];
    598 	switch ( c ) {
    599 	case CTL1:
    600 		return 3 & (s->table[s->idx]>>CTL1SHIFT(chan));
    601 	case CTL7:
    602 		return 0xff & (s->table[s->idx]>>CTL7SHIFT(chan));
    603 	case CTL14:
    604 	case RPN:
    605 	case NRPN:
    606 		break;
    607 	}
    608 	return 0xffff & (s->table[s->idx]>>CTLESHIFT(chan));
    609 }
    610 
    611 static void
    612 store_update(midictl_store *s, class c, uint_fast8_t chan,
    613     uint_fast16_t key, uint16_t value)
    614 {
    615 	uint64_t orig;
    616 
    617 	KASSERT(mutex_owned(s->lock));
    618 
    619 	orig = s->table[s->idx];
    620 	if ( !(orig & IS_USED) ) {
    621 		orig = s->key;
    622 		++ s->used;
    623 	}
    624 
    625 	chan %= packing[c];
    626 
    627 	switch ( c ) {
    628 	case CTL1:
    629 		orig &= ~(((uint64_t)3)<<CTL1SHIFT(chan));
    630 		orig |= ((uint64_t)(3 & value)) << CTL1SHIFT(chan);
    631 		break;
    632 	case CTL7:
    633 		orig &= ~(((uint64_t)0xff)<<CTL7SHIFT(chan));
    634 		orig |= ((uint64_t)(0xff & value)) << CTL7SHIFT(chan);
    635 		break;
    636 	case CTL14:
    637 	case RPN:
    638 	case NRPN:
    639 		orig &= ~(((uint64_t)0xffff)<<CTLESHIFT(chan));
    640 		orig |= ((uint64_t)value) << CTLESHIFT(chan);
    641 		break;
    642 	}
    643 
    644 	s->table[s->idx] = orig;
    645 	if (NEED_REHASH(s))
    646 		cv_broadcast(&s->cv);
    647 }
    648 
    649 static uint32_t
    650 store_idx(uint32_t lgcapacity, uint64_t *table,
    651           uint64_t key, uint64_t mask)
    652 {
    653 	uint32_t val;
    654 	uint32_t k, h1, h2;
    655 	int32_t idx;
    656 
    657 	k = key;
    658 
    659 	h1 = ((k * 0x61c88646) >> (32-lgcapacity)) & ((1<<lgcapacity) - 1);
    660 	h2 = ((k * 0x9e3779b9) >> (32-lgcapacity)) & ((1<<lgcapacity) - 1);
    661 	h2 |= 1;
    662 
    663 	for ( idx = h1 ;; idx -= h2 ) {
    664 		if ( idx < 0 )
    665 			idx += 1<<lgcapacity;
    666 		val = (uint32_t)(table[idx] & mask);
    667 		if ( val == k )
    668 			break;
    669 		if ( !(val & IS_USED) )
    670 			break;
    671 	}
    672 
    673 	return idx;
    674 }
    675 
    676 static void
    677 store_rehash(midictl_store *s)
    678 {
    679 	uint64_t *newtbl, *oldtbl, mask;
    680 	uint32_t oldlgcap, newlgcap, oidx, nidx;
    681 
    682 	KASSERT(mutex_owned(s->lock));
    683 
    684 	oldlgcap = s->lgcapacity;
    685 	newlgcap = oldlgcap + s->lgcapacity;
    686 
    687 	mutex_exit(s->lock);
    688 	newtbl = kmem_zalloc(sizeof(*newtbl) << newlgcap, KM_SLEEP);
    689 	mutex_enter(s->lock);
    690 
    691 	if (newtbl == NULL) {
    692 		kpause("midictl", false, hz, s->lock);
    693 		return;
    694 	}
    695 	if (oldlgcap != s->lgcapacity) {
    696 		mutex_exit(s->lock);
    697 		kmem_free(newtbl, sizeof(*newtbl) << newlgcap);
    698 		mutex_enter(s->lock);
    699 		return;
    700 	}
    701 
    702 	for ( oidx = 1<<s->lgcapacity ; oidx --> 0 ; ) {
    703 		if (!(s->table[oidx] & IS_USED) )
    704 			continue;
    705 		if ( s->table[oidx] & IS_CTL7 )
    706 			mask = 0xffff;
    707 		else
    708 			mask = 0x3fffff;
    709 		nidx = store_idx(newlgcap, newtbl,
    710 		    s->table[oidx] & mask, mask);
    711 		newtbl[nidx] = s->table[oidx];
    712 	}
    713 	oldtbl = s->table;
    714 	s->table = newtbl;
    715 	s->lgcapacity = newlgcap;
    716 
    717 	mutex_exit(s->lock);
    718 	kmem_free(oldtbl, sizeof(*oldtbl) << oldlgcap);
    719 	mutex_enter(s->lock);
    720 }
    721