Posts

Showing posts with the label pi

Guide: Improving raspberry pi SD card lifetime for remote servers

 Having built two  rPI NAS boxes, I've had a chance to see how well they survive in the wild. The answer: each one has failed within a couple years. 

The first one failed because the power supply was undersized. It worked fine for a while, but eventually the powered hub that served the pi and the external hard drive could no longer support both, which killed the hard drive being used. Solution: but an external hard drive that comes with its own power brick. It had better be enough if they include it in the box. 

The 2nd one failed due to SD card corruption. This can be caused by power issues as well, but I don't think that's what happened. I think the issue is that it was too small, and too old. As with all flash devices there's a limited number of times each cell can be written before they start to fail. On a small SD card the number of cells is likewise small, so there's less space to spread the writes out. I was using a 2gb card, which had enough space to fit a lite pi OS install, but didn't have much spare space left over. I didn't need extra space for building a NAS, but that limited space means that there wasn't room to do write leveling.

Beyond that, it's worth trying to reduce the amount of writes to the SD card so that you don't even get into the point that significant write leveling is need. 

Reduce swapping

Some people think you should eliminate swap all together, but doing that risks causing the out of memory killer shutting software down indiscriminately. Instead, let's reduce the amount of swapping that happens. Linux swaps memory to disk opportunistically in order to maintain extra free memory for immediate use. This keeps your computer more responsive, but some of that swapping will be unnecessary. Let's reduce that as much as possible.

echo vm.swappiness = 0 >  /etc/sysctl.d/00-swappiness.conf

Note this file probably doesn't exist on your computer(yet); the default value is 60, which you can check with cat /proc/sys/vm/swappiness . Note that zero doesn't turn off swap entirely, just reduces opportunist swapping.  You might try running top to see how much swap is being used before you change this value. Don't expect the value to go down until after you reboot. 

RAMDISK logs or reduced logging

Logs can be a constant source of disk access. One option is to store them in ram instead, but then you lose them with each reboot (I like to reboot every week) and logs can be useful for catching configuration problems or failing hardware.

SSH is by far the biggest source of writes, at least on a world-accessible machine. Every 2-3 seconds it writes a new message reporting the latest attempt of somebody to log into your machine (as root, of course) via SSH. You can see this for yourself: 

watch -d ls -l /var/log

In theory this is an important thing to log and keep track of, because OMG, somebody is trying to hack your machine!!! But in reality it's all automated sniffing from botnets around the world and is meaningless noise unless you are building a honeypot. I certainly don't want to wear out my SD card keeping track of it.

Rather than putting all logs in ram, I suggest two less severe mitigations. One is security via obscurity: change your ssh port. You will get a lot less traffic with any port that's above 1024. Or, you can turn off logs of authentication attempts all together, which is my preference. You'd think that editing

/etc/ssh/sshd_config  to include  LogLevel QUIET

would do this, but you still get some messages; you also need to instruct rsyslog to reject all messages from sshd by adding 

 :programname, isequal, "sshd" stop  as the first rule in   /etc/rsyslog.conf

But you are not done; you still get failed logins recorded to a binary file called /var/log/btmp. btmp exists outside the syslog framework, so you can't block it that way. The activity comes from openssh and can only be turned off by recompiling openssh! Yikes, what a dumb choice that is. There's a file system work-around though: you can make btmp immutable:

chattr +i /var/log/btmp

Finally, there's the systemd journal, which is the modern duplicate of syslog. That is to say both should have all the messages you care about in them, but you use different tools to search them. systemd journal has much less options for controlling what gets written to it, and I find that >90% of it is failed logins, even after the tweaks above.  Two options: make it volatile, (entirely stored in memory), or change the rate at which it's flushed to disk (default is every 5 minutes). These options are in /etc/systemd/journald.conf

It seems like by far the easiest option is to change your SSH port.

Stop recording access time

Linux records the last time files were accessed, so a regularly running system is going to incur some writes just from reading configuration files, etc.. There's already an /etc/fstab option that's the default on newer releases of PiOS to keep this to a minimum called noatime, but it's also suggested that adding norelatime would reduce the writes further. Might as well. 






Pi0 and Pi0w GPIO layout map with landmarks

After counting pins many times to figure out where to wire up a Pi0 / pi0 Wireless it occurred to me that there might be some landmarks on the printed circuit board that would make it easier to find the desired GPIO pin without counting. The photos below are my attempt at this idea, and it does work, though it would be much better if the Pi folks had added a few silkscreened labels for this purpose.  Next rev, perhaps?

If you print these: these look good at 150 dpi in color, or as large as you can go in black and white.

As always, pin 1 is closest to the SD card slot.







