From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 5437BC48260 for ; Thu, 8 Feb 2024 12:53:36 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 88D7C6B0071; Thu, 8 Feb 2024 07:53:35 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 83FA56B0074; Thu, 8 Feb 2024 07:53:35 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 6DE7A6B0075; Thu, 8 Feb 2024 07:53:35 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id 5B7EF6B0071 for ; Thu, 8 Feb 2024 07:53:35 -0500 (EST) Received: from smtpin18.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 0BC4440E86 for ; Thu, 8 Feb 2024 12:53:35 +0000 (UTC) X-FDA: 81768627990.18.5A04102 Received: from mail-vs1-f49.google.com (mail-vs1-f49.google.com [209.85.217.49]) by imf02.hostedemail.com (Postfix) with ESMTP id 3D4528000B for ; Thu, 8 Feb 2024 12:53:32 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=TGOHKXbm; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf02.hostedemail.com: domain of aliceryhl@google.com designates 209.85.217.49 as permitted sender) smtp.mailfrom=aliceryhl@google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1707396813; a=rsa-sha256; cv=none; b=b9KPWgakRqbAxRb77XTWJGmcOdkQkLqyJBmseaR/nJLxifwrpvYRtY4QNiTX6RAeRgK95e ztRUnNEWOhd94DZ2bI5rMy1sXTRrRpfRez/9l3RX7BH7JuJfuL2nG9gHxLQX4TpJ/extDV RE23btrFAis5g9mt/xhhclHbWUOgmqM= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=TGOHKXbm; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf02.hostedemail.com: domain of aliceryhl@google.com designates 209.85.217.49 as permitted sender) smtp.mailfrom=aliceryhl@google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1707396813; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=N1tCtLJ/RjQd559OCm1MWYW/kF4GUTJKVOlOzEx+/HI=; b=FOP6dh5hQt3VEVL5EVHAZdznzKSZQXwH5t98ByQmjQKbSUNT2PwK/U5LniWGAY+dEwlw1f 7VHLAZBvaeRUSvSihhBdO5CNFoxaCMxyv5qWSehTLAprqTpTWuxLf4pGvu56/gmMgv6o1j 6CJ4U0GiiGqMEfttxOgPf9XBeIH/OJY= Received: by mail-vs1-f49.google.com with SMTP id ada2fe7eead31-46d29ed4574so480534137.2 for ; Thu, 08 Feb 2024 04:53:32 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1707396812; x=1708001612; darn=kvack.org; h=content-transfer-encoding:cc:to:subject:message-id:date:from :in-reply-to:references:mime-version:from:to:cc:subject:date :message-id:reply-to; bh=N1tCtLJ/RjQd559OCm1MWYW/kF4GUTJKVOlOzEx+/HI=; b=TGOHKXbmIgHOABw5gi5s4jBd2GzH6rH4YsWa8j4OQU4pgVVxqCWRK5D8ymZTEacqhm R7whYTFgKeqmkG97se4yW7r46xFDITzrpCFTbSnxIcCj7cdg7LkJw/HyIEQz+e/7TwND qPYY3mcextekaChig1mFBJp8fWKr/vh9hI3Wl+gpTS53Ntx5Pc0S9fU0BO71YMyBIjde iVukpBVCNbXHcLC35Xz3HgejD4y1qWYaK1cH0REZqFXfaO01cNOlZItKLOg2oaIb61Mm 2NT6e1igZ4R0yzwO8FWZ2CcUTcna4cynJ8VMylLLIqEOc+zKNauHcdNXoTmN9HbE/alv Azyg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1707396812; x=1708001612; h=content-transfer-encoding:cc:to:subject:message-id:date:from :in-reply-to:references:mime-version:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=N1tCtLJ/RjQd559OCm1MWYW/kF4GUTJKVOlOzEx+/HI=; b=dA/97jHG7f3MSNQKZafEt0oe2kxF4QpfY6nOlrcHHAAqHzi+/gxWpcnj8GbemaywvU 62tXQQvl2DwklvD0FbH7rqZY1ohgqMDDFpzEOWnxbZOPqtqfm4rJQufHN8Oa0IhgwMDN XrfY8YoNVI2bmPgKOwoqYkyEbpSpR8aGFGBA3RawhoLApxdZlu8f7/UEz3UPsUj61RZw BALZ8u8PTVRv6gPpaa98I/odB9/H6Oyyz+dqTVUwSV8FKIZ4PM/XTK4kEYIrlsJ/oxNU lwANPRhDmZ857RpmulSRLOenVkAUYBxoWjzzFDjtFpwJwrirasqgN91Z7lw6FUB6d8qt P/HA== X-Gm-Message-State: AOJu0YxnBFWgeslfi1b+Q70Gxh/T9kVZPPmTxFGRJcpSwnw34WwxPzql wGPtgfWV9TU3yn5qmukUyQju9eK1tp6yzpQNQJR4m66hI80sOH3UlV2H81jlgQRcvGqGMBUeCw9 J2YEvksVpKpzvJBjpvurCtK4Vwj2SuU6mk7Vf X-Google-Smtp-Source: AGHT+IEJqJTUEToVLsAz3TUs3hv4M1JTAA/j5bflNrbMaYu8pXjrLGnrKB2V/bcpV5X6FMXZ3OqejllkDm2rWH2sDhE= X-Received: by 2002:a05:6102:4193:b0:46d:2f8b:d7 with SMTP id cd19-20020a056102419300b0046d2f8b00d7mr6451934vsb.22.1707396812044; Thu, 08 Feb 2024 04:53:32 -0800 (PST) MIME-Version: 1.0 References: <20240124-alice-mm-v1-0-d1abcec83c44@google.com> <20240124-alice-mm-v1-1-d1abcec83c44@google.com> In-Reply-To: From: Alice Ryhl Date: Thu, 8 Feb 2024 13:53:20 +0100 Message-ID: Subject: Re: [PATCH 1/3] rust: add userspace pointers To: Trevor Gross Cc: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?UTF-8?Q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Kees Cook , Al Viro , Andrew Morton , Greg Kroah-Hartman , =?UTF-8?B?QXJ2ZSBIasO4bm5ldsOlZw==?= , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Arnd Bergmann , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Christian Brauner Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable X-Rspam-User: X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 3D4528000B X-Stat-Signature: 3adzujwfgtnbgmkb68m4q43y6cg7r6wa X-HE-Tag: 1707396812-522256 X-HE-Meta: U2FsdGVkX198dvwcylL0k8ySHxbXnQR7J0sK5JvaBtMDJw6ssdEHAUXV3zOFBVvtAbcKYuHF80KIJN4dTr625th/FSj2Ae9TfOXNnk0SS3FOKl7sMJ0rOcADCLdr36K3UMI2x70s+yRCwYjjy6YD2Dshv6F/6ArTejSQJpzD3NPIfxY4cYEfjDePxyILRLASrLEwpKxGu0s1TJqcvrCEU1kNuhA7OkIdYXxRW1I/5zqDBGJpviKlAVB7ZJRV/fw5tSgwXA7rvyAyeZLwJS7myX3rAZyzFFsjY3K5Fg39BUze8gov4ggdEgIExXcNfVNNtG5Tk1C4kCZH6o/KnPNlK3Mq+6vshVJwJTRJIA+V6rXGX4fHEbHqazRhifrf2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: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: On Thu, Feb 1, 2024 at 5:06=E2=80=AFAM Trevor Gross wro= te: > > On Wed, Jan 24, 2024 at 6:21=E2=80=AFAM Alice Ryhl = wrote: > > +/// A pointer to an area in userspace memory, which can be either read= -only or > > +/// read-write. > > +/// > > +/// All methods on this struct are safe: invalid pointers return `EFAU= LT`. > > Maybe > > ... attempting to read or write invalid pointers will return `EFAULT`= . Sure, that works. > > +/// Concurrent access, *including data races to/from userspace memory*= , is > > +/// permitted, because fundamentally another userspace thread/process = could > > +/// always be modifying memory at the same time (in the same way that = userspace > > +/// Rust's [`std::io`] permits data races with the contents of files o= n disk). > > +/// In the presence of a race, the exact byte values read/written are > > +/// unspecified but the operation is well-defined. Kernelspace code sh= ould > > +/// validate its copy of data after completing a read, and not expect = that > > +/// multiple reads of the same address will return the same value. > > +/// > > +/// These APIs are designed to make it difficult to accidentally write= TOCTOU > > +/// bugs. Every time you read from a memory location, the pointer is a= dvanced by > > +/// the length so that you cannot use that reader to read the same mem= ory > > +/// location twice. Preventing double-fetches avoids TOCTOU bugs. This= is > > +/// accomplished by taking `self` by value to prevent obtaining multip= le readers > > +/// on a given [`UserSlicePtr`], and the readers only permitting forwa= rd reads. > > +/// If double-fetching a memory location is necessary for some reason,= then that > > +/// is done by creating multiple readers to the same memory location, = e.g. using > > +/// [`clone_reader`]. > > Maybe something like > > Every time a memory location is read, the reader's position is advanc= ed by > the read length and the next read will start from there. This helps p= revent > accidentally reading the same location twice and causing a TOCTOU bug= . > > Creating a [`UserSlicePtrReader`] and/or [`UserSlicePtrWriter`] > consumes the `UserSlicePtr`, helping ensure that there aren't multipl= e > readers or writers to the same location. > > If double fetching a memory location... That makes sense to me. I'll update that. > > +/// > > +/// Constructing a [`UserSlicePtr`] performs no checks on the provided= address > > +/// and length, it can safely be constructed inside a kernel thread wi= th no > > +/// current userspace process. Reads and writes wrap the kernel APIs > > Maybe some of this is better documented on `new` rather than the type? I agree. I will move it. > > +/// `copy_from_user` and `copy_to_user`, which check the memory map of= the > > +/// current process and enforce that the address range is within the u= ser range > > +/// (no additional calls to `access_ok` are needed). > > +/// > > +/// [`std::io`]: https://doc.rust-lang.org/std/io/index.html > > +/// [`clone_reader`]: UserSlicePtrReader::clone_reader > > +pub struct UserSlicePtr(*mut c_void, usize); > > I think just `UserSlice` could work for the name here, since > `SlicePtr` is a bit redundant (slices automatically containing a > pointer). Also makes the Reader/Writer types a bit less wordy. Though > I understand wanting to make it discoverable for C users. Sure, renamed. > Is some sort of `Debug` implementation useful? Leaking pointer addresses in logs is frowned upon in the kernel, so I don't think we should include that. > > + /// Reads the entirety of the user slice. > > + /// > > + /// Returns `EFAULT` if the address does not currently point to > > + /// mapped, readable memory. > > + pub fn read_all(self) -> Result> { > > + self.reader().read_all() > > + } > > std::io uses the signature > > fn read_to_end(&mut self, buf: &mut Vec) -> Result { ... } > > Maybe this could be better here too, since it allows reusing the > vector without going through `read_raw`. > > https://doc.rust-lang.org/std/io/trait.Read.html#method.read_to_end I updated the signature so that it appends to an existing vector instead of creating a new one. > > + /// Constructs a [`UserSlicePtrReader`]. > > + pub fn reader(self) -> UserSlicePtrReader { > > + UserSlicePtrReader(self.0, self.1) > > + } > > I wonder if this should be called `into_reader` to note that it is a > consuming method. Indifferent here, since there aren't any non-`self` > variants. Hmm. I think the current name is good enough, since there aren't any non-self methods, as you mention. > > + > > + /// Constructs a [`UserSlicePtrWriter`]. > > + pub fn writer(self) -> UserSlicePtrWriter { > > + UserSlicePtrWriter(self.0, self.1) > > + } > > + > > + /// Constructs both a [`UserSlicePtrReader`] and a [`UserSlicePtrW= riter`]. > > Could you add a brief about what is or isn't allowed when you have a > reader and a writer to the same location? Ultimately, you can do whatever you want. But I'll add this: /// Usually when this is used, you will first read the data, and then /// overwrite it afterwards. > > + pub fn reader_writer(self) -> (UserSlicePtrReader, UserSlicePtrWri= ter) { > > + ( > > + UserSlicePtrReader(self.0, self.1), > > + UserSlicePtrWriter(self.0, self.1), > > + ) > > + } > > +} > > + > > +/// A reader for [`UserSlicePtr`]. > > +/// > > +/// Used to incrementally read from the user slice. > > +pub struct UserSlicePtrReader(*mut c_void, usize); > > + > > +impl UserSlicePtrReader { > > + /// Skip the provided number of bytes. > > + /// > > + /// Returns an error if skipping more than the length of the buffe= r. > > + pub fn skip(&mut self, num_skip: usize) -> Result { > > + // Update `self.1` first since that's the fallible one. > > + self.1 =3D self.1.checked_sub(num_skip).ok_or(EFAULT)?; > > + self.0 =3D self.0.wrapping_add(num_skip); > > I think it would be better to change to named structs to make this more c= lear. Good idea. Changed to named fields. > > + Ok(()) > > + } > > + > > + /// Create a reader that can access the same range of data. > > + /// > > + /// Reading from the clone does not advance the current reader. > > + /// > > + /// The caller should take care to not introduce TOCTOU issues. > > Could you add an example of what should be avoided? > > > + pub fn clone_reader(&self) -> UserSlicePtrReader { > > + UserSlicePtrReader(self.0, self.1) > > + } > > + > > + /// Returns the number of bytes left to be read from this. > > Remove "from this" or change to "from this reader". Done. > > + /// > > + /// Note that even reading less than this number of bytes may fail= .> + pub fn len(&self) -> usize { > > + self.1 > > + } > > + > > + /// Returns `true` if no data is available in the io buffer. > > + pub fn is_empty(&self) -> bool { > > + self.1 =3D=3D 0 > > + } > > + > > + /// Reads raw data from the user slice into a raw kernel buffer. > > + /// > > + /// Fails with `EFAULT` if the read encounters a page fault. > > This is raised if the address is invalid right, not just page faults? > Or, are page faults just the only mode of indication that a pointer > isn't valid. > > I know this is the same as copy_from_user, but I don't understand that > too well myself. I'm also a bit curious what happens if you pass a > kernel pointer to these methods. Basically, if the userspace process wouldn't be able to dereference the pointer, then you get this error. > > + /// # Safety > > + /// > > + /// The `out` pointer must be valid for writing `len` bytes. > > + pub unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Res= ult { > > What is the motivation for taking raw pointers rather than a slice > here? In which case it could just be called `read`. The second patch will introduce a method called `read`, so we can't use that name. I don't think a slice gains that much compared to a raw pointer. It would have to be an `&mut [MaybeUninit]` due to uninit memory, but that doesn't actually allow the caller to use this method without unsafe, since the caller would have to unsafely assert that the slice has been initialized by this call themselves. Making this method usable safely would require that we start using something along the lines of the standard library's BorrowedBuf [1], which seems way overkill to me. [1]: https://doc.rust-lang.org/stable/std/io/struct.BorrowedBuf.html > > + if len > self.1 || len > MAX_USER_OP_LEN { > > + return Err(EFAULT); > > + } > > + // SAFETY: The caller promises that `out` is valid for writing= `len` bytes. > > + let res =3D unsafe { bindings::copy_from_user(out.cast::(), self.0, len as c_ulong) }; > > To me, it would be more clear to `c_ulong::try_from(len).map_err(|_| > EFAULT)?` rather than using MAX_USER_OP_LEN with an `as` cast, since > it makes it immediately clear that the conversion is ok (and is doing > that same comparison) Thanks for the suggestion. I changed this. > > + let len =3D self.len(); > > + let mut data =3D Vec::::try_with_capacity(len)?; > > + > > + // SAFETY: The output buffer is valid for `len` bytes as we ju= st allocated that much space. > > + unsafe { self.read_raw(data.as_mut_ptr(), len)? }; > > If making the change above (possibly even if not), going through > https://doc.rust-lang.org/std/vec/struct.Vec.html#method.spare_capacity_m= ut > can be more clear about uninitialized data. > > > + > > + // SAFETY: Since the call to `read_raw` was successful, the fi= rst `len` bytes of the vector > > + // have been initialized. > > + unsafe { data.set_len(len) }; > > + Ok(data) > > + } > > +} > > + > > +/// A writer for [`UserSlicePtr`]. > > +/// > > +/// Used to incrementally write into the user slice. > > +pub struct UserSlicePtrWriter(*mut c_void, usize); > > + > > +impl UserSlicePtrWriter { > > + /// Returns the amount of space remaining in this buffer. > > + /// > > + /// Note that even writing less than this number of bytes may fail= . > > + pub fn len(&self) -> usize { > > + self.1 > > + } > > + > > + /// Returns `true` if no more data can be written to this buffer. > > + pub fn is_empty(&self) -> bool { > > + self.1 =3D=3D 0 > > + } > > + > > + /// Writes raw data to this user pointer from a raw kernel buffer. > > + /// > > + /// Fails with `EFAULT` if the write encounters a page fault. > > + /// > > + /// # Safety > > + /// > > + /// The `data` pointer must be valid for reading `len` bytes. > > + pub unsafe fn write_raw(&mut self, data: *const u8, len: usize) ->= Result { > > Same as for Reader regarding signature I suppose we could have only `write_slice`. But if we're going to have a read_raw, then having write_raw too makes sense to me. Besides, a memcpy of uninit memory isn't UB by itself, so the raw method would let you write uninit memory if you needed to. > > + if res !=3D 0 { > > + return Err(EFAULT); > > + } > > + // Since this is not a pointer to a valid object in our progra= m, > > + // we cannot use `add`, which has C-style rules for defined > > + // behavior. > > + self.0 =3D self.0.wrapping_add(len); > > + self.1 -=3D len; > > + Ok(()) > > + } > > + > > + /// Writes the provided slice to this user pointer. > > + /// > > + /// Fails with `EFAULT` if the write encounters a page fault. > > + pub fn write_slice(&mut self, data: &[u8]) -> Result { > > This could probably just be called `write`, which would be consistent > with std::io::Write. This would also name conflict with the second patch. > The docs could use usage examples, but I am sure you are planning on > that already :) I'll add some. Alice