08-19-05 10:54 PM
Roman Mashak wrote:
> FD_SET(1, &readfds);
[...]
> __asm__ __volatile__ ("btsl %1,%0" : "=m" (((&readfds)->__fds_bits)[((
1) /
> (8 * sizeof (__fd_mask)))]) : \
> "r" (((int) (0)) % (8 * sizeof (__fd_mask))) : "cc","memory");
>
> I understand what "btsl" instruction is doing, and also I know 'readfds' i
s
> array of integers, in which every element's bit corresponds to descriptor.
> But I can't understand how is it done in this macro, seems the trick is
> within '(((&readfds)->__fds_bits[...]'....
Let us take it step by step. The following assumes Linux on x86, which
seems to be what you are using anyways.
FD_SET is implemented with the btsl (bit test and set) instruction, but
the two take slightly different arguments, so FD_SET has to translate
its arguments into something the btsl instruction can use.
Instead of using the btsl instruction, I am going to use the set_bit()
function in <asm/bitops.h> to make explanation more clear.
FD_SET(n, array) sets the nth bit in the array. The array consists of a
sequence of long int (__fd_mask) element. One element is 32 bits wide
(sizeof(__fd_mask) gives us bytes per long int, so we must multiply by
8 to get bits per long int); let us call this value element_size.
set_bit(i, address) sets the ith bit at address, where 0 <= i < 32.
Please note that set_bit() cannot set bits beyond the 31th bit.
So, in order to set the nth bit, where n > 31, we need to find out:
1. which long int in the array the nth bit is part of, and
2. which bit inside the long int the nth bit is.
The former is found by dividing the number n (from the nth bit) with
element_size. For example, the 5th bit resides in the first element of
the array (5 / 32 = 0), and the 42th bit is in the second element
(42 / 32 = 1).
The latter is found by taking the remainder of the division of n by
element_size. So, the 5th bit is the 5th bit inside the first element
(5 / 32 = 0 and 5 % 32 = 5), and the 42th bit is the 10th bit in the
second element (42 / 32 = 1 and 42 % 32 = 10).
So, FD_SET(n, array) could be implemented like this:
set_bit(n / element_size, &array[n % element_size])
I hope that helps.
--
mail1dotstofanetdotdk
[ Post a follow-up to this message ]
|