Search Results: "ron"

23 March 2014

David Moreno: New Debian mailing list: debian-astro

I will try to report my Debian activities here. I am trying to retake them and as I'm usually busy at work, I have limited amount of time to do so, they stand small for now. A new mailing list, debian-astro, has been created. This was requested to create a space to allow a discussion space around astronomy for Debian, both for professionals and amateurs, to potentially look into a blend, and in general to talk about packaging and development of astronomy-related tools into Debian. Thanks to those interested on making this happen. Go subscribe today!

22 March 2014

Lars Wirzenius: Obnam 1.7.1 and 1.7.2 releases (backup software)

I have just released version 1.7.2 of Obnam, my backup program. While I was releasing 1.7.1, I found a new problem, so I fixed that. Due to sillinesses in my CI/release system, I had to bump the version number to 1.7.2. Version 1.7.2, released 2014-03-22 Bug fixes: Version 1.7.1, released 2014-03-22 Bug fixes:

Keith Packard: glamor-core

Core Rendering with Glamor I ve hacked up the intel driver to bypass all of the UXA paths when Glamor is enabled so I m currently running an X server that uses only Glamor for all rendering. There are still too many fall backs, and performance for some operations is not what I d like, but it s entirely usable. It supports DRI3, so I even have GL applications running. Core Rendering Status I ve continued to focus on getting the core X protocol rendering operations complete and correct; those remain a critical part of many X applications and are a poor match for GL. At this point, I ve got accelerated versions of the basic spans functions, filled rectangles, text and copies. GL and Scrolling OpenGL has been on a many-year vendetta against one of the most common 2D accelerated operations copying data within the same object, even when that operation overlaps itself. This used to be the most performance-critical operation in X; it was used for scrolling your terminal windows and when moving windows around on the screen. Reviewing the OpenGL 3.x spec, Eric and I both read the glCopyPixels specification as clearly requiring correct semantics for overlapping copy operations it says that the operation must be equivalent to reading the pixels and then writing the pixels. My CopyArea acceleration thus uses this path for the self-copy case. However, the ARB decided that having a well defined blt operation was too nice to the users, so the current 4.4 specification adds explicit language to assert that this is not well defined anymore (even in the face of the existing language which is pretty darn unambiguous). I suspect we ll end up creating an extension that offers what we need here; applications are unlikely to stop scrolling stuff around, and GPUs (at least Intel) will continue to do what we want. This is the kind of thing that makes GL maddening for 2D graphics the GPU does what we want, and the GL doesn t let us get at it. For implementations not capable of supporting the required semantic, someone will presumably need to write code that creates a temporary copy of the data. PBOs for fall backs For operations which Glamor can t manage, we need to fall back to using a software solution. Direct-to-hardware acceleration architectures do this by simply mapping the underlying GPU object to the CPU. GL doesn t provide this access, and it s probably a good thing as such access needs to be carefully synchronized with GPU access, and attempting to access tiled GPU objects with the CPU require either piles of CPU code to de-tile accesses (ala wfb), or special hardware detilers (like the Intel GTT). However, GL does provide a fairly nice abstraction called pixel buffer objects (PBOs) which work to speed access to GPU data from the CPU. The fallback code allocates a PBO for each relevant X drawable, asks GL to copy pixels in, and then calls fb, with the drawable now referencing the temporary buffer. On the way back out, any potentially modified pixels are copied back through GL and the PBOs are freed. This turns out to be dramatically faster than malloc ing temporary buffers as it allows the GL to allocate memory that it likes, and for it to manage the data upload and buffer destruction asynchronously. Because X pixmaps can contain many X windows (the root pixmap being the most obvious example), they are often significantly larger than the actual rendering target area. As an optimization, the code only copies data from the relevant area of the pixmap, saving considerable time as a result. There s even an interface which further restricts that to a subset of the target drawable which the Composite function uses. Using Scissoring for Clipping The GL scissor operation provides a single clipping rectangle. X provides a list of rectangles to clip to. There are two obvious ways to perform clipping here either perform all clipping in software, or hand each X clipping rectangle in turn to GL and re-execute the entire rendering operation for each rectangle. You d think that the former plan would be the obvious choice; clearly re-executing the entire rendering operation potentially many times is going to take a lot of time in the GPU. However, the reality is that most X drawing occurs under a single clipping rectangle. Accelerating this common case by using the hardware clipper provides enough benefit that we definitely want to use it when it works. We could duplicate all of the rendering paths and perform CPU-based clipping when the number of rectangles was above some threshold, but the additional code complexity isn t obviously worth the effort, given how infrequently it will be used. So I haven t bothered. Most operations look like this:
Allocate VBO space for data
Fill VBO with X primitives
loop over clip rects  
    glScissor()
    glDrawArrays()
 
This obviously out-sources as much of the problem as possible to the GL library, reducing the CPU time spent in glamor to a minimum. A Peek at Some Code With all of these changes in place, drawing something like a list of rectangles becomes a fairly simple piece of code: First, make sure the program we want to use is available and can be used with our GC configuration:
prog = glamor_use_program_fill(pixmap, gc,
                               &glamor_priv->poly_fill_rect_program,
                               &glamor_facet_polyfillrect);
if (!prog)
    goto bail_ctx;
Next, allocate the VBO space and copy all of the X data into it. Note that the data transfer is simply memcpy here that s because we break the X objects apart in the vertex shader using instancing, avoiding the CPU overhead of computing four corner coordinates.
/* Set up the vertex buffers for the points */
v = glamor_get_vbo_space(drawable->pScreen, nrect * (4 * sizeof (GLshort)), &vbo_offset);
glEnableVertexAttribArray(GLAMOR_VERTEX_POS);
glVertexAttribDivisor(GLAMOR_VERTEX_POS, 1);
glVertexAttribPointer(GLAMOR_VERTEX_POS, 4, GL_SHORT, GL_FALSE,
                      4 * sizeof (GLshort), vbo_offset);
memcpy(v, prect, nrect * sizeof (xRectangle));
glamor_put_vbo_space(screen);
Finally, loop over the pixmap tile fragments, and then over the clip list, selecting the drawing target and painting the rectangles:
glEnable(GL_SCISSOR_TEST);
glamor_pixmap_loop(pixmap_priv, box_x, box_y)  
    int nbox = RegionNumRects(gc->pCompositeClip);
    BoxPtr box = RegionRects(gc->pCompositeClip);
    glamor_set_destination_drawable(drawable, box_x, box_y, TRUE, FALSE, prog->matrix_uniform, &off_x, &off_y);
    while (nbox--)  
        glScissor(box->x1 + off_x,
                  box->y1 + off_y,
                  box->x2 - box->x1,
                  box->y2 - box->y1);
        box++;
        glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, nrect);
     
 
