Thursday, February 2, 2012

Fourier Transforms



Fourier Transforms

K="#FF0000">


Fourier Transforms




The Fourier transform defines a relationship between a signal in the
time domain and its representation in the frequency domain. Being a
transform, no information is created or lost in the process, so the
original signal can be recovered from knowing the Fourier transform,
and vice versa.



The Fourier transform of a signal is a continuous complex valued
signal capable of representing real valued or complex valued
continuous time signals.










The tool allows you to view these complex valued
signals as either their real and quadrature (also known as imaginary)
components separately, or by a magnitude and phase
representation. You may switch between these two representations at
any point. Mathematically switching between the two representations
for a given complex value can be expressed as






and




or equivalently,






and





where

and

are the magnitude and phase of the complex number, and

and

are the real and quadrature components of the complex number. In this
tool, the magnitude is plotted on a dB scale. Select a few
signals, such as unit pulses and sine waves, and view them using the
two methods to see how they are related.




The Fourier transform itself is defined by the equation








where

is the Fourier transform of

Frequency is measured in Hertz, with

as the frequency variable.



Fourier transform of signals




Using the tool, display the Fourier transform of a 4ms unit
pulse. You will observe that the frequency response is a continuous
signal with a maximum at 0 Hz, and some periodicity. The frequency
response is zero at every multiple of 250Hz. Compare this with the
frequency response of a unit pulse of 8ms in duration. Here the
general shape of the signal is the same, but the zero crossings are at
a spacing of 125Hz. These figures are the reciprocals of the pulse
duration, indicating that there are inverse relationships between
time and frequency. Generally, longer time periods relate to smaller
frequency spans.



The formula for the frequency response of a unit pulse may
be calculated directly from the Fourier transform equation as









where

is the duration of the pulse. You can observe the changes in magnitude
caused by the different values of

, as well as the changes in the spacing of the zero crossings, a
function of the sin component.




Sinusoids and cosinusoids are signals that by definition contain only
one frequency of signal. The tool has two examples of these
with frequencies 333Hz and 500Hz. The time domain and frequency
transform of a 500Hz cosine wave is given by the following
equations










Delaying a 500Hz cosine wave by 0.5ms results in a sine wave signal,
and its transform can be seen to be










As this change is made, by adding the delay, you will observe that the
phase of the frequency transform changes, but the magnitude remains
the same. Alternatively, using the real and quadrature representation,
components that were purely real before becoming imaginary after the
delay.



Delay and phase change




Any of the signals can be advanced or delayed by a number of
predefined delays of up to 4ms. Alternatively, you can delay a signal
by an arbitrary amount by clicking and dragging the graph whilst
holding down a key on the keyboard. In the frequency domain this
relates to alteration of the phase of the signal, thus no difference
will be observed when viewing the Fourier transform magnitude plot,
but will be evident when viewing the phase of the transform or the
real and imaginary parts together.




Try this out for various types of signal.




Take particular note of the scaled unit impulse as without any delay
it results in a purely real transform of height 0.004 (the scaling
factor). When this signal is delayed, the transform becomes a
cosinusoid in the real component and a sinusoid in the imaginary. The
formula for this is









where is the
value of the delay.




This implies that a delay of a specific amount in the time domain
equates to multiplication by a phasor in the frequency domain. Set
the delay for the scaled unit impulse to 0.5ms as was done for the
500Hz cosine waveform in the previous section. Now note the values of
the real and imaginary parts of the transform at 500Hz and -500Hz. Now
switch the input signal to the 500Hz cosine and you should be able to
explain how the purely real transform of the undelayed waveform
relates to the purely imaginary transform of the delayed
signal.




Not only can the time domain signal be delayed, but the frequency
transform can be shifted, resulting in a phase change in the time
domain. Experiment with this observing the time domain signal as
magnitude and phase, and as real and quadrature to see the effects
that can be obtained. Try shifting the frequency response of a
cosinusoid, or a sinusoid, so that one of the frequency samples is set
to 0Hz. The result will be a complex phasor, consisting of a
cosinusoid and sinusoid in the real and imaginary components of the
time domain plus a DC offset from the 0Hz component.



Multiplication and convolution



Using the tool, review the transforms of the unit
pulse function and the cosine function. For the moment it is best to
view these using the magnitude and phase representation of the
frequency domain.




Now switch to one of the 8ms segment of a cosine or sine
waveforms. You should observe that the frequency domain plot is some
form of combination of the two types of signal. Strictly speaking, the
time domain signal is the multiplication of a unit pulse of 8ms
duration delayed by 4ms, and a cosinusoid or sinusoid waveform of the
selected frequency. The frequency domain transform is then the
addition of two sa functions which have been shifted in
frequency. Notice where the highest peaks are and you should observe
that these correspond with the frequency of the sine or cosine
signal. What has happened is that in the frequency domain the sa
function from the unit pulse and the two impulses from the sine or
cosine function have been convolved together. This is an example of
the general rule that multiplication in the time domain equates to
convolution in the frequency domain.




You can reconstruct the two constituent waveforms by shifting the
frequency response of the 8ms unit pulse to 500Hz, and to -500Hz.You
should find that the real component of the two shifted signals are the
same, but that the quadrature components are the complement of each
other. Thus when they are summed together, the result is a signal with
a real component and a zero quadrature component.



In fact an equivalent rule also holds that
convolution in the time domain equates to multiplication in the
frequency domain. Thus, for example, a complex phasor in the frequency
domain multiplied by a given signal's transform produces a time domain
function where an impulse is convolved with signal. This is precisely
what is happening when the delay value is being altered.






Next: Summary
Up: EE4 page
Previous: Correlation




Read More..

Correlation



Correlation

K="#FF0000">


Correlation



Correlation is a technique that is very similar in mechanism to
convolution, with one subtle difference.




The correlation integral is given by








While this may appear to be similar to equation (1) with some changes
of variable, unlike convolution where

is time reversed, in correlation this is not the case. The integral
thus no longer represents the output of a filter driven by an
input signal. Rather it is a tool used to measure the similarity
between two signals. A large correlation value (positive or
negative) represents a strong similarity between the two
signals, while a value near zero represents little
similarity. The delay value,

allows this comparison to be made on two signals at
different delay separations.



Using the correlation tool








compare a number of signals with a unit pulse shape, noting the
maximum values that you can obtain, and the delay at which these
values occur. For all signals that you correlate, except for
those signals incorporating impulses, the maximum value that you
will obtain will be found by those signals similar in shape to
the one you are correlating with. This is because correlation
identifies the similarity between the two signals.




If a signal is correlated with itself, a process known as
autocorrelation, then the maximum value of the correlation can
be found at a time shift of 0. Verify this yourself for any
signals that you wish to test out. For the correlation between
two different signals, known as cross-correlation, this is not
necessarily the case.






Next: Fourier Transforms
Up: EE4 page
Previous: The Application of Discrete Convolution



Read More..


The Application of Discrete Time Convolution

K="#FF0000">


The Application of Discrete Time Convolution




Discrete time convolution can be used to determine the output of a
sampled data system from its input and pulse response. A
commonly used discrete system is a finite impulse response (FIR)
filter.








This tool presents you with a schematic of a FIR Filter. The boxes
marked

represent delay elements whose output is the previous value of
their input. Using the single step button you can observe the
input signal,

as its samples work their way through the delay elements.




There are a number of multiplication symbols in the filter with
weights, which are the system response, associated with them.The
product of these weights and the input signal samples are summed
together to give the output of the filter,



You can view the values at various points in the filter as
either a bar denoting the size of the value, by a number, or by
both means. The colours of the values or bars correspond to the
colours of the graphs. Observing both windows simultaneously,
the mechanism by which the convolution is performed can be seen.
The system response is coded in the multiplication weights, the
product of the input signal and the system response is
calculated at the output of the multipliers, and the final sum
is calculated by the summation unit driving the filter output.



Experiment with setting various system responses and signals
such as setting a single value of the input to 1 to convince
yourself that the system response values of the filter define
the unit pulse response of the filter.







Next: Correlation
Up: EE4 page
Previous: Discrete Convolution



Read More..

Convolution



Convolution

K="#FF0000">


Convolution



Convolution is the term given to the mathematical technique for
determining a system output given an input signal and the
system impulse response. It is written as





(1)





When you start the convolution tool









you will find that you can select signals, run animations, and control
the display properties. The current input signal and system
impulse response are displayed - you can change the data in
these graphs by clicking and dragging with the mouse or you can
select pre-defined signals using the menus. It is helpful if you
ensure that the signal and system response are coloured differently.