postscript: I scavenged the board images and GPIO layout diagrams from the internet, so I cannot claim any ownership of the final composited image, just the idea. Instead of trying to stake a claim, however, I'd just enjoy if people could take this idea and make it better, perhaps improving the printability of the resulting image (the circuit board is awfully muddy on my printer). 

automatic port forwarding for the raspberry pi NAS

My pi-based NAS is working great, but I'd like it to be more robust to being moved between networks/routers. In particular I need an external port opened up for SSH. There's a nice tool for this called miniupnp which is in the raspberry pi repositories (you will have to apt-get install it).

This page describes how to automate port forwarding with upnp nicely, but since links are fragile, here's the key script:

#!/bin/bash
export LC_ALL=C

upnpc="upnpc " # extra options here
external=3333
port=22
ip=$($upnpc -l | grep "Local LAN ip address" | cut -d: -f2)

$upnpc -d $external TCP >/dev/null 2>&1
$upnpc -a $ip $port $external TCP >/dev/null 2>&1
you put this script where it will be executed any time you get a new IP from your router:
/etc/dhcp/dhclient-exit-hooks.d/
and just to be safe call it every time you reboot as well (you don't get a new IP from your router each time you reboot, so this script won't be called otherwise).
crontab -e
@reboot sleep 10 /etc/dhcp/dhclient-exit-hooks.d/port_forward
FYI not all routers support UPNP for instance ATT U-verse does not.

Enable root login on Raspberry Pi & create MS DOS for the 21st century!

I use my Raspberry Pi like a MS-DOS computer for 21st century, so of course I want to run as root - and login that way too. It's easy:

Give root a password:

sudo passwd root

enable login as root:

sudo nano /etc/ssh/sshd_config

find (ctrl-w): #PermitRootLogin prohibit-password

make it look like

PermitRootLogin yes

then restart ssh:

sudo service ssh restart

Of course it's dangerous to run as root, but if you want to access hardware directly it's the only way to go. You might think about setting up a trashcan alternative to rm since you can get yourself into a lot of trouble with those two letters plus a typo or to.  Add this to the end of your .bashrc

alias emptyTrash='ls ~/.trashcan; du -sh ~/.trashcan; rm ~/.trashcan/* -rf'
del () { du -sh $*; mv $* ~/.trashcan/; }
[[ $- == *i* ]] && du -sh ~/.trashcan

and then in your home folder, do this once:

mkdir .trahscan

also why not autologin as root on the console?

First, use raspi-config to enable autologin for the pi user, then fix it to use root instead:

 nano /etc/systemd/system/getty@tty1.service.d/autologin.conf

give yourself a line line this:

ExecStart=-/sbin/agetty --autologin root --noclear %I $TERM

Introducing the piLagTesterPRO - a complete input lag testing kit for your Raspberry Pi

The piLagTesterPRO measures input lag (the delay between signal being sent to your display and being able to see it) using a high-temporal resolution brightness sensor. In contrast to my previous input lag device that used a pi zero + a high speed camera, this is a complete package you plug into to your Raspberry Pi.

UPDATE: order the piLagTesterPRO here. 

Because it runs on the Pi, it's possible to display what's being sampled in real time, which at the very least is interesting to look at, but can also help diagnose what's going on as you change display settings or if you get unexpected variance in the lag reported. Here's a live photo of it in use:



The sideways graph in the center is the brightness recorded with the sensor, time locked to when the white probe rectangles were displayed on the right side of the screen (the top one is cut off by the sensor itself). The sawtooth shape throughout is caused by the display back-light being pulsed, and yes it complicates measuring lag. What we are interested in is the peaks of that sawtooth over time. 

If your color sensitivity is excellent you might be able to see that the graph is color coded:
  • the white region at the top is what happened after the probe signal was sent over the video cable, but before the display responded.
  • the start of the red region is where the piLagTesterPRO detected that the display has started to respond to the new input. I call this the "1st response". This is what is typically reported as input lag.
  • the end of the red region and the start of the final, yellow region is when the display has finished responding to the probe. I call this the "full response". This is typically reported as response time - note here it is black to white response time, which is not the same as gray-2-gray which manufacturers report, but the idea is similar.
Determining the 1st response and full response is a somewhat tricky affair if your monitor's brightness drifts over time (many/all do). To this end the program can average over as many trials as you wish. 

The other nice thing about running on a Pi is it's possible to save all the data collected for later analysis. Here's an example of the pretty plots one can make using octave:  


The horizontal lines show the maximum brightness before the probe is shown, and after. The x and the o are the automatically extracted 1st and full responses. These are set when the measured brightness has gone 5% and 80% of the way to the maximum brightness post-probe. You'll notice that it takes a really long time to reach 100% - over 150ms in this example. This is why I use the 80% point instead. The human visual system tends to respond to the log of brightness anyway, so the difference between 80% and 100% is not that salient. 

