From owner-freebsd-hackers@FreeBSD.ORG Mon Jun 2 12:23:10 2003 Return-Path: Delivered-To: freebsd-hackers@freebsd.org Received: from mx1.FreeBSD.org (mx1.freebsd.org [216.136.204.125]) by hub.freebsd.org (Postfix) with ESMTP id 87DE437B401 for ; Mon, 2 Jun 2003 12:23:10 -0700 (PDT) Received: from mail.speakeasy.net (mail12.speakeasy.net [216.254.0.212]) by mx1.FreeBSD.org (Postfix) with ESMTP id 917BD43F3F for ; Mon, 2 Jun 2003 12:23:09 -0700 (PDT) (envelope-from jhb@FreeBSD.org) Received: (qmail 6079 invoked from network); 2 Jun 2003 19:23:08 -0000 Received: from unknown (HELO server.baldwin.cx) ([216.27.160.63]) (envelope-sender )encrypted SMTP for ; 2 Jun 2003 19:23:08 -0000 Received: from laptop.baldwin.cx (gw1.twc.weather.com [216.133.140.1]) by server.baldwin.cx (8.12.8/8.12.8) with ESMTP id h52JN6p0000786; Mon, 2 Jun 2003 15:23:06 -0400 (EDT) (envelope-from jhb@FreeBSD.org) Message-ID: X-Mailer: XFMail 1.5.4 on FreeBSD X-Priority: 3 (Normal) Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 8bit MIME-Version: 1.0 In-Reply-To: <20030602075328.GV45118@garage.freebsd.pl> Date: Mon, 02 Jun 2003 15:23:07 -0400 (EDT) From: John Baldwin To: Pawel Jakub Dawidek cc: freebsd-hackers@freebsd.org Subject: RE: Locking, locking... X-BeenThere: freebsd-hackers@freebsd.org X-Mailman-Version: 2.1.1 Precedence: list List-Id: Technical Discussions relating to FreeBSD List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Mon, 02 Jun 2003 19:23:10 -0000 On 02-Jun-2003 Pawel Jakub Dawidek wrote: > Hello hackers... > > I need advice how to handle with one locking problem. > > For example I got some list with some values. This list could be > modified by any process. I want to get values from this list and > copy them to allocated table. But how to count number of needed > fields? > > mtx_lock(&mtx_list_lock); > n = 0; > SLIST_FOREACH(elem, &list_head, l_next) { > n++; > } > mtx_unlock(&mtx_list_lock); > tab = malloc(n * sizeof(something), M_TEMP, M_WAITOK); > mtx_lock(&mtx_list_lock); > [...] > > As we all knew size of list could be changed when we were in malloc(). > Of course we could check list size again after malloc() and mtx_lock(), > but what to do when it was changed? Recall memory allocation? > If size of this list depends on every process there is a chance to DoS > such piece of code. Return an error? Not always it is possible. > > IMHO there should be malloc() version that could be called under lock. > Malloc() M_NOWAIT could be called in such scenario? > How do you handle with situations like this? In the process case, the all process list is protected by an sx lock (which you can hold across malloc(M_WAITOK)). Another solution in some cases is that if the list grows, just copy out the first n items. -- John Baldwin <>< http://www.FreeBSD.org/~jhb/ "Power Users Use the Power to Serve!" - http://www.FreeBSD.org/