GL texture size limits X pixmaps use 16 bit dimensions for width and height, allowing them to be up to 65536 x 65536 pixels. Because the X coordinate space is signed, only a quarter of this space is actually useful, which makes the useful size of X pixmaps only 32767 x 32767. This is still larger than most GL implementations offer as a maximum texture size though, and while it would be nice to just say we don t allow pixmaps larger than GL textures , the reality is that many applications expect to be able to allocate such pixmaps today, largely to hold the ever increasing size of digital photographs. Glamor has always supported large X pixmaps; it does this by splitting them up into tiles, each of which is no larger than the largest texture supported by the driver. What I ve added to Glamor is some simple macros that walk over the array of tiles, making it easy for the rendering code to support large pixmaps without needing any special case code. Glamor also had some simple testing support you can compile the code to ignore the system-provided maximum texture size and supply your own value. This code had gone stale, and couldn t work as there were parts of the code for which tiling support just doesn t make sense, like the glyph cache, or the X scanout buffer. I fixed things so that you could leave those special cases as solitary large tiles while breaking up all other pixmaps into tiles no larger than 32 pixels square. I hope to remove the single-tile case and leave the code supporting only the multiple-tile case; we have to have the latter code, and so having the single-tile code around simply increases our code size for not obvious benefit. Getting accelerated copies between tiled pixmaps added a new coordinate system to the mix and took a few hours of fussing until it was working. Rebasing Many (many) Times I m sure most of us remember the days before git; changes were often monolithic, and the notion of changing how the changes were made for the sake of clarity never occurred to anyone. It used to be that the final code was the only interesting artifact; how you got there didn t matter to anyone. Things are different today; I probably spend a third of my development time communicating how the code should change with other developers by changing the sequence of patches that are to be applied. In the case of Glamor, I ve now got a set of 28 patches. The first few are fixes outside of the glamor tree that make the rest of the server work better. Then there are a few general glamor infrastructure additions. After that, each core operation is replaced, one a at a time. Finally, a bit of stale code is removed. By sequencing things in a logical fashion, I hope to make review of the code easier, which should mean that people will spend less time trying to figure out what I did and be able to spend more time figuring out if what I did is reasonable and correct. Supporting Older Versions of GL All of the new code uses vertex instancing to move coordinate computation from the CPU to the GPU. I m also pulling textures apart using integer operations. Right now, we should correctly fall back to software for older hardware, but it would probably be nicer to just fall back to simpler GL instead. Unless everyone decides to go buy hardware with new enough GL driver support, someone is going to need to write simplified code paths for glamor. If you ve got such hardware, and are interested in making it work well, please take this as an opportunity to help yourself and others. Near-term Glamor Goals I m pretty sure we ll have the code in good enough shape to merge before the window closes for X server 1.16. Eric is in charge of the glamor tree, so it s up to him when stuff is pulled in. He and Markus Wick have also been generating code and reviewing stuff, but we could always use additional testing and review to make the code as good as possible before the merge window closes. Markus has expressed an interest in working on Glamor as a part of the X.org summer of code this year; there s clearly plenty of work to do here, Eric and I haven t touched the render acceleration stuff at all, and that code could definitely use some updating to use more modern GL features. If that works as well as the core rendering code changes, then we can look forward to a Glamor which offers GPU-limited performance for classic X applications, without requiring GPU-specific drivers for every generation of every chip.

21 March 2014

Sylvestre Ledru: Rebuild of Debian using Clang 3.4

Using the AWS donation, David Suarez and myself have been able to rebuild the whole archive with Clang 3.4.
The rebuild has been done January 10th but, with my new job, I did not find the time to publish the result.
Releases after releases, the results are getting better and better. Currently, 2193 packages in the archive are failing to build from source.
That is roughly the same number of build failures as with the precedent rebuild with Clang 3.3.
However, this is good news for two reasons:
* the number of new packages in Debian increased (18854 at time of the 3.3 release, 21204 for the 3.4)
* clang 3.4 has more checks and error detections. I also started to update clang to make it closer to gcc. For example, I transformed wrong usage of -O (> 6) error to be treated as regular warning. However, a critical bug has emerged during this release. When using -D_FORTIFY_SOURCE=2 (which is the case of many Debian packages), the binaries produced freeze (infinity loop in the ASM). This has been reported upstream as bug 16821 and concerns about 150 packages (including Firefox, gcc, LLVM, etc). Hopefully, this will be fixed in 3.5 (this is unlikely for 3.4.1). About the new build failures, now, Clang triggers an error (or warning + -Werror) on: * Wrong usage of the default argument (should be done in the definition)
16 occurrences * Usage of C++11 feature without the appropriate argument
7 occurrences * Unused static const declaration
5 occurrences * Recursive template instantiation exceeded
4 occurrences * Defitinion of a builtin function
3 occurrences * Read-only variable is not assignable
2 occurrences By the way, I proposed a Google Summer of Code Project to work faster on a support of Debian built by Clang. As requirements, I asked students to fix some bugs, they already did a great job.

Justus Winter: Debian/Hurd switches to sysvinit

Previously, Debian/Hurd used a home-grown init system. Last year, I participated in the gsoc and set out to make it boot using sysvinit instead. On Debian/Hurd, one can switch between the available init systems using update-alternatives(8). With the latest Debian/Hurd packages uploaded earlier today, the priority of the old init system was lowered so that sysvinit is preferred. So as of now, Debian/Hurd is using sysvinit by default. (If you are upgrading your Debian/Hurd installation now, please remember that you must use reboot-hurd or halt-hurd to shut it down whenever you switch to a different init system.) And because screenshots of booting operating systems are just awesome, here is a current one. Note how smooth it is:
start ext2fs: Hurd server bootstrap: ext2fs[device:hd0s1] exec init proc auth
INIT: version 2.88 booting
Using makefile-style concurrent boot in runlevel S.
Activating swap...done.
Checking root file system...fsck from util-linux 2.20.1
/dev/hd0s1: clean, 29799/181056 files, 206131/723200 blocks
done.
Creating compatibility symlink from /etc/mtab to /proc/mounts. ... (warning).
mount: cannot remount /proc: Invalid argument
Activating lvm and md swap...done.
Checking file systems...fsck from util-linux 2.20.1
done.
Cleaning up temporary files... /tmp.
Mounting local filesystems...done.
Activating swapfile swap...done.
Cleaning up temporary files....
Configuring network interfaces...Internet Systems Consortium DHCP Client 4.2.2
Copyright 2004-2011 Internet Systems Consortium.
All rights reserved.
For info, please visit https://www.isc.org/software/dhcp/
Listening on Socket//dev/eth0
Sending on   Socket//dev/eth0
DHCPDISCOVER on /dev/eth0 to 255.255.255.255 port 67 interval 7
DHCPREQUEST on /dev/eth0 to 255.255.255.255 port 67
DHCPOFFER from 10.0.2.2
DHCPACK from 10.0.2.2
bound to 10.0.2.15 -- renewal in 40021 seconds.
done.
Cleaning up temporary files....
INIT: Entering runlevel: 2
Using makefile-style concurrent boot in runlevel 2.
Starting enhanced syslogd: rsyslogd.
Starting deferred execution scheduler: atd.
Starting periodic command scheduler: cron.
Starting OpenBSD Secure Shell server: sshd.
Debian GNU/Hurd jessie/sid debian console
login:

Michal Čihař: Automatically checking pull request on GitHub

Since introduction of Developer's Certificate of Origin in phpMyAdmin, we've struggled with automatically checking pull requests on GitHub that they match this. First attempt was to integrate this check into Travis environment, but that proven to be hard to understand by potential contributors as it did not give direct feedback what went wrong. So it was still useful for us, but still we had to explain the situation. With recent flood of contributions from potential GSoC students, it became quite tedious task. So let's automate that. GitHub has quite powerful API, so it should not be that hard. Looking at Webhooks documentation, it is quite easy to get hooked on pull request creation and updates and checking commits and adding comments is just a piece of cake. The hardest choice was choosing language in which to implement it :-). While not finding binding for GitHub in any of my favorite language packaged in Debian. I've decided to hack this quickly in PHP without using any library and if this turns out to be limitation in future, it can be easily rewritten. First incarnation of our commit checker did check just Signed-Off-By lines in commit messages, but I've found that there might be some other useful checks. So the script got extended for various simple coding style violations, which we see quite often like wrong indentation or using DOS end of lines (the example of all fired checks can be found in pull request 1081). You can find the code for it in our scripts repository.

Filed under: English phpMyAdmin 0 comments Flattr this!

20 March 2014

Laura Arjona: Hello, world! I m a Debian contributor