The other graphs show the time-reversed input signal and the system
response, the product of the time-reversed input signal
(due to the

in equation (1)) and the system response, and their convolution. The
product and convolution data will change as the time-reversed
input signal is moved relative to the system impulse response.



When the system impulse response is a unit pulse and the input is a
ramp function, you can test out the convolution process by
clicking on the

symbol in the combined time-reversed system impulse response and
signal graph and dragging the time reversed input signal
backwards and forwards through the system impulse response.
You can also let the tool do this for you by clicking on the
double arrow button.



As the ramp signal is shifted through the unit pulse, the product
graph clearly shows that the convolution is calculating the area
under a selected portion of the ramp signal. The convolution
graph plots the increasing, and then decreasing area of this
product. The system with this impulse response is known as a
finite time integrator as it performs integration over a finite
length of the input signal. Experiment with other input signals
such as sine waves, other unit pulses, impulses, etc.



Convolution with an impulse



Change the system response to a single impulse at 2ms. As you perform
the convolution, as before, you will find that the output is a
copy of the input signal, except that it is delayed by 2ms. In
this instance, the impulse is performing a sampling function of
the input signal as described by








Examination of the product will reveal that the integrand,

, is also an impulse. In fact, the impulse is a scaled unit impulse,
the scaling resulting in an impulse of area

, hence the final convolution result of

Thus, analytically we find that the system response of a unit impulse
results in the output of the system being a copy of the input
signal, with the only difference being a time shift.



As a heuristic argument as to why this should be the case, think of
the system response as the system output when the input signal
is an impulse function at time

When the system response is also an impulse, then the input signal
shape doesn't alter. If that impulse is at a non-zero time
value, then there is a time shift between the input and the
output of the system. (For real systems any time shift must
represent a delay, otherwise the system would predict its own
input signal)!



A system that sums two delayed versions of the input signal is
represented by two impulses in the system response. Experiment
with the effects that you can obtain by examining system
responses consisting of impulses.






Next: Discrete Convolution
Up: EE4 page



Read More..





Signal Processing Fundamentals






























Signal Processing Fundamentals


Dennis Bohn, Rane Corporation

RaneNote 134 written 1997; last revised 5/04


Screaming To Be Heard


In space, no one can hear you scream ... because there is no air or other medium for sound to travel. Sound needs a medium; an intervening substance through which it can travel from point to point; it must be carried on something. That something can be solid, liquid or gas. They can hear you scream underwater ... briefly. Water is a medium. Air is a medium. Nightclub walls are a medium. Sound travels in air by rapidly changing the air pressure relative to its normal value (atmospheric pressure). Sound is a disturbance in the surrounding medium. A vibration that spreads out from the source, creating a series of expanding shells of high pressure and low pressure ... high pressure ... low pressure ... high pressure ... low pressure. Moving ever outward these cycles of alternating pressure zones travel until finally dissipating, or reflecting off surfaces (nightclub walls), or passing through boundaries, or getting absorbed -- usually a combination of all three. Left unobstructed, sound travels outward, but not forever. The air (or other medium) robs some of the sound's power as it passes. The price of passage: the medium absorbs its energy. This power loss is experienced as a reduction in how loud it is (the term loudness is used to describe how loud it is from moment to moment) as the signal travels away from its source. The loudness of the signal is reduced by one-fourth for each doubling of distance from the source. This means that it is 6 dB less loud as you double your distance from it. [This is known as the inverse square law since the decrease is inversely proportional to the square of the distance traveled; for example, 2 times the distance equals a 1/4 decrease in loudness, and so on.]


How do we create sound, and how do we capture sound? We do this using opposite sides of the same electromagnetic coin. Electricity and magnetism are kinfolk: If you pass a coil of wire through a magnetic field, electricity is generated within the coil. Turn the coin over and flip it again: If you pass electricity through a coil of wire, a magnetic field is generated. Move the magnet, get a voltage; apply a voltage, create a magnet ... this is the essence of all electromechanical objects.


Microphones and loudspeakers are electromechanical objects. At their hearts there is a coil of wire (the voice coil) and a magnet (the magnet). Speaking causes sound vibrations to travel outward from your mouth. Speaking into a moving-coil (aka dynamic) microphone causes the voice coil to move within a magnetic field. This causes a voltage to be developed and a current to flow proportional to the sound -- sound has been captured. At the other end of the chain, a voltage is applied to the loudspeaker voice coil causing a current to flow which produces a magnetic field that makes the cone move proportional to the audio signal applied -- sound has been created. The microphone translates sound into an electrical signal, and the loudspeaker translates an electrical signal into sound. One capturing, the other creating. Everything in-between is just details. And in case you're wondering: yes; turned around, a microphone can be a loudspeaker (that makes teeny tiny sounds), and a loudspeaker can be a microphone (if you SHOUT REALLY LOUD).


Crossovers: Simple Division


Loudspeaker crossovers are a necessary evil. A different universe, a different set of physics and maybe we could have what we want: one loudspeaker that does it all. One speaker that reproduces all audio frequencies equally well, with no distortion, at loudness levels adequate for whatever venue we play. Well, we live here, and our system of physics does not allow such extravagance. The hard truth is, no one loudspeaker can do it all. We need at least two -- more if we can afford them. Woofers and tweeters. A big woofer for the lows and a little tweeter for the highs. This is known as a 2-way system. (Check the accompanying diagrams for the following discussions.) But with two speakers, the correct frequencies must be routed (or crossed over) to each loudspeaker.


Passive


At the simplest level a crossover is a passive network. A passive network is one not needing a power supply to operate -- if it has a line cord, or runs off batteries, then it is not a passive circuit. The simplest passive crossover network consists of only two components: a capacitor connecting to the high frequency driver and an inductor (aka a coil) connecting to the low frequency driver. A capacitor is an electronic component that passes high frequencies (the passband) and blocks low frequencies (the stopband); an inductor does just the opposite: it passes low frequencies and blocks high frequencies. But as the frequency changes, neither component reacts suddenly. They do it gradually; they slowly start to pass (or stop passing) their respective frequencies. The rate at which this occurs is called the crossover slope. It is measured in dB per octave, or shortened to dB/octave. The slope increases or decreases so many dB/octave. At the simplest level, each component gives you a 6 dB/octave slope (a physical fact of our universe). Again, at the simplest level, adding more components increases the slope in 6 dB increments, creating slopes of 12 dB/oct, 18 dB/oct, 24 dB/oct, and so on. The number of components, or 6 dB slope increments, is called the crossover order. Therefore, a 4th-order crossover has (at least) four components, and produces steep slopes of 24 dB/octave. The steeper the better for most drivers, since speakers only perform well for a certain band of frequencies; beyond that they misbehave, sometimes badly. Steep slopes prevent these frequencies from getting to the driver.


You can combine capacitors and inductors to create a third path that eliminates the highest highs and the lowest lows, and forms a mid-frequency crossover section. This is naturally called a 3-way system. (See diagram) The "mid" section forms a bandpass filter, since it only passes a specific frequency band. Note from the diagram that the high frequency passband and low frequency passband terms are often shortened to just high-pass and low-pass. A 3-way system allows optimizing each driver for a narrower band of frequencies, producing a better overall sound.


So why not just use passive boxes?



Problems


The single biggest problem is that one passive cabinet (or a pair) won't play loud enough and clean enough for large spaces. If the sound system is for your bedroom or garage, passive systems would work just fine -- maybe even better. But it isn't. Once you try to fill a relatively large space with equally loud sound you start to understand the problems. And it doesn't take stadiums, just normal size clubs. It is really difficult to produce the required loudness with passive boxes. Life would be a lot easier if you could just jack everyone into their own cans amp -- like a bunch of HC 4 or HC 6 Headphone Amps scattered throughout the audience. Let them do the work; then everyone could hear equally well, and choose their own listening level. But life is hard, and headphone amps must be restricted to practice and recording.


Monitor speakers on the other hand most likely have passive crossovers. Again, it's a matter of distance and loudness. Monitors are usually close and not overly loud -- too loud and they will feed back into your microphone or be heard along with the main mix: not good. Monitor speakers are similar to hi-fi speakers, where passive designs dominate ... because of the relatively small listening areas. It is quite easy to fill small listening rooms with pristine sounds even at ear-splitting levels. But move those same speakers into your local club and they will sound thin, dull and lifeless. Not only will they not play loud enough, but they may need the sonic benefits of sound bouncing off close walls to reinforce and fill the direct sound. In large venues, these walls are way too far away to benefit anyone.



2-way crossover


