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