My blog is included now in Planet Debian, so this post is to say hello :) And what can be better to explain who I am, that saying that I am a Debian Contributor? What does Debian Contributor mean? There are lots of tasks that people accomplish to make Debian better, and Debian Contributor is a new hat to credit any participation in the Debian Project, of any kind (even if the contributor is not a full-member of Debian). The idea was started and promoted by Enrico Zini. In less than one year, a website with a list of Debian Contributors, data source schemes and much more pieces have been designed. The site is working, and evolving, according to a roadmap. There are some working data sources already, some other proof of concept , pending to adopt or refine. There are much more kind of contributions that still have no data source created. Everybody can help on that! An example: my contributions I m listed now as wiki editor (at least, I edit once a month when doing my spam fighting tasks), website committer (I upload translations to the Spanish part of the website), and publicity (I ve sent some news to Debian Project News from time to time). Having your name in a list may seem a small thing, but happiness is made of small things!! The website committers data source is one of the proof of concepts and it s not being updated recently. I hope that somebody in the www team takes care of that oh wait, I m part of the www team I m part of the Spam Fighting Force too, but the data source tracks the spam reports reviewers, and I don t do that, I only report spam. That s why I m not there (yet). I m also a translator, member of the Spanish team. Translators are already credited in the translation coordination pages (for example this one), but we want to include them in the main list of Debian Contributors too. That means modifying the bot that tracks the mailing lists. I have joined the i18n team and I hope I can understand how it works and try to propose the required changes. If in the meanwhile, other person comes with the solution, the better! I have given a talk (and two lightning talks) in the last MiniDebConf Barcelona 2014. Most of the speakers in Debian events are available via the Debconf website, for example: http://penta.debconf.org/dc13_schedule/speakers.en.html I m sure a data source can be created somehow! More examples of data sources As I said, these are only examples (it s not about crediting my contributions, but everybody s). So if you explore the already managed data sources, you can find the Debian Sysadmin and Security teams, package maintainers, package uploaders to FTP sites, committers to several source code repositories of Debian-related software, people helping mentoring other people in Debian, people helping in the New Member process, people subtitling talks But we need more!! Please have a look at DcSiteDevel where you can learn how to create a data source and the tools for extracting information in an easy way. If each Debian Team cares of their own data source (which allows to credit their members) it is a sustainable way and also improves those Team s visibility (and new contributions, probably!). Identity management The last updates to Debian Contributors project are about identity management. Right now the site only shows data of contributors having a @debian.org account or an account in Alioth (the Debian software forge, used for many subprojects). It also uses the email field to merge contributions made in areas where you login with other kind of user (e.g. the wiki). This is a great step towards crediting people that are not full Debian members (yet), if they want their names to appear in the Debian Contributors list (they can opt-out too, or show/hide each contribution separately). So, what next? There is a Roadmap and a TODO list. But nobody as individual can know all the roles and actual work in the Debian project. It s better that each team cares about how to send their contribution info to the site. There are some mining tools available to extract for example names of committers in source code repositories, or senders in mailing lists. Not much code is required. Please think about it and join the wave of making Debian diversity skills more visible!
Filed under: Interesting sites, My experiences and opinion, Uncategorized Tagged: Communities, Contributing to libre software, data mining, Debian, Developer motivations, English, libre software, Project Management, statistics, translations

Daniel Pocock: xTuple consults community on best license options

xTuple, the makers of PostBooks, the compelling PostgreSQL-based accounting and CRM suite have started a discussion about how to move to a more recognised license. It is really good to see a company dealing with these issues in an open manner and engaging the community for feedback. For those who are familiar with these issues or have practical experience of how businesses have been successful with GPL and other free licenses, please share your comments on John's blog. Some of the reasons why companies need to think about licensing issues like this:
  • They not only want to be open source, they also want to engage the community through Github, hoping to make it easier for developer collaboration. A familiar license makes this easier.
  • They want to extend the product more rapidly by using other open source libraries and need to maintain compatibility of licenses. Using a less well known license can make this more awkward. In the case of xTuple, they are now using a number of libraries and frameworks to support their powerful new web front end.
  • Having a recognised and respected license like GPL can also be a factor in other initiatives like crowd funding.

19 March 2014

Jan Dittberner: CLT 2014 was great again

as in previous years we had a Debian booth at the Chemnitzer Linux-Tage it was as well organized as the years before and I enjoyed meeting a lot of great people from the Debian and free software communities as well as CAcert again. At our booth we presented the awesome work of Debian Installer translators in a BabelBox surrounded by xpenguins which attracted young as well as older passers-by. We got thanks for our work which I want to forward to the whole Debian community. A Debian user told us that he is able to use some PC hardware from the late 1990s that does not work with other desktop OSes anymore. We fed 3 kg of strategic jelly bear reserves as well as some packs of savoury snacks to our visitors. Alexander Wirt brought some T-Shirts, Stickers and Hoodies that we sold almost completely. We did some keysigning at the booth to help to get better keys into the Debian keyring and helped a prospective new Debian Developer to get a strong key signed to his FD approval. I also attended the Key signing party organized by Jens Kubieziel. Thanks to all people who helped at the booth:
  • Alexander Mundt
  • Alexander Wirt
  • Florian Baumann
  • Jan H rsch
  • Jan Wagner
  • Jonas Genannt
  • Rene Engelhard
  • Rhalina
  • Y Plentyn
Thanks to TMT for sponsoring the booth hardware.

Wouter Verhelst: Spelling should not be hard

I know, I know, I should resist saying this. But every time I see it, I wonder why it happens, and I should just get this off my chest. The difference between "its" and "it's" is something that many people, even native english speakers, seem to miss. Yet, it's so extremely simple that I, a non-native english speaker, have been baffled about that common mistake for as long as I can remember. The apostrophe (') in any sentence usually means that something at the location of that apostrophe is gone out to lunch. In this particular case, it means that the " " and the "i" in the phrase "it is" were hungry. So rather than "it is", we contract that to "it's", and allow the space and the i to enjoy their meal while the apostrophe keeps their seats warm. Practically, what that means is that every time you want to write "it's", you should consider whether you can replace it with "it is" without making the sentence sound like junk. If you can't, you probably meant to write "its" rather than "it's". For instance, consider the following sentence: "It's not possible to repair this car within the budget that its owner wants to pay" It's perfectly possible to say "it is not possible" here, so we need to have the apostrophe keep a seat warm for the space and the i. It makes no sense to say "it is owner", unless you're trying to speak a much deformed form of english, so that makes it a possessive pronoun (similar to "hers", "his", "theirs", etc) and you shouldn't use an apostrophe. Speaking of food, it's time for lunch now.

18 March 2014

Elena 'valhalla' Grandi: back from the Barcelona minidebconf

I'm back home from the MiniDebConf Barcelona 2014 (and I've had a full night of uninterrupted sleep! :) ), so it's time to thank everybody who were there (both in person and via IRC) and especially the organizers who did a great job at creating a welcoming environment and a smooth experience for all of us.

It was my first @Debian community experience (although I had already met a few of the members in various occasions) and it made me glad of my decision to start contributing to the project. (I realize that I've probably met a sanitized and newbie-friendlier version of the community, but it's also made up of people who are working to improve the not-so-friendly parts.)

It was also my first time speaking to an international audience; I believe it went overall well: I'm happy with what I said and how, not so much with what I forgot to say (e.g. mentioning testing and other non-packaging skills in my answer to Enrico's question "what skills are needed in the 3dprinter team", or actually showing the last slide with reference urls at least this one will be available as soon as I'll send the slides to be uploaded to the site).

Random mentions:

We had free software, and also free beer, from one of the sponsors (I didn't catch which one), but the venue had to remain beer free, which encourages bad puns of the kind I love :)

Contrary to what some people was fearing, the cake was real and not a lie! (also, it tasted like banana bread with chestnut flour).

Video team duty is fun and something I'll do again (and try to use in our local community what I learn in the process), but I don't think I'll let the Galadriel in my mind bully me into subtitling stuff, sorry.

To ease worries of package mistreatment, the cows in the arriero slides looked more like they were moving between pastures in transhumance rather than being led to be slaughtered.

There are curves in B ziers, France (and also bad coffee and great pastries: definitely a better place_with_geek_name to have breakfast than Perl, Germany)!

The stickers with "May I sign your PGP keys" were a nice idea, although they didn't work as well as they could (possibly because there was little time and lots of things to do). I did manage to reduce my dependency on Enrico's key to find trustpaths, however, which is nice :)

I like the idea to draw a pentacle on the floor, and forcing speakers to remain inside, as suggested by a meeting of videoteaming italian cabal members.

Lots of other things I'm forgetting to mention, but now it's time to stop writing this and start work on my todolist where a few things received a priority bump during the conf. :)

Vincent Bernat: EDNS client subnet support for BIND

To provide geolocation-aware answers with BIND, a common solution is to use a patch adding GeoIP support. A client can be directed to the closest (and hopefully fastest) web server:
view "FRANCE"  
     match-clients   geoip_cityDB_country_FR;  ;
     zone "example.com" in  
         type master;
         file "france.example.com.dns";
      ;
 ;
view "GERMANY"  
     match-clients   geoip_cityDB_country_DE;  ;
     zone "example.com" in  
         type master;
         file "germany.example.com.dns";
      ;
 ;
/* [...] */
view "DEFAULT"  
    zone "example.com" in  
        type master;
        file "example.com.dns";
     ;
 ;
However, an end user does not usually talk directly to authoritative servers. They proxy the query to a third-party recursor server which will query the authoritative server on their behalf. The recursor also caches the answer to be able to serve it directly to other clients. On most cases, we can still rely on the recursor GeoIP location to forward the client to the closest web server because it is located in the client s ISP network, as shown on the following schema: Query for www.example.com through an ISP recursor
  1. Juan is located in China and wants to know the IP address of www.example.com. She queries her ISP resolver.
  2. The resolver asks the authoritative server for the answer.
  3. Because the IP address of the resolver is located in China, the authoritative server decides to answer with the IP address of the web server located in Japan which is the closest one.
  4. Juan can now enjoy short round-trips with the web server.
However, this is not the case when using a public recursor as provided by Google or OpenDNS. In this case, the IP address of the end client and the source IP address of the recursor may not share the same locality. For example, in the following schema, the authoritative server now thinks it is in relation with an European customer and answers with the IP address of the web server located in Europe: Query for www.example.com through an open recursor Moreover, caching makes the problem worse. To solve this problem, a new EDNS extension to expose the client subnet has been proposed. When using this extension, the recursor will provide the client subnet to the authoritative server for it to build an optimized reply. The subnet is vague enough to respect client s privacy but precise enough to be able to locate it. A patched version of dig allows one to make queries with this new extension:
$ geoiplookup 138.231.136.0
GeoIP Country Edition: FR, France
$ ./bin/dig/dig @dns-02.dailymotion.com www.dailymotion.com \
>     +client=138.231.136.0/24
; <<>> DiG 9.8.1-P1-geoip-1.3 <<>> @dns-02.dailymotion.com www.dailymotion.com +client=138.231.136.0/24
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23312
;; flags: qr aa rd; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
; CLIENT-SUBNET: 138.231.136.0/24/24
;; QUESTION SECTION:
;www.dailymotion.com.           IN      A
;; ANSWER SECTION:
www.dailymotion.com.    600     IN      A       195.8.215.136
www.dailymotion.com.    600     IN      A       195.8.215.137
;; Query time: 20 msec
;; SERVER: 188.65.127.2#53(188.65.127.2)
;; WHEN: Sun Oct 20 15:44:47 2013
;; MSG SIZE  rcvd: 91
$ geoiplookup 195.8.215.136
GeoIP Country Edition: FR, France
In the above example, a client located in France gets a reply with two IP addresses located in France. If we now are an US client, we will get IP addresses located in the US:
$ geoiplookup 170.149.100.0
GeoIP Country Edition: US, United States
$ ./bin/dig/dig @dns-02.dailymotion.com www.dailymotion.com \
>     +client=170.149.100.0/24
; <<>> DiG 9.8.1-P1-geoip-1.3 <<>> @dns-02.dailymotion.com www.dailymotion.com +client=170.149.100.0/24
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23187
;; flags: qr aa rd; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
; CLIENT-SUBNET: 170.149.100.0/24/24
;; QUESTION SECTION:
;www.dailymotion.com.           IN      A
;; ANSWER SECTION:
www.dailymotion.com.    600     IN      A       188.65.120.135
www.dailymotion.com.    600     IN      A       188.65.120.136
;; Query time: 18 msec
;; SERVER: 188.65.127.2#53(188.65.127.2)
;; WHEN: Sun Oct 20 15:47:22 2013
;; MSG SIZE  rcvd: 91
$ geoiplookup 188.65.120.135
GeoIP Country Edition: US, United States
The recursor is expected to cache the two different answers and only serve them if the client matches the appropriate subnet (the one confirmed in the answer from the authoritative server). With this new extension, the authoritative server knows that Juan is located in China and answers with the appropriate IP address: Query for www.example.com through an open recursor with client subnet Not many authoritative servers support this extension (PowerDNS and gdnsd, as far as I know). At Dailymotion, we have built a patch for BIND. It only works when BIND is configured as an authoritative server and it doesn t expose no configuration knobs. Feel free to use it (at your own risk). Once installed, you need to register yourself to OpenDNS and to Google to receive queries with the extension enabled.

17 March 2014

Mario Lang: grub-efi-amd64 on a MacBook Air

When I installed Debian on my MacBookAir4,1 in 2012, there was no way to do it without manual intervention yet. I followed a tutorial on how to boot GRUB from the EFI Boot option in the MacBook EFI Menu. I did not want to fiddle with rEFIt, and I didn't want to boot GRUB by default. When I want to boot Linux, I press the Option key during power up and select EFI Boot from the Apple boot menu. Unfortunately, I neglected to collect notes about how I did it manually. However, Linux 3.2 is getting a bit old, so I finally wanted to replace my manual boot configuration with something handled by the package system. In case you don't have /boot/efi in /etc/fstab yet, you need to mount /dev/sda1 on /boot/efi for the following to work. The documentation I found on the net suggested to just reinstall grub-efi-amd64 and everything should work. That is not quite true. When I do
# apt-get install --reinstall grub-efi-amd64
Nothing changes in /boot/efi. I sort of expected that /boot/efi/EFI/debian would be created, and the EFI image should be placed in there. However, that did not happen. Why is that? It turns out that when I installed grub-efi-amd64 manually in 2012, I created /boot/efi/EFI/boot/bootx64.efi which is the EFI fallback location, and apparently exactly what I want on this MacBook which does not support multiple boot options. Matthew Garrett posted an interesting article called Booting with EFI which sheds light on this issue, go and read it. Looking at /var/lib/dpkg/info/grub-efi-amd64.postinst revealed that /boot/efi/EFI/debian needs to be created manually first. If this directory does not exist, grub-efi-amd64 basically does nothing on reinstall. Running grub-install will actually create a new EFI image. However, it is being created in the wrong place for this machine.
# grub-install --target=x86_64-efi
does the trick. Now /boot/efi/EFI/debian/grubx64.efi gets created. However, since I don't want to make GRUB the default, there is yet another manual step to do:
# cp /boot/efi/EFI/debian/grubx64.efi /boot/efi/EFI/boot/bootx64.efi
Now I can select EFI Boot after pressing the Option key during startup. GRUB is loaded and Linux 3.13 gets booted. Strike! Looking more closely reveals that there is actually a way to tell grub-install that it should install to the fallback location directly. The --removable option does that. For the faint of heart, what does grub-install actually do on an EFI system? It does not directly write to the disk, therefore it does not need a device specified. It looks for files in /boot/efi and assumes the EFI partition is mounted there. So for my use case, the correct way to upgrade to a current GRUB EFI image should have been:
# grub-install --removable --target=x86_64-efi
Meanwhile I've been made aware of Bug#708430. I guess it would be nice to have an option in /etc/default/grub which would indicate that installation to the fallback location is desired. While this is a rather ugly hack to work around a stupid limitation, it is still what I'd like on this MacBook. At least since I don't have a triplle boot situation. Fallback location works fine with just two OSes coexisting.

Rapha&#235;l Hertzog: Kickstart the Arabic Translation of the Debian Handbook

Cover of the Debian Administrator's Handbook (Wheezy edition)I just wanted to highlight that Muhammad Saied, a volunteer translator of the Debian Administrator s Handbook, is currently running a crowdfunding campaign with Mohamed Amine so that they can complete the Arabic translation that they started. There s only 6 days left to collect the last $2500 click here to help spread Debian to the Arabic world.

No comment Liked this article? Click here. My blog is Flattr-enabled.

16 March 2014

Russell Coker: BTRFS Status March 2014

I m currently using BTRFS on most systems that I can access easily. It s not nearly reliable enough that I want to install it on a server in another country or an embedded device that s only accessible via 3G, but for systems where I can access the console it s not doing too badly. Balancing and Space Allocation # btrfs filesystem df /
Data, single: total=103.97GiB, used=85.91GiB
System, DUP: total=32.00MiB, used=20.00KiB
Metadata, DUP: total=1.78GiB, used=1.31GiB
# df -h /
Filesystem Size Used Avail Use% Mounted on
/dev/disk/by-uuid/ac696117-473c-4945-a71e-917e09c6503c 108G 89G 19G 84% /
Currently there are still situations where it can run out of space and deadlock on freeing space. The above shows the output of the btrfs df command and the regular df command, I have about 106G of disk space used by data and metadata in BTRFS while df shows that the entire filesystem (IE the block device) is 108G. So if I use another 2G of data or metadata then the system is at risk of deadlocking. To avoid that happening I have to run btrfs balance start / to start a balance which defragments the space use and frees some blocks. Currently there is a bug in BTRFS (present in all Debian/Unstable kernels) which prevents a balance operation from completing when systemd is used in a default configuration (there s something about the way systemd accesses it s journal files that triggers a BTRFS bug). This is really inconvenient, particularly given that there s probably a strong correlation between people who use experimental filesystems and people who use experimental init programs. When you get to the stage of the filesystem being deadlocked you can sometimes recover by removing snapshots and sometimes by adding a new device to the filesystem (even a USB flash drive will do). But I once had a filesystem get into a state where there wasn t enough space to balance, add a device, or remove a snapshot so I had to do a backup/format/restore. Quota Groups Last time I asked the developers (a few weeks ago) they told me that quota groups aren t ready to use. They also said that they know about enough bugs that there s no benefit in testing that feature. Even people who want to report bugs in BTRFS shouldn t use quotas. Kernel Panics with Kmail I ve had three systems develop filesystem corruption on files related to Kmail (the email program from KDE). I suspect that Kmail is triggering a bug in BTRFS. On all three systems the filesystem developed corruption that persisted across a reboot. One of the three systems was fixed by deleting the file for the Outbox, the others are waiting for kernel 3.14 which is supposed to fix the bug that causes kernel panics when accessing the corrupted files in question. I don t know whether kernel 3.14 will fix the bug that caused the corruption in the first place. Conclusion As I don t use quotas BTRFS is working well for me on systems that have plenty of storage space and don t run Kmail. There are some systems running systemd where I plan to upgrade the kernel before all the filesystem space is allocated. One of my systems is currently running SysVinit so I can balance the filesystem. Apart from these issues BTRFS is working reasonably well for me. I haven t yet had it s filesystem checksums correct corrupted data from disk in any situation other than tests (I have had ZFS correct such an error, so hardware I use does benefit from this). I have restored data from BTRFS snapshots on many occasions, so that feature has been a major benefit for me. When I had a system with faulty RAM the internal checks in BTRFS alerted me to the problem and I didn t lose any data, the filesystem became read-only and I was able to copy everything off even though it was too corrupted for writes.

14 March 2014

Andrew Pollock: [life] Day 45, BJJ, Science Friday and baking cookies

We had a pretty busy day today. Sarah dropped Zoe off at around 8:30am. I reminded Zoe that she'd forgotten to give Sarah her crown that she'd made at Playgroup the previous day, so she gave that to her. After Sarah left, I let Zoe watch a little bit of TV while I finished getting myself organised. We drove to Brazilian Jiu Jitsu class today, because I wanted to go directly to the Planetarium afterwards. Zoe's BFF Megan came to BJJ class today for a trial class. Zoe was very excited. Megan picked everything up really quickly, and the girls had a good time. She didn't want to wear her uniform today though. I managed to get out of her later that she felt it made her sweaty. I told her it was probably all the running around that made her sweaty, not the uniform. We went out for a coffee with Megan, her Dad and her little sister afterwards. We found a little take away shop around the corner. Not quite the place that did babyccinos unfortunately, so Megan's Dad very cleverly got a chocolate milk and split it three ways with the girls and called it a "milkshake". I've realised that for Science Friday, I've pretty much been doing solely chemistry so far, so I wanted to throw in a bit of astronomy this week. The Sir Thomas Brisbane Planetarium had just recently reopened after getting a spanky new projector because 1978 called and wanted theirs back. Unfortunately, they weren't showing Perfect Little Planet today, but the slightly more specific Black Holes: Journey into the Unknown. I wanted Zoe to see something in the auditorium, so I thought we'd give it a shot anyway. I think we got to the Planetarium at around 11am, and the next show was at 1:30pm, so we had a bit of a look around the foyer for a bit, which Zoe quite enjoyed. They had a life-size model of Neil Armstrong's spacesuit, and a scale model of a Saturn V rocket. Zoe quite enjoyed both of them. I'll have to dig up some Youtube footage of a Saturn V launch. We then headed over to the cafe in the adjacent Botantic Gardens, and had a reasonable lunch. After lunch we wandered around the Botanic Gardens to kill some time, so you could say that today's Science Friday also included a goodly amount of botany as well. We went into the Tropical Dome and looked at the fish in the lily pond, and toured the fern garden, before heading back. We timed it pretty well, and got back to the Planetarium with about 10 minutes to kill. I'd prepped Zoe for the presentation, and told her that she needed to keep quiet, and if we had to leave we wouldn't be able to go back in again, and she could whisper to me if she needed to. I have to say, she was so well behaved. She sat through the whole 45 minute presentation and the projected tour of the night sky. I guess the presentation was sufficiently visually interesting to hold her attention for the duration. There was certainly a lot of "wow" out of her. I was so proud of how she went that I had to go and buy her an ice cream as a reward. After that, we went for a drive around Mount Coot-tha. I pointed out the TV towers that we can see from our balcony, and then she fell asleep on the way home. She didn't wake up particularly happy from her late, short nap, when we got home, but once she got herself sorted out, we baked the cookies that we'd made yesterday. They came out very nicely indeed. Once they were all baked, we dropped off a dozen to Megan's place, and then came home to have dinner. Bedtime went pretty well. I hope she has a good night's sleep, as we have a big day tomorrow.