Figure 1. Passive 2-Way Crossover


3-way crossover


Figure 2. Passive 3-Way Crossover



So why not use a bunch of passive boxes? You can, and some people do. However, for reasons to follow, it only works for a couple of cabinets. Even so, you won't be able to get the high loudness levels if the room is large. Passive systems can only be optimized so much.


Once you start needing multiple cabinets, active crossovers become necessary. To get good coverage of like-frequencies, you want to stack like-drivers. This prevents using passive boxes since each one contains (at least) a high-frequency driver and a low-frequency driver. It's easiest to put together a sound system when each cabinet covers only one frequency range. For instance, for a nice sounding 3-way system, you would have low-frequency boxes (the big ones), then medium-sized mid-frequency boxes and finally the smaller high-frequency boxes. These would be stacked or hung, or both -- in some sort of array. A loudspeaker array is the optimum stacking shape for each set of cabinets to give the best combined coverage and overall sound. You've no doubt seen many different array shapes. There are tall towers, high walls, and all sorts of polyhedrons and arcs. The only efficient way to do this is with active crossovers.


Some smaller systems combine active and passive boxes. Even within a single cabinet it is common to find an active crossover used to separate the low- and mid-frequency drivers, while a built-in passive network is used for the high-frequency driver. This is particularly common for super tweeters operating over the last audio octave. At the other end, an active crossover often is used to add a subwoofer to a passive 2-way system. All combinations are used, but each time a passive crossover shows up, it comes with problems.


One of these is power loss. Passive networks waste valuable power. The extra power needed to make the drivers louder, instead boils off the components and comes out of the box as heat -- not sound. Therefore, passive units make you buy a bigger amp.


A couple of additional passive network problems has to do with their impedance. Impedance restricts power transfer; it's like resistance, only frequency sensitive. In order for the passive network to work exactly right, the source impedance (the amplifier's output plus the wiring impedance) must be as close to zero as possible and not frequency-dependent, and the load impedance (the loudspeaker's characteristics) must be fixed and not frequency-dependent (sorry, not in this universe; only on Star Trek). Since these things are not possible, the passive network must be (at best), a simplified and compromised solution to a very complex problem. Consequently, the crossover's behavior changes with frequency -- not something you want for a good sounding system.


One last thing to make matters worse. There is something called back-emf (back-electromotive force: literally, back-voltage) which further contributes to poor sounding speaker systems. This is the phenomena where, after the signal stops, the speaker cone continues moving, causing the voice coil to move through the magnetic field (now acting like a microphone), creating a new voltage that tries to drive the cable back to the amplifier's output! If the speaker is allowed to do this, the cone flops around like a dying fish. It does not sound good! The only way to stop back-emf is to make the loudspeaker "see" a dead short, i.e., zero ohms looking backward, or as close to it as possible -- something that's not gonna happen with a passive network slung between it and the power amp.


All this, and not to mention that inductors saturate at high signal levels causing distortion -- another reason you can't get enough loudness. Or the additional weight and bulk caused by the large inductors required for good low frequency response. Or that it is almost impossible to get high-quality steep slopes passively, so the response suffers. Or that inductors are way too good at picking up local radio, TV, emergency, and cellular broadcasts, and joyfully mixing them into your audio.


Such is life with passive speaker systems.



2-way crossover


Figure 3. Active 2-Way Crossover


3-way crossover


Figure 4. Active 3-Way Crossover



Active


Active crossover networks require a power supply to operate and usually come packaged in single-space, rack-mount units. (Although of late, powered loudspeakers with built-in active crossovers and power amplifiers are becoming increasingly popular.) Looking at the accompanying diagram shows how active crossovers differ from their passive cousins. For a 2-way system instead of one power amp, you now have two, but they can be smaller for the same loudness level. How much smaller depends on the sensitivity rating of the drivers (more on this later). Likewise a 3-way system requires three power amps. You also see and hear the terms bi-amped, and tri-amped applied to 2- and 3-way systems.


Active crossovers cure many ills of the passive systems. Since the crossover filters themselves are safely tucked away inside their own box, away from the driving and loading impedance problems plaguing passive units, they can be made to operate in an almost mathematically perfect manner. Extremely steep, smooth and well-behaved crossover slopes are easily achieved by active circuitry.


There are no amplifier power loss problems, since active circuits operate from their own low voltage power supplies. And with the inefficiencies of the passive network removed, the power amps more easily achieve the loudness levels required.


Loudspeaker jitters and tremors caused by inadequately damped back-emf all but disappear once the passive network is removed. What remains is the amplifier's inherent output impedance and that of the connecting wire. Here's where the term damping factor comes up. [Note that the word is damp-ing, not damp-ning as is so often heard; impress your friends.] Damping is a measure of a system's ability to control the motion of the loudspeaker cone after the signal disappears. No more dying fish.


Siegfried & Russ


Active crossovers go by many names. First, they are either 2-way or 3-way (or even 4-way and 5-way). Then there is the slope rate and order: 24 dB/oct (4th-order), or 18 dB/oct (3rd-order), and so on. And finally there is a name for the kind of design. The two most common being Linkwitz-Riley and Butterworth, named after Siegfried Linkwitz and Russ Riley who first proposed this application, and Stephen Butterworth who first described the response in 1930. Up until the mid `80s, the 3rd-order (18 dB/oct) Butterworth design dominated, but still had some problems. Since then, the development (pioneered by Rane and Sundholm) of the 4th-order (24 dB/oct) Linkwitz-Riley design solved these problems, and today is the norm.


What this adds up to is active crossovers are the rule. Luckily, the hardest thing about an active crossover is getting the money to buy one. After that, most of the work is already done for you. At the most basic level all you really need from an active crossover are two things: to let you set the correct crossover point, and to let you balance driver levels. That's all. The first is done by consulting the loudspeaker manufacturer's data sheet, and dialing it in on the front panel. (That's assuming a complete factory-made 2-way loudspeaker cabinent, for example. If the box is homemade, then both drivers must be carefully selected so they have the same crossover frequency, otherwise a severe response problem can result.) Balancing levels is necessary because high frequency drivers are more efficient than low frequency drivers. This means that if you put the same amount of power into each driver, one will sound louder than the other. The one that is the most efficient plays louder. Several methods to balance drivers are always outlined in any good owner's manual.


Equalizers


You may have heard it said that equalizers are nothing more than glorified tone controls. That's pretty accurate and helps explain their usefulness and importance. Simply put, equalizers allow you to change the tonal balance of whatever you are controlling. You can increase (boost) or decrease (cut) on a band-by-band basis just the desired frequencies. Equalizers come in all different sizes and shapes, varying greatly in design and complexity. Select from a simple single-channel unit with 10 controls on 1-octave frequency spacing (a mono 10-band octave equalizer), all the way up to a full-featured, two-channel box with 31 controls on 1/3-octave frequency spacing (a stereo 1/3-oct equalizer). There are graphic models with slide controls (sliders) that roughly "graph" the equalizer's frequency response by the shape they form, and there are parametric models where you choose the frequency, amplitude, and bandwidth desired (the filter parameters - see diagram below) for each band provided. Far and away, the simplest and most popular are the 1/3- and 2/3-octave graphics. They offer the best combination of control, complexity and cost.


In selecting graphic equalizers, the primary features to consider are the number of input/output channels, the number of boost/cut bands, the center-frequency spacing of each, and the accuracy of the output vs. the front panel settings. Up until the recent development of true response graphics, the front panel settings only approximated the equalizer's actual response. Prior to true response graphics, adjacent band interaction caused the actual output response to deviate from the front panel settings. Described as either constant-Q or variable-Q (see diagrams), the individual filter bandwidth behavior determined the interaction. In the early '80s, Rane developed the first constant-Q designs to preserve the same shape (bandwidth) over the entire boost/cut range. In contrast, variable-Q designs have varying bandwidths (the shape changes) as a function of boost/cut amount. Rane's constant-Q design offered a big improvement in output response vs. front panel settings and became the most popular design until Rane and others developed the first true response graphic equalizers. Now true response graphics offer the best response.


Using Equalizers


Equalizers can do wonders for a sound system. Let's start with loudspeaker performance. An unfortunate truth regarding budget loudspeakers is they don't sound very good. Usually this is due to an uneven frequency response, or more correctly a non-flat power response. An ideal cabinet has a flat power response. This means that if you pick, say, 1 kHz as a reference signal, use it to drive the speaker with exactly one watt, measure the loudness, and sweep the generator over the speaker's entire frequency range, all frequencies will measure equally loud. Sadly, with all but the most expensive speaker systems, they will not. Equalizers can help these frequency deficiencies. By adding a little here and taking away a little there, pretty soon you create an acceptable power response - and a whole lot better sounding system. It's surprising how just a little equalization can change a poor sounding system into something quite decent.


The best way to deal with budget speakers -- although it costs more -- is to commit one equalizer channel for each cabinet. This becomes a marriage. The equalizer is set, a security cover is bolted-on, and forever more they are inseparable. (Use additional equalizers to assist with the room problems.) And now for the hard part, but the most important part: If you do your measurements outside (no reflections off walls or ceiling) and up in the air (no reflections off the ground) you can get a very accurate picture of just the loudspeaker's response, free from room effects. This gives you the room-independent response. This is really important, because no matter where this box is used, it has these problems. Of course, you must make sure the cost of the budget speaker plus the equalizer adds up to substantially less than buying a really flat speaker system to begin with. Luckily (or should this be sadly) this is usually the case. Again, the truth is that most cabinets are not flat. It is only the very expensive loudspeakers that have world-class responses. (Hmmm ... maybe that's why they cost so much!)


The next thing you can do with equalizers is to improve the way each venue sounds. Every room sounds different -- fact of life -- fact of physics. Using exactly the same equipment, playing exactly the same music in exactly the same way, different rooms sound different -- guaranteed. Each enclosed space treats your sound differently.


Reflected sound causes the problems. What the audience hears is made up of the direct sound (what comes straight out of the loudspeaker directly to the listener) and reflected sound (it bounces off everything before getting to the listener). And if the room is big enough, then reverberation comes into play, which is all the reflected sound that has traveled so far, and for such a (relatively) long time that it arrives and re-arrives at the listener delayed enough to sound like a second and third source, or even an echo if the room is really big.


It's basically a geometry problem. Each room differs in its dimensions; not only in its basic length-by-width size, but in its ceiling height, the distance from you and your equipment to the audience, what's hung (or not hung), on the walls, how many windows and doors there are, and where. Every detail about the space affects your sound. And regretfully, there is very little you can do about any of it. Most of the factors affecting your sound you cannot change. You certainly can't change the dimensions, or alter the window and door locations. But there are a few things you can do, and equalization is one of them. But before you equalize you want to optimize how and where you place your speakers. This is probably the number one item to attend to. Keep your loudspeakers out of corners whenever possible. Remove all restrictions between your speakers and your audience, including banners, stage equipment, and performers. What you want is for most of the sound your audience hears to come directly from the speakers. You want to minimize all reflected sound. If you have done a good job in selecting and equalizing your loudspeakers, then you already know your direct sound is good. So what's left is to minimize the reflected sound.


Next use equalization to help with some of the room's more troublesome features. If the room is exceptionally bright you can beef up the low end to help offset it, or roll-off some of the highs. Or if the room tends to be boomy, you can tone-down the low end to reduce the resonance. Another way EQ is quite effective is in controlling troublesome feedback tones. Feedback is that terrible squeal or scream sound systems get when the audio from the loudspeaker gets picked-up by one of the stage microphones, re-amplified and pumped out the speaker, only to be picked-up again by the microphone, and re-amplified, and so on. Most often, this happens when the system is playing loud. Which makes sense, because for softer sounds, the signal either isn't big enough to make it to the microphone, or if it does, it is too small to build-up. The problem is one of an out-of-control, closed-loop, positive-feedback system building up until something breaks, or the audience leaves. Use your equalizer to cut those frequencies that want to howl; you not only stop the squeal, but you allow the system to play louder. The technical phrase for this is maximizing system gain before feedback.


It's important to understand at the beginning that you cannot fix room related sound problems with equalization, but you can move the trouble spots around. You can rearrange things sonically, which helps tame excesses. You win by making it sound better. Equalization helps.



bandpass filter


Figure 5. Bandpass Filter Parameters


variable-q filter

Figure 6. Variable-Q Graphic


constant-q filter

Figure 7. Constant-Q Graphic



Equalizers are useful in augmenting your instrument or voice. With practice you will learn to use your equalizer to enhance your sound for your best personal expression: deepen the lows, fill the middle, or exaggerate the highs ... whatever you want. Just as an equalizer can improve the sound of a poor loudspeaker, it can improve the sound of a marginal microphone, or enhance any musical instrument. Equalizers give you that something extra, that edge. (We all know where "radio voices" really come from.)


Seeing Sound


To make loudspeaker and sound system measurements easy, you need a real-time analyzer (RTA). An RTA allows you to see the power response, not only for the loudspeaker, but even more importantly, for the whole system. Stand-alone RTAs use an LED or LCD matrix to display the response. A built-in pink noise generator (a special kind of shaped noise containing all audible frequencies, optimized for measuring sound systems) is used as the test signal. A measuring microphone is included for sampling the response. The display is arranged to show amplitude verses frequency. Depending upon cost, the number of frequency columns varies from 10 on 1-octave centers, up to 31 on 1/3-octave centers (agreeing with graphic equalizers). Amplitude range and precision varies with price. With the cost of laptop computers tumbling, the latest form of RTA involves an accessory box and software that works with your computer. These are particularly nice, and loaded with special memory, calculations and multipurpose functions like also being an elaborate SPL meter. Highly recommended if the budget allows.


Dynamic Controllers


Dynamic controllers or processors represent a class of signal processing devices used to alter an audio signal based solely upon its frequency content and amplitude level, thus the term "dynamic" since the processing is completely program dependent. The two most common dynamic effects are compressors and expanders, with limiters and noise gates (or just "gates") being special cases of these.


The dynamic range of an audio passage is the ratio of the loudest (undistorted) signal to the quietest (just audible) signal, expressed in dB. Usually the maximum output signal is restricted by the size of the power supplies (you cannot swing more voltage than is available), while the minimum output signal is fixed by the noise floor (you cannot put out an audible signal less than the noise). Professional-grade analog signal processing equipment can output maximum levels of +26 dBu, with the best noise floors being down around -94 dBu. This gives a maximum dynamic range of 120 dB (equivalent to 20-bit digital audio) -- pretty impressive number -- but very difficult to work with. Thus were born dynamic processors.


Compressors


Compressors are signal processing units used to reduce (compress) the dynamic range of the signal passing through them. The modern use for compressors is to turn down just the loudest signals dynamically. For instance, an input dynamic range of 110 dB might pass through a compressor and exit with a new dynamic range of 70 dB. This clever bit of processing is normally done using a VCA (voltage controlled amplifier) whose gain is determined by a control voltage derived from the input signal. Therefore, whenever the input signal exceeds the threshold point, the control voltage becomes proportional to the signal's dynamic content. This lets the music peaks turn down the gain. Before compressors, a human did this at the mixing board and we called it gain-riding. This person literally turned down the gain anytime it got too loud for the system to handle.


You need to reduce the dynamic range because extreme ranges of dynamic material are very difficult for sound systems to handle. If you turn it up as loud as you want for the average signals, then along comes these huge musical peaks, which are vital to the punch and drama of the music, yet are way too large for the power amps and loudspeakers to handle. Either the power amps clip, or the loudspeakers bottom out (reach their travel limits), or both -- and the system sounds terrible. Or going the other way, if you set the system gain to prevent these overload occurrences, then when things get nice and quiet, and the vocals drop real low, nobody can hear a thing. It's always something. So you buy a compressor.


Using it is quite simple: Set a threshold point, above which everything will be turned down a certain amount, and then select a ratio defining just how much a "certain amount" is. All audio below the threshold point is unaffected and all audio above this point is compressed by the ratio amount. The earlier example of reducing 110 dB to 70 dB requires a ratio setting of 1.6:1 (110/70 = 1.6). The key to understanding compressors is to always think in terms of increasing level changes in dB above the threshold point. A compressor makes these increases smaller. From our example, for every 1.6 dB increase above the threshold point the output only increases 1 dB. In this regard compressors make loud sounds quieter. If the sound gets louder by 1.6 dB and the output only increases by 1 dB, then the loud sound has been made quieter.


Some compressors include attack and release controls. The attack time is the amount of time that passes between the moment the input signal exceeds the threshold and the moment that the gain is actually reduced. The release time is just the opposite -- the amount of time that passes between the moment the input signal drops below the threshold and the moment that the gain is restored. These controls are very difficult to set, and yet once set, rarely need changing. Because of this difficulty, and the terrible sounding consequences of wrong settings, Rane correctly presets these controls to cover a wide variety of music and speech -- one less thing for you to worry about.


System overload is not the only place we find compressors. Another popular use is in the making of sound. For example when used in conjunction with microphones and musical instrument pick-ups, compressors help determine the final timbre (tone) by selectively compressing specific frequencies and waveforms. Common examples are "fattening" drum sounds, increasing guitar sustain, vocal "smoothing," and "bringing up" specific sounds out of the mix, etc. It is quite amazing what a little compression can do. Check your owner's manual for more tips.




Figure 8. Gate/Expander/Compressor/Limiter Action



Expanders


Expanders are signal processing units used to increase (expand) the dynamic range of the signal passing through it. However, modern expanders operate only below the set threshold point, that is, they operate only on low-level audio. Operating in this manner they make the quiet parts quieter. The term downward expander or downward expansion evolved to describe this type of application. The most common use is noise reduction. For example, say, an expander's threshold level is set to be just below the quietest vocal level being recorded, and the ratio control is set for 2:1. What happens is this: when the vocals stop, the signal level drops below the set point down to the noise floor. There has been a step decrease from the smallest signal level down to the noise floor. If that step change is, say, -10 dB, then the expander's output attenuates 20 dB (i.e., due to the 2:1 ratio, a 10 dB decrease becomes a 20 dB decrease), thus resulting in a noise reduction improvement of 10 dB. It's now 10 dB quieter than it would have been without the expander.


Limiters


Limiters are compressors with fixed ratios of 10:1 or greater. Here, the dynamic action prevents the audio signal from becoming any bigger than the threshold setting. For example, say the threshold is set for +16 dBu and a musical peak suddenly comes along and causes the input to jump by 10 dB to +26 dB, the output will only increase by 1 dB to +17 dBu -- basically remaining level. Limiters find use in preventing equipment and recording media overloads. A limiter is the extreme case of compression.


You will hear the term pumping used in conjunction with poorly designed or improperly set limiters. Pumping describes an audible problem caused by actually hearing the gain change -- it makes a kind of "pumping" sound. This is particularly a problem with limiters that operate too abruptly. Rest assured that Rane limiters are designed not to have any audible side-effects.


Noise Gates


Noise gates (or gates) are expanders with fixed "infinite" downward expansion ratios. They are used extensively for controlling unwanted noise, such as preventing "open" microphones and "hot" instrument pick-ups from introducing extraneous sounds into your system. When the incoming audio signal drops below the threshold point, the gate prevents further output by reducing the gain to "zero." Typically, this means attenuating all signals by about 80 dB. Therefore once audio drops below the threshold, the output level basically becomes the residual noise of the gate. Common terminology refers to the gate "opening" and "closing." A gate is the extreme case of downward expansion.


Just as poorly designed limiters can cause pumping, poorly designed gates can cause breathing. The term breathing is used to describe an audible problem caused by being able to hear the noise floor of a product rise and lower, sounding a lot like the unit was "breathing." It takes careful design to get all the dynamic timing exactly right so breathing does not occur. Rane works very hard to make sure all of its dynamic processors have no audible funny business.


Another popular application for noise gates is to enhance musical instrument sounds, especially percussion instruments. Correctly setting a noise gate's attack (turn-on) and release (turn-off) adds "punch," or "tightens" the percussive sound, making it more pronounced -- this is how Phil Collins gets his cool snare sound, for instance.


PDF "Signal Processing Fundamentals" This note in PDF.




 






Read More..

Tuesday, August 30, 2011

/* #HIDUP HANYA SEBENTAR# */

#include (SEBENTAR_senang) /* ganti tanda kurungnya dulu */
#include (SEBENTAR_sedih)
#include (SEBENTAR_bokek)
#include (SEBENTAR_berduit)
#include (SEBENTAR_ketawa)
int hidup(){
var SEBENTAR_lagi=1;
while (time==idul_fitri){
printf "LEBARAN Idul Fitri 1432H";
printf "untuk SEGENAP KELUARGA BESAR POLITEKNIK BANYUWANGI ";
printf "Saya mengucapkan Minal aidzin wal faidzin";
printf "Mohon Maaf Lahir Batin";
SEBENTAR_lagi--;
}

if (SEBENTAR_lagi==0){
salam_salaman;
}
if (salam_salaman==~);{
printf "Makan kue tetangga,sahabat,saudara,pacar,mantan,selingkuhan";
printf "minum softdrink tetangga,sahabat,saudara,pacar,mantan,selingkuhan";
printf "sebelum pulang jangan lupa minta angpau,pacar,mantan,selingkuhan";
printf "kalau g dikasi angpau bawa pulang kuenya,pacar,mantan,selingkuhan";
}
return 0;
}
Read More..

Tuesday, July 26, 2011

PROSES ADDRESS SPACE

Ketika user mode process meminta alokasi memori, maka proses tersebut bagi kernel :

  • Dianggap nonurgent sehingga proses tersebut tidak dengan segera mendapat alokasi memori.

  • Tidak bersih dari error sehingga kernel harus berusaha menangguli error yang ada.


Karena kernel berusaha sebisa mungkin untuk menunda permintaan alokasi memory maka user mode process menggunakan sebuah interval linier address yang baru yang merupakan bagian dari address space yang disebut memory region.

Address space sebuah proses terdiri dari semua linier address yang proses tersebut dapat gunakan. Interval linier address tersebut disebut memory region. Memory region dikarakterisasi dengan initial address, length (panjang) dan hak akses. Untuk alasan efisiensi, maka initial address dan panjang dari memory region harus merupakan kelipatan dari 4096.


  1. Memory descriptor

Segala informasi yang berhubungan dengan process address space terdapat dalam tabel referensi mm field dari process descriptor. Struktur data mm_struct :

struct mm_struct {

struct vm_area_struct *mmap, *mmap_avl, *mmap_cache;

pgd_t *pgd;

atomic_t count;

int map_count;

struct semaphore mmap_sem;

unsigned long context;

unsigned long start_code, end_code, start_data,

end_data;

unsigned long start_brk, brk, start_stack;

unsigned long arg_start, arg_end, env_start, env_end;

unsigned long rss, total_vm, locked_vm;

unsigned long def_flags;

unsigned long cpu_vm_mask;

unsigned long swap_cnt;

unsigned long swap_address;

void *segments;

};


Field yang penting :

  • pgd dan segments : menunjuk Page Global Directory dan Local Descriptor Table dari proses.

  • rss : menspesifikasikan jumlah page frame yang dialokasikan untuk proses.

  • total_vm : melambangkan ukuran proses dalam jumlah pages.

  • locked_vm : menghitung jumlah “locked” pages, yaitu pages yang tidak bisa diswap.

  • count : merupakan jumlah prses yang menggunakan mm_struct deskriptor yang sama.


Fungsi mm_alloc () digunakan untuk mendapatkan memori deskriptor yang baru. Karena deskriptor ini terletak dalam slab allocator cache, maka mm_alloc () memanggil kmem_cache_alloc () untuk menginisialisasi memori deskriptor baru dengan menduplikasi isi dari memori deskriptor yang ada dan countnya diset 1.


  1. Memory Regions

Memory region dideskripsikan degna vm_area struct :


struct vm_area_struct {

struct mm_struct *vm_mm;

unsigned long vm_start;

unsigned long vm_end;

struct vm_area_struct *vm_next;

pgprot_t vm_page_prot;

unsigned short vm_flags;

short vm_avl_height;

struct vm_area_struct *vm_avl_left, *vm_avl_right;

struct vm_area_struct *vm_next_share,**vm_pprev_share;

struct vm_operations_struct *vm_ops;

unsigned long vm_offset;

struct file *vm_file;

unsigned long vm_pte;

};


Tiap memory region deskriptor mengindentifikasi sebuah interval linier address tertentu. vm_start berisi linier address dalam interval yang pertama sementara vm_end berisi linier address pertama diluar interval sehingga vm_end – vm_start merupakan panjang dari memory region.

Memory region tiap proses tidak pernah overlap. Jika ada 2 memory region yang bersinggungan maka kernel akan berusaha untuk menggabungkannya. Jika tidak bisa maka akan dibuat saling bersebelahan saja. Pada proses dialokasi, jika yang didisalokasi ada ditengah-tengah sebuah memory region maka memory region tersebut akan terbagi 2.


  1. Page Fault Handler

Linux Page Fault exception handler harus membedakan eksepsi yang disebabkan oleh kesalahan programming dari eksepsi yang disebabkan oleh pengacuan ke sebuah page yang berada pada process address space , tetapi belum dialokasi. Fungsi do_page_fault()yang merupakan rutin servis interup Page Fault membandingkan linear address yang menyebabkan page fault dengan memori region dari proses current hal ini merupakan hal yang tepat untuk meng-handle exception.

Jenis page fault handler antara lain : copy on write, demand paging, send SIGSEGV, kill process and kernel “Oops”, dan “fixup code”.


  1. Copy on Write

Sistem Unix generasi pertama mengimplementasikan pembuatan proses dengan cara yang ceroboh : saat fork()dipanggil, kernel menduplikasi seluruh process address space parentdan meng-assign salinan proses ke child process. Kernel Unix modern memperkenalkan pendekatan yang lebih efisien yang disebut Copy OnWrite (COW). Idenya adalah daripada menduplikasi page frames, maka terjadi pembagian antara parent process dan child process.


  1. Managing the Heap

Setiap proses Unix mempunyai memory region spesifik yang disebut heap yang digunakan untuk memenuhi permintaan proses dinamik memori. Field memory descriptor start_brk dan brk membatasi alamat awal dan akhir pada region tersebut.

Fungsi libary C berikut bisa digunakan oleh proses untuk meminta dan membebaskan dynamic memory :

  • malloc (size), meminta ukuran byte dynamic memory

  • calloc(n, size), meminta sebuah array yang terdiri atas n elemen dari size, jika alokasi suskses maka akan menginisialisasi komponen array dengan 0 dan mengembalikan linear address dari elemen pertama.

  • free(addr), membebaskan memory region yang dialokasikan oleh malloc() atau calloc() yang mempunyai alamat inisial addr.

  • brk(addr), memodifikasi ukuran heap secara langsung, parameter addr menentukan nilai baru dari current->mm->brk, dan return value-nya adalah alamat akhir yang baru dari memory region.


Read More..

MEMORY MANAGEMENT




Beberapa bagian dari RAM digunakan oleh ke

rnel untuk menyimpan kode kernel dan struktur data statis kernel. Sisa dari bagian yang digunakan oleh kernel tersebut disebut dynamic memory. Dynamic memory ini tidak hanya digunakan oleh proses, tetapi juga oleh kernel senidri. Kualitas pe

rformansi dari keseluruhan sistem tergantung pada seberap

a efisien manajemen dynaimc memory. Manajemen mem

ori yang akan dibahas berikut menggambarkan bagaimana kernel mengalokasikan memori untuk keperluannya. Macam teknik manajemen memori :


1. Physically contigous memory areas

a. Page Frame Management

  1. Memory Area Management

  1. Physically noncontigous memory areas


a. Noncontigous Memory Area Management



Contiguous Memory Area Management


Page Frame Management




Linux menggunakan ukuran page frame 4KB sebagai standar untuk memory alocation unit, alasannya :

  1. Kernel bisa langsung mengetahui memory allocation unit di mana page fault terjadi.

  2. Ukuran 4KB merupakan kelipatan terkecil dari hampir seluruh ukura

    n blok disk.

Page frame descriptor diinisialisasi oleh fungsi free_area_init(), yang mempunyai 2 parameter : start_mem dan end_mem.

Kemudian fungsi mem_init() mengosongkan flag PG_reserved , dan flag PG_DMA dari semua page frame yang mempunyai alamat fisik sama dengan atau lebih besar dari 0x1000000.

Gambar 2 : Layout Memori



Requesting & Releasing Page Frame

Page frame bisa direquest dengan fungsi dan makro berikut :

  • _ _get_free_pages(gfp_mask, order), untuk merequest 2order page frame kontigu.

  • _ _get_dma_pages(gfp_mask, order), makro untuk mendapatkan page frame yang cocok untuk DMA; berkembang menjadi : _ _get_free_pages(gfp_mask | GFP_DMA, order).

  • _ _get_free_page(gfp_mask), makro untuk mendapatkan page frame tunggal, berkembang ke : _ _get_free_pages(gfp_mask, 0).

  • get_free_page(gfp_mask), fungsi yang

    memanggil _ _get_free_page(gfp_mask) dan kemudian mengisi page frame yang didapatkan dengan 0


Page frame bisa dibebaskan (direlease) melalui fungsi dan makro berikut :

  • free_pages(addr, order), fungsi yang mengecek page

    descriptor dari page frame yang mempunyai alamat fisik addr.

  • _ _free_page(p), membebaskan page frame yang descriptornya ditunjuk oleh parameter p.

  • free_page(addr), makro untuk membebaskan page frame dengan alamat fisik addr, berkembang ke free_pages(addr, 0).



Parameter gfp_mask menspesifikasikan bagaimana mencari page frame yang bebas. Terdiri atas flag – flag :

  • _ _GFP_WAIT , diset apabila kernel diijinkan untuk membuang isi page frame untuk membebaskan memori sebelum memenuhi request.

  • _ _GFP_IO, diset apabila kernel diijinkan untuk menulis page ke disk dengan tujuan membebaskan page frame yang bersangkutan.

  • _ _GFP_DMA, diset apabila page frame yang diminta harus sesuai untuk DMA.

  • _ _GFP_HIGH, _ _GFP_MED, _ _GFP_LOW, me

    nspesifikasikan prioritas request. _ _GFP_LOW biasanya diasosiasikan dengan request dynamic memory oleh proses User Mode, dan prioritas yang lain diasosiasikan dengan request dari kernel.



Buddy System Algorithm

Teknik yang digunakan linux untuk mengatasi fragmentasi eksternal adalah algoritma sistem buddy.


Sistem Buddy merupakan cara mengelola memori utama dengan memanfaatkan kelebihan penggunaan bilangan biner.

Semua page frame dibagi menjadi 10 list blok yang terdiri dari group 1, 2, 4, 8, 16, 32, 64, 128, 256, dan 512 page frame yang kontigu, secara berurutan : alamat page frame pertama dari blok merupakan kelipatan dari ukuran group, misalnya, blok frame 16 merupakan kelipatan dari 16 × 212

Misalnya suatu memori utama pada awalnya me

miliki satu lubang besar berukuran 1 Mbyte. Jika suatu proses A berukuran 90Kbyte memasuki memori, maka permintaan 90 Kbyte akan dialokasikan ke lokasi terdekat yang dapat memuatnya yaitu 128 Kbyte. Karena tidak tersedia blok ukuran 128, maka blok 1 Mbyte dipecah menjadi 2 blok masing-masing berukuran 512 Kbyte. Blok ini dibagi lagi menjadi blok-blok berukuran 256 Kbyte, selanjutnya masih dibagi menjadi blok-blok 1

28 Kbyte. Kemudian Proses B yang berukuran 50 Kbyte akan menempati lubang 64 Kbyte berikutnya dengan cara membagi blok 64 Kbyte. Jika tidak ada blok yang dapat dialokasikan maka akan melaporkan error.


Dengan menggunakan sistem buddy ini akan mudah melakukan dealokasi proses. Jika suatu proses dibebaskan, kernel akan melakukan penggabungan dari pasangan blok buddy yang bebas dengan ukuran b ke dalam blok tunggal dengan ukuran 2b. Dua blok dapat digabung jika kedua buddy mempunyai ukuran yang sama, dialokasikan pada alamat fisik yang kontigu, dan alamat fisik dari page pertama dari blok pertama merupaka kelipatan dari 2b x 212. Penggabungan ini dilakukan secara iteratif.

          1. Struktur Data


Linux menggnakan 2 sistem buddy yang berbeda. Satu sistem untuk meng-handle page frame yang sesuai untuk ISA DMA, sementara yang lainya meng-handle page frame yang tersisa. Masing-masing sistem buddy ini menggunkan struktur data :

  • array mem_map (array yang mengandung page frame descriptor).

  • array yang mempunyai 10 elemen dengan tipe free_area_struct, satu elemen untuk tiap ukuran group. Variabel free_area[0] menunjuk pada array yang digunakan sistem buddy untuk page frame yang tidak sesuai untuk ISA DMA

    , sementara free_area[1] menunjuk pada array yang digunakan sistem buddy untuk page frames yang sesuai untuk ISA DMA.

  • 10 array biner yang dinamakan bitmaps, 1 untuk tiap ukuran group. Tiap-tiap sistem buddy mempunyai himpunan bitmapsnya sendiri yang digunakan untuk menjaga track dari blok yang dialokasikan.



          1. Allocation


Untuk mengalokasikan suatu page frame, sistem buddy menggunakan function __get_free_pages().


Algoritma : Pertama mengecek apakah ada ruang yang cukup, yaitu jika nr_free_pages lebih besar daripada freepages.min. Jika tidak, maka perlu mendapatkan kembali page frame, atau tetap mengalokasikan dengan mengeksekusi kode y

ang terkandung di macro RMQUEUE_TYPE. Jika page frame telah dialokasikan, kode di macro RMQUEUE_TYPE mengeksekusi return statement, lalu menterminasi function __get_free_pages(). Kemudian jika kode pada RMQUEUE_TYPE dieksekusi lagi dengan parameter kedua = 1, maka request untuk alokasi memori dipenuhi dengan menggunakan page frame yang sesuai dengan DMA.

Macro kemudian melakukan pencarian blok yang tersedia pada list. Jika loop while (untuk search) selesai, jika tidak ada blok yang cocok yang ditemukan, maka __get_free_pages() mengembalikan nilai NULL, jik

a blok yang sesuai ditemukan, maka descriptor dari page frame pertama dihapus dari list, kemudian bitmap yang sesuai di update, dan melakukan decreament pada nilai nr_free_pages. Jika blok yang ditemukan berasal dari list mempunyai ukuran new_order lebih besar daripada ukurang yang direquest, loop while di eksekusi. Akhirnya, RMQUEUE_TYPE meng-update counter untuk page descriptor yang diasosiasikan dengan blok yang dipilih dan mengeksekusi instruksi hasil. Sebagai

hasilnya, function __get_free_pages() mengembalikan nilai alamat dari blok yang ditemukan


          1. Deallocation


Sistem buddy menggunakan function free_pages_ok() untuk membebaskan page frame dengan menggunakan 3 parameter input.

    • map_nr, yaitu nomor page dari salah satu page frame yang terkandung dari blok yang akan dibebaskan.

    • order, yaitu ukuran logik blok


    • type, biner, 1 jika page frame sesuai untuk DMA dan 0 jika tidak


Algoritma : Fungsi ini dimulai dengan men-declare dan menginisialisasi local variable.


struct page *next, *prev;

struct free_area_struct *area =&free_area[type][order];

unsigned long index = map_nr >> (1 + order);

unsigned long mask = (~0UL) << order;

unsigned long flags;


variabel mask mengandung komplemen dua dari 2order yang digunakan untuk mengubah map_nr ke dalam nomor dari page frame pertama blok yang dibebaskan dan untuk melakukan increament nr_free_pages.

Kemudian fungsi mulai mengeksekusi cycle paling banyak (9-order), satu kali untuk tiap kemungkinan untuk menggabungkan blok dengan buddynya. Di dalam body loop dilakukan pengecekan apakah buddy dari blok yang mempunyai map_nr bebas atau tidak. Pada akir iterasi, fungsi melakukan update terhadap mask, area, index, dan map

_nr. Kemudian fungsi ini melanjutkan pada iterasi selanjutnya, mencoba untuk menggabungkan blok-blok bebas untuk yang kedua kalinya menjadi satu blok bebas dengan ukuran yang lebih besar.



Memory Area Managemet



Manajemen memory area ini digunakan untuk mengatasi request untu memory area dengan ukuran kecil. Dengan adanya manajemen memory area maka internal fragmentation yang terjadi akibat adanya sistem buddy dapat dikurangi. Untuk iu digunakan algoritma slab allocator.

The Slab Allocator

Algoritma ini menggambarkan memory area sebagai objek-objek yang terdiri dari struktur data dan pasangan metode, yaitu constructor yang berfungsi untuk menginisialisasi memory area, dan destructor yang berfungsi untuk meng-deinisialisasi memory area. Objek-objek yang ada dikelompokkan ke dalam caches. Area dari main memory terdiri dari suatu cache yang dibagi menjadi slab-slab yang terdiri dari satu atau lebih page frame yang kontigu yang juga terdiri dari dari objek yang sudah dialokasikan dan yang masih bebas.


Gambar 3 : Keterhubungan Cache, Slab dan Objek



Slab allocator tidak pernah membuang objek yang telah dialokasikan, namun membebaskannya tetapi tetap menyimpannya di dalam memory. Hal ini dilakukan agar ketika ada request untuk objek baru maka dapat diambil dari memori tanpa melakukan inisialisasi ulang. Jadi secara umum, tujuan dari penggunaan slab allocator ini adalah untuk mengurangi pemanggilan buddy sistem allocator.

Kernel function cenderung untuk me-request memory area dengan tipe yang sama secara berulang-ulang sehingga tidak perlu melakukan alokasi dan dealokasi page frame yang mengandung memory area yang sama secara berulang-ulang, tetapi cukup dengan menyimpannya dalam cache dan menggunakan ulang ketika diperlukan.


Cache Descriptor

Tiap cache descriptor terdiri dari tabel dengan struktur data :

  • c_name, menunjuk nama dari cache

  • c_firstp, c_lastp, menunjuk first dan last slab descriptor dari cache.

  • c_freep, menunjuk slab descriptor pertama yang setidaknya mengandung satu objek bebas.

  • c_num, merupakan jumlah objek dalam satu slab tunggal. Semua slab dari suatu cache mempunyai ukuran yang sama.

  • c_offset, merupakan ukuran dari objek yang terkandung dalam suatu cache.

  • c_gfporder, angka logaritma dari jumlah page frame kontigu yang terdapat pada suatu slab tunggal.

  • c_ctor, c_dtor, menunjuk pada constructor dan destructor

  • c_nextp, menunjuk next cache descriptor

  • c_flags, suatu array flag yang mendeskripsikan beberapa permanent dari cache.


  • c_magic, mengandung magic number yang digunakan untuk mengecek keadaan suatu cache pada saat ini dan konsistensinya.


Slab Descriptor

Tiap slab pada cache mempunyai deskriptornya masing-masing dengan type struct kmem_slab_s. Field-field yang penting pada suatu slab descriptor antara lain :

  • s_inuse, merupakan jumlah objek pada slab yang sedang dialokasikan.


  • s_mem, menunjuk pada objek pertama pada slab, baik yang sudah dialokasikan ataupun yang masih bebas.

  • s_freep, menunjuk objek bebas pertama pada slab jika ada.

  • s_nextp, s_prevp, menunjuk next dan previous slab descriptor.


  • s_dma, diset oleh flag untuk menunjukkan bahwa objek pada slab dapat digunakan oleh DMA.

  • s_magic, mengandung magic number yang digunakan untuk mengecek keadaan suatu slab pada saat ini dan konsistensinya.

Slab descriptor disimpan dengan dua kemungkinan tergantung pada ukuran objek pada slab. Jika ukuran objek kurang dari 512 bytes, slab descriptor disimpan diakhir slab; dan sebaliknya jika ukuran objek dalam slab itu lebih dari 512 bytes maka slab descriptor disimpan di luar slab.



General And Specific Caches

Cache dibedakan menjadi dua jenis, yaitu general dan spesifik. General caches hanya digunakan oleh slab allocator untuk tujuannya, sementara cache spesifik digunakan oleh bagian lain dari kernel.

General caches terdiri dari :

  • Cache pertama yang terdiri dari cache deskriptor yang digunakan oleh kernel.

  • Cache kedua terdiri dari slab descriptor yang tidak disimpan dalam slab.

  • Tiga belas cache tambahan terdiri dari memori area yang terdistribusi secara geometri. Tabel dengan nama cache_sizes yang elemen-elemennya merupakan type cache_sizes_t yang menunjuk pada 13 cache descriptor yang diasosiasikan dalam memory area dengan ukuran : 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65

    536, dan 131072 bytes.

Specific caches dibuat oleh fungsi kmem_cache_sizes_init(). Berdasarkan parameter, fungsi ini pertama kali menentukan cara paling baik untuk meng-handle cache baru. Kemudian membuat cache descriptor untuk cache baru itu dan memasukkan descriptor ke dalam general cache cache_cache. Sekali cache sudah dibuat maka tidak dapat dihilangkan.


Allocating A Slab to A Cache

Cache yang baru dibuat tidak mengandung slab, oleh karena itu tidak mengandung objek bebas. Slab baru dapat di-assign ke dalam cache dengan syarat :

  • Request telah dikeluarkan untuk mengalokasikan objek baru.

  • Cache tidak mengandung objek bebas.


Ketika kedua syarat tersebut dipenuhi maka slab baru di-assign ke dalam cache dengan memanggil fungsi kmem_cache_grow(). Fungsi ini memanggil fungsi kmem_getpages() untuk mendapatkan kumpulan page frame dari buddy sistem, kemudian memanggil fungsi kmem_cache_slabmgmt() untuk mendapatkan slab descriptor baru. Kemudian memanggil fungsi kmem_cache_init_objs() yang menggunakan metode constructor kepada semua objek yang dikandung pada slab baru. Kemudian memanggil fungsi kmem_slab_link_end() yang memasukkan slab descriptor pada akhir list slab pada cache (insert last).


Releasing a Slab from a Cache

Slab allocator tidak pernah membebaskan page frame dari slab yang kosong, namun slab dapat dibebaskan hanya jika :

  • Buddy system tidak mampu memenuhi request page frame.

  • Slab kosong, dan semua objek yang dikandungnya bebas.


Ketika kernel mencari page frame bebas tambahan, maka kernel memanggil fungsi try_to_free_pages(). Fungsi ini mungkin memanggil fungsi kmem_cache_reap() yang memilih cache yang sedikitnya mengandung satu slab kosong. Kemudian fungsi kmem_slab_unlink() menghapus slab dari list. Kemudian dihilangkan sama sekali dengan menggunakan fungsi kmem_slab_destroy().


Object Descriptor

Seperti halnya slab descriptor, objek descriptor juga dapat disimpan dalam dua cara, yaitu:

  • External object descriptor

Objek descriptor disimpan di luar slab.

  • Internal object descriptor


Objek descriptor disimpan di dalam slab, ditempatkan sesudah objek yang dideskripsikannya.

Slab allocator akan menggunakan cara pertama (External object descriptor) jika ukuran objek kelipatan dari 512, 1024, 2048, atau 4096 karena jika untuk ukuran tersebut objek disimpan di dalam slab maka kemungkinan adanya internal fragmentation semakin besar. Jika ukuran objek kurang dari 512 bytes atau bukan merupakan kelipatan dari 512, 1024, 2048, atau 4096, maka objek tersebut disimpan di dalam slab.

Struktur data dari objek descriptor :

typedef struct kmem_bufctl_s {

union {

struct kmem_bufctl_s * buf_nextp;

kmem_slab_t * buf_slabp;

void * buf_objp;

} u;

} kmem_bufctl_t;

#define buf_nextp u.buf_nextp

#define buf_slabp u.buf_slabp

#define buf_objp u.buf_objp




buf_nextp, menunjuk objek bebas selanjutnya pada slab jika objek bebas.

buf_objp, menunjuk pada objek jika objek sudah dialokasikan dan objek descriptornya disimpan di luar slab.

buf_slabp, menunjuk pada slab descriptor dari slab dimana objek disimpan jika objek yang dialokasikan dan objek descriptornya disimpan di dalam slab.


Noncontiguous Memory Area Management


Pemetaan Memory area ke Page Frame yang kontigu lebih banyak digunakan karena penggunaan cache yang lebih maksimal dan waktu akses memori yang lebih rendah. Namun jika permintaan akses akan memori area jarang, maka alokasi berdasarkan page frame yang non kontigu melalui linier address yang kontigu dapat digunakan.

Keuntungan dari skema tersebut adalah menghindari external fragmentation. Hal ini dikarenakan penggunaan list yang besarnya telah ditentukan sebelum akan dialokasikan. Sedangkan kerugiannya adalah kita harus banyak berurusan dengan Page Table Kernel. Ukuran dari noncontiguous memory area merupakan kelipatan dari 4096. Linux menggunakan noncontiguous memory area untuk mengalokasikan struktur data untuk swap area aktif, alokasi space utnuk modul atau alokasi buffer untuk perangkat I/O.


Linier Address untuk Memori Area Nonkontigu

Untuk mencari interval linier address kita dapat memulai dari PAGE_OFFSET. PAG_OFFSET merupakan gigabyte keempat dari total 4 GB linier address yang bisa digunakan. Kita tahu bahwa Kernel menggunakan bagian awal dari memory dimulai dari PAGE_OFFSET ini. Namun itu hanya sebagian kecil saja. Semua linier address setelah bagian tersebut dapat bebas digunakan untuk memetakan noncontiguous memory area. Antara memory area yang satu dengan yang lain dipisahkan oleh interval 4-8 KB ( noncontiguous ).


Gambar 4 : Linier Address Gigabyte keempat


Deskriptor Memori Area Nonkontigu

Noncontiguous memory area dideskripsikan dengan struktur data vm_struct :


struct vm_struct {

unsigned long flags;

void *addr;

unsigned long size;

struct vm_struct *next; };


Deskriptor ini memiliki next yang mendefinisikan area selanjutnya. Address dari first element disimpan di variabel vmlist. Sedangkan addr menyimpan linier address untuk memory cell area yang pertama dan size menyimpan ukuran + 4096.

Fungsi get_vm_area () digunakan untuk membuat deskriptor baru dari tipe vm_struct tadi. Parameternya adalah size yang menspesifikasikan ukuran dari memory area yang diinginkan.

Fungsi get_vm_area () pertama kali memanggil kmalloc () untuk memperoleh memory area dari deskriptor yang baru. Fungsi tersebut mencari range linier yang memungkinkan untuk dialokasi dengan ukuran size + 4096. Jika range tersebut ada, maka fungsi tersebut akan mengembalikan initial address dari noncontiguous memory area dan jika gagal akan mengembalikan NULL.


Alokasi Memori Area Nonkontigu

Fungsi vmalloc () digunakan untuk mengalokasikan sebuah noncontiguous memory area pada kernel. Parameter yang digunakan adalah size yang menyatakan ukuran. Jika fungsi ini berhasil maka akan mengembalikan initial linier address dari area yang baru atau mengembalikan NULL jika gagal.

Pertama kali fungsi vmalloc () akan didekatkan ke kelipatan dari 4096. Selain itu akan diperiksa apakah size tadi > 0 dan <= jumlah page frame yang tersedia. Jika syarat tersebut dipenuhi maka vmalloc () akan memanggil fungsi get_vm_area () yang menciptakan deskriptor dan mengembalikan linier address yang diassign ke memory area. Lalu vmalloc () akan memanggil vmalloc_area_ pages () untuk merequest noncontiguous page frame dan diterminasi dengan mengembalikan initial linier address dari noncontiguous memory area.



Fungsi vmalloc_area_ pages () menggunakan 2 parameter : address, sebagai initial linier address dari area dan size sebagai ukuran. Akhir dari linier address merupakan penjumlahan dari address dengan size.

Fungsi vmalloc_area_ pages () menggunakan makro pgd_offset_k untuk menurunkan entry di Page Global Direktory yang berhubungan dengan initial address dari area yang dialokasi. Lalu fungis vmalloc_area_pages () tersebut dalam setiap siklusnya memanggil pmd_alloc_kernel () untuk membuat Page Middle Directory untuk area yang baru lalu memanggil alloc_area_pmd () untuk mengalokasikan semua Page Table yang berhubungan dengan Page Middle Directory baru tadi. Selanjutnya set_pgdir () dipanggil untuk mengupdate entry yang berkorespondensi dengan Page Middle Directory yang baru di semua Page Global Directories yang ada. Siklus ini berlangsung hingga semua Page Table entries yang merujuk ke noncontiguous memory area baru berhasil diset.

Dalam alloc_area_pmd () dipanggil pte_alloc_kernel () yang mengalokasikan Page Table yang baru dan mengupdate entry yang berkorespondensi dalam Page Middle Directory. Selanjutnya alloc_area_pte () mengalokasikan semua page frame yang berkorespondensi dengan entry di Page Table.

Setiap page frame dialokasikan melalui fungsi __get_free_page () yang dipanggil dalam alloc_area_pte (). Alamat fisik dari page frame yang baru ditulis ke dalam Page Table dengan macro set_pte dan mk_pte.


Releasing Memori Area Nonkontigu

Untuk membebaskan noncontiguous memory area digunakan fungsi vfree (). Parameter yang digunakan adalah addr yang berisi initial linier address area yang akan dibebaskan.

Pertama kali vfree () akan mencari area deskriptor yang berasosiasi dengan area yang akan dibebaskan. Size dari deskriptor mendefinisikan ukuran dari area yang akan dibebaskan. Area itu sendiri dibebaskan dengan fungsi vmfree_area_pages () sedangkan deskriptornya dengan fungsi kfree ().

Fungsi vmfree_area_pages () menggunakan 2 parameter : initial linier address dan size area. Di dalamnya akan memanggil free_area_pmd () yang merupakan kebalikan aksi dari alloc_area_pmd () dan free_area_pte () yang merupakan kebalikan aksi dari alloc_area_pte ().

Tiap page frame yang dialokasikan ke noncontiguous memory area dibebaskan dengan fungsi free_page () dan entry yang berkorespondensi di Page Table diset 0 dengan makro pte_clear.

Read More..