xref: /openbmc/linux/block/sed-opal.c (revision 93696d8f)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright © 2016 Intel Corporation
4  *
5  * Authors:
6  *    Scott  Bauer      <scott.bauer@intel.com>
7  *    Rafael Antognolli <rafael.antognolli@intel.com>
8  */
9 
10 #define pr_fmt(fmt) KBUILD_MODNAME ":OPAL: " fmt
11 
12 #include <linux/delay.h>
13 #include <linux/device.h>
14 #include <linux/kernel.h>
15 #include <linux/list.h>
16 #include <linux/blkdev.h>
17 #include <linux/slab.h>
18 #include <linux/uaccess.h>
19 #include <uapi/linux/sed-opal.h>
20 #include <linux/sed-opal.h>
21 #include <linux/string.h>
22 #include <linux/kdev_t.h>
23 #include <linux/key.h>
24 #include <linux/key-type.h>
25 #include <keys/user-type.h>
26 
27 #include "opal_proto.h"
28 
29 #define IO_BUFFER_LENGTH 2048
30 #define MAX_TOKS 64
31 
32 /* Number of bytes needed by cmd_finalize. */
33 #define CMD_FINALIZE_BYTES_NEEDED 7
34 
35 static struct key *sed_opal_keyring;
36 
37 struct opal_step {
38 	int (*fn)(struct opal_dev *dev, void *data);
39 	void *data;
40 };
41 typedef int (cont_fn)(struct opal_dev *dev);
42 
43 enum opal_atom_width {
44 	OPAL_WIDTH_TINY,
45 	OPAL_WIDTH_SHORT,
46 	OPAL_WIDTH_MEDIUM,
47 	OPAL_WIDTH_LONG,
48 	OPAL_WIDTH_TOKEN
49 };
50 
51 /*
52  * On the parsed response, we don't store again the toks that are already
53  * stored in the response buffer. Instead, for each token, we just store a
54  * pointer to the position in the buffer where the token starts, and the size
55  * of the token in bytes.
56  */
57 struct opal_resp_tok {
58 	const u8 *pos;
59 	size_t len;
60 	enum opal_response_token type;
61 	enum opal_atom_width width;
62 	union {
63 		u64 u;
64 		s64 s;
65 	} stored;
66 };
67 
68 /*
69  * From the response header it's not possible to know how many tokens there are
70  * on the payload. So we hardcode that the maximum will be MAX_TOKS, and later
71  * if we start dealing with messages that have more than that, we can increase
72  * this number. This is done to avoid having to make two passes through the
73  * response, the first one counting how many tokens we have and the second one
74  * actually storing the positions.
75  */
76 struct parsed_resp {
77 	int num;
78 	struct opal_resp_tok toks[MAX_TOKS];
79 };
80 
81 struct opal_dev {
82 	u32 flags;
83 
84 	void *data;
85 	sec_send_recv *send_recv;
86 
87 	struct mutex dev_lock;
88 	u16 comid;
89 	u32 hsn;
90 	u32 tsn;
91 	u64 align; /* alignment granularity */
92 	u64 lowest_lba;
93 	u32 logical_block_size;
94 	u8  align_required; /* ALIGN: 0 or 1 */
95 
96 	size_t pos;
97 	u8 *cmd;
98 	u8 *resp;
99 
100 	struct parsed_resp parsed;
101 	size_t prev_d_len;
102 	void *prev_data;
103 
104 	struct list_head unlk_lst;
105 };
106 
107 
108 static const u8 opaluid[][OPAL_UID_LENGTH] = {
109 	/* users */
110 	[OPAL_SMUID_UID] =
111 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff },
112 	[OPAL_THISSP_UID] =
113 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 },
114 	[OPAL_ADMINSP_UID] =
115 		{ 0x00, 0x00, 0x02, 0x05, 0x00, 0x00, 0x00, 0x01 },
116 	[OPAL_LOCKINGSP_UID] =
117 		{ 0x00, 0x00, 0x02, 0x05, 0x00, 0x00, 0x00, 0x02 },
118 	[OPAL_ENTERPRISE_LOCKINGSP_UID] =
119 		{ 0x00, 0x00, 0x02, 0x05, 0x00, 0x01, 0x00, 0x01 },
120 	[OPAL_ANYBODY_UID] =
121 		{ 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x01 },
122 	[OPAL_SID_UID] =
123 		{ 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x06 },
124 	[OPAL_ADMIN1_UID] =
125 		{ 0x00, 0x00, 0x00, 0x09, 0x00, 0x01, 0x00, 0x01 },
126 	[OPAL_USER1_UID] =
127 		{ 0x00, 0x00, 0x00, 0x09, 0x00, 0x03, 0x00, 0x01 },
128 	[OPAL_USER2_UID] =
129 		{ 0x00, 0x00, 0x00, 0x09, 0x00, 0x03, 0x00, 0x02 },
130 	[OPAL_PSID_UID] =
131 		{ 0x00, 0x00, 0x00, 0x09, 0x00, 0x01, 0xff, 0x01 },
132 	[OPAL_ENTERPRISE_BANDMASTER0_UID] =
133 		{ 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x80, 0x01 },
134 	[OPAL_ENTERPRISE_ERASEMASTER_UID] =
135 		{ 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x84, 0x01 },
136 
137 	/* tables */
138 	[OPAL_TABLE_TABLE] =
139 		{ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01 },
140 	[OPAL_LOCKINGRANGE_GLOBAL] =
141 		{ 0x00, 0x00, 0x08, 0x02, 0x00, 0x00, 0x00, 0x01 },
142 	[OPAL_LOCKINGRANGE_ACE_START_TO_KEY] =
143 		{ 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0xD0, 0x01 },
144 	[OPAL_LOCKINGRANGE_ACE_RDLOCKED] =
145 		{ 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0xE0, 0x01 },
146 	[OPAL_LOCKINGRANGE_ACE_WRLOCKED] =
147 		{ 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0xE8, 0x01 },
148 	[OPAL_MBRCONTROL] =
149 		{ 0x00, 0x00, 0x08, 0x03, 0x00, 0x00, 0x00, 0x01 },
150 	[OPAL_MBR] =
151 		{ 0x00, 0x00, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00 },
152 	[OPAL_AUTHORITY_TABLE] =
153 		{ 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00},
154 	[OPAL_C_PIN_TABLE] =
155 		{ 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x00},
156 	[OPAL_LOCKING_INFO_TABLE] =
157 		{ 0x00, 0x00, 0x08, 0x01, 0x00, 0x00, 0x00, 0x01 },
158 	[OPAL_ENTERPRISE_LOCKING_INFO_TABLE] =
159 		{ 0x00, 0x00, 0x08, 0x01, 0x00, 0x00, 0x00, 0x00 },
160 	[OPAL_DATASTORE] =
161 		{ 0x00, 0x00, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00 },
162 
163 	/* C_PIN_TABLE object ID's */
164 	[OPAL_C_PIN_MSID] =
165 		{ 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x84, 0x02},
166 	[OPAL_C_PIN_SID] =
167 		{ 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x01},
168 	[OPAL_C_PIN_ADMIN1] =
169 		{ 0x00, 0x00, 0x00, 0x0B, 0x00, 0x01, 0x00, 0x01},
170 
171 	/* half UID's (only first 4 bytes used) */
172 	[OPAL_HALF_UID_AUTHORITY_OBJ_REF] =
173 		{ 0x00, 0x00, 0x0C, 0x05, 0xff, 0xff, 0xff, 0xff },
174 	[OPAL_HALF_UID_BOOLEAN_ACE] =
175 		{ 0x00, 0x00, 0x04, 0x0E, 0xff, 0xff, 0xff, 0xff },
176 
177 	/* special value for omitted optional parameter */
178 	[OPAL_UID_HEXFF] =
179 		{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
180 };
181 
182 /*
183  * TCG Storage SSC Methods.
184  * Derived from: TCG_Storage_Architecture_Core_Spec_v2.01_r1.00
185  * Section: 6.3 Assigned UIDs
186  */
187 static const u8 opalmethod[][OPAL_METHOD_LENGTH] = {
188 	[OPAL_PROPERTIES] =
189 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x01 },
190 	[OPAL_STARTSESSION] =
191 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x02 },
192 	[OPAL_REVERT] =
193 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x02, 0x02 },
194 	[OPAL_ACTIVATE] =
195 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x02, 0x03 },
196 	[OPAL_EGET] =
197 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x06 },
198 	[OPAL_ESET] =
199 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x07 },
200 	[OPAL_NEXT] =
201 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x08 },
202 	[OPAL_EAUTHENTICATE] =
203 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0c },
204 	[OPAL_GETACL] =
205 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0d },
206 	[OPAL_GENKEY] =
207 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x10 },
208 	[OPAL_REVERTSP] =
209 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x11 },
210 	[OPAL_GET] =
211 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x16 },
212 	[OPAL_SET] =
213 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x17 },
214 	[OPAL_AUTHENTICATE] =
215 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x1c },
216 	[OPAL_RANDOM] =
217 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x06, 0x01 },
218 	[OPAL_ERASE] =
219 		{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x08, 0x03 },
220 };
221 
222 static int end_opal_session_error(struct opal_dev *dev);
223 static int opal_discovery0_step(struct opal_dev *dev);
224 
225 struct opal_suspend_data {
226 	struct opal_lock_unlock unlk;
227 	u8 lr;
228 	struct list_head node;
229 };
230 
231 /*
232  * Derived from:
233  * TCG_Storage_Architecture_Core_Spec_v2.01_r1.00
234  * Section: 5.1.5 Method Status Codes
235  */
236 static const char * const opal_errors[] = {
237 	"Success",
238 	"Not Authorized",
239 	"Unknown Error",
240 	"SP Busy",
241 	"SP Failed",
242 	"SP Disabled",
243 	"SP Frozen",
244 	"No Sessions Available",
245 	"Uniqueness Conflict",
246 	"Insufficient Space",
247 	"Insufficient Rows",
248 	"Invalid Function",
249 	"Invalid Parameter",
250 	"Invalid Reference",
251 	"Unknown Error",
252 	"TPER Malfunction",
253 	"Transaction Failure",
254 	"Response Overflow",
255 	"Authority Locked Out",
256 };
257 
258 static const char *opal_error_to_human(int error)
259 {
260 	if (error == 0x3f)
261 		return "Failed";
262 
263 	if (error >= ARRAY_SIZE(opal_errors) || error < 0)
264 		return "Unknown Error";
265 
266 	return opal_errors[error];
267 }
268 
269 static void print_buffer(const u8 *ptr, u32 length)
270 {
271 #ifdef DEBUG
272 	print_hex_dump_bytes("OPAL: ", DUMP_PREFIX_OFFSET, ptr, length);
273 	pr_debug("\n");
274 #endif
275 }
276 
277 /*
278  * Allocate/update a SED Opal key and add it to the SED Opal keyring.
279  */
280 static int update_sed_opal_key(const char *desc, u_char *key_data, int keylen)
281 {
282 	key_ref_t kr;
283 
284 	if (!sed_opal_keyring)
285 		return -ENOKEY;
286 
287 	kr = key_create_or_update(make_key_ref(sed_opal_keyring, true), "user",
288 				  desc, (const void *)key_data, keylen,
289 				  KEY_USR_VIEW | KEY_USR_SEARCH | KEY_USR_WRITE,
290 				  KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_BUILT_IN |
291 					KEY_ALLOC_BYPASS_RESTRICTION);
292 	if (IS_ERR(kr)) {
293 		pr_err("Error adding SED key (%ld)\n", PTR_ERR(kr));
294 		return PTR_ERR(kr);
295 	}
296 
297 	return 0;
298 }
299 
300 /*
301  * Read a SED Opal key from the SED Opal keyring.
302  */
303 static int read_sed_opal_key(const char *key_name, u_char *buffer, int buflen)
304 {
305 	int ret;
306 	key_ref_t kref;
307 	struct key *key;
308 
309 	if (!sed_opal_keyring)
310 		return -ENOKEY;
311 
312 	kref = keyring_search(make_key_ref(sed_opal_keyring, true),
313 			      &key_type_user, key_name, true);
314 
315 	if (IS_ERR(kref))
316 		return PTR_ERR(kref);
317 
318 	key = key_ref_to_ptr(kref);
319 	down_read(&key->sem);
320 	ret = key_validate(key);
321 	if (ret == 0) {
322 		if (buflen > key->datalen)
323 			buflen = key->datalen;
324 
325 		ret = key->type->read(key, (char *)buffer, buflen);
326 	}
327 	up_read(&key->sem);
328 
329 	key_ref_put(kref);
330 
331 	return ret;
332 }
333 
334 static int opal_get_key(struct opal_dev *dev, struct opal_key *key)
335 {
336 	int ret = 0;
337 
338 	switch (key->key_type) {
339 	case OPAL_INCLUDED:
340 		/* the key is ready to use */
341 		break;
342 	case OPAL_KEYRING:
343 		/* the key is in the keyring */
344 		ret = read_sed_opal_key(OPAL_AUTH_KEY, key->key, OPAL_KEY_MAX);
345 		if (ret > 0) {
346 			if (ret > U8_MAX) {
347 				ret = -ENOSPC;
348 				goto error;
349 			}
350 			key->key_len = ret;
351 			key->key_type = OPAL_INCLUDED;
352 		}
353 		break;
354 	default:
355 		ret = -EINVAL;
356 		break;
357 	}
358 	if (ret < 0)
359 		goto error;
360 
361 	/* must have a PEK by now or it's an error */
362 	if (key->key_type != OPAL_INCLUDED || key->key_len == 0) {
363 		ret = -EINVAL;
364 		goto error;
365 	}
366 	return 0;
367 error:
368 	pr_debug("Error getting password: %d\n", ret);
369 	return ret;
370 }
371 
372 static bool check_tper(const void *data)
373 {
374 	const struct d0_tper_features *tper = data;
375 	u8 flags = tper->supported_features;
376 
377 	if (!(flags & TPER_SYNC_SUPPORTED)) {
378 		pr_debug("TPer sync not supported. flags = %d\n",
379 			 tper->supported_features);
380 		return false;
381 	}
382 
383 	return true;
384 }
385 
386 static bool check_lcksuppt(const void *data)
387 {
388 	const struct d0_locking_features *lfeat = data;
389 	u8 sup_feat = lfeat->supported_features;
390 
391 	return !!(sup_feat & LOCKING_SUPPORTED_MASK);
392 }
393 
394 static bool check_lckenabled(const void *data)
395 {
396 	const struct d0_locking_features *lfeat = data;
397 	u8 sup_feat = lfeat->supported_features;
398 
399 	return !!(sup_feat & LOCKING_ENABLED_MASK);
400 }
401 
402 static bool check_locked(const void *data)
403 {
404 	const struct d0_locking_features *lfeat = data;
405 	u8 sup_feat = lfeat->supported_features;
406 
407 	return !!(sup_feat & LOCKED_MASK);
408 }
409 
410 static bool check_mbrenabled(const void *data)
411 {
412 	const struct d0_locking_features *lfeat = data;
413 	u8 sup_feat = lfeat->supported_features;
414 
415 	return !!(sup_feat & MBR_ENABLED_MASK);
416 }
417 
418 static bool check_mbrdone(const void *data)
419 {
420 	const struct d0_locking_features *lfeat = data;
421 	u8 sup_feat = lfeat->supported_features;
422 
423 	return !!(sup_feat & MBR_DONE_MASK);
424 }
425 
426 static bool check_sum(const void *data)
427 {
428 	const struct d0_single_user_mode *sum = data;
429 	u32 nlo = be32_to_cpu(sum->num_locking_objects);
430 
431 	if (nlo == 0) {
432 		pr_debug("Need at least one locking object.\n");
433 		return false;
434 	}
435 
436 	pr_debug("Number of locking objects: %d\n", nlo);
437 
438 	return true;
439 }
440 
441 static u16 get_comid_v100(const void *data)
442 {
443 	const struct d0_opal_v100 *v100 = data;
444 
445 	return be16_to_cpu(v100->baseComID);
446 }
447 
448 static u16 get_comid_v200(const void *data)
449 {
450 	const struct d0_opal_v200 *v200 = data;
451 
452 	return be16_to_cpu(v200->baseComID);
453 }
454 
455 static int opal_send_cmd(struct opal_dev *dev)
456 {
457 	return dev->send_recv(dev->data, dev->comid, TCG_SECP_01,
458 			      dev->cmd, IO_BUFFER_LENGTH,
459 			      true);
460 }
461 
462 static int opal_recv_cmd(struct opal_dev *dev)
463 {
464 	return dev->send_recv(dev->data, dev->comid, TCG_SECP_01,
465 			      dev->resp, IO_BUFFER_LENGTH,
466 			      false);
467 }
468 
469 static int opal_recv_check(struct opal_dev *dev)
470 {
471 	size_t buflen = IO_BUFFER_LENGTH;
472 	void *buffer = dev->resp;
473 	struct opal_header *hdr = buffer;
474 	int ret;
475 
476 	do {
477 		pr_debug("Sent OPAL command: outstanding=%d, minTransfer=%d\n",
478 			 hdr->cp.outstandingData,
479 			 hdr->cp.minTransfer);
480 
481 		if (hdr->cp.outstandingData == 0 ||
482 		    hdr->cp.minTransfer != 0)
483 			return 0;
484 
485 		memset(buffer, 0, buflen);
486 		ret = opal_recv_cmd(dev);
487 	} while (!ret);
488 
489 	return ret;
490 }
491 
492 static int opal_send_recv(struct opal_dev *dev, cont_fn *cont)
493 {
494 	int ret;
495 
496 	ret = opal_send_cmd(dev);
497 	if (ret)
498 		return ret;
499 	ret = opal_recv_cmd(dev);
500 	if (ret)
501 		return ret;
502 	ret = opal_recv_check(dev);
503 	if (ret)
504 		return ret;
505 	return cont(dev);
506 }
507 
508 static void check_geometry(struct opal_dev *dev, const void *data)
509 {
510 	const struct d0_geometry_features *geo = data;
511 
512 	dev->align = be64_to_cpu(geo->alignment_granularity);
513 	dev->lowest_lba = be64_to_cpu(geo->lowest_aligned_lba);
514 	dev->logical_block_size = be32_to_cpu(geo->logical_block_size);
515 	dev->align_required = geo->reserved01 & 1;
516 }
517 
518 static int execute_step(struct opal_dev *dev,
519 			const struct opal_step *step, size_t stepIndex)
520 {
521 	int error = step->fn(dev, step->data);
522 
523 	if (error) {
524 		pr_debug("Step %zu (%pS) failed with error %d: %s\n",
525 			 stepIndex, step->fn, error,
526 			 opal_error_to_human(error));
527 	}
528 
529 	return error;
530 }
531 
532 static int execute_steps(struct opal_dev *dev,
533 			 const struct opal_step *steps, size_t n_steps)
534 {
535 	size_t state = 0;
536 	int error;
537 
538 	/* first do a discovery0 */
539 	error = opal_discovery0_step(dev);
540 	if (error)
541 		return error;
542 
543 	for (state = 0; state < n_steps; state++) {
544 		error = execute_step(dev, &steps[state], state);
545 		if (error)
546 			goto out_error;
547 	}
548 
549 	return 0;
550 
551 out_error:
552 	/*
553 	 * For each OPAL command the first step in steps starts some sort of
554 	 * session. If an error occurred in the initial discovery0 or if an
555 	 * error occurred in the first step (and thus stopping the loop with
556 	 * state == 0) then there was an error before or during the attempt to
557 	 * start a session. Therefore we shouldn't attempt to terminate a
558 	 * session, as one has not yet been created.
559 	 */
560 	if (state > 0)
561 		end_opal_session_error(dev);
562 
563 	return error;
564 }
565 
566 static int opal_discovery0_end(struct opal_dev *dev, void *data)
567 {
568 	struct opal_discovery *discv_out = data; /* may be NULL */
569 	u8 __user *buf_out;
570 	u64 len_out;
571 	bool found_com_id = false, supported = true, single_user = false;
572 	const struct d0_header *hdr = (struct d0_header *)dev->resp;
573 	const u8 *epos = dev->resp, *cpos = dev->resp;
574 	u16 comid = 0;
575 	u32 hlen = be32_to_cpu(hdr->length);
576 
577 	print_buffer(dev->resp, hlen);
578 	dev->flags &= OPAL_FL_SUPPORTED;
579 
580 	if (hlen > IO_BUFFER_LENGTH - sizeof(*hdr)) {
581 		pr_debug("Discovery length overflows buffer (%zu+%u)/%u\n",
582 			 sizeof(*hdr), hlen, IO_BUFFER_LENGTH);
583 		return -EFAULT;
584 	}
585 
586 	if (discv_out) {
587 		buf_out = (u8 __user *)(uintptr_t)discv_out->data;
588 		len_out = min_t(u64, discv_out->size, hlen);
589 		if (buf_out && copy_to_user(buf_out, dev->resp, len_out))
590 			return -EFAULT;
591 
592 		discv_out->size = hlen; /* actual size of data */
593 	}
594 
595 	epos += hlen; /* end of buffer */
596 	cpos += sizeof(*hdr); /* current position on buffer */
597 
598 	while (cpos < epos && supported) {
599 		const struct d0_features *body =
600 			(const struct d0_features *)cpos;
601 
602 		switch (be16_to_cpu(body->code)) {
603 		case FC_TPER:
604 			supported = check_tper(body->features);
605 			break;
606 		case FC_SINGLEUSER:
607 			single_user = check_sum(body->features);
608 			if (single_user)
609 				dev->flags |= OPAL_FL_SUM_SUPPORTED;
610 			break;
611 		case FC_GEOMETRY:
612 			check_geometry(dev, body);
613 			break;
614 		case FC_LOCKING:
615 			if (check_lcksuppt(body->features))
616 				dev->flags |= OPAL_FL_LOCKING_SUPPORTED;
617 			if (check_lckenabled(body->features))
618 				dev->flags |= OPAL_FL_LOCKING_ENABLED;
619 			if (check_locked(body->features))
620 				dev->flags |= OPAL_FL_LOCKED;
621 			if (check_mbrenabled(body->features))
622 				dev->flags |= OPAL_FL_MBR_ENABLED;
623 			if (check_mbrdone(body->features))
624 				dev->flags |= OPAL_FL_MBR_DONE;
625 			break;
626 		case FC_ENTERPRISE:
627 		case FC_DATASTORE:
628 			/* some ignored properties */
629 			pr_debug("Found OPAL feature description: %d\n",
630 				 be16_to_cpu(body->code));
631 			break;
632 		case FC_OPALV100:
633 			comid = get_comid_v100(body->features);
634 			found_com_id = true;
635 			break;
636 		case FC_OPALV200:
637 			comid = get_comid_v200(body->features);
638 			found_com_id = true;
639 			break;
640 		case 0xbfff ... 0xffff:
641 			/* vendor specific, just ignore */
642 			break;
643 		default:
644 			pr_debug("OPAL Unknown feature: %d\n",
645 				 be16_to_cpu(body->code));
646 
647 		}
648 		cpos += body->length + 4;
649 	}
650 
651 	if (!supported) {
652 		pr_debug("This device is not Opal enabled. Not Supported!\n");
653 		return -EOPNOTSUPP;
654 	}
655 
656 	if (!single_user)
657 		pr_debug("Device doesn't support single user mode\n");
658 
659 
660 	if (!found_com_id) {
661 		pr_debug("Could not find OPAL comid for device. Returning early\n");
662 		return -EOPNOTSUPP;
663 	}
664 
665 	dev->comid = comid;
666 
667 	return 0;
668 }
669 
670 static int opal_discovery0(struct opal_dev *dev, void *data)
671 {
672 	int ret;
673 
674 	memset(dev->resp, 0, IO_BUFFER_LENGTH);
675 	dev->comid = OPAL_DISCOVERY_COMID;
676 	ret = opal_recv_cmd(dev);
677 	if (ret)
678 		return ret;
679 
680 	return opal_discovery0_end(dev, data);
681 }
682 
683 static int opal_discovery0_step(struct opal_dev *dev)
684 {
685 	const struct opal_step discovery0_step = {
686 		opal_discovery0, NULL
687 	};
688 
689 	return execute_step(dev, &discovery0_step, 0);
690 }
691 
692 static size_t remaining_size(struct opal_dev *cmd)
693 {
694 	return IO_BUFFER_LENGTH - cmd->pos;
695 }
696 
697 static bool can_add(int *err, struct opal_dev *cmd, size_t len)
698 {
699 	if (*err)
700 		return false;
701 
702 	if (remaining_size(cmd) < len) {
703 		pr_debug("Error adding %zu bytes: end of buffer.\n", len);
704 		*err = -ERANGE;
705 		return false;
706 	}
707 
708 	return true;
709 }
710 
711 static void add_token_u8(int *err, struct opal_dev *cmd, u8 tok)
712 {
713 	if (!can_add(err, cmd, 1))
714 		return;
715 
716 	cmd->cmd[cmd->pos++] = tok;
717 }
718 
719 static void add_short_atom_header(struct opal_dev *cmd, bool bytestring,
720 				  bool has_sign, int len)
721 {
722 	u8 atom;
723 	int err = 0;
724 
725 	atom = SHORT_ATOM_ID;
726 	atom |= bytestring ? SHORT_ATOM_BYTESTRING : 0;
727 	atom |= has_sign ? SHORT_ATOM_SIGNED : 0;
728 	atom |= len & SHORT_ATOM_LEN_MASK;
729 
730 	add_token_u8(&err, cmd, atom);
731 }
732 
733 static void add_medium_atom_header(struct opal_dev *cmd, bool bytestring,
734 				   bool has_sign, int len)
735 {
736 	u8 header0;
737 
738 	header0 = MEDIUM_ATOM_ID;
739 	header0 |= bytestring ? MEDIUM_ATOM_BYTESTRING : 0;
740 	header0 |= has_sign ? MEDIUM_ATOM_SIGNED : 0;
741 	header0 |= (len >> 8) & MEDIUM_ATOM_LEN_MASK;
742 
743 	cmd->cmd[cmd->pos++] = header0;
744 	cmd->cmd[cmd->pos++] = len;
745 }
746 
747 static void add_token_u64(int *err, struct opal_dev *cmd, u64 number)
748 {
749 	size_t len;
750 	int msb;
751 
752 	if (!(number & ~TINY_ATOM_DATA_MASK)) {
753 		add_token_u8(err, cmd, number);
754 		return;
755 	}
756 
757 	msb = fls64(number);
758 	len = DIV_ROUND_UP(msb, 8);
759 
760 	if (!can_add(err, cmd, len + 1)) {
761 		pr_debug("Error adding u64: end of buffer.\n");
762 		return;
763 	}
764 	add_short_atom_header(cmd, false, false, len);
765 	while (len--)
766 		add_token_u8(err, cmd, number >> (len * 8));
767 }
768 
769 static u8 *add_bytestring_header(int *err, struct opal_dev *cmd, size_t len)
770 {
771 	size_t header_len = 1;
772 	bool is_short_atom = true;
773 
774 	if (len & ~SHORT_ATOM_LEN_MASK) {
775 		header_len = 2;
776 		is_short_atom = false;
777 	}
778 
779 	if (!can_add(err, cmd, header_len + len)) {
780 		pr_debug("Error adding bytestring: end of buffer.\n");
781 		return NULL;
782 	}
783 
784 	if (is_short_atom)
785 		add_short_atom_header(cmd, true, false, len);
786 	else
787 		add_medium_atom_header(cmd, true, false, len);
788 
789 	return &cmd->cmd[cmd->pos];
790 }
791 
792 static void add_token_bytestring(int *err, struct opal_dev *cmd,
793 				 const u8 *bytestring, size_t len)
794 {
795 	u8 *start;
796 
797 	start = add_bytestring_header(err, cmd, len);
798 	if (!start)
799 		return;
800 	memcpy(start, bytestring, len);
801 	cmd->pos += len;
802 }
803 
804 static int build_locking_range(u8 *buffer, size_t length, u8 lr)
805 {
806 	if (length > OPAL_UID_LENGTH) {
807 		pr_debug("Can't build locking range. Length OOB\n");
808 		return -ERANGE;
809 	}
810 
811 	memcpy(buffer, opaluid[OPAL_LOCKINGRANGE_GLOBAL], OPAL_UID_LENGTH);
812 
813 	if (lr == 0)
814 		return 0;
815 
816 	buffer[5] = LOCKING_RANGE_NON_GLOBAL;
817 	buffer[7] = lr;
818 
819 	return 0;
820 }
821 
822 static int build_locking_user(u8 *buffer, size_t length, u8 lr)
823 {
824 	if (length > OPAL_UID_LENGTH) {
825 		pr_debug("Can't build locking range user. Length OOB\n");
826 		return -ERANGE;
827 	}
828 
829 	memcpy(buffer, opaluid[OPAL_USER1_UID], OPAL_UID_LENGTH);
830 
831 	buffer[7] = lr + 1;
832 
833 	return 0;
834 }
835 
836 static void set_comid(struct opal_dev *cmd, u16 comid)
837 {
838 	struct opal_header *hdr = (struct opal_header *)cmd->cmd;
839 
840 	hdr->cp.extendedComID[0] = comid >> 8;
841 	hdr->cp.extendedComID[1] = comid;
842 	hdr->cp.extendedComID[2] = 0;
843 	hdr->cp.extendedComID[3] = 0;
844 }
845 
846 static int cmd_finalize(struct opal_dev *cmd, u32 hsn, u32 tsn)
847 {
848 	struct opal_header *hdr;
849 	int err = 0;
850 
851 	/*
852 	 * Close the parameter list opened from cmd_start.
853 	 * The number of bytes added must be equal to
854 	 * CMD_FINALIZE_BYTES_NEEDED.
855 	 */
856 	add_token_u8(&err, cmd, OPAL_ENDLIST);
857 
858 	add_token_u8(&err, cmd, OPAL_ENDOFDATA);
859 	add_token_u8(&err, cmd, OPAL_STARTLIST);
860 	add_token_u8(&err, cmd, 0);
861 	add_token_u8(&err, cmd, 0);
862 	add_token_u8(&err, cmd, 0);
863 	add_token_u8(&err, cmd, OPAL_ENDLIST);
864 
865 	if (err) {
866 		pr_debug("Error finalizing command.\n");
867 		return -EFAULT;
868 	}
869 
870 	hdr = (struct opal_header *) cmd->cmd;
871 
872 	hdr->pkt.tsn = cpu_to_be32(tsn);
873 	hdr->pkt.hsn = cpu_to_be32(hsn);
874 
875 	hdr->subpkt.length = cpu_to_be32(cmd->pos - sizeof(*hdr));
876 	while (cmd->pos % 4) {
877 		if (cmd->pos >= IO_BUFFER_LENGTH) {
878 			pr_debug("Error: Buffer overrun\n");
879 			return -ERANGE;
880 		}
881 		cmd->cmd[cmd->pos++] = 0;
882 	}
883 	hdr->pkt.length = cpu_to_be32(cmd->pos - sizeof(hdr->cp) -
884 				      sizeof(hdr->pkt));
885 	hdr->cp.length = cpu_to_be32(cmd->pos - sizeof(hdr->cp));
886 
887 	return 0;
888 }
889 
890 static const struct opal_resp_tok *response_get_token(
891 				const struct parsed_resp *resp,
892 				int n)
893 {
894 	const struct opal_resp_tok *tok;
895 
896 	if (!resp) {
897 		pr_debug("Response is NULL\n");
898 		return ERR_PTR(-EINVAL);
899 	}
900 
901 	if (n >= resp->num) {
902 		pr_debug("Token number doesn't exist: %d, resp: %d\n",
903 			 n, resp->num);
904 		return ERR_PTR(-EINVAL);
905 	}
906 
907 	tok = &resp->toks[n];
908 	if (tok->len == 0) {
909 		pr_debug("Token length must be non-zero\n");
910 		return ERR_PTR(-EINVAL);
911 	}
912 
913 	return tok;
914 }
915 
916 static ssize_t response_parse_tiny(struct opal_resp_tok *tok,
917 				   const u8 *pos)
918 {
919 	tok->pos = pos;
920 	tok->len = 1;
921 	tok->width = OPAL_WIDTH_TINY;
922 
923 	if (pos[0] & TINY_ATOM_SIGNED) {
924 		tok->type = OPAL_DTA_TOKENID_SINT;
925 	} else {
926 		tok->type = OPAL_DTA_TOKENID_UINT;
927 		tok->stored.u = pos[0] & 0x3f;
928 	}
929 
930 	return tok->len;
931 }
932 
933 static ssize_t response_parse_short(struct opal_resp_tok *tok,
934 				    const u8 *pos)
935 {
936 	tok->pos = pos;
937 	tok->len = (pos[0] & SHORT_ATOM_LEN_MASK) + 1;
938 	tok->width = OPAL_WIDTH_SHORT;
939 
940 	if (pos[0] & SHORT_ATOM_BYTESTRING) {
941 		tok->type = OPAL_DTA_TOKENID_BYTESTRING;
942 	} else if (pos[0] & SHORT_ATOM_SIGNED) {
943 		tok->type = OPAL_DTA_TOKENID_SINT;
944 	} else {
945 		u64 u_integer = 0;
946 		ssize_t i, b = 0;
947 
948 		tok->type = OPAL_DTA_TOKENID_UINT;
949 		if (tok->len > 9) {
950 			pr_debug("uint64 with more than 8 bytes\n");
951 			return -EINVAL;
952 		}
953 		for (i = tok->len - 1; i > 0; i--) {
954 			u_integer |= ((u64)pos[i] << (8 * b));
955 			b++;
956 		}
957 		tok->stored.u = u_integer;
958 	}
959 
960 	return tok->len;
961 }
962 
963 static ssize_t response_parse_medium(struct opal_resp_tok *tok,
964 				     const u8 *pos)
965 {
966 	tok->pos = pos;
967 	tok->len = (((pos[0] & MEDIUM_ATOM_LEN_MASK) << 8) | pos[1]) + 2;
968 	tok->width = OPAL_WIDTH_MEDIUM;
969 
970 	if (pos[0] & MEDIUM_ATOM_BYTESTRING)
971 		tok->type = OPAL_DTA_TOKENID_BYTESTRING;
972 	else if (pos[0] & MEDIUM_ATOM_SIGNED)
973 		tok->type = OPAL_DTA_TOKENID_SINT;
974 	else
975 		tok->type = OPAL_DTA_TOKENID_UINT;
976 
977 	return tok->len;
978 }
979 
980 static ssize_t response_parse_long(struct opal_resp_tok *tok,
981 				   const u8 *pos)
982 {
983 	tok->pos = pos;
984 	tok->len = ((pos[1] << 16) | (pos[2] << 8) | pos[3]) + 4;
985 	tok->width = OPAL_WIDTH_LONG;
986 
987 	if (pos[0] & LONG_ATOM_BYTESTRING)
988 		tok->type = OPAL_DTA_TOKENID_BYTESTRING;
989 	else if (pos[0] & LONG_ATOM_SIGNED)
990 		tok->type = OPAL_DTA_TOKENID_SINT;
991 	else
992 		tok->type = OPAL_DTA_TOKENID_UINT;
993 
994 	return tok->len;
995 }
996 
997 static ssize_t response_parse_token(struct opal_resp_tok *tok,
998 				    const u8 *pos)
999 {
1000 	tok->pos = pos;
1001 	tok->len = 1;
1002 	tok->type = OPAL_DTA_TOKENID_TOKEN;
1003 	tok->width = OPAL_WIDTH_TOKEN;
1004 
1005 	return tok->len;
1006 }
1007 
1008 static int response_parse(const u8 *buf, size_t length,
1009 			  struct parsed_resp *resp)
1010 {
1011 	const struct opal_header *hdr;
1012 	struct opal_resp_tok *iter;
1013 	int num_entries = 0;
1014 	int total;
1015 	ssize_t token_length;
1016 	const u8 *pos;
1017 	u32 clen, plen, slen;
1018 
1019 	if (!buf)
1020 		return -EFAULT;
1021 
1022 	if (!resp)
1023 		return -EFAULT;
1024 
1025 	hdr = (struct opal_header *)buf;
1026 	pos = buf;
1027 	pos += sizeof(*hdr);
1028 
1029 	clen = be32_to_cpu(hdr->cp.length);
1030 	plen = be32_to_cpu(hdr->pkt.length);
1031 	slen = be32_to_cpu(hdr->subpkt.length);
1032 	pr_debug("Response size: cp: %u, pkt: %u, subpkt: %u\n",
1033 		 clen, plen, slen);
1034 
1035 	if (clen == 0 || plen == 0 || slen == 0 ||
1036 	    slen > IO_BUFFER_LENGTH - sizeof(*hdr)) {
1037 		pr_debug("Bad header length. cp: %u, pkt: %u, subpkt: %u\n",
1038 			 clen, plen, slen);
1039 		print_buffer(pos, sizeof(*hdr));
1040 		return -EINVAL;
1041 	}
1042 
1043 	if (pos > buf + length)
1044 		return -EFAULT;
1045 
1046 	iter = resp->toks;
1047 	total = slen;
1048 	print_buffer(pos, total);
1049 	while (total > 0) {
1050 		if (pos[0] <= TINY_ATOM_BYTE) /* tiny atom */
1051 			token_length = response_parse_tiny(iter, pos);
1052 		else if (pos[0] <= SHORT_ATOM_BYTE) /* short atom */
1053 			token_length = response_parse_short(iter, pos);
1054 		else if (pos[0] <= MEDIUM_ATOM_BYTE) /* medium atom */
1055 			token_length = response_parse_medium(iter, pos);
1056 		else if (pos[0] <= LONG_ATOM_BYTE) /* long atom */
1057 			token_length = response_parse_long(iter, pos);
1058 		else if (pos[0] == EMPTY_ATOM_BYTE) /* empty atom */
1059 			token_length = 1;
1060 		else /* TOKEN */
1061 			token_length = response_parse_token(iter, pos);
1062 
1063 		if (token_length < 0)
1064 			return token_length;
1065 
1066 		if (pos[0] != EMPTY_ATOM_BYTE)
1067 			num_entries++;
1068 
1069 		pos += token_length;
1070 		total -= token_length;
1071 		iter++;
1072 	}
1073 
1074 	resp->num = num_entries;
1075 
1076 	return 0;
1077 }
1078 
1079 static size_t response_get_string(const struct parsed_resp *resp, int n,
1080 				  const char **store)
1081 {
1082 	u8 skip;
1083 	const struct opal_resp_tok *tok;
1084 
1085 	*store = NULL;
1086 	tok = response_get_token(resp, n);
1087 	if (IS_ERR(tok))
1088 		return 0;
1089 
1090 	if (tok->type != OPAL_DTA_TOKENID_BYTESTRING) {
1091 		pr_debug("Token is not a byte string!\n");
1092 		return 0;
1093 	}
1094 
1095 	switch (tok->width) {
1096 	case OPAL_WIDTH_TINY:
1097 	case OPAL_WIDTH_SHORT:
1098 		skip = 1;
1099 		break;
1100 	case OPAL_WIDTH_MEDIUM:
1101 		skip = 2;
1102 		break;
1103 	case OPAL_WIDTH_LONG:
1104 		skip = 4;
1105 		break;
1106 	default:
1107 		pr_debug("Token has invalid width!\n");
1108 		return 0;
1109 	}
1110 
1111 	*store = tok->pos + skip;
1112 
1113 	return tok->len - skip;
1114 }
1115 
1116 static u64 response_get_u64(const struct parsed_resp *resp, int n)
1117 {
1118 	const struct opal_resp_tok *tok;
1119 
1120 	tok = response_get_token(resp, n);
1121 	if (IS_ERR(tok))
1122 		return 0;
1123 
1124 	if (tok->type != OPAL_DTA_TOKENID_UINT) {
1125 		pr_debug("Token is not unsigned int: %d\n", tok->type);
1126 		return 0;
1127 	}
1128 
1129 	if (tok->width != OPAL_WIDTH_TINY && tok->width != OPAL_WIDTH_SHORT) {
1130 		pr_debug("Atom is not short or tiny: %d\n", tok->width);
1131 		return 0;
1132 	}
1133 
1134 	return tok->stored.u;
1135 }
1136 
1137 static bool response_token_matches(const struct opal_resp_tok *token, u8 match)
1138 {
1139 	if (IS_ERR(token) ||
1140 	    token->type != OPAL_DTA_TOKENID_TOKEN ||
1141 	    token->pos[0] != match)
1142 		return false;
1143 	return true;
1144 }
1145 
1146 static u8 response_status(const struct parsed_resp *resp)
1147 {
1148 	const struct opal_resp_tok *tok;
1149 
1150 	tok = response_get_token(resp, 0);
1151 	if (response_token_matches(tok, OPAL_ENDOFSESSION))
1152 		return 0;
1153 
1154 	if (resp->num < 5)
1155 		return DTAERROR_NO_METHOD_STATUS;
1156 
1157 	tok = response_get_token(resp, resp->num - 5);
1158 	if (!response_token_matches(tok, OPAL_STARTLIST))
1159 		return DTAERROR_NO_METHOD_STATUS;
1160 
1161 	tok = response_get_token(resp, resp->num - 1);
1162 	if (!response_token_matches(tok, OPAL_ENDLIST))
1163 		return DTAERROR_NO_METHOD_STATUS;
1164 
1165 	return response_get_u64(resp, resp->num - 4);
1166 }
1167 
1168 /* Parses and checks for errors */
1169 static int parse_and_check_status(struct opal_dev *dev)
1170 {
1171 	int error;
1172 
1173 	print_buffer(dev->cmd, dev->pos);
1174 
1175 	error = response_parse(dev->resp, IO_BUFFER_LENGTH, &dev->parsed);
1176 	if (error) {
1177 		pr_debug("Couldn't parse response.\n");
1178 		return error;
1179 	}
1180 
1181 	return response_status(&dev->parsed);
1182 }
1183 
1184 static void clear_opal_cmd(struct opal_dev *dev)
1185 {
1186 	dev->pos = sizeof(struct opal_header);
1187 	memset(dev->cmd, 0, IO_BUFFER_LENGTH);
1188 }
1189 
1190 static int cmd_start(struct opal_dev *dev, const u8 *uid, const u8 *method)
1191 {
1192 	int err = 0;
1193 
1194 	clear_opal_cmd(dev);
1195 	set_comid(dev, dev->comid);
1196 
1197 	add_token_u8(&err, dev, OPAL_CALL);
1198 	add_token_bytestring(&err, dev, uid, OPAL_UID_LENGTH);
1199 	add_token_bytestring(&err, dev, method, OPAL_METHOD_LENGTH);
1200 
1201 	/*
1202 	 * Every method call is followed by its parameters enclosed within
1203 	 * OPAL_STARTLIST and OPAL_ENDLIST tokens. We automatically open the
1204 	 * parameter list here and close it later in cmd_finalize.
1205 	 */
1206 	add_token_u8(&err, dev, OPAL_STARTLIST);
1207 
1208 	return err;
1209 }
1210 
1211 static int start_opal_session_cont(struct opal_dev *dev)
1212 {
1213 	u32 hsn, tsn;
1214 	int error = 0;
1215 
1216 	error = parse_and_check_status(dev);
1217 	if (error)
1218 		return error;
1219 
1220 	hsn = response_get_u64(&dev->parsed, 4);
1221 	tsn = response_get_u64(&dev->parsed, 5);
1222 
1223 	if (hsn != GENERIC_HOST_SESSION_NUM || tsn < FIRST_TPER_SESSION_NUM) {
1224 		pr_debug("Couldn't authenticate session\n");
1225 		return -EPERM;
1226 	}
1227 
1228 	dev->hsn = hsn;
1229 	dev->tsn = tsn;
1230 
1231 	return 0;
1232 }
1233 
1234 static void add_suspend_info(struct opal_dev *dev,
1235 			     struct opal_suspend_data *sus)
1236 {
1237 	struct opal_suspend_data *iter;
1238 
1239 	list_for_each_entry(iter, &dev->unlk_lst, node) {
1240 		if (iter->lr == sus->lr) {
1241 			list_del(&iter->node);
1242 			kfree(iter);
1243 			break;
1244 		}
1245 	}
1246 	list_add_tail(&sus->node, &dev->unlk_lst);
1247 }
1248 
1249 static int end_session_cont(struct opal_dev *dev)
1250 {
1251 	dev->hsn = 0;
1252 	dev->tsn = 0;
1253 
1254 	return parse_and_check_status(dev);
1255 }
1256 
1257 static int finalize_and_send(struct opal_dev *dev, cont_fn cont)
1258 {
1259 	int ret;
1260 
1261 	ret = cmd_finalize(dev, dev->hsn, dev->tsn);
1262 	if (ret) {
1263 		pr_debug("Error finalizing command buffer: %d\n", ret);
1264 		return ret;
1265 	}
1266 
1267 	print_buffer(dev->cmd, dev->pos);
1268 
1269 	return opal_send_recv(dev, cont);
1270 }
1271 
1272 static int generic_get_columns(struct opal_dev *dev, const u8 *table,
1273 			       u64 start_column, u64 end_column)
1274 {
1275 	int err;
1276 
1277 	err = cmd_start(dev, table, opalmethod[OPAL_GET]);
1278 
1279 	add_token_u8(&err, dev, OPAL_STARTLIST);
1280 
1281 	add_token_u8(&err, dev, OPAL_STARTNAME);
1282 	add_token_u8(&err, dev, OPAL_STARTCOLUMN);
1283 	add_token_u64(&err, dev, start_column);
1284 	add_token_u8(&err, dev, OPAL_ENDNAME);
1285 
1286 	add_token_u8(&err, dev, OPAL_STARTNAME);
1287 	add_token_u8(&err, dev, OPAL_ENDCOLUMN);
1288 	add_token_u64(&err, dev, end_column);
1289 	add_token_u8(&err, dev, OPAL_ENDNAME);
1290 
1291 	add_token_u8(&err, dev, OPAL_ENDLIST);
1292 
1293 	if (err)
1294 		return err;
1295 
1296 	return finalize_and_send(dev, parse_and_check_status);
1297 }
1298 
1299 /*
1300  * request @column from table @table on device @dev. On success, the column
1301  * data will be available in dev->resp->tok[4]
1302  */
1303 static int generic_get_column(struct opal_dev *dev, const u8 *table,
1304 			      u64 column)
1305 {
1306 	return generic_get_columns(dev, table, column, column);
1307 }
1308 
1309 /*
1310  * see TCG SAS 5.3.2.3 for a description of the available columns
1311  *
1312  * the result is provided in dev->resp->tok[4]
1313  */
1314 static int generic_get_table_info(struct opal_dev *dev, const u8 *table_uid,
1315 				  u64 column)
1316 {
1317 	u8 uid[OPAL_UID_LENGTH];
1318 	const unsigned int half = OPAL_UID_LENGTH_HALF;
1319 
1320 	/* sed-opal UIDs can be split in two halves:
1321 	 *  first:  actual table index
1322 	 *  second: relative index in the table
1323 	 * so we have to get the first half of the OPAL_TABLE_TABLE and use the
1324 	 * first part of the target table as relative index into that table
1325 	 */
1326 	memcpy(uid, opaluid[OPAL_TABLE_TABLE], half);
1327 	memcpy(uid + half, table_uid, half);
1328 
1329 	return generic_get_column(dev, uid, column);
1330 }
1331 
1332 static int gen_key(struct opal_dev *dev, void *data)
1333 {
1334 	u8 uid[OPAL_UID_LENGTH];
1335 	int err;
1336 
1337 	memcpy(uid, dev->prev_data, min(sizeof(uid), dev->prev_d_len));
1338 	kfree(dev->prev_data);
1339 	dev->prev_data = NULL;
1340 
1341 	err = cmd_start(dev, uid, opalmethod[OPAL_GENKEY]);
1342 
1343 	if (err) {
1344 		pr_debug("Error building gen key command\n");
1345 		return err;
1346 
1347 	}
1348 
1349 	return finalize_and_send(dev, parse_and_check_status);
1350 }
1351 
1352 static int get_active_key_cont(struct opal_dev *dev)
1353 {
1354 	const char *activekey;
1355 	size_t keylen;
1356 	int error = 0;
1357 
1358 	error = parse_and_check_status(dev);
1359 	if (error)
1360 		return error;
1361 
1362 	keylen = response_get_string(&dev->parsed, 4, &activekey);
1363 	if (!activekey) {
1364 		pr_debug("%s: Couldn't extract the Activekey from the response\n",
1365 			 __func__);
1366 		return OPAL_INVAL_PARAM;
1367 	}
1368 
1369 	dev->prev_data = kmemdup(activekey, keylen, GFP_KERNEL);
1370 
1371 	if (!dev->prev_data)
1372 		return -ENOMEM;
1373 
1374 	dev->prev_d_len = keylen;
1375 
1376 	return 0;
1377 }
1378 
1379 static int get_active_key(struct opal_dev *dev, void *data)
1380 {
1381 	u8 uid[OPAL_UID_LENGTH];
1382 	int err;
1383 	u8 *lr = data;
1384 
1385 	err = build_locking_range(uid, sizeof(uid), *lr);
1386 	if (err)
1387 		return err;
1388 
1389 	err = generic_get_column(dev, uid, OPAL_ACTIVEKEY);
1390 	if (err)
1391 		return err;
1392 
1393 	return get_active_key_cont(dev);
1394 }
1395 
1396 static int generic_table_write_data(struct opal_dev *dev, const u64 data,
1397 				    u64 offset, u64 size, const u8 *uid)
1398 {
1399 	const u8 __user *src = (u8 __user *)(uintptr_t)data;
1400 	u8 *dst;
1401 	u64 len;
1402 	size_t off = 0;
1403 	int err;
1404 
1405 	/* do we fit in the available space? */
1406 	err = generic_get_table_info(dev, uid, OPAL_TABLE_ROWS);
1407 	if (err) {
1408 		pr_debug("Couldn't get the table size\n");
1409 		return err;
1410 	}
1411 
1412 	len = response_get_u64(&dev->parsed, 4);
1413 	if (size > len || offset > len - size) {
1414 		pr_debug("Does not fit in the table (%llu vs. %llu)\n",
1415 			  offset + size, len);
1416 		return -ENOSPC;
1417 	}
1418 
1419 	/* do the actual transmission(s) */
1420 	while (off < size) {
1421 		err = cmd_start(dev, uid, opalmethod[OPAL_SET]);
1422 		add_token_u8(&err, dev, OPAL_STARTNAME);
1423 		add_token_u8(&err, dev, OPAL_WHERE);
1424 		add_token_u64(&err, dev, offset + off);
1425 		add_token_u8(&err, dev, OPAL_ENDNAME);
1426 
1427 		add_token_u8(&err, dev, OPAL_STARTNAME);
1428 		add_token_u8(&err, dev, OPAL_VALUES);
1429 
1430 		/*
1431 		 * The bytestring header is either 1 or 2 bytes, so assume 2.
1432 		 * There also needs to be enough space to accommodate the
1433 		 * trailing OPAL_ENDNAME (1 byte) and tokens added by
1434 		 * cmd_finalize.
1435 		 */
1436 		len = min(remaining_size(dev) - (2+1+CMD_FINALIZE_BYTES_NEEDED),
1437 			  (size_t)(size - off));
1438 		pr_debug("Write bytes %zu+%llu/%llu\n", off, len, size);
1439 
1440 		dst = add_bytestring_header(&err, dev, len);
1441 		if (!dst)
1442 			break;
1443 
1444 		if (copy_from_user(dst, src + off, len)) {
1445 			err = -EFAULT;
1446 			break;
1447 		}
1448 
1449 		dev->pos += len;
1450 
1451 		add_token_u8(&err, dev, OPAL_ENDNAME);
1452 		if (err)
1453 			break;
1454 
1455 		err = finalize_and_send(dev, parse_and_check_status);
1456 		if (err)
1457 			break;
1458 
1459 		off += len;
1460 	}
1461 
1462 	return err;
1463 }
1464 
1465 static int generic_lr_enable_disable(struct opal_dev *dev,
1466 				     u8 *uid, bool rle, bool wle,
1467 				     bool rl, bool wl)
1468 {
1469 	int err;
1470 
1471 	err = cmd_start(dev, uid, opalmethod[OPAL_SET]);
1472 
1473 	add_token_u8(&err, dev, OPAL_STARTNAME);
1474 	add_token_u8(&err, dev, OPAL_VALUES);
1475 	add_token_u8(&err, dev, OPAL_STARTLIST);
1476 
1477 	add_token_u8(&err, dev, OPAL_STARTNAME);
1478 	add_token_u8(&err, dev, OPAL_READLOCKENABLED);
1479 	add_token_u8(&err, dev, rle);
1480 	add_token_u8(&err, dev, OPAL_ENDNAME);
1481 
1482 	add_token_u8(&err, dev, OPAL_STARTNAME);
1483 	add_token_u8(&err, dev, OPAL_WRITELOCKENABLED);
1484 	add_token_u8(&err, dev, wle);
1485 	add_token_u8(&err, dev, OPAL_ENDNAME);
1486 
1487 	add_token_u8(&err, dev, OPAL_STARTNAME);
1488 	add_token_u8(&err, dev, OPAL_READLOCKED);
1489 	add_token_u8(&err, dev, rl);
1490 	add_token_u8(&err, dev, OPAL_ENDNAME);
1491 
1492 	add_token_u8(&err, dev, OPAL_STARTNAME);
1493 	add_token_u8(&err, dev, OPAL_WRITELOCKED);
1494 	add_token_u8(&err, dev, wl);
1495 	add_token_u8(&err, dev, OPAL_ENDNAME);
1496 
1497 	add_token_u8(&err, dev, OPAL_ENDLIST);
1498 	add_token_u8(&err, dev, OPAL_ENDNAME);
1499 
1500 	return err;
1501 }
1502 
1503 static inline int enable_global_lr(struct opal_dev *dev, u8 *uid,
1504 				   struct opal_user_lr_setup *setup)
1505 {
1506 	int err;
1507 
1508 	err = generic_lr_enable_disable(dev, uid, !!setup->RLE, !!setup->WLE,
1509 					0, 0);
1510 	if (err)
1511 		pr_debug("Failed to create enable global lr command\n");
1512 
1513 	return err;
1514 }
1515 
1516 static int setup_locking_range(struct opal_dev *dev, void *data)
1517 {
1518 	u8 uid[OPAL_UID_LENGTH];
1519 	struct opal_user_lr_setup *setup = data;
1520 	u8 lr;
1521 	int err;
1522 
1523 	lr = setup->session.opal_key.lr;
1524 	err = build_locking_range(uid, sizeof(uid), lr);
1525 	if (err)
1526 		return err;
1527 
1528 	if (lr == 0)
1529 		err = enable_global_lr(dev, uid, setup);
1530 	else {
1531 		err = cmd_start(dev, uid, opalmethod[OPAL_SET]);
1532 
1533 		add_token_u8(&err, dev, OPAL_STARTNAME);
1534 		add_token_u8(&err, dev, OPAL_VALUES);
1535 		add_token_u8(&err, dev, OPAL_STARTLIST);
1536 
1537 		add_token_u8(&err, dev, OPAL_STARTNAME);
1538 		add_token_u8(&err, dev, OPAL_RANGESTART);
1539 		add_token_u64(&err, dev, setup->range_start);
1540 		add_token_u8(&err, dev, OPAL_ENDNAME);
1541 
1542 		add_token_u8(&err, dev, OPAL_STARTNAME);
1543 		add_token_u8(&err, dev, OPAL_RANGELENGTH);
1544 		add_token_u64(&err, dev, setup->range_length);
1545 		add_token_u8(&err, dev, OPAL_ENDNAME);
1546 
1547 		add_token_u8(&err, dev, OPAL_STARTNAME);
1548 		add_token_u8(&err, dev, OPAL_READLOCKENABLED);
1549 		add_token_u64(&err, dev, !!setup->RLE);
1550 		add_token_u8(&err, dev, OPAL_ENDNAME);
1551 
1552 		add_token_u8(&err, dev, OPAL_STARTNAME);
1553 		add_token_u8(&err, dev, OPAL_WRITELOCKENABLED);
1554 		add_token_u64(&err, dev, !!setup->WLE);
1555 		add_token_u8(&err, dev, OPAL_ENDNAME);
1556 
1557 		add_token_u8(&err, dev, OPAL_ENDLIST);
1558 		add_token_u8(&err, dev, OPAL_ENDNAME);
1559 	}
1560 	if (err) {
1561 		pr_debug("Error building Setup Locking range command.\n");
1562 		return err;
1563 	}
1564 
1565 	return finalize_and_send(dev, parse_and_check_status);
1566 }
1567 
1568 static int response_get_column(const struct parsed_resp *resp,
1569 			       int *iter,
1570 			       u8 column,
1571 			       u64 *value)
1572 {
1573 	const struct opal_resp_tok *tok;
1574 	int n = *iter;
1575 	u64 val;
1576 
1577 	tok = response_get_token(resp, n);
1578 	if (IS_ERR(tok))
1579 		return PTR_ERR(tok);
1580 
1581 	if (!response_token_matches(tok, OPAL_STARTNAME)) {
1582 		pr_debug("Unexpected response token type %d.\n", n);
1583 		return OPAL_INVAL_PARAM;
1584 	}
1585 	n++;
1586 
1587 	if (response_get_u64(resp, n) != column) {
1588 		pr_debug("Token %d does not match expected column %u.\n",
1589 			 n, column);
1590 		return OPAL_INVAL_PARAM;
1591 	}
1592 	n++;
1593 
1594 	val = response_get_u64(resp, n);
1595 	n++;
1596 
1597 	tok = response_get_token(resp, n);
1598 	if (IS_ERR(tok))
1599 		return PTR_ERR(tok);
1600 
1601 	if (!response_token_matches(tok, OPAL_ENDNAME)) {
1602 		pr_debug("Unexpected response token type %d.\n", n);
1603 		return OPAL_INVAL_PARAM;
1604 	}
1605 	n++;
1606 
1607 	*value = val;
1608 	*iter = n;
1609 
1610 	return 0;
1611 }
1612 
1613 static int locking_range_status(struct opal_dev *dev, void *data)
1614 {
1615 	u8 lr_buffer[OPAL_UID_LENGTH];
1616 	u64 resp;
1617 	bool rlocked, wlocked;
1618 	int err, tok_n = 2;
1619 	struct opal_lr_status *lrst = data;
1620 
1621 	err = build_locking_range(lr_buffer, sizeof(lr_buffer),
1622 				  lrst->session.opal_key.lr);
1623 	if (err)
1624 		return err;
1625 
1626 	err = generic_get_columns(dev, lr_buffer, OPAL_RANGESTART,
1627 				  OPAL_WRITELOCKED);
1628 	if (err) {
1629 		pr_debug("Couldn't get lr %u table columns %d to %d.\n",
1630 			 lrst->session.opal_key.lr, OPAL_RANGESTART,
1631 			 OPAL_WRITELOCKED);
1632 		return err;
1633 	}
1634 
1635 	/* range start */
1636 	err = response_get_column(&dev->parsed, &tok_n, OPAL_RANGESTART,
1637 				  &lrst->range_start);
1638 	if (err)
1639 		return err;
1640 
1641 	/* range length */
1642 	err = response_get_column(&dev->parsed, &tok_n, OPAL_RANGELENGTH,
1643 				  &lrst->range_length);
1644 	if (err)
1645 		return err;
1646 
1647 	/* RLE */
1648 	err = response_get_column(&dev->parsed, &tok_n, OPAL_READLOCKENABLED,
1649 				  &resp);
1650 	if (err)
1651 		return err;
1652 
1653 	lrst->RLE = !!resp;
1654 
1655 	/* WLE */
1656 	err = response_get_column(&dev->parsed, &tok_n, OPAL_WRITELOCKENABLED,
1657 				  &resp);
1658 	if (err)
1659 		return err;
1660 
1661 	lrst->WLE = !!resp;
1662 
1663 	/* read locked */
1664 	err = response_get_column(&dev->parsed, &tok_n, OPAL_READLOCKED, &resp);
1665 	if (err)
1666 		return err;
1667 
1668 	rlocked = !!resp;
1669 
1670 	/* write locked */
1671 	err = response_get_column(&dev->parsed, &tok_n, OPAL_WRITELOCKED, &resp);
1672 	if (err)
1673 		return err;
1674 
1675 	wlocked = !!resp;
1676 
1677 	/* opal_lock_state can not map 'read locked' only state. */
1678 	lrst->l_state = OPAL_RW;
1679 	if (rlocked && wlocked)
1680 		lrst->l_state = OPAL_LK;
1681 	else if (wlocked)
1682 		lrst->l_state = OPAL_RO;
1683 	else if (rlocked) {
1684 		pr_debug("Can not report read locked only state.\n");
1685 		return -EINVAL;
1686 	}
1687 
1688 	return 0;
1689 }
1690 
1691 static int start_generic_opal_session(struct opal_dev *dev,
1692 				      enum opal_uid auth,
1693 				      enum opal_uid sp_type,
1694 				      const char *key,
1695 				      u8 key_len)
1696 {
1697 	u32 hsn;
1698 	int err;
1699 
1700 	if (key == NULL && auth != OPAL_ANYBODY_UID)
1701 		return OPAL_INVAL_PARAM;
1702 
1703 	hsn = GENERIC_HOST_SESSION_NUM;
1704 	err = cmd_start(dev, opaluid[OPAL_SMUID_UID],
1705 			opalmethod[OPAL_STARTSESSION]);
1706 
1707 	add_token_u64(&err, dev, hsn);
1708 	add_token_bytestring(&err, dev, opaluid[sp_type], OPAL_UID_LENGTH);
1709 	add_token_u8(&err, dev, 1);
1710 
1711 	switch (auth) {
1712 	case OPAL_ANYBODY_UID:
1713 		break;
1714 	case OPAL_ADMIN1_UID:
1715 	case OPAL_SID_UID:
1716 	case OPAL_PSID_UID:
1717 		add_token_u8(&err, dev, OPAL_STARTNAME);
1718 		add_token_u8(&err, dev, 0); /* HostChallenge */
1719 		add_token_bytestring(&err, dev, key, key_len);
1720 		add_token_u8(&err, dev, OPAL_ENDNAME);
1721 		add_token_u8(&err, dev, OPAL_STARTNAME);
1722 		add_token_u8(&err, dev, 3); /* HostSignAuth */
1723 		add_token_bytestring(&err, dev, opaluid[auth],
1724 				     OPAL_UID_LENGTH);
1725 		add_token_u8(&err, dev, OPAL_ENDNAME);
1726 		break;
1727 	default:
1728 		pr_debug("Cannot start Admin SP session with auth %d\n", auth);
1729 		return OPAL_INVAL_PARAM;
1730 	}
1731 
1732 	if (err) {
1733 		pr_debug("Error building start adminsp session command.\n");
1734 		return err;
1735 	}
1736 
1737 	return finalize_and_send(dev, start_opal_session_cont);
1738 }
1739 
1740 static int start_anybodyASP_opal_session(struct opal_dev *dev, void *data)
1741 {
1742 	return start_generic_opal_session(dev, OPAL_ANYBODY_UID,
1743 					  OPAL_ADMINSP_UID, NULL, 0);
1744 }
1745 
1746 static int start_SIDASP_opal_session(struct opal_dev *dev, void *data)
1747 {
1748 	int ret;
1749 	const u8 *key = dev->prev_data;
1750 
1751 	if (!key) {
1752 		const struct opal_key *okey = data;
1753 
1754 		ret = start_generic_opal_session(dev, OPAL_SID_UID,
1755 						 OPAL_ADMINSP_UID,
1756 						 okey->key,
1757 						 okey->key_len);
1758 	} else {
1759 		ret = start_generic_opal_session(dev, OPAL_SID_UID,
1760 						 OPAL_ADMINSP_UID,
1761 						 key, dev->prev_d_len);
1762 		kfree(key);
1763 		dev->prev_data = NULL;
1764 	}
1765 
1766 	return ret;
1767 }
1768 
1769 static int start_admin1LSP_opal_session(struct opal_dev *dev, void *data)
1770 {
1771 	struct opal_key *key = data;
1772 
1773 	return start_generic_opal_session(dev, OPAL_ADMIN1_UID,
1774 					  OPAL_LOCKINGSP_UID,
1775 					  key->key, key->key_len);
1776 }
1777 
1778 static int start_PSID_opal_session(struct opal_dev *dev, void *data)
1779 {
1780 	const struct opal_key *okey = data;
1781 
1782 	return start_generic_opal_session(dev, OPAL_PSID_UID,
1783 					  OPAL_ADMINSP_UID,
1784 					  okey->key,
1785 					  okey->key_len);
1786 }
1787 
1788 static int start_auth_opal_session(struct opal_dev *dev, void *data)
1789 {
1790 	struct opal_session_info *session = data;
1791 	u8 lk_ul_user[OPAL_UID_LENGTH];
1792 	size_t keylen = session->opal_key.key_len;
1793 	int err = 0;
1794 
1795 	u8 *key = session->opal_key.key;
1796 	u32 hsn = GENERIC_HOST_SESSION_NUM;
1797 
1798 	if (session->sum)
1799 		err = build_locking_user(lk_ul_user, sizeof(lk_ul_user),
1800 					 session->opal_key.lr);
1801 	else if (session->who != OPAL_ADMIN1 && !session->sum)
1802 		err = build_locking_user(lk_ul_user, sizeof(lk_ul_user),
1803 					 session->who - 1);
1804 	else
1805 		memcpy(lk_ul_user, opaluid[OPAL_ADMIN1_UID], OPAL_UID_LENGTH);
1806 
1807 	if (err)
1808 		return err;
1809 
1810 	err = cmd_start(dev, opaluid[OPAL_SMUID_UID],
1811 			opalmethod[OPAL_STARTSESSION]);
1812 
1813 	add_token_u64(&err, dev, hsn);
1814 	add_token_bytestring(&err, dev, opaluid[OPAL_LOCKINGSP_UID],
1815 			     OPAL_UID_LENGTH);
1816 	add_token_u8(&err, dev, 1);
1817 	add_token_u8(&err, dev, OPAL_STARTNAME);
1818 	add_token_u8(&err, dev, 0);
1819 	add_token_bytestring(&err, dev, key, keylen);
1820 	add_token_u8(&err, dev, OPAL_ENDNAME);
1821 	add_token_u8(&err, dev, OPAL_STARTNAME);
1822 	add_token_u8(&err, dev, 3);
1823 	add_token_bytestring(&err, dev, lk_ul_user, OPAL_UID_LENGTH);
1824 	add_token_u8(&err, dev, OPAL_ENDNAME);
1825 
1826 	if (err) {
1827 		pr_debug("Error building STARTSESSION command.\n");
1828 		return err;
1829 	}
1830 
1831 	return finalize_and_send(dev, start_opal_session_cont);
1832 }
1833 
1834 static int revert_tper(struct opal_dev *dev, void *data)
1835 {
1836 	int err;
1837 
1838 	err = cmd_start(dev, opaluid[OPAL_ADMINSP_UID],
1839 			opalmethod[OPAL_REVERT]);
1840 	if (err) {
1841 		pr_debug("Error building REVERT TPER command.\n");
1842 		return err;
1843 	}
1844 
1845 	return finalize_and_send(dev, parse_and_check_status);
1846 }
1847 
1848 static int internal_activate_user(struct opal_dev *dev, void *data)
1849 {
1850 	struct opal_session_info *session = data;
1851 	u8 uid[OPAL_UID_LENGTH];
1852 	int err;
1853 
1854 	memcpy(uid, opaluid[OPAL_USER1_UID], OPAL_UID_LENGTH);
1855 	uid[7] = session->who;
1856 
1857 	err = cmd_start(dev, uid, opalmethod[OPAL_SET]);
1858 	add_token_u8(&err, dev, OPAL_STARTNAME);
1859 	add_token_u8(&err, dev, OPAL_VALUES);
1860 	add_token_u8(&err, dev, OPAL_STARTLIST);
1861 	add_token_u8(&err, dev, OPAL_STARTNAME);
1862 	add_token_u8(&err, dev, 5); /* Enabled */
1863 	add_token_u8(&err, dev, OPAL_TRUE);
1864 	add_token_u8(&err, dev, OPAL_ENDNAME);
1865 	add_token_u8(&err, dev, OPAL_ENDLIST);
1866 	add_token_u8(&err, dev, OPAL_ENDNAME);
1867 
1868 	if (err) {
1869 		pr_debug("Error building Activate UserN command.\n");
1870 		return err;
1871 	}
1872 
1873 	return finalize_and_send(dev, parse_and_check_status);
1874 }
1875 
1876 static int revert_lsp(struct opal_dev *dev, void *data)
1877 {
1878 	struct opal_revert_lsp *rev = data;
1879 	int err;
1880 
1881 	err = cmd_start(dev, opaluid[OPAL_THISSP_UID],
1882 			opalmethod[OPAL_REVERTSP]);
1883 	add_token_u8(&err, dev, OPAL_STARTNAME);
1884 	add_token_u64(&err, dev, OPAL_KEEP_GLOBAL_RANGE_KEY);
1885 	add_token_u8(&err, dev, (rev->options & OPAL_PRESERVE) ?
1886 			OPAL_TRUE : OPAL_FALSE);
1887 	add_token_u8(&err, dev, OPAL_ENDNAME);
1888 	if (err) {
1889 		pr_debug("Error building REVERT SP command.\n");
1890 		return err;
1891 	}
1892 
1893 	return finalize_and_send(dev, parse_and_check_status);
1894 }
1895 
1896 static int erase_locking_range(struct opal_dev *dev, void *data)
1897 {
1898 	struct opal_session_info *session = data;
1899 	u8 uid[OPAL_UID_LENGTH];
1900 	int err;
1901 
1902 	if (build_locking_range(uid, sizeof(uid), session->opal_key.lr) < 0)
1903 		return -ERANGE;
1904 
1905 	err = cmd_start(dev, uid, opalmethod[OPAL_ERASE]);
1906 
1907 	if (err) {
1908 		pr_debug("Error building Erase Locking Range Command.\n");
1909 		return err;
1910 	}
1911 
1912 	return finalize_and_send(dev, parse_and_check_status);
1913 }
1914 
1915 static int set_mbr_done(struct opal_dev *dev, void *data)
1916 {
1917 	u8 *mbr_done_tf = data;
1918 	int err;
1919 
1920 	err = cmd_start(dev, opaluid[OPAL_MBRCONTROL],
1921 			opalmethod[OPAL_SET]);
1922 
1923 	add_token_u8(&err, dev, OPAL_STARTNAME);
1924 	add_token_u8(&err, dev, OPAL_VALUES);
1925 	add_token_u8(&err, dev, OPAL_STARTLIST);
1926 	add_token_u8(&err, dev, OPAL_STARTNAME);
1927 	add_token_u8(&err, dev, OPAL_MBRDONE);
1928 	add_token_u8(&err, dev, *mbr_done_tf); /* Done T or F */
1929 	add_token_u8(&err, dev, OPAL_ENDNAME);
1930 	add_token_u8(&err, dev, OPAL_ENDLIST);
1931 	add_token_u8(&err, dev, OPAL_ENDNAME);
1932 
1933 	if (err) {
1934 		pr_debug("Error Building set MBR Done command\n");
1935 		return err;
1936 	}
1937 
1938 	return finalize_and_send(dev, parse_and_check_status);
1939 }
1940 
1941 static int set_mbr_enable_disable(struct opal_dev *dev, void *data)
1942 {
1943 	u8 *mbr_en_dis = data;
1944 	int err;
1945 
1946 	err = cmd_start(dev, opaluid[OPAL_MBRCONTROL],
1947 			opalmethod[OPAL_SET]);
1948 
1949 	add_token_u8(&err, dev, OPAL_STARTNAME);
1950 	add_token_u8(&err, dev, OPAL_VALUES);
1951 	add_token_u8(&err, dev, OPAL_STARTLIST);
1952 	add_token_u8(&err, dev, OPAL_STARTNAME);
1953 	add_token_u8(&err, dev, OPAL_MBRENABLE);
1954 	add_token_u8(&err, dev, *mbr_en_dis);
1955 	add_token_u8(&err, dev, OPAL_ENDNAME);
1956 	add_token_u8(&err, dev, OPAL_ENDLIST);
1957 	add_token_u8(&err, dev, OPAL_ENDNAME);
1958 
1959 	if (err) {
1960 		pr_debug("Error Building set MBR done command\n");
1961 		return err;
1962 	}
1963 
1964 	return finalize_and_send(dev, parse_and_check_status);
1965 }
1966 
1967 static int write_shadow_mbr(struct opal_dev *dev, void *data)
1968 {
1969 	struct opal_shadow_mbr *shadow = data;
1970 
1971 	return generic_table_write_data(dev, shadow->data, shadow->offset,
1972 					shadow->size, opaluid[OPAL_MBR]);
1973 }
1974 
1975 static int generic_pw_cmd(u8 *key, size_t key_len, u8 *cpin_uid,
1976 			  struct opal_dev *dev)
1977 {
1978 	int err;
1979 
1980 	err = cmd_start(dev, cpin_uid, opalmethod[OPAL_SET]);
1981 
1982 	add_token_u8(&err, dev, OPAL_STARTNAME);
1983 	add_token_u8(&err, dev, OPAL_VALUES);
1984 	add_token_u8(&err, dev, OPAL_STARTLIST);
1985 	add_token_u8(&err, dev, OPAL_STARTNAME);
1986 	add_token_u8(&err, dev, OPAL_PIN);
1987 	add_token_bytestring(&err, dev, key, key_len);
1988 	add_token_u8(&err, dev, OPAL_ENDNAME);
1989 	add_token_u8(&err, dev, OPAL_ENDLIST);
1990 	add_token_u8(&err, dev, OPAL_ENDNAME);
1991 
1992 	return err;
1993 }
1994 
1995 static int set_new_pw(struct opal_dev *dev, void *data)
1996 {
1997 	u8 cpin_uid[OPAL_UID_LENGTH];
1998 	struct opal_session_info *usr = data;
1999 
2000 	memcpy(cpin_uid, opaluid[OPAL_C_PIN_ADMIN1], OPAL_UID_LENGTH);
2001 
2002 	if (usr->who != OPAL_ADMIN1) {
2003 		cpin_uid[5] = 0x03;
2004 		if (usr->sum)
2005 			cpin_uid[7] = usr->opal_key.lr + 1;
2006 		else
2007 			cpin_uid[7] = usr->who;
2008 	}
2009 
2010 	if (generic_pw_cmd(usr->opal_key.key, usr->opal_key.key_len,
2011 			   cpin_uid, dev)) {
2012 		pr_debug("Error building set password command.\n");
2013 		return -ERANGE;
2014 	}
2015 
2016 	return finalize_and_send(dev, parse_and_check_status);
2017 }
2018 
2019 static int set_sid_cpin_pin(struct opal_dev *dev, void *data)
2020 {
2021 	u8 cpin_uid[OPAL_UID_LENGTH];
2022 	struct opal_key *key = data;
2023 
2024 	memcpy(cpin_uid, opaluid[OPAL_C_PIN_SID], OPAL_UID_LENGTH);
2025 
2026 	if (generic_pw_cmd(key->key, key->key_len, cpin_uid, dev)) {
2027 		pr_debug("Error building Set SID cpin\n");
2028 		return -ERANGE;
2029 	}
2030 	return finalize_and_send(dev, parse_and_check_status);
2031 }
2032 
2033 static void add_authority_object_ref(int *err,
2034 				     struct opal_dev *dev,
2035 				     const u8 *uid,
2036 				     size_t uid_len)
2037 {
2038 	add_token_u8(err, dev, OPAL_STARTNAME);
2039 	add_token_bytestring(err, dev,
2040 			     opaluid[OPAL_HALF_UID_AUTHORITY_OBJ_REF],
2041 			     OPAL_UID_LENGTH/2);
2042 	add_token_bytestring(err, dev, uid, uid_len);
2043 	add_token_u8(err, dev, OPAL_ENDNAME);
2044 }
2045 
2046 static void add_boolean_object_ref(int *err,
2047 				   struct opal_dev *dev,
2048 				   u8 boolean_op)
2049 {
2050 	add_token_u8(err, dev, OPAL_STARTNAME);
2051 	add_token_bytestring(err, dev, opaluid[OPAL_HALF_UID_BOOLEAN_ACE],
2052 			     OPAL_UID_LENGTH/2);
2053 	add_token_u8(err, dev, boolean_op);
2054 	add_token_u8(err, dev, OPAL_ENDNAME);
2055 }
2056 
2057 static int set_lr_boolean_ace(struct opal_dev *dev,
2058 			      unsigned int opal_uid,
2059 			      u8 lr,
2060 			      const u8 *users,
2061 			      size_t users_len)
2062 {
2063 	u8 lr_buffer[OPAL_UID_LENGTH];
2064 	u8 user_uid[OPAL_UID_LENGTH];
2065 	u8 u;
2066 	int err;
2067 
2068 	memcpy(lr_buffer, opaluid[opal_uid], OPAL_UID_LENGTH);
2069 	lr_buffer[7] = lr;
2070 
2071 	err = cmd_start(dev, lr_buffer, opalmethod[OPAL_SET]);
2072 
2073 	add_token_u8(&err, dev, OPAL_STARTNAME);
2074 	add_token_u8(&err, dev, OPAL_VALUES);
2075 
2076 	add_token_u8(&err, dev, OPAL_STARTLIST);
2077 	add_token_u8(&err, dev, OPAL_STARTNAME);
2078 	add_token_u8(&err, dev, 3);
2079 
2080 	add_token_u8(&err, dev, OPAL_STARTLIST);
2081 
2082 	for (u = 0; u < users_len; u++) {
2083 		if (users[u] == OPAL_ADMIN1)
2084 			memcpy(user_uid, opaluid[OPAL_ADMIN1_UID],
2085 			       OPAL_UID_LENGTH);
2086 		else {
2087 			memcpy(user_uid, opaluid[OPAL_USER1_UID],
2088 			       OPAL_UID_LENGTH);
2089 			user_uid[7] = users[u];
2090 		}
2091 
2092 		add_authority_object_ref(&err, dev, user_uid, sizeof(user_uid));
2093 
2094 		/*
2095 		 * Add boolean operator in postfix only with
2096 		 * two or more authorities being added in ACE
2097 		 * expresion.
2098 		 * */
2099 		if (u > 0)
2100 			add_boolean_object_ref(&err, dev, OPAL_BOOLEAN_OR);
2101 	}
2102 
2103 	add_token_u8(&err, dev, OPAL_ENDLIST);
2104 	add_token_u8(&err, dev, OPAL_ENDNAME);
2105 	add_token_u8(&err, dev, OPAL_ENDLIST);
2106 	add_token_u8(&err, dev, OPAL_ENDNAME);
2107 
2108 	return err;
2109 }
2110 
2111 static int add_user_to_lr(struct opal_dev *dev, void *data)
2112 {
2113 	int err;
2114 	struct opal_lock_unlock *lkul = data;
2115 	const u8 users[] = {
2116 		lkul->session.who
2117 	};
2118 
2119 	err = set_lr_boolean_ace(dev,
2120 				 lkul->l_state == OPAL_RW ?
2121 					OPAL_LOCKINGRANGE_ACE_WRLOCKED :
2122 					OPAL_LOCKINGRANGE_ACE_RDLOCKED,
2123 				 lkul->session.opal_key.lr, users,
2124 				 ARRAY_SIZE(users));
2125 	if (err) {
2126 		pr_debug("Error building add user to locking range command.\n");
2127 		return err;
2128 	}
2129 
2130 	return finalize_and_send(dev, parse_and_check_status);
2131 }
2132 
2133 static int add_user_to_lr_ace(struct opal_dev *dev, void *data)
2134 {
2135 	int err;
2136 	struct opal_lock_unlock *lkul = data;
2137 	const u8 users[] = {
2138 		OPAL_ADMIN1,
2139 		lkul->session.who
2140 	};
2141 
2142 	err = set_lr_boolean_ace(dev, OPAL_LOCKINGRANGE_ACE_START_TO_KEY,
2143 				 lkul->session.opal_key.lr, users,
2144 				 ARRAY_SIZE(users));
2145 
2146 	if (err) {
2147 		pr_debug("Error building add user to locking ranges ACEs.\n");
2148 		return err;
2149 	}
2150 
2151 	return finalize_and_send(dev, parse_and_check_status);
2152 }
2153 
2154 static int lock_unlock_locking_range(struct opal_dev *dev, void *data)
2155 {
2156 	u8 lr_buffer[OPAL_UID_LENGTH];
2157 	struct opal_lock_unlock *lkul = data;
2158 	u8 read_locked = 1, write_locked = 1;
2159 	int err = 0;
2160 
2161 	if (build_locking_range(lr_buffer, sizeof(lr_buffer),
2162 				lkul->session.opal_key.lr) < 0)
2163 		return -ERANGE;
2164 
2165 	switch (lkul->l_state) {
2166 	case OPAL_RO:
2167 		read_locked = 0;
2168 		write_locked = 1;
2169 		break;
2170 	case OPAL_RW:
2171 		read_locked = 0;
2172 		write_locked = 0;
2173 		break;
2174 	case OPAL_LK:
2175 		/* vars are initialized to locked */
2176 		break;
2177 	default:
2178 		pr_debug("Tried to set an invalid locking state... returning to uland\n");
2179 		return OPAL_INVAL_PARAM;
2180 	}
2181 
2182 	err = cmd_start(dev, lr_buffer, opalmethod[OPAL_SET]);
2183 
2184 	add_token_u8(&err, dev, OPAL_STARTNAME);
2185 	add_token_u8(&err, dev, OPAL_VALUES);
2186 	add_token_u8(&err, dev, OPAL_STARTLIST);
2187 
2188 	add_token_u8(&err, dev, OPAL_STARTNAME);
2189 	add_token_u8(&err, dev, OPAL_READLOCKED);
2190 	add_token_u8(&err, dev, read_locked);
2191 	add_token_u8(&err, dev, OPAL_ENDNAME);
2192 
2193 	add_token_u8(&err, dev, OPAL_STARTNAME);
2194 	add_token_u8(&err, dev, OPAL_WRITELOCKED);
2195 	add_token_u8(&err, dev, write_locked);
2196 	add_token_u8(&err, dev, OPAL_ENDNAME);
2197 
2198 	add_token_u8(&err, dev, OPAL_ENDLIST);
2199 	add_token_u8(&err, dev, OPAL_ENDNAME);
2200 
2201 	if (err) {
2202 		pr_debug("Error building SET command.\n");
2203 		return err;
2204 	}
2205 
2206 	return finalize_and_send(dev, parse_and_check_status);
2207 }
2208 
2209 
2210 static int lock_unlock_locking_range_sum(struct opal_dev *dev, void *data)
2211 {
2212 	u8 lr_buffer[OPAL_UID_LENGTH];
2213 	u8 read_locked = 1, write_locked = 1;
2214 	struct opal_lock_unlock *lkul = data;
2215 	int ret;
2216 
2217 	clear_opal_cmd(dev);
2218 	set_comid(dev, dev->comid);
2219 
2220 	if (build_locking_range(lr_buffer, sizeof(lr_buffer),
2221 				lkul->session.opal_key.lr) < 0)
2222 		return -ERANGE;
2223 
2224 	switch (lkul->l_state) {
2225 	case OPAL_RO:
2226 		read_locked = 0;
2227 		write_locked = 1;
2228 		break;
2229 	case OPAL_RW:
2230 		read_locked = 0;
2231 		write_locked = 0;
2232 		break;
2233 	case OPAL_LK:
2234 		/* vars are initialized to locked */
2235 		break;
2236 	default:
2237 		pr_debug("Tried to set an invalid locking state.\n");
2238 		return OPAL_INVAL_PARAM;
2239 	}
2240 	ret = generic_lr_enable_disable(dev, lr_buffer, 1, 1,
2241 					read_locked, write_locked);
2242 
2243 	if (ret < 0) {
2244 		pr_debug("Error building SET command.\n");
2245 		return ret;
2246 	}
2247 
2248 	return finalize_and_send(dev, parse_and_check_status);
2249 }
2250 
2251 static int activate_lsp(struct opal_dev *dev, void *data)
2252 {
2253 	struct opal_lr_act *opal_act = data;
2254 	u8 user_lr[OPAL_UID_LENGTH];
2255 	int err, i;
2256 
2257 	err = cmd_start(dev, opaluid[OPAL_LOCKINGSP_UID],
2258 			opalmethod[OPAL_ACTIVATE]);
2259 
2260 	if (opal_act->sum) {
2261 		err = build_locking_range(user_lr, sizeof(user_lr),
2262 					  opal_act->lr[0]);
2263 		if (err)
2264 			return err;
2265 
2266 		add_token_u8(&err, dev, OPAL_STARTNAME);
2267 		add_token_u64(&err, dev, OPAL_SUM_SET_LIST);
2268 
2269 		add_token_u8(&err, dev, OPAL_STARTLIST);
2270 		add_token_bytestring(&err, dev, user_lr, OPAL_UID_LENGTH);
2271 		for (i = 1; i < opal_act->num_lrs; i++) {
2272 			user_lr[7] = opal_act->lr[i];
2273 			add_token_bytestring(&err, dev, user_lr, OPAL_UID_LENGTH);
2274 		}
2275 		add_token_u8(&err, dev, OPAL_ENDLIST);
2276 		add_token_u8(&err, dev, OPAL_ENDNAME);
2277 	}
2278 
2279 	if (err) {
2280 		pr_debug("Error building Activate LockingSP command.\n");
2281 		return err;
2282 	}
2283 
2284 	return finalize_and_send(dev, parse_and_check_status);
2285 }
2286 
2287 /* Determine if we're in the Manufactured Inactive or Active state */
2288 static int get_lsp_lifecycle(struct opal_dev *dev, void *data)
2289 {
2290 	u8 lc_status;
2291 	int err;
2292 
2293 	err = generic_get_column(dev, opaluid[OPAL_LOCKINGSP_UID],
2294 				 OPAL_LIFECYCLE);
2295 	if (err)
2296 		return err;
2297 
2298 	lc_status = response_get_u64(&dev->parsed, 4);
2299 	/* 0x08 is Manufactured Inactive */
2300 	/* 0x09 is Manufactured */
2301 	if (lc_status != OPAL_MANUFACTURED_INACTIVE) {
2302 		pr_debug("Couldn't determine the status of the Lifecycle state\n");
2303 		return -ENODEV;
2304 	}
2305 
2306 	return 0;
2307 }
2308 
2309 static int get_msid_cpin_pin(struct opal_dev *dev, void *data)
2310 {
2311 	const char *msid_pin;
2312 	size_t strlen;
2313 	int err;
2314 
2315 	err = generic_get_column(dev, opaluid[OPAL_C_PIN_MSID], OPAL_PIN);
2316 	if (err)
2317 		return err;
2318 
2319 	strlen = response_get_string(&dev->parsed, 4, &msid_pin);
2320 	if (!msid_pin) {
2321 		pr_debug("Couldn't extract MSID_CPIN from response\n");
2322 		return OPAL_INVAL_PARAM;
2323 	}
2324 
2325 	dev->prev_data = kmemdup(msid_pin, strlen, GFP_KERNEL);
2326 	if (!dev->prev_data)
2327 		return -ENOMEM;
2328 
2329 	dev->prev_d_len = strlen;
2330 
2331 	return 0;
2332 }
2333 
2334 static int write_table_data(struct opal_dev *dev, void *data)
2335 {
2336 	struct opal_read_write_table *write_tbl = data;
2337 
2338 	return generic_table_write_data(dev, write_tbl->data, write_tbl->offset,
2339 					write_tbl->size, write_tbl->table_uid);
2340 }
2341 
2342 static int read_table_data_cont(struct opal_dev *dev)
2343 {
2344 	int err;
2345 	const char *data_read;
2346 
2347 	err = parse_and_check_status(dev);
2348 	if (err)
2349 		return err;
2350 
2351 	dev->prev_d_len = response_get_string(&dev->parsed, 1, &data_read);
2352 	dev->prev_data = (void *)data_read;
2353 	if (!dev->prev_data) {
2354 		pr_debug("%s: Couldn't read data from the table.\n", __func__);
2355 		return OPAL_INVAL_PARAM;
2356 	}
2357 
2358 	return 0;
2359 }
2360 
2361 /*
2362  * IO_BUFFER_LENGTH = 2048
2363  * sizeof(header) = 56
2364  * No. of Token Bytes in the Response = 11
2365  * MAX size of data that can be carried in response buffer
2366  * at a time is : 2048 - (56 + 11) = 1981 = 0x7BD.
2367  */
2368 #define OPAL_MAX_READ_TABLE (0x7BD)
2369 
2370 static int read_table_data(struct opal_dev *dev, void *data)
2371 {
2372 	struct opal_read_write_table *read_tbl = data;
2373 	int err;
2374 	size_t off = 0, max_read_size = OPAL_MAX_READ_TABLE;
2375 	u64 table_len, len;
2376 	u64 offset = read_tbl->offset, read_size = read_tbl->size - 1;
2377 	u8 __user *dst;
2378 
2379 	err = generic_get_table_info(dev, read_tbl->table_uid, OPAL_TABLE_ROWS);
2380 	if (err) {
2381 		pr_debug("Couldn't get the table size\n");
2382 		return err;
2383 	}
2384 
2385 	table_len = response_get_u64(&dev->parsed, 4);
2386 
2387 	/* Check if the user is trying to read from the table limits */
2388 	if (read_size > table_len || offset > table_len - read_size) {
2389 		pr_debug("Read size exceeds the Table size limits (%llu vs. %llu)\n",
2390 			  offset + read_size, table_len);
2391 		return -EINVAL;
2392 	}
2393 
2394 	while (off < read_size) {
2395 		err = cmd_start(dev, read_tbl->table_uid, opalmethod[OPAL_GET]);
2396 
2397 		add_token_u8(&err, dev, OPAL_STARTLIST);
2398 		add_token_u8(&err, dev, OPAL_STARTNAME);
2399 		add_token_u8(&err, dev, OPAL_STARTROW);
2400 		add_token_u64(&err, dev, offset + off); /* start row value */
2401 		add_token_u8(&err, dev, OPAL_ENDNAME);
2402 
2403 		add_token_u8(&err, dev, OPAL_STARTNAME);
2404 		add_token_u8(&err, dev, OPAL_ENDROW);
2405 
2406 		len = min(max_read_size, (size_t)(read_size - off));
2407 		add_token_u64(&err, dev, offset + off + len); /* end row value
2408 							       */
2409 		add_token_u8(&err, dev, OPAL_ENDNAME);
2410 		add_token_u8(&err, dev, OPAL_ENDLIST);
2411 
2412 		if (err) {
2413 			pr_debug("Error building read table data command.\n");
2414 			break;
2415 		}
2416 
2417 		err = finalize_and_send(dev, read_table_data_cont);
2418 		if (err)
2419 			break;
2420 
2421 		/* len+1: This includes the NULL terminator at the end*/
2422 		if (dev->prev_d_len > len + 1) {
2423 			err = -EOVERFLOW;
2424 			break;
2425 		}
2426 
2427 		dst = (u8 __user *)(uintptr_t)read_tbl->data;
2428 		if (copy_to_user(dst + off, dev->prev_data, dev->prev_d_len)) {
2429 			pr_debug("Error copying data to userspace\n");
2430 			err = -EFAULT;
2431 			break;
2432 		}
2433 		dev->prev_data = NULL;
2434 
2435 		off += len;
2436 	}
2437 
2438 	return err;
2439 }
2440 
2441 static int end_opal_session(struct opal_dev *dev, void *data)
2442 {
2443 	int err = 0;
2444 
2445 	clear_opal_cmd(dev);
2446 	set_comid(dev, dev->comid);
2447 	add_token_u8(&err, dev, OPAL_ENDOFSESSION);
2448 
2449 	if (err < 0)
2450 		return err;
2451 
2452 	return finalize_and_send(dev, end_session_cont);
2453 }
2454 
2455 static int end_opal_session_error(struct opal_dev *dev)
2456 {
2457 	const struct opal_step error_end_session = {
2458 		end_opal_session,
2459 	};
2460 
2461 	return execute_step(dev, &error_end_session, 0);
2462 }
2463 
2464 static inline void setup_opal_dev(struct opal_dev *dev)
2465 {
2466 	dev->tsn = 0;
2467 	dev->hsn = 0;
2468 	dev->prev_data = NULL;
2469 }
2470 
2471 static int check_opal_support(struct opal_dev *dev)
2472 {
2473 	int ret;
2474 
2475 	mutex_lock(&dev->dev_lock);
2476 	setup_opal_dev(dev);
2477 	ret = opal_discovery0_step(dev);
2478 	if (!ret)
2479 		dev->flags |= OPAL_FL_SUPPORTED;
2480 	mutex_unlock(&dev->dev_lock);
2481 
2482 	return ret;
2483 }
2484 
2485 static void clean_opal_dev(struct opal_dev *dev)
2486 {
2487 
2488 	struct opal_suspend_data *suspend, *next;
2489 
2490 	mutex_lock(&dev->dev_lock);
2491 	list_for_each_entry_safe(suspend, next, &dev->unlk_lst, node) {
2492 		list_del(&suspend->node);
2493 		kfree(suspend);
2494 	}
2495 	mutex_unlock(&dev->dev_lock);
2496 }
2497 
2498 void free_opal_dev(struct opal_dev *dev)
2499 {
2500 	if (!dev)
2501 		return;
2502 
2503 	clean_opal_dev(dev);
2504 	kfree(dev->resp);
2505 	kfree(dev->cmd);
2506 	kfree(dev);
2507 }
2508 EXPORT_SYMBOL(free_opal_dev);
2509 
2510 struct opal_dev *init_opal_dev(void *data, sec_send_recv *send_recv)
2511 {
2512 	struct opal_dev *dev;
2513 
2514 	dev = kmalloc(sizeof(*dev), GFP_KERNEL);
2515 	if (!dev)
2516 		return NULL;
2517 
2518 	/*
2519 	 * Presumably DMA-able buffers must be cache-aligned. Kmalloc makes
2520 	 * sure the allocated buffer is DMA-safe in that regard.
2521 	 */
2522 	dev->cmd = kmalloc(IO_BUFFER_LENGTH, GFP_KERNEL);
2523 	if (!dev->cmd)
2524 		goto err_free_dev;
2525 
2526 	dev->resp = kmalloc(IO_BUFFER_LENGTH, GFP_KERNEL);
2527 	if (!dev->resp)
2528 		goto err_free_cmd;
2529 
2530 	INIT_LIST_HEAD(&dev->unlk_lst);
2531 	mutex_init(&dev->dev_lock);
2532 	dev->flags = 0;
2533 	dev->data = data;
2534 	dev->send_recv = send_recv;
2535 	if (check_opal_support(dev) != 0) {
2536 		pr_debug("Opal is not supported on this device\n");
2537 		goto err_free_resp;
2538 	}
2539 
2540 	return dev;
2541 
2542 err_free_resp:
2543 	kfree(dev->resp);
2544 
2545 err_free_cmd:
2546 	kfree(dev->cmd);
2547 
2548 err_free_dev:
2549 	kfree(dev);
2550 
2551 	return NULL;
2552 }
2553 EXPORT_SYMBOL(init_opal_dev);
2554 
2555 static int opal_secure_erase_locking_range(struct opal_dev *dev,
2556 					   struct opal_session_info *opal_session)
2557 {
2558 	const struct opal_step erase_steps[] = {
2559 		{ start_auth_opal_session, opal_session },
2560 		{ get_active_key, &opal_session->opal_key.lr },
2561 		{ gen_key, },
2562 		{ end_opal_session, }
2563 	};
2564 	int ret;
2565 
2566 	ret = opal_get_key(dev, &opal_session->opal_key);
2567 	if (ret)
2568 		return ret;
2569 	mutex_lock(&dev->dev_lock);
2570 	setup_opal_dev(dev);
2571 	ret = execute_steps(dev, erase_steps, ARRAY_SIZE(erase_steps));
2572 	mutex_unlock(&dev->dev_lock);
2573 
2574 	return ret;
2575 }
2576 
2577 static int opal_get_discv(struct opal_dev *dev, struct opal_discovery *discv)
2578 {
2579 	const struct opal_step discovery0_step = {
2580 		opal_discovery0, discv
2581 	};
2582 	int ret = 0;
2583 
2584 	mutex_lock(&dev->dev_lock);
2585 	setup_opal_dev(dev);
2586 	ret = execute_step(dev, &discovery0_step, 0);
2587 	mutex_unlock(&dev->dev_lock);
2588 	if (ret)
2589 		return ret;
2590 	return discv->size; /* modified to actual length of data */
2591 }
2592 
2593 static int opal_revertlsp(struct opal_dev *dev, struct opal_revert_lsp *rev)
2594 {
2595 	/* controller will terminate session */
2596 	const struct opal_step steps[] = {
2597 		{ start_admin1LSP_opal_session, &rev->key },
2598 		{ revert_lsp, rev }
2599 	};
2600 	int ret;
2601 
2602 	ret = opal_get_key(dev, &rev->key);
2603 	if (ret)
2604 		return ret;
2605 	mutex_lock(&dev->dev_lock);
2606 	setup_opal_dev(dev);
2607 	ret = execute_steps(dev, steps, ARRAY_SIZE(steps));
2608 	mutex_unlock(&dev->dev_lock);
2609 
2610 	return ret;
2611 }
2612 
2613 static int opal_erase_locking_range(struct opal_dev *dev,
2614 				    struct opal_session_info *opal_session)
2615 {
2616 	const struct opal_step erase_steps[] = {
2617 		{ start_auth_opal_session, opal_session },
2618 		{ erase_locking_range, opal_session },
2619 		{ end_opal_session, }
2620 	};
2621 	int ret;
2622 
2623 	ret = opal_get_key(dev, &opal_session->opal_key);
2624 	if (ret)
2625 		return ret;
2626 	mutex_lock(&dev->dev_lock);
2627 	setup_opal_dev(dev);
2628 	ret = execute_steps(dev, erase_steps, ARRAY_SIZE(erase_steps));
2629 	mutex_unlock(&dev->dev_lock);
2630 
2631 	return ret;
2632 }
2633 
2634 static int opal_enable_disable_shadow_mbr(struct opal_dev *dev,
2635 					  struct opal_mbr_data *opal_mbr)
2636 {
2637 	u8 enable_disable = opal_mbr->enable_disable == OPAL_MBR_ENABLE ?
2638 		OPAL_TRUE : OPAL_FALSE;
2639 
2640 	const struct opal_step mbr_steps[] = {
2641 		{ start_admin1LSP_opal_session, &opal_mbr->key },
2642 		{ set_mbr_done, &enable_disable },
2643 		{ end_opal_session, },
2644 		{ start_admin1LSP_opal_session, &opal_mbr->key },
2645 		{ set_mbr_enable_disable, &enable_disable },
2646 		{ end_opal_session, }
2647 	};
2648 	int ret;
2649 
2650 	if (opal_mbr->enable_disable != OPAL_MBR_ENABLE &&
2651 	    opal_mbr->enable_disable != OPAL_MBR_DISABLE)
2652 		return -EINVAL;
2653 
2654 	ret = opal_get_key(dev, &opal_mbr->key);
2655 	if (ret)
2656 		return ret;
2657 	mutex_lock(&dev->dev_lock);
2658 	setup_opal_dev(dev);
2659 	ret = execute_steps(dev, mbr_steps, ARRAY_SIZE(mbr_steps));
2660 	mutex_unlock(&dev->dev_lock);
2661 
2662 	return ret;
2663 }
2664 
2665 static int opal_set_mbr_done(struct opal_dev *dev,
2666 			     struct opal_mbr_done *mbr_done)
2667 {
2668 	u8 mbr_done_tf = mbr_done->done_flag == OPAL_MBR_DONE ?
2669 		OPAL_TRUE : OPAL_FALSE;
2670 
2671 	const struct opal_step mbr_steps[] = {
2672 		{ start_admin1LSP_opal_session, &mbr_done->key },
2673 		{ set_mbr_done, &mbr_done_tf },
2674 		{ end_opal_session, }
2675 	};
2676 	int ret;
2677 
2678 	if (mbr_done->done_flag != OPAL_MBR_DONE &&
2679 	    mbr_done->done_flag != OPAL_MBR_NOT_DONE)
2680 		return -EINVAL;
2681 
2682 	ret = opal_get_key(dev, &mbr_done->key);
2683 	if (ret)
2684 		return ret;
2685 	mutex_lock(&dev->dev_lock);
2686 	setup_opal_dev(dev);
2687 	ret = execute_steps(dev, mbr_steps, ARRAY_SIZE(mbr_steps));
2688 	mutex_unlock(&dev->dev_lock);
2689 
2690 	return ret;
2691 }
2692 
2693 static int opal_write_shadow_mbr(struct opal_dev *dev,
2694 				 struct opal_shadow_mbr *info)
2695 {
2696 	const struct opal_step mbr_steps[] = {
2697 		{ start_admin1LSP_opal_session, &info->key },
2698 		{ write_shadow_mbr, info },
2699 		{ end_opal_session, }
2700 	};
2701 	int ret;
2702 
2703 	if (info->size == 0)
2704 		return 0;
2705 
2706 	ret = opal_get_key(dev, &info->key);
2707 	if (ret)
2708 		return ret;
2709 	mutex_lock(&dev->dev_lock);
2710 	setup_opal_dev(dev);
2711 	ret = execute_steps(dev, mbr_steps, ARRAY_SIZE(mbr_steps));
2712 	mutex_unlock(&dev->dev_lock);
2713 
2714 	return ret;
2715 }
2716 
2717 static int opal_save(struct opal_dev *dev, struct opal_lock_unlock *lk_unlk)
2718 {
2719 	struct opal_suspend_data *suspend;
2720 
2721 	suspend = kzalloc(sizeof(*suspend), GFP_KERNEL);
2722 	if (!suspend)
2723 		return -ENOMEM;
2724 
2725 	suspend->unlk = *lk_unlk;
2726 	suspend->lr = lk_unlk->session.opal_key.lr;
2727 
2728 	mutex_lock(&dev->dev_lock);
2729 	setup_opal_dev(dev);
2730 	add_suspend_info(dev, suspend);
2731 	mutex_unlock(&dev->dev_lock);
2732 
2733 	return 0;
2734 }
2735 
2736 static int opal_add_user_to_lr(struct opal_dev *dev,
2737 			       struct opal_lock_unlock *lk_unlk)
2738 {
2739 	const struct opal_step steps[] = {
2740 		{ start_admin1LSP_opal_session, &lk_unlk->session.opal_key },
2741 		{ add_user_to_lr, lk_unlk },
2742 		{ add_user_to_lr_ace, lk_unlk },
2743 		{ end_opal_session, }
2744 	};
2745 	int ret;
2746 
2747 	if (lk_unlk->l_state != OPAL_RO &&
2748 	    lk_unlk->l_state != OPAL_RW) {
2749 		pr_debug("Locking state was not RO or RW\n");
2750 		return -EINVAL;
2751 	}
2752 
2753 	if (lk_unlk->session.who < OPAL_USER1 ||
2754 	    lk_unlk->session.who > OPAL_USER9) {
2755 		pr_debug("Authority was not within the range of users: %d\n",
2756 			 lk_unlk->session.who);
2757 		return -EINVAL;
2758 	}
2759 
2760 	if (lk_unlk->session.sum) {
2761 		pr_debug("%s not supported in sum. Use setup locking range\n",
2762 			 __func__);
2763 		return -EINVAL;
2764 	}
2765 
2766 	ret = opal_get_key(dev, &lk_unlk->session.opal_key);
2767 	if (ret)
2768 		return ret;
2769 	mutex_lock(&dev->dev_lock);
2770 	setup_opal_dev(dev);
2771 	ret = execute_steps(dev, steps, ARRAY_SIZE(steps));
2772 	mutex_unlock(&dev->dev_lock);
2773 
2774 	return ret;
2775 }
2776 
2777 static int opal_reverttper(struct opal_dev *dev, struct opal_key *opal, bool psid)
2778 {
2779 	/* controller will terminate session */
2780 	const struct opal_step revert_steps[] = {
2781 		{ start_SIDASP_opal_session, opal },
2782 		{ revert_tper, }
2783 	};
2784 	const struct opal_step psid_revert_steps[] = {
2785 		{ start_PSID_opal_session, opal },
2786 		{ revert_tper, }
2787 	};
2788 
2789 	int ret;
2790 
2791 	ret = opal_get_key(dev, opal);
2792 
2793 	if (ret)
2794 		return ret;
2795 	mutex_lock(&dev->dev_lock);
2796 	setup_opal_dev(dev);
2797 	if (psid)
2798 		ret = execute_steps(dev, psid_revert_steps,
2799 				    ARRAY_SIZE(psid_revert_steps));
2800 	else
2801 		ret = execute_steps(dev, revert_steps,
2802 				    ARRAY_SIZE(revert_steps));
2803 	mutex_unlock(&dev->dev_lock);
2804 
2805 	/*
2806 	 * If we successfully reverted lets clean
2807 	 * any saved locking ranges.
2808 	 */
2809 	if (!ret)
2810 		clean_opal_dev(dev);
2811 
2812 	return ret;
2813 }
2814 
2815 static int __opal_lock_unlock(struct opal_dev *dev,
2816 			      struct opal_lock_unlock *lk_unlk)
2817 {
2818 	const struct opal_step unlock_steps[] = {
2819 		{ start_auth_opal_session, &lk_unlk->session },
2820 		{ lock_unlock_locking_range, lk_unlk },
2821 		{ end_opal_session, }
2822 	};
2823 	const struct opal_step unlock_sum_steps[] = {
2824 		{ start_auth_opal_session, &lk_unlk->session },
2825 		{ lock_unlock_locking_range_sum, lk_unlk },
2826 		{ end_opal_session, }
2827 	};
2828 
2829 	if (lk_unlk->session.sum)
2830 		return execute_steps(dev, unlock_sum_steps,
2831 				     ARRAY_SIZE(unlock_sum_steps));
2832 	else
2833 		return execute_steps(dev, unlock_steps,
2834 				     ARRAY_SIZE(unlock_steps));
2835 }
2836 
2837 static int __opal_set_mbr_done(struct opal_dev *dev, struct opal_key *key)
2838 {
2839 	u8 mbr_done_tf = OPAL_TRUE;
2840 	const struct opal_step mbrdone_step[] = {
2841 		{ start_admin1LSP_opal_session, key },
2842 		{ set_mbr_done, &mbr_done_tf },
2843 		{ end_opal_session, }
2844 	};
2845 
2846 	return execute_steps(dev, mbrdone_step, ARRAY_SIZE(mbrdone_step));
2847 }
2848 
2849 static void opal_lock_check_for_saved_key(struct opal_dev *dev,
2850 			    struct opal_lock_unlock *lk_unlk)
2851 {
2852 	struct opal_suspend_data *iter;
2853 
2854 	if (lk_unlk->l_state != OPAL_LK ||
2855 			lk_unlk->session.opal_key.key_len > 0)
2856 		return;
2857 
2858 	/*
2859 	 * Usually when closing a crypto device (eg: dm-crypt with LUKS) the
2860 	 * volume key is not required, as it requires root privileges anyway,
2861 	 * and root can deny access to a disk in many ways regardless.
2862 	 * Requiring the volume key to lock the device is a peculiarity of the
2863 	 * OPAL specification. Given we might already have saved the key if
2864 	 * the user requested it via the 'IOC_OPAL_SAVE' ioctl, we can use
2865 	 * that key to lock the device if no key was provided here, the
2866 	 * locking range matches and the appropriate flag was passed with
2867 	 * 'IOC_OPAL_SAVE'.
2868 	 * This allows integrating OPAL with tools and libraries that are used
2869 	 * to the common behaviour and do not ask for the volume key when
2870 	 * closing a device.
2871 	 */
2872 	setup_opal_dev(dev);
2873 	list_for_each_entry(iter, &dev->unlk_lst, node) {
2874 		if ((iter->unlk.flags & OPAL_SAVE_FOR_LOCK) &&
2875 				iter->lr == lk_unlk->session.opal_key.lr &&
2876 				iter->unlk.session.opal_key.key_len > 0) {
2877 			lk_unlk->session.opal_key.key_len =
2878 				iter->unlk.session.opal_key.key_len;
2879 			memcpy(lk_unlk->session.opal_key.key,
2880 				iter->unlk.session.opal_key.key,
2881 				iter->unlk.session.opal_key.key_len);
2882 			break;
2883 		}
2884 	}
2885 }
2886 
2887 static int opal_lock_unlock(struct opal_dev *dev,
2888 			    struct opal_lock_unlock *lk_unlk)
2889 {
2890 	int ret;
2891 
2892 	if (lk_unlk->session.who > OPAL_USER9)
2893 		return -EINVAL;
2894 
2895 	mutex_lock(&dev->dev_lock);
2896 	opal_lock_check_for_saved_key(dev, lk_unlk);
2897 	ret = opal_get_key(dev, &lk_unlk->session.opal_key);
2898 	if (!ret)
2899 		ret = __opal_lock_unlock(dev, lk_unlk);
2900 	mutex_unlock(&dev->dev_lock);
2901 
2902 	return ret;
2903 }
2904 
2905 static int opal_take_ownership(struct opal_dev *dev, struct opal_key *opal)
2906 {
2907 	const struct opal_step owner_steps[] = {
2908 		{ start_anybodyASP_opal_session, },
2909 		{ get_msid_cpin_pin, },
2910 		{ end_opal_session, },
2911 		{ start_SIDASP_opal_session, opal },
2912 		{ set_sid_cpin_pin, opal },
2913 		{ end_opal_session, }
2914 	};
2915 	int ret;
2916 
2917 	if (!dev)
2918 		return -ENODEV;
2919 
2920 	ret = opal_get_key(dev, opal);
2921 	if (ret)
2922 		return ret;
2923 	mutex_lock(&dev->dev_lock);
2924 	setup_opal_dev(dev);
2925 	ret = execute_steps(dev, owner_steps, ARRAY_SIZE(owner_steps));
2926 	mutex_unlock(&dev->dev_lock);
2927 
2928 	return ret;
2929 }
2930 
2931 static int opal_activate_lsp(struct opal_dev *dev,
2932 			     struct opal_lr_act *opal_lr_act)
2933 {
2934 	const struct opal_step active_steps[] = {
2935 		{ start_SIDASP_opal_session, &opal_lr_act->key },
2936 		{ get_lsp_lifecycle, },
2937 		{ activate_lsp, opal_lr_act },
2938 		{ end_opal_session, }
2939 	};
2940 	int ret;
2941 
2942 	if (!opal_lr_act->num_lrs || opal_lr_act->num_lrs > OPAL_MAX_LRS)
2943 		return -EINVAL;
2944 
2945 	ret = opal_get_key(dev, &opal_lr_act->key);
2946 	if (ret)
2947 		return ret;
2948 	mutex_lock(&dev->dev_lock);
2949 	setup_opal_dev(dev);
2950 	ret = execute_steps(dev, active_steps, ARRAY_SIZE(active_steps));
2951 	mutex_unlock(&dev->dev_lock);
2952 
2953 	return ret;
2954 }
2955 
2956 static int opal_setup_locking_range(struct opal_dev *dev,
2957 				    struct opal_user_lr_setup *opal_lrs)
2958 {
2959 	const struct opal_step lr_steps[] = {
2960 		{ start_auth_opal_session, &opal_lrs->session },
2961 		{ setup_locking_range, opal_lrs },
2962 		{ end_opal_session, }
2963 	};
2964 	int ret;
2965 
2966 	ret = opal_get_key(dev, &opal_lrs->session.opal_key);
2967 	if (ret)
2968 		return ret;
2969 	mutex_lock(&dev->dev_lock);
2970 	setup_opal_dev(dev);
2971 	ret = execute_steps(dev, lr_steps, ARRAY_SIZE(lr_steps));
2972 	mutex_unlock(&dev->dev_lock);
2973 
2974 	return ret;
2975 }
2976 
2977 static int opal_locking_range_status(struct opal_dev *dev,
2978 			  struct opal_lr_status *opal_lrst,
2979 			  void __user *data)
2980 {
2981 	const struct opal_step lr_steps[] = {
2982 		{ start_auth_opal_session, &opal_lrst->session },
2983 		{ locking_range_status, opal_lrst },
2984 		{ end_opal_session, }
2985 	};
2986 	int ret;
2987 
2988 	mutex_lock(&dev->dev_lock);
2989 	setup_opal_dev(dev);
2990 	ret = execute_steps(dev, lr_steps, ARRAY_SIZE(lr_steps));
2991 	mutex_unlock(&dev->dev_lock);
2992 
2993 	/* skip session info when copying back to uspace */
2994 	if (!ret && copy_to_user(data + offsetof(struct opal_lr_status, range_start),
2995 				(void *)opal_lrst + offsetof(struct opal_lr_status, range_start),
2996 				sizeof(*opal_lrst) - offsetof(struct opal_lr_status, range_start))) {
2997 		pr_debug("Error copying status to userspace\n");
2998 		return -EFAULT;
2999 	}
3000 
3001 	return ret;
3002 }
3003 
3004 static int opal_set_new_pw(struct opal_dev *dev, struct opal_new_pw *opal_pw)
3005 {
3006 	const struct opal_step pw_steps[] = {
3007 		{ start_auth_opal_session, &opal_pw->session },
3008 		{ set_new_pw, &opal_pw->new_user_pw },
3009 		{ end_opal_session, }
3010 	};
3011 	int ret;
3012 
3013 	if (opal_pw->session.who > OPAL_USER9  ||
3014 	    opal_pw->new_user_pw.who > OPAL_USER9)
3015 		return -EINVAL;
3016 
3017 	mutex_lock(&dev->dev_lock);
3018 	setup_opal_dev(dev);
3019 	ret = execute_steps(dev, pw_steps, ARRAY_SIZE(pw_steps));
3020 	mutex_unlock(&dev->dev_lock);
3021 
3022 	if (ret)
3023 		return ret;
3024 
3025 	/* update keyring with new password */
3026 	ret = update_sed_opal_key(OPAL_AUTH_KEY,
3027 				  opal_pw->new_user_pw.opal_key.key,
3028 				  opal_pw->new_user_pw.opal_key.key_len);
3029 
3030 	return ret;
3031 }
3032 
3033 static int opal_activate_user(struct opal_dev *dev,
3034 			      struct opal_session_info *opal_session)
3035 {
3036 	const struct opal_step act_steps[] = {
3037 		{ start_admin1LSP_opal_session, &opal_session->opal_key },
3038 		{ internal_activate_user, opal_session },
3039 		{ end_opal_session, }
3040 	};
3041 	int ret;
3042 
3043 	/* We can't activate Admin1 it's active as manufactured */
3044 	if (opal_session->who < OPAL_USER1 ||
3045 	    opal_session->who > OPAL_USER9) {
3046 		pr_debug("Who was not a valid user: %d\n", opal_session->who);
3047 		return -EINVAL;
3048 	}
3049 
3050 	ret = opal_get_key(dev, &opal_session->opal_key);
3051 	if (ret)
3052 		return ret;
3053 	mutex_lock(&dev->dev_lock);
3054 	setup_opal_dev(dev);
3055 	ret = execute_steps(dev, act_steps, ARRAY_SIZE(act_steps));
3056 	mutex_unlock(&dev->dev_lock);
3057 
3058 	return ret;
3059 }
3060 
3061 bool opal_unlock_from_suspend(struct opal_dev *dev)
3062 {
3063 	struct opal_suspend_data *suspend;
3064 	bool was_failure = false;
3065 	int ret = 0;
3066 
3067 	if (!dev)
3068 		return false;
3069 
3070 	if (!(dev->flags & OPAL_FL_SUPPORTED))
3071 		return false;
3072 
3073 	mutex_lock(&dev->dev_lock);
3074 	setup_opal_dev(dev);
3075 
3076 	list_for_each_entry(suspend, &dev->unlk_lst, node) {
3077 		dev->tsn = 0;
3078 		dev->hsn = 0;
3079 
3080 		ret = __opal_lock_unlock(dev, &suspend->unlk);
3081 		if (ret) {
3082 			pr_debug("Failed to unlock LR %hhu with sum %d\n",
3083 				 suspend->unlk.session.opal_key.lr,
3084 				 suspend->unlk.session.sum);
3085 			was_failure = true;
3086 		}
3087 
3088 		if (dev->flags & OPAL_FL_MBR_ENABLED) {
3089 			ret = __opal_set_mbr_done(dev, &suspend->unlk.session.opal_key);
3090 			if (ret)
3091 				pr_debug("Failed to set MBR Done in S3 resume\n");
3092 		}
3093 	}
3094 	mutex_unlock(&dev->dev_lock);
3095 
3096 	return was_failure;
3097 }
3098 EXPORT_SYMBOL(opal_unlock_from_suspend);
3099 
3100 static int opal_read_table(struct opal_dev *dev,
3101 			   struct opal_read_write_table *rw_tbl)
3102 {
3103 	const struct opal_step read_table_steps[] = {
3104 		{ start_admin1LSP_opal_session, &rw_tbl->key },
3105 		{ read_table_data, rw_tbl },
3106 		{ end_opal_session, }
3107 	};
3108 	int ret = 0;
3109 
3110 	if (!rw_tbl->size)
3111 		return ret;
3112 
3113 	return execute_steps(dev, read_table_steps,
3114 			     ARRAY_SIZE(read_table_steps));
3115 }
3116 
3117 static int opal_write_table(struct opal_dev *dev,
3118 			    struct opal_read_write_table *rw_tbl)
3119 {
3120 	const struct opal_step write_table_steps[] = {
3121 		{ start_admin1LSP_opal_session, &rw_tbl->key },
3122 		{ write_table_data, rw_tbl },
3123 		{ end_opal_session, }
3124 	};
3125 	int ret = 0;
3126 
3127 	if (!rw_tbl->size)
3128 		return ret;
3129 
3130 	return execute_steps(dev, write_table_steps,
3131 			     ARRAY_SIZE(write_table_steps));
3132 }
3133 
3134 static int opal_generic_read_write_table(struct opal_dev *dev,
3135 					 struct opal_read_write_table *rw_tbl)
3136 {
3137 	int ret, bit_set;
3138 
3139 	ret = opal_get_key(dev, &rw_tbl->key);
3140 	if (ret)
3141 		return ret;
3142 	mutex_lock(&dev->dev_lock);
3143 	setup_opal_dev(dev);
3144 
3145 	bit_set = fls64(rw_tbl->flags) - 1;
3146 	switch (bit_set) {
3147 	case OPAL_READ_TABLE:
3148 		ret = opal_read_table(dev, rw_tbl);
3149 		break;
3150 	case OPAL_WRITE_TABLE:
3151 		ret = opal_write_table(dev, rw_tbl);
3152 		break;
3153 	default:
3154 		pr_debug("Invalid bit set in the flag (%016llx).\n",
3155 			 rw_tbl->flags);
3156 		ret = -EINVAL;
3157 		break;
3158 	}
3159 
3160 	mutex_unlock(&dev->dev_lock);
3161 
3162 	return ret;
3163 }
3164 
3165 static int opal_get_status(struct opal_dev *dev, void __user *data)
3166 {
3167 	struct opal_status sts = {0};
3168 
3169 	/*
3170 	 * check_opal_support() error is not fatal,
3171 	 * !dev->supported is a valid condition
3172 	 */
3173 	if (!check_opal_support(dev))
3174 		sts.flags = dev->flags;
3175 	if (copy_to_user(data, &sts, sizeof(sts))) {
3176 		pr_debug("Error copying status to userspace\n");
3177 		return -EFAULT;
3178 	}
3179 	return 0;
3180 }
3181 
3182 static int opal_get_geometry(struct opal_dev *dev, void __user *data)
3183 {
3184 	struct opal_geometry geo = {0};
3185 
3186 	if (check_opal_support(dev))
3187 		return -EINVAL;
3188 
3189 	geo.align = dev->align_required;
3190 	geo.logical_block_size = dev->logical_block_size;
3191 	geo.alignment_granularity =  dev->align;
3192 	geo.lowest_aligned_lba = dev->lowest_lba;
3193 
3194 	if (copy_to_user(data, &geo, sizeof(geo))) {
3195 		pr_debug("Error copying geometry data to userspace\n");
3196 		return -EFAULT;
3197 	}
3198 
3199 	return 0;
3200 }
3201 
3202 int sed_ioctl(struct opal_dev *dev, unsigned int cmd, void __user *arg)
3203 {
3204 	void *p;
3205 	int ret = -ENOTTY;
3206 
3207 	if (!capable(CAP_SYS_ADMIN))
3208 		return -EACCES;
3209 	if (!dev)
3210 		return -EOPNOTSUPP;
3211 	if (!(dev->flags & OPAL_FL_SUPPORTED))
3212 		return -EOPNOTSUPP;
3213 
3214 	if (cmd & IOC_IN) {
3215 		p = memdup_user(arg, _IOC_SIZE(cmd));
3216 		if (IS_ERR(p))
3217 			return PTR_ERR(p);
3218 	}
3219 
3220 	switch (cmd) {
3221 	case IOC_OPAL_SAVE:
3222 		ret = opal_save(dev, p);
3223 		break;
3224 	case IOC_OPAL_LOCK_UNLOCK:
3225 		ret = opal_lock_unlock(dev, p);
3226 		break;
3227 	case IOC_OPAL_TAKE_OWNERSHIP:
3228 		ret = opal_take_ownership(dev, p);
3229 		break;
3230 	case IOC_OPAL_ACTIVATE_LSP:
3231 		ret = opal_activate_lsp(dev, p);
3232 		break;
3233 	case IOC_OPAL_SET_PW:
3234 		ret = opal_set_new_pw(dev, p);
3235 		break;
3236 	case IOC_OPAL_ACTIVATE_USR:
3237 		ret = opal_activate_user(dev, p);
3238 		break;
3239 	case IOC_OPAL_REVERT_TPR:
3240 		ret = opal_reverttper(dev, p, false);
3241 		break;
3242 	case IOC_OPAL_LR_SETUP:
3243 		ret = opal_setup_locking_range(dev, p);
3244 		break;
3245 	case IOC_OPAL_ADD_USR_TO_LR:
3246 		ret = opal_add_user_to_lr(dev, p);
3247 		break;
3248 	case IOC_OPAL_ENABLE_DISABLE_MBR:
3249 		ret = opal_enable_disable_shadow_mbr(dev, p);
3250 		break;
3251 	case IOC_OPAL_MBR_DONE:
3252 		ret = opal_set_mbr_done(dev, p);
3253 		break;
3254 	case IOC_OPAL_WRITE_SHADOW_MBR:
3255 		ret = opal_write_shadow_mbr(dev, p);
3256 		break;
3257 	case IOC_OPAL_ERASE_LR:
3258 		ret = opal_erase_locking_range(dev, p);
3259 		break;
3260 	case IOC_OPAL_SECURE_ERASE_LR:
3261 		ret = opal_secure_erase_locking_range(dev, p);
3262 		break;
3263 	case IOC_OPAL_PSID_REVERT_TPR:
3264 		ret = opal_reverttper(dev, p, true);
3265 		break;
3266 	case IOC_OPAL_GENERIC_TABLE_RW:
3267 		ret = opal_generic_read_write_table(dev, p);
3268 		break;
3269 	case IOC_OPAL_GET_STATUS:
3270 		ret = opal_get_status(dev, arg);
3271 		break;
3272 	case IOC_OPAL_GET_LR_STATUS:
3273 		ret = opal_locking_range_status(dev, p, arg);
3274 		break;
3275 	case IOC_OPAL_GET_GEOMETRY:
3276 		ret = opal_get_geometry(dev, arg);
3277 		break;
3278 	case IOC_OPAL_REVERT_LSP:
3279 		ret = opal_revertlsp(dev, p);
3280 		break;
3281 	case IOC_OPAL_DISCOVERY:
3282 		ret = opal_get_discv(dev, p);
3283 		break;
3284 
3285 	default:
3286 		break;
3287 	}
3288 
3289 	if (cmd & IOC_IN)
3290 		kfree(p);
3291 	return ret;
3292 }
3293 EXPORT_SYMBOL_GPL(sed_ioctl);
3294 
3295 static int __init sed_opal_init(void)
3296 {
3297 	struct key *kr;
3298 
3299 	kr = keyring_alloc(".sed_opal",
3300 			   GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),
3301 			   (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW |
3302 			   KEY_USR_READ | KEY_USR_SEARCH | KEY_USR_WRITE,
3303 			   KEY_ALLOC_NOT_IN_QUOTA,
3304 			   NULL, NULL);
3305 	if (IS_ERR(kr))
3306 		return PTR_ERR(kr);
3307 
3308 	sed_opal_keyring = kr;
3309 
3310 	return 0;
3311 }
3312 late_initcall(sed_opal_init);
3313