Neil Williams: LAVA server on an arndale

(ARMv7 A15 dual core) I ve covered how I set up my home LAVA lab and how I got two iMX.53 boards running, the next step was to sort out the LAVA server. My initial setup relied on using my Thinkpad as the server. This was somewhat convenient as that s how I develop the code, but didn t help me run jobs like health checks because the laptop was usually somewhere other than on the home LAN. There had been a long-standing problem with using LAVA on ARM the uwsgi support didn t compile but the code being used was old. As the same code has been in Debian for a long time, I suspected that this was fixed with a newer version. So as part of migrating LAVA to django1.6, apache2.4, postgres9.3, django-tables2 0.13 and a few other updated dependencies, I have been using the version of uwsgi from Debian unstable for quite a while without problems on x86. A simple tweak to the LAVA setup scripts and a newer version of uwsgi became available and it builds just fine on armhf. (I haven t tried armel because Linaro is ARMv7 or newer and we don t test with ARMv5/ARMv6 boards, so there s no point in trying armel it s not likely to be an issue for this fix though.) (Only the current lava-deployment-tool methods need to actually compile uwsgi directly from upstream without any patches the packaging which will replace l-d-t uses precompiled binaries, just as any admin would expect.) That initial install was on one of the iMX.53 boards, which ran as slowly as anyone who has used an iMX.53 would expect. I haven t run test jobs on that install, it had a hard enough time serving the frontend. Clearly some more cores would be a good step and when an arndale became available for the home lab, the next step was to get a SATA drive onto the arndale, put Debian unstable on that and then deploy LAVA to the arndale using the Debian packages. As a bonus, these packages are built for django1.6 (using an unreleased branch). Sounds simple enough. It works on iMX.53, it should work on an arndale. Well, it does but only after some unexpected faff. arndale, u-boot and SATA I hate u-boot every single time I ever touch it, the little I know about any other u-boot device is completely useless. Uniformity is a good thing infinite permutations are just rope to hang ourselves with cute embedded nonsense hacks and I m bored of that whole scene. So, boot the arndale, interrupt the bootloader to get to the prompt. What s the first thing most people would want? help. Denied this particular u-boot has been compiled without the ability to display any help messages. u-boot has just sunk further into the depths of please can we have something else which is uniform across devices . OK, well maybe I can get by without help. sata init unknown command sata . (Go away, do something else for a bit.) The arndale isn t one of the newest boards in the ARMv7 world, LAVA has been using them for a while, so someone has probably done some work to fix this . nope. There s a workaround a nice detailed guide by Phil Endecott which details that the kernel needs to continue to be loaded from SD and then the SATA can be used for just the rootfs. Mildly annoyed (I was hoping to be able to update the arndale kernel without the hassle of mounting the SD card at all), the rest was straight-forward. Preparing the SATA and installing Debian Due to the complexity of some of the transitions currently ongoing in Debian ahead of the Jessie release freeze, uwsgi is not in Debian testing right now so this install has to be Debian unstable. That s OK, I ve been running Debian unstable on all my machines for several years now usually updating ~5 times a week.

# parted /dev/sda -s unit mb mktable msdos
# parted /dev/sda -s unit mb mkpart primary 1 -- "-0"
# mkfs.ext4 /dev/sda1
# mount /dev/sda1 /mnt/root/
(note the in the mkpart command, that catches me out most times I try this. Without it, the special -0 gets interpreted as an option to parted but parted doesn t then tell you how to fix it, it just complains about an unknown option.) The SD image I am using is a LAVA master image, based on Ubuntu, so it was easy to put debootstrap onto it.

# apt-get install debootstrap
# debootstrap --arch=armhf sid /mnt/root/ http://ftp.uk.debian.org/debian
# chroot /mnt/root/
Inside the chroot, it s Debian as usual:

apt-get update
apt-get install emdebian-archive-keyring
passwd
emdebian-archive-keyring is a package I (ab)use to sign my LAVA packaging as it has the advantage of being in Debian and Ubuntu going back to the time of Lenny, so it is always available from a repository which has already been authenticated to apt and doesn t involve downloading some random key from a website. I use passwd manually because this rootfs won t be using auto-login, it will have regular users. root passwords can be automated, if necessary. Thinking about login, remember to give the rootfs a usable tty. (The LAVA master image has a nasty habit of mangling editors like nano and vi when used over serial, so I m using echo.) For the arndale you need:

# echo T0:23:respawn:/sbin/getty -L ttySAC2 115200 vt102 >> ./etc/inittab
# echo >> ./etc/securetty
# echo ttySAC2 >> ./etc/securetty
Then to make the hostname useful, adapt this to your needs:

echo 127.0.0.1 arndale.codehelp arndale >> ./etc/hosts
Finally, get the network running at boot and add the LAVA repository:

# echo auto lo eth0 > ./etc/network/interfaces.d/arndale
# echo iface lo inet loopback >> ./etc/network/interfaces.d/arndale
# echo iface eth0 inet dhcp >> ./etc/network/interfaces.d/arndale
# echo deb http://people.linaro.org/~neil.williams/lava sid main >> ./etc/apt/sources.list.d/lava.list
# apt-get update
# exit
Once the LAVA packaging is finalised, the packages will be uploaded to a normal Linaro PPA, I ll update the packages to use an official download location and we ll move to using sane version string handling. For now, the packages are still in development. Code for the packaging is in Alioth but there are issues with anonymous access to the pkg-linaro-lava repositories currently, so I ve also pushed to http://github.com/Linaro if you are interested in building the packages yourself. See also my packaging guide which is also linked from the Links page on my own site. With that done, time to reboot, set the SATA drive as the rootfs using the horrid u-boot and install LAVA.

# reboot
> setenv bootargs console=tty0 console=ttySAC2,115200n8 drm_kms_helper.edid_firmware=edid-1920x1080.fw root=/dev/sda1
> boot
login
# apt-get install postgresql
After this operation, 63.0 MB of additional disk space will be used.

# apt-get install lava-server
After this operation, 231 MB of additional disk space will be used.

# a2dissite 000-default
# a2ensite lava-server
# apache2ctl restart
# service lava-server restart
Take note of the IP address of your new ARM LAVA server and sign in with your regular details, e.g. using OpenID before creating a temporary superuser:

# lava-server manage createsuperuser --username default --email=user@example.com
Choose a temporary password, log out, log in as the temporary superuser, promote your regular user to superuser and default owner of unrestricted devices in the django admin interface. Finally, log out and login as regular user to delete the temporary user. (Yes, that probably could do with some improvement remind me later and I ll see if a known user can be promoted from the command line.) See also Senthil s recent post on LAVA unit tests. Getting those to run without so many steps is also on the TODO list. Results
IP Address: 127.0.0.1
Is Master? : True
Uptime: 6:02:23.700000
Architecture: armv7l
Platform: Linux-3.10.1.0-1-linaro-arndale-armv7l-with-debian-jessie-sid
Insignal Arndale evaluation board based on EXYNOS5250
System memory: 1998MiB
Next! I m working on some code upstream to make it easier to add devices from the command line. The aim is that a set of simple commands will set up an initial device, run a job on that device and submit a result bundle to the LAVA server as job #1. This gives some assurance that everything has gone well. Now I can finally add health checks for the iMX.53 boards and start regular tests on those boards. The cubie boards will wait for a later blog post, there are interesting problems with the bootloader and serial connections. That s a whole different rant.

12 March 2014

Vasudev Kamath: Working around type system of Go with unsafe