In the octave code I've written you can click where you think the 1st response should be and compare that average to the automatically extracted one if you wish. 

At the moment there's no photo of the device - because it's a pile of wires on my workbench. I'm not really sure where to go from here in that regard - building a nice box is really beyond my means and interest. I think I could put together a kit of parts already connected/soldered so that all you would have to do is plug it in to the GPIO header on your Pi, but it would still have a DIY ethos and appearance. 

I'd be curious to hear how interested people would be in owning one of these kits to add to their raspberry pi, and how important it be that it look like a professional project.

Update: here's some input lag data collected with the piInputLagPRO. Some interesting results already, like an TV that scans-out at faster than the display refresh rate.

Publicly available hardware is available now for $40, so if you are interested in getting one use the email option below to contact me. 

added to the piLagTester: test images generator to check for scaling and cliping

Of significant interest to retro gaming enthusiasts is how the display upscales low resolution input (such as 640p) to the native resolution of the display. Somewhat shockingly I've even found that some panels will scale/clip native resolution input too!!

To that end I've written some simple test image generating programs for my piLagTester program (and upcoming piLagTesterPro). Obviously this has little to do with display lag, but it's a sensible place to stash them given that they also run on a Raspberry pi (chosen for maximal physical portability) and relate to display characterization.

The first is lines, which just draws a set of 45 degree lines on the screen, starting at the upper left corner. This gives an easy way to see if the upscaling is picture perfect or not.

Here are two examples of 45 degree lines that aren't clean (none of this is camera artifacts).



The nice thing is this is generated pixel perfect on demand for the current resolution, so you can do tv480i; lines at the command prompt to test that resolution, or tv1080p; lines, etc. (the semicolon allows two commands on one line, you could substitute for ;). 

The other test generator is called dots. By default it produces a checkerboard where each check is 1 pixel. On most modern screens this is going to look gray. The question is, does it look uniform gray, or does the gray vary vertically or horizontally, indicating sampling issues in the upscaler. I literally can't take a photo of this, because it's a camera's worst nightmare.

The program has a bonus option that lets you set the check size which can be handy, sometimes the upscaling issues only appear at 2 or 3 pixel sized checks. And if you use a check-size of 20 or more, it doubles as a clipping tester, which I can show you, though it too is hard to photograph. Below is an example with 20 pixel wide checks:


In this photo you can see that first check that's fully visible starts 40 pixels from the left edge. Checks are spaced every 20 pixels, so that means that about (can you guess?)........... 20 pixels are cut off here. Note: the same resolution changing options work here as with lines (ie tv720p;check 20)

If you want to give them a try on your Raspberry Pi download them here.





Raspberry Pi Zero as a high-speed datalogger

How well suited is the RPI zero as a high speed data logger? Depends on the definition "high speed", but I was able to sample a 16 bit number about 10 times per millisecond over the ic2 bus, and you could probably do better.

(1) The Pi can keep up!
I'm using a relatively bog-standard distribution of Linux on a raspberry pi zero, not RT linux or anything like that. My sampling device is the TI ADS1015, which only provides 3300 unique samples per second at 12 bits. That's  3.3 samples per millisecond, so the pi is overkill for keeping up with it.

Now, that's not to say it's always hitting every 0.1ms mark. (1) is a representative graph of the time between samples taken over the IC2 bus in a tight loop(1*) without any other significant activity going on (networking is active, but not pushing anything in or out) for 300ms.  Killing the network hardware and stack does improve things, maybe 25% more samples? I've not measured carefully).
This is running as root, with nice(-18); during capture (and 0 otherwise to unstarve the kernel/whatever). As you can clearly see there are some regular glitches in the capture, apparently every 120ms, which is an odd frequency, I don't know what that is). But in my use case, 5 samples per MS still beats the ADS1015. Occasionally I do actually drop a single ADS1015 sample on the floor, but it's rare, and in my use case I can just repeat the measurements again automatically if the glitch occurs in an important part of the data. 

To underscore that point see (2), the histogram of the same data showing the count of samples taken more than 0.1ms appart (everything near 0.1 ms and below is waaaaay off the top of the chart).  Data only get lost on average when the delta is > 0.3ms, which only happened 5 times, out of ~3500 samples. 

(2) very few dropped samples
I'm satisfied, especially given that this $5 device has a HDMI port, which is critical for my use case. 



notes:
(1*)

int readval() {
  if (read(fd, readBuf, 2) != 2)  // read conversion register
{ perror("Read conversion"); exit(-1); }
 return readBuf[0] << 8 | readBuf[1]; // could also multiply by 256 then add readBuf[1]
 }

for(...) {
 on_buff[i]=readval();
 on_times[i] =  (microsec();- start); 
}

Email me

Name

Email *

Message *