Go language has a strong type system unlike C, and some times this will be head ache when we want to interact with C data types with Cgo or just to convert a Go type to lets say byte slice. I recently faced the same problem and after poking around things, I learned the Go provides unsafe package which can be used to work around the Go's type system.
Problem Recently I started using Cgo to use some C library I had to write some tools for development and testing. The reason I chose Go for this was prototyping and writing some quick tools is much easier in Go than done in C. The C library had some function which takes pointer to array types and fills it with some values. The problem I was facing here was how to create a C array in Go. Go does have array but its largely used as internal representation for much efficient type called slice and I can't directly cast a byte slice into an C array. Second problem I had was I had to store arbitrary Go types like float (float32,float64) and int (int32, int64) etc. into C array. So in brief, the problems that needed to solve are
  1. Find a way to convert byte slice from Go into C array and vice versa.
  2. Find a way to convert and store Go types into a C array.
Solution Basically C array are sequence of memory location which can be statically or dynamically allocated. In Cgo its possible to access C standard library functions for memory allocation, so why not use it. The memory allocation function then returns the pointer to starting of allocated memory, we can use this pointer to write Go's bytes into the memory location and bytes from memory location into Go's slice. The pointer returned by C allocation functions are not directly usable for memory dereferencing in Go, here is where unsafe package kicks in. We will cast the return of C allocation function as unsafe.Pointer type and from the documentation of unsafe package,
  1. A pointer value of any type can be converted to a Pointer.
  2. A Pointer can be converted to a pointer value of any type.
  3. A uintptr can be converted to a Pointer.
  4. A Pointer can be converted to a uintptr.
So we can then cast unsafe.Pointer to uintptr which is the Go type which is large enough to hold any memory address in Go and can be used for pointer arithmetic just like we do in C (of course with some more castings). Below I'm pasting a simplified code in C which I wrote for this post.
#ifndef __BYTETEST_H__
#define __BYTETEST_H__
typedef unsigned char UBYTE;
extern void ArrayReadFunc(UBYTE *arrayout);
extern void ArrayWriteFunc(UBYTE *arrayin);
#endif
#include "bytetest.h"
#include <stdio.h>
#include <string.h>
void ArrayReadFunc(UBYTE *arrayout)
 
     UBYTE array[20] =  1, 2, 3, 4,5, 6, 7, 8, 9, 10,
                        11, 12, 13, 14, 15, 16, 17,
                        18, 19, 20 ;
     memcpy(arrayout, array, 20);
 
void ArrayWriteFunc(UBYTE *arrayin)
 
     UBYTE array[20];
     memcpy(array, arrayin, 20);
     printf("Byte slice array received from Go:\n");
     for(int i = 0; i < 20; i ++) 
             printf("%d ", array[i]);
      
     printf("\n");
 
Functions are written just for this post and they don't really do anything. As you can see ArrayReadFunc takes a pointer to array and fills it with content of another array using memcpy. Function ArrayWriteFunc on other hand takes pointer to array and copies its content to internal array. I've added print logic to ArrayWriteFunc just to show that values passed from Go are making it here. Below is the Go code which uses the above C files passes byte slice to get value out of C code and array made of byte slice to C function to send values in.
package main
/*
#cgo CFLAGS: -std=c99
#include "bytetest.h"
#include <stdlib.h>
*/
import "C"
import (
     "fmt"
     "unsafe"
)
func ReadArray() unsafe.Pointer  
       var outArray = unsafe.Pointer (C.calloc(20,1))
       C.ArrayReadFunc((*C.UBYTE)(outArray))
       return outArray
 
func WriteArray(inArray unsafe.Pointer)  
       C.ArrayWriteFunc((*C.UBYTE)(inArray))
 
func CArrayToByteSlice(array unsafe.Pointer, size int) []byte  
       var arrayptr = uintptr(array)
       var byteSlice = make([]byte, size)
       for i := 0; i < len(byteSlice); i ++  
               byteSlice[i] = byte(*(*C.UBYTE)(unsafe.Pointer(arrayptr)))
               arrayptr ++
        
       return byteSlice
 
func ByteSliceToCArray (byteSlice []byte) unsafe.Pointer  
       var array = unsafe.Pointer(C.calloc(C.size_t(len(byteSlice)), 1))
       var arrayptr = uintptr(array)
       for i := 0; i < len(byteSlice); i ++  
              *(*C.UBYTE)(unsafe.Pointer(arrayptr)) = C.UBYTE(byteSlice[i])
              arrayptr ++
        
       return array
 
func main() 
        carray := ReadArray()
        defer C.free(carray)
        carraybytes := CArrayToByteSlice(carray, 20)
        fmt.Println("C array converted to byte slice:")
        for i := 0; i < len(carraybytes); i ++  
                fmt.Printf("%d ", carraybytes[i])
         
        fmt.Println()
        gobytes := []byte 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
                31, 32, 33, 34, 35, 36, 37, 38, 39, 40 
        gobytesarray := ByteSliceToCArray(gobytes)
        defer C.free(gobytesarray)
        WriteArray(gobytesarray)
 
Functions ReadArray and WriteArray are just wrapper to the calls to C counter parts ArrayReadFunc and ArrayWriteFunc. ReadArray returns unsafe.Pointer which is allocated C array and should be freed by caller. WriteArray takes unsafe.Pointer which is pointing to memory location containing C array. Now the functions of interest are CArrayToByteSlice and ByteSliceToCArray. It should be pretty clear from the above code to understand what is happening in these functions. Still I will just put explain them briefly. ByteSliceToCArray allocates a C array using calloc from C standard library. It then creates a uintptr, a pointer type in Go which is used to dereference the each memory location and store bytes from the input byte slice in them. CArrayToByteSlice on other hands creates a uintptr type by casting input unsafe.Pointer type and then uses this pointer type to dereference values from memoy and store it in byte slice with suitable casting. So lets build the code and run it and see the output:
C array converted to byte slice:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Byte slice array received from Go:
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
So yes it actually works and values are moving across C and Go. This solves first problem in hand next is converting arbitrary Go types into byte slices. There are many cases where we would like to convert an arbitrary Go types like (int, float) into bytes. One such use case I found was when writing a TCP client for communicating with a Server written using C speaking custom protocol. Here I'm just going to show how to convert types like float, int to byte slice, I've not tried converting structures but it is certainly possible. Below is the function which can convert int32,float32 into byte slice it can also be extended for other types.
func CopyValueToByte(value interface ) []byte  
     var valptr uintptr
     var slice []byte
     switch t := value.(type)  
     case int32:
             i := value.(int32)
             valptr = uintptr(unsafe.Pointer(&i))
             slice = make([]byte, unsafe.Sizeof(i))
     case float32:
             f := value.(float32)
             valptr = uintptr(unsafe.Pointer(&f))
             slice = make([]byte, unsafe.Sizeof(f))
     default:
             fmt.Fprintf(os.Stderr,"Unsupported type: %T\n", t)
             os.Exit(1)
      
     for i := 0; i < len(slice); i++  
             slice[i] = byte(*(*byte)(unsafe.Pointer(valptr)))
             valptr++
      
     return slice
 
This function is generic which can take various types of value. First we will use Go's type assertion to determine the type and creates a uintptr pointer for the value and allocates byte slice depending on the size of the value as calculated using unsafe.Sizeof. Later it uses the pointer to dereference value from memory location and copies each byte into byte slice. The idea used here is every type is represented as certain number of bytes in the memory. Below is the entire program.
package main
import (
     "fmt"
     "unsafe"
     "os"
)
func CopyValueToByte(value interface ) []byte  
     var valptr uintptr
     var slice []byte
     switch t := value.(type)  
     case int32:
             i := value.(int32)
             valptr = uintptr(unsafe.Pointer(&i))
             slice = make([]byte, unsafe.Sizeof(i))
     case float32:
             f := value.(float32)
             valptr = uintptr(unsafe.Pointer(&f))
             slice = make([]byte, unsafe.Sizeof(f))
     default:
             fmt.Fprintf(os.Stderr,"Unsupported type: %T\n", t)
             os.Exit(1)
      
     for i := 0; i < len(slice); i++  
             slice[i] = byte(*(*byte)(unsafe.Pointer(valptr)))
             valptr++
      
     return slice
 
func main()  
     a := float32(-10.3)
     floatbytes := CopyValueToByte(a)
     fmt.Println("Float value as byte slice:")
     for i := 0; i < len(floatbytes); i++  
             fmt.Printf("%x ", floatbytes[i])
      
     fmt.Println()
     b := new(float32)
     bptr := uintptr(unsafe.Pointer(b))
     for i := 0; i < len(floatbytes); i++  
             *(*byte)(unsafe.Pointer(bptr)) = floatbytes[i]
             bptr++
      
     fmt.Printf("Byte value copied to float var: %f\n", *b)
 
The above conversion can also be achieved using encoding/binary package provided by Go. But its been told to me that it makes things pretty slow.
Conclusion So goes unsafe.Pointer is really powerful thing which allows us to work around the Go's type system but as package documentation says it should be used with care
PS: I'm not really sure if its recommended to use allocation functions from C standard library, I will wait for expert gophers to comment on that.

11 March 2014

Steve Langasek: My CuBox-i has arrived

A couple of weeks ago, Gunnar Wolf mentioned on IRC that his CuBox-i4 had arrived. This resulted in various jealous noises from me; having heard about this device making the rounds at the Kernel Summit, I ordered one for myself back in December, as part of the long-delayed HDification of our home entertainment system and coinciding with the purchase of a new Samsung SmartTV. We've been running an Intel Coppermine Celeron for a decade as a MythTV frontend and encoder (hardware-assisted with a PVR-250), which is fine for SD video, but really doesn't cut it for anything HD. So after finally getting a TV that would showcase HD in all its glory, I figured it was time to upgrade from an S-Video-out, barely-limping-along tower machine to something more modern with HDMI out, eSATA, hardware video decoding, and whose biggest problem is it's so small that it threatens to get lost in the wiring! Since placing the order, I've been bemused to find that the SmartTV is so smart that it has had a dramatic impact on how we consume media; between that and our decision to not be a boiled frog in the face of DISH Network's annual price increase, the MythTV frontend has become a much less important part of our entertainment center, well before I ever got a chance to lay hands on the intended replacement hardware. But that's a topic for another day. Anyway, the CuBox-i4 finally arrived in the mail on Friday, so of course I immediately needed to start hacking on it! Like Gunnar, who wrote last week about his own experience getting a "proper" Debian install on the box, I'm not content with running a binary distribution image prepared by some third party; I expect my hardware toys to run official distro packages assembled using official distro tools and, if at all possible, distributed on official distro images for a minimum of hassle. Whereas Gunnar was willing to settle for using third-party binaries for the bootloader and kernel, however, I'm not inclined to do any such thing. And between my stint at Linaro a few years ago and the recent work on Ubuntu for phones, I do have a little knowledge of Linux on ARM (probably just enough to be dangerous), so I set to work trying to get the CuBox-i4 bootable with stock Debian unstable. Being such a cutting-edge piece of hardware, that does pose some challenges. Support for the i.MX6 chip is in the process of being upstreamed to U-Boot, but the support for the CuBox-i devices isn't there yet, nor is the support for SPL on i.MX6 (which allows booting the variants of the CuBox-i with a single U-Boot build, instead of requiring a different bootloader build for each flavor). The CuBox-i U-Boot that SolidRun makes available (with source at github) is based on U-Boot 2013.10-rc4, so more than a full release behind Debian unstable, and the patches there don't apply to U-Boot 2014.01 without a bit of effort. But if it's worth doing, it's worth doing right, so I've taken the time to rebase the CuBox-i patches on top of 2014.01, publishing the results of the rebase to my own github repository and submitting a bug to the Debian U-Boot maintainers requesting its inclusion. The next step is to get a Debian kernel that not only works, but fully supports the hardware out of the box (a 3.13 generic arm kernel will boot on the machine, but little things like ethernet and hdmi don't work yet). I've created a page in the Debian wiki for tracking the status of this work.

Andrew Pollock: [life] Day 42, a good night's sleep, Kindergarten, make up swim class and dinner with Nana

Zoe slept through the night for the first time in recent memory, and was up at around 6am. It was lovely. I'm thinking the slightly lower temperature helped. I'm definitely going to explore air conditioning for the bedrooms before next Summer. I'd picked up some egg cups on the weekend, so we did soft boiled eggs in the Thermomix for breakfast. They turned out lovely this time, and Zoe seemed to enjoy eating hers. She dressed herself while they were cooking. Her Kindergarten t-shirts arrived yesterday, so now she looks like all the other kids. It's very cute. It rained on and off in the morning, and I was in two minds about whether to chance it on the bike or not. As it happened we ended up messing around a bit before leaving, so we drove, and it was a good call, because it started raining again as we pulled out of the driveway. Drop off was super smooth. Megan had been away yesterday, but was back today, so Zoe was very happy to see her. My financial advisor came out for a chat about investments mid-morning, and then I got stuck into my US taxes. I will not miss having to do these tax returns. The 2013 one is going to be particularly complicated by the fact we sold our home and were only in the country for like 80 days. I biked over to Kindergarten to pick up Zoe, as the weather had improved. Surprisingly, she was awake, but her teacher said she'd just woken up from a nap. We managed to clear out pretty quickly. I stopped at the health food shop on the way home to get some peanut oil for the dinner I was making. Due to a miscommunication, Zoe had missed her Saturday swim class. I explained to the swim school the error, and they were kind enough to allow Zoe to have a make up class anyway, so we went to that after Kindergarten. Zoe wanted to do some more practice riding her bike. She's got a little 10 inch bike with no training wheels and a gyrobike front wheel. We haven't had a lot of success learning to ride to date, due to a combination of her height and just time, so it was interesting that she decided today she wanted to do some more practice. She wanted to "ride" her bike from home to the park on the way to swim class, but I managed to convince her to walk the bike to the park. It turns out even walking the bike is a bit of a challenge for her, so I ended up carrying it most of the way. It's heavy. We got to the park, and had a bit of a run with the bike. I'm glad I decided to take her knee pads and elbow pads, because she did stack it fairly decently, but managed to survive mostly unscathed. To her credit, she even got back on the bike again. She's a tough kid. Once we made it to the playground, she lost all interest in the bike, and we had about 15 minutes to kill before we needed to continue to the pool. We walked/carried the bike from the park to the pool, and the make up class Zoe ended up in was Megan's regular class, so the girls had a great time together. After swim class, we walked back home. Zoe's Nana was coming over for dinner, and I wanted to make a satay chicken dish. I'd bought some peanuts from the Peanut Wagon on Sunday, when I was in Nanango for my uncle's 90th birthday party, and I wanted to try making peanut butter from scratch in the Thermomix, and use that to make the satay sauce. Long story short, dinner wasn't super great. I'd made a satay chicken in the Thermomix previously, but I couldn't find the recipe I used last time. I used this recipe tonight, but didn't really follow it properly because I was trying to cut corners due to the time. I tried cooking wild rice in the microwave and it was a total flop. The satay chicken itself turned out okay, but it was a shame about the rice. It was cool making my own peanut butter. Zoe had a great time playing with her Nana, and after we dropped her off at the train station went to bed without a peep.

Next.

Previous.