57932848361bf566fd7725a2b4888679c16c8a33
[linux-2.6-microblaze.git] / drivers / crypto / nx / nx-842-pseries.c
1 /*
2  * Driver for IBM Power 842 compression accelerator
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  *
18  * Copyright (C) IBM Corporation, 2012
19  *
20  * Authors: Robert Jennings <rcj@linux.vnet.ibm.com>
21  *          Seth Jennings <sjenning@linux.vnet.ibm.com>
22  */
23
24 #include <asm/vio.h>
25
26 #include "nx-842.h"
27 #include "nx_csbcpb.h" /* struct nx_csbcpb */
28
29 MODULE_LICENSE("GPL");
30 MODULE_AUTHOR("Robert Jennings <rcj@linux.vnet.ibm.com>");
31 MODULE_DESCRIPTION("842 H/W Compression driver for IBM Power processors");
32 MODULE_ALIAS_CRYPTO("842");
33 MODULE_ALIAS_CRYPTO("842-nx");
34
35 static struct nx842_constraints nx842_pseries_constraints = {
36         .alignment =    DDE_BUFFER_ALIGN,
37         .multiple =     DDE_BUFFER_LAST_MULT,
38         .minimum =      DDE_BUFFER_LAST_MULT,
39         .maximum =      PAGE_SIZE, /* dynamic, max_sync_size */
40 };
41
42 static int check_constraints(unsigned long buf, unsigned int *len, bool in)
43 {
44         if (!IS_ALIGNED(buf, nx842_pseries_constraints.alignment)) {
45                 pr_debug("%s buffer 0x%lx not aligned to 0x%x\n",
46                          in ? "input" : "output", buf,
47                          nx842_pseries_constraints.alignment);
48                 return -EINVAL;
49         }
50         if (*len % nx842_pseries_constraints.multiple) {
51                 pr_debug("%s buffer len 0x%x not multiple of 0x%x\n",
52                          in ? "input" : "output", *len,
53                          nx842_pseries_constraints.multiple);
54                 if (in)
55                         return -EINVAL;
56                 *len = round_down(*len, nx842_pseries_constraints.multiple);
57         }
58         if (*len < nx842_pseries_constraints.minimum) {
59                 pr_debug("%s buffer len 0x%x under minimum 0x%x\n",
60                          in ? "input" : "output", *len,
61                          nx842_pseries_constraints.minimum);
62                 return -EINVAL;
63         }
64         if (*len > nx842_pseries_constraints.maximum) {
65                 pr_debug("%s buffer len 0x%x over maximum 0x%x\n",
66                          in ? "input" : "output", *len,
67                          nx842_pseries_constraints.maximum);
68                 if (in)
69                         return -EINVAL;
70                 *len = nx842_pseries_constraints.maximum;
71         }
72         return 0;
73 }
74
75 /* I assume we need to align the CSB? */
76 #define WORKMEM_ALIGN   (256)
77
78 struct nx842_workmem {
79         /* scatterlist */
80         char slin[4096];
81         char slout[4096];
82         /* coprocessor status/parameter block */
83         struct nx_csbcpb csbcpb;
84
85         char padding[WORKMEM_ALIGN];
86 } __aligned(WORKMEM_ALIGN);
87
88 /* Macros for fields within nx_csbcpb */
89 /* Check the valid bit within the csbcpb valid field */
90 #define NX842_CSBCBP_VALID_CHK(x) (x & BIT_MASK(7))
91
92 /* CE macros operate on the completion_extension field bits in the csbcpb.
93  * CE0 0=full completion, 1=partial completion
94  * CE1 0=CE0 indicates completion, 1=termination (output may be modified)
95  * CE2 0=processed_bytes is source bytes, 1=processed_bytes is target bytes */
96 #define NX842_CSBCPB_CE0(x)     (x & BIT_MASK(7))
97 #define NX842_CSBCPB_CE1(x)     (x & BIT_MASK(6))
98 #define NX842_CSBCPB_CE2(x)     (x & BIT_MASK(5))
99
100 /* The NX unit accepts data only on 4K page boundaries */
101 #define NX842_HW_PAGE_SIZE      (4096)
102 #define NX842_HW_PAGE_MASK      (~(NX842_HW_PAGE_SIZE-1))
103
104 struct ibm_nx842_counters {
105         atomic64_t comp_complete;
106         atomic64_t comp_failed;
107         atomic64_t decomp_complete;
108         atomic64_t decomp_failed;
109         atomic64_t swdecomp;
110         atomic64_t comp_times[32];
111         atomic64_t decomp_times[32];
112 };
113
114 static struct nx842_devdata {
115         struct vio_dev *vdev;
116         struct device *dev;
117         struct ibm_nx842_counters *counters;
118         unsigned int max_sg_len;
119         unsigned int max_sync_size;
120         unsigned int max_sync_sg;
121 } __rcu *devdata;
122 static DEFINE_SPINLOCK(devdata_mutex);
123
124 #define NX842_COUNTER_INC(_x) \
125 static inline void nx842_inc_##_x( \
126         const struct nx842_devdata *dev) { \
127         if (dev) \
128                 atomic64_inc(&dev->counters->_x); \
129 }
130 NX842_COUNTER_INC(comp_complete);
131 NX842_COUNTER_INC(comp_failed);
132 NX842_COUNTER_INC(decomp_complete);
133 NX842_COUNTER_INC(decomp_failed);
134 NX842_COUNTER_INC(swdecomp);
135
136 #define NX842_HIST_SLOTS 16
137
138 static void ibm_nx842_incr_hist(atomic64_t *times, unsigned int time)
139 {
140         int bucket = fls(time);
141
142         if (bucket)
143                 bucket = min((NX842_HIST_SLOTS - 1), bucket - 1);
144
145         atomic64_inc(&times[bucket]);
146 }
147
148 /* NX unit operation flags */
149 #define NX842_OP_COMPRESS       0x0
150 #define NX842_OP_CRC            0x1
151 #define NX842_OP_DECOMPRESS     0x2
152 #define NX842_OP_COMPRESS_CRC   (NX842_OP_COMPRESS | NX842_OP_CRC)
153 #define NX842_OP_DECOMPRESS_CRC (NX842_OP_DECOMPRESS | NX842_OP_CRC)
154 #define NX842_OP_ASYNC          (1<<23)
155 #define NX842_OP_NOTIFY         (1<<22)
156 #define NX842_OP_NOTIFY_INT(x)  ((x & 0xff)<<8)
157
158 static unsigned long nx842_get_desired_dma(struct vio_dev *viodev)
159 {
160         /* No use of DMA mappings within the driver. */
161         return 0;
162 }
163
164 struct nx842_slentry {
165         __be64 ptr; /* Real address (use __pa()) */
166         __be64 len;
167 };
168
169 /* pHyp scatterlist entry */
170 struct nx842_scatterlist {
171         int entry_nr; /* number of slentries */
172         struct nx842_slentry *entries; /* ptr to array of slentries */
173 };
174
175 /* Does not include sizeof(entry_nr) in the size */
176 static inline unsigned long nx842_get_scatterlist_size(
177                                 struct nx842_scatterlist *sl)
178 {
179         return sl->entry_nr * sizeof(struct nx842_slentry);
180 }
181
182 static int nx842_build_scatterlist(unsigned long buf, int len,
183                         struct nx842_scatterlist *sl)
184 {
185         unsigned long entrylen;
186         struct nx842_slentry *entry;
187
188         sl->entry_nr = 0;
189
190         entry = sl->entries;
191         while (len) {
192                 entry->ptr = cpu_to_be64(nx842_get_pa((void *)buf));
193                 entrylen = min_t(int, len,
194                                  LEN_ON_SIZE(buf, NX842_HW_PAGE_SIZE));
195                 entry->len = cpu_to_be64(entrylen);
196
197                 len -= entrylen;
198                 buf += entrylen;
199
200                 sl->entry_nr++;
201                 entry++;
202         }
203
204         return 0;
205 }
206
207 static int nx842_validate_result(struct device *dev,
208         struct cop_status_block *csb)
209 {
210         /* The csb must be valid after returning from vio_h_cop_sync */
211         if (!NX842_CSBCBP_VALID_CHK(csb->valid)) {
212                 dev_err(dev, "%s: cspcbp not valid upon completion.\n",
213                                 __func__);
214                 dev_dbg(dev, "valid:0x%02x cs:0x%02x cc:0x%02x ce:0x%02x\n",
215                                 csb->valid,
216                                 csb->crb_seq_number,
217                                 csb->completion_code,
218                                 csb->completion_extension);
219                 dev_dbg(dev, "processed_bytes:%d address:0x%016lx\n",
220                                 be32_to_cpu(csb->processed_byte_count),
221                                 (unsigned long)be64_to_cpu(csb->address));
222                 return -EIO;
223         }
224
225         /* Check return values from the hardware in the CSB */
226         switch (csb->completion_code) {
227         case 0: /* Completed without error */
228                 break;
229         case 64: /* Compression ok, but output larger than input */
230                 dev_dbg(dev, "%s: output size larger than input size\n",
231                                         __func__);
232                 break;
233         case 13: /* Output buffer too small */
234                 dev_dbg(dev, "%s: Out of space in output buffer\n",
235                                         __func__);
236                 return -ENOSPC;
237         case 65: /* Calculated CRC doesn't match the passed value */
238                 dev_dbg(dev, "%s: CRC mismatch for decompression\n",
239                                         __func__);
240                 return -EINVAL;
241         case 66: /* Input data contains an illegal template field */
242         case 67: /* Template indicates data past the end of the input stream */
243                 dev_dbg(dev, "%s: Bad data for decompression (code:%d)\n",
244                                         __func__, csb->completion_code);
245                 return -EINVAL;
246         default:
247                 dev_dbg(dev, "%s: Unspecified error (code:%d)\n",
248                                         __func__, csb->completion_code);
249                 return -EIO;
250         }
251
252         /* Hardware sanity check */
253         if (!NX842_CSBCPB_CE2(csb->completion_extension)) {
254                 dev_err(dev, "%s: No error returned by hardware, but "
255                                 "data returned is unusable, contact support.\n"
256                                 "(Additional info: csbcbp->processed bytes "
257                                 "does not specify processed bytes for the "
258                                 "target buffer.)\n", __func__);
259                 return -EIO;
260         }
261
262         return 0;
263 }
264
265 /**
266  * nx842_pseries_compress - Compress data using the 842 algorithm
267  *
268  * Compression provide by the NX842 coprocessor on IBM Power systems.
269  * The input buffer is compressed and the result is stored in the
270  * provided output buffer.
271  *
272  * Upon return from this function @outlen contains the length of the
273  * compressed data.  If there is an error then @outlen will be 0 and an
274  * error will be specified by the return code from this function.
275  *
276  * @in: Pointer to input buffer
277  * @inlen: Length of input buffer
278  * @out: Pointer to output buffer
279  * @outlen: Length of output buffer
280  * @wrkmem: ptr to buffer for working memory, size determined by
281  *          nx842_pseries_driver.workmem_size
282  *
283  * Returns:
284  *   0          Success, output of length @outlen stored in the buffer at @out
285  *   -ENOMEM    Unable to allocate internal buffers
286  *   -ENOSPC    Output buffer is to small
287  *   -EIO       Internal error
288  *   -ENODEV    Hardware unavailable
289  */
290 static int nx842_pseries_compress(const unsigned char *in, unsigned int inlen,
291                                   unsigned char *out, unsigned int *outlen,
292                                   void *wmem)
293 {
294         struct nx842_devdata *local_devdata;
295         struct device *dev = NULL;
296         struct nx842_workmem *workmem;
297         struct nx842_scatterlist slin, slout;
298         struct nx_csbcpb *csbcpb;
299         int ret = 0;
300         unsigned long inbuf, outbuf;
301         struct vio_pfo_op op = {
302                 .done = NULL,
303                 .handle = 0,
304                 .timeout = 0,
305         };
306         unsigned long start = get_tb();
307
308         inbuf = (unsigned long)in;
309         if (check_constraints(inbuf, &inlen, true))
310                 return -EINVAL;
311
312         outbuf = (unsigned long)out;
313         if (check_constraints(outbuf, outlen, false))
314                 return -EINVAL;
315
316         rcu_read_lock();
317         local_devdata = rcu_dereference(devdata);
318         if (!local_devdata || !local_devdata->dev) {
319                 rcu_read_unlock();
320                 return -ENODEV;
321         }
322         dev = local_devdata->dev;
323
324         /* Init scatterlist */
325         workmem = PTR_ALIGN(wmem, WORKMEM_ALIGN);
326         slin.entries = (struct nx842_slentry *)workmem->slin;
327         slout.entries = (struct nx842_slentry *)workmem->slout;
328
329         /* Init operation */
330         op.flags = NX842_OP_COMPRESS_CRC;
331         csbcpb = &workmem->csbcpb;
332         memset(csbcpb, 0, sizeof(*csbcpb));
333         op.csbcpb = nx842_get_pa(csbcpb);
334
335         if ((inbuf & NX842_HW_PAGE_MASK) ==
336             ((inbuf + inlen - 1) & NX842_HW_PAGE_MASK)) {
337                 /* Create direct DDE */
338                 op.in = nx842_get_pa((void *)inbuf);
339                 op.inlen = inlen;
340         } else {
341                 /* Create indirect DDE (scatterlist) */
342                 nx842_build_scatterlist(inbuf, inlen, &slin);
343                 op.in = nx842_get_pa(slin.entries);
344                 op.inlen = -nx842_get_scatterlist_size(&slin);
345         }
346
347         if ((outbuf & NX842_HW_PAGE_MASK) ==
348             ((outbuf + *outlen - 1) & NX842_HW_PAGE_MASK)) {
349                 /* Create direct DDE */
350                 op.out = nx842_get_pa((void *)outbuf);
351                 op.outlen = *outlen;
352         } else {
353                 /* Create indirect DDE (scatterlist) */
354                 nx842_build_scatterlist(outbuf, *outlen, &slout);
355                 op.out = nx842_get_pa(slout.entries);
356                 op.outlen = -nx842_get_scatterlist_size(&slout);
357         }
358
359         dev_dbg(dev, "%s: op.in %lx op.inlen %ld op.out %lx op.outlen %ld\n",
360                 __func__, (unsigned long)op.in, (long)op.inlen,
361                 (unsigned long)op.out, (long)op.outlen);
362
363         /* Send request to pHyp */
364         ret = vio_h_cop_sync(local_devdata->vdev, &op);
365
366         /* Check for pHyp error */
367         if (ret) {
368                 dev_dbg(dev, "%s: vio_h_cop_sync error (ret=%d, hret=%ld)\n",
369                         __func__, ret, op.hcall_err);
370                 ret = -EIO;
371                 goto unlock;
372         }
373
374         /* Check for hardware error */
375         ret = nx842_validate_result(dev, &csbcpb->csb);
376         if (ret)
377                 goto unlock;
378
379         *outlen = be32_to_cpu(csbcpb->csb.processed_byte_count);
380         dev_dbg(dev, "%s: processed_bytes=%d\n", __func__, *outlen);
381
382 unlock:
383         if (ret)
384                 nx842_inc_comp_failed(local_devdata);
385         else {
386                 nx842_inc_comp_complete(local_devdata);
387                 ibm_nx842_incr_hist(local_devdata->counters->comp_times,
388                         (get_tb() - start) / tb_ticks_per_usec);
389         }
390         rcu_read_unlock();
391         return ret;
392 }
393
394 /**
395  * nx842_pseries_decompress - Decompress data using the 842 algorithm
396  *
397  * Decompression provide by the NX842 coprocessor on IBM Power systems.
398  * The input buffer is decompressed and the result is stored in the
399  * provided output buffer.  The size allocated to the output buffer is
400  * provided by the caller of this function in @outlen.  Upon return from
401  * this function @outlen contains the length of the decompressed data.
402  * If there is an error then @outlen will be 0 and an error will be
403  * specified by the return code from this function.
404  *
405  * @in: Pointer to input buffer
406  * @inlen: Length of input buffer
407  * @out: Pointer to output buffer
408  * @outlen: Length of output buffer
409  * @wrkmem: ptr to buffer for working memory, size determined by
410  *          nx842_pseries_driver.workmem_size
411  *
412  * Returns:
413  *   0          Success, output of length @outlen stored in the buffer at @out
414  *   -ENODEV    Hardware decompression device is unavailable
415  *   -ENOMEM    Unable to allocate internal buffers
416  *   -ENOSPC    Output buffer is to small
417  *   -EINVAL    Bad input data encountered when attempting decompress
418  *   -EIO       Internal error
419  */
420 static int nx842_pseries_decompress(const unsigned char *in, unsigned int inlen,
421                                     unsigned char *out, unsigned int *outlen,
422                                     void *wmem)
423 {
424         struct nx842_devdata *local_devdata;
425         struct device *dev = NULL;
426         struct nx842_workmem *workmem;
427         struct nx842_scatterlist slin, slout;
428         struct nx_csbcpb *csbcpb;
429         int ret = 0;
430         unsigned long inbuf, outbuf;
431         struct vio_pfo_op op = {
432                 .done = NULL,
433                 .handle = 0,
434                 .timeout = 0,
435         };
436         unsigned long start = get_tb();
437
438         /* Ensure page alignment and size */
439         inbuf = (unsigned long)in;
440         if (check_constraints(inbuf, &inlen, true))
441                 return -EINVAL;
442
443         outbuf = (unsigned long)out;
444         if (check_constraints(outbuf, outlen, false))
445                 return -EINVAL;
446
447         rcu_read_lock();
448         local_devdata = rcu_dereference(devdata);
449         if (!local_devdata || !local_devdata->dev) {
450                 rcu_read_unlock();
451                 return -ENODEV;
452         }
453         dev = local_devdata->dev;
454
455         workmem = PTR_ALIGN(wmem, WORKMEM_ALIGN);
456
457         /* Init scatterlist */
458         slin.entries = (struct nx842_slentry *)workmem->slin;
459         slout.entries = (struct nx842_slentry *)workmem->slout;
460
461         /* Init operation */
462         op.flags = NX842_OP_DECOMPRESS_CRC;
463         csbcpb = &workmem->csbcpb;
464         memset(csbcpb, 0, sizeof(*csbcpb));
465         op.csbcpb = nx842_get_pa(csbcpb);
466
467         if ((inbuf & NX842_HW_PAGE_MASK) ==
468             ((inbuf + inlen - 1) & NX842_HW_PAGE_MASK)) {
469                 /* Create direct DDE */
470                 op.in = nx842_get_pa((void *)inbuf);
471                 op.inlen = inlen;
472         } else {
473                 /* Create indirect DDE (scatterlist) */
474                 nx842_build_scatterlist(inbuf, inlen, &slin);
475                 op.in = nx842_get_pa(slin.entries);
476                 op.inlen = -nx842_get_scatterlist_size(&slin);
477         }
478
479         if ((outbuf & NX842_HW_PAGE_MASK) ==
480             ((outbuf + *outlen - 1) & NX842_HW_PAGE_MASK)) {
481                 /* Create direct DDE */
482                 op.out = nx842_get_pa((void *)outbuf);
483                 op.outlen = *outlen;
484         } else {
485                 /* Create indirect DDE (scatterlist) */
486                 nx842_build_scatterlist(outbuf, *outlen, &slout);
487                 op.out = nx842_get_pa(slout.entries);
488                 op.outlen = -nx842_get_scatterlist_size(&slout);
489         }
490
491         dev_dbg(dev, "%s: op.in %lx op.inlen %ld op.out %lx op.outlen %ld\n",
492                 __func__, (unsigned long)op.in, (long)op.inlen,
493                 (unsigned long)op.out, (long)op.outlen);
494
495         /* Send request to pHyp */
496         ret = vio_h_cop_sync(local_devdata->vdev, &op);
497
498         /* Check for pHyp error */
499         if (ret) {
500                 dev_dbg(dev, "%s: vio_h_cop_sync error (ret=%d, hret=%ld)\n",
501                         __func__, ret, op.hcall_err);
502                 goto unlock;
503         }
504
505         /* Check for hardware error */
506         ret = nx842_validate_result(dev, &csbcpb->csb);
507         if (ret)
508                 goto unlock;
509
510         *outlen = be32_to_cpu(csbcpb->csb.processed_byte_count);
511
512 unlock:
513         if (ret)
514                 /* decompress fail */
515                 nx842_inc_decomp_failed(local_devdata);
516         else {
517                 nx842_inc_decomp_complete(local_devdata);
518                 ibm_nx842_incr_hist(local_devdata->counters->decomp_times,
519                         (get_tb() - start) / tb_ticks_per_usec);
520         }
521
522         rcu_read_unlock();
523         return ret;
524 }
525
526 /**
527  * nx842_OF_set_defaults -- Set default (disabled) values for devdata
528  *
529  * @devdata - struct nx842_devdata to update
530  *
531  * Returns:
532  *  0 on success
533  *  -ENOENT if @devdata ptr is NULL
534  */
535 static int nx842_OF_set_defaults(struct nx842_devdata *devdata)
536 {
537         if (devdata) {
538                 devdata->max_sync_size = 0;
539                 devdata->max_sync_sg = 0;
540                 devdata->max_sg_len = 0;
541                 return 0;
542         } else
543                 return -ENOENT;
544 }
545
546 /**
547  * nx842_OF_upd_status -- Check the device info from OF status prop
548  *
549  * The status property indicates if the accelerator is enabled.  If the
550  * device is in the OF tree it indicates that the hardware is present.
551  * The status field indicates if the device is enabled when the status
552  * is 'okay'.  Otherwise the device driver will be disabled.
553  *
554  * @prop - struct property point containing the maxsyncop for the update
555  *
556  * Returns:
557  *  0 - Device is available
558  *  -ENODEV - Device is not available
559  */
560 static int nx842_OF_upd_status(struct property *prop)
561 {
562         const char *status = (const char *)prop->value;
563
564         if (!strncmp(status, "okay", (size_t)prop->length))
565                 return 0;
566         if (!strncmp(status, "disabled", (size_t)prop->length))
567                 return -ENODEV;
568         dev_info(devdata->dev, "%s: unknown status '%s'\n", __func__, status);
569
570         return -EINVAL;
571 }
572
573 /**
574  * nx842_OF_upd_maxsglen -- Update the device info from OF maxsglen prop
575  *
576  * Definition of the 'ibm,max-sg-len' OF property:
577  *  This field indicates the maximum byte length of a scatter list
578  *  for the platform facility. It is a single cell encoded as with encode-int.
579  *
580  * Example:
581  *  # od -x ibm,max-sg-len
582  *  0000000 0000 0ff0
583  *
584  *  In this example, the maximum byte length of a scatter list is
585  *  0x0ff0 (4,080).
586  *
587  * @devdata - struct nx842_devdata to update
588  * @prop - struct property point containing the maxsyncop for the update
589  *
590  * Returns:
591  *  0 on success
592  *  -EINVAL on failure
593  */
594 static int nx842_OF_upd_maxsglen(struct nx842_devdata *devdata,
595                                         struct property *prop) {
596         int ret = 0;
597         const unsigned int maxsglen = of_read_number(prop->value, 1);
598
599         if (prop->length != sizeof(maxsglen)) {
600                 dev_err(devdata->dev, "%s: unexpected format for ibm,max-sg-len property\n", __func__);
601                 dev_dbg(devdata->dev, "%s: ibm,max-sg-len is %d bytes long, expected %lu bytes\n", __func__,
602                                 prop->length, sizeof(maxsglen));
603                 ret = -EINVAL;
604         } else {
605                 devdata->max_sg_len = min_t(unsigned int,
606                                             maxsglen, NX842_HW_PAGE_SIZE);
607         }
608
609         return ret;
610 }
611
612 /**
613  * nx842_OF_upd_maxsyncop -- Update the device info from OF maxsyncop prop
614  *
615  * Definition of the 'ibm,max-sync-cop' OF property:
616  *  Two series of cells.  The first series of cells represents the maximums
617  *  that can be synchronously compressed. The second series of cells
618  *  represents the maximums that can be synchronously decompressed.
619  *  1. The first cell in each series contains the count of the number of
620  *     data length, scatter list elements pairs that follow â€“ each being
621  *     of the form
622  *    a. One cell data byte length
623  *    b. One cell total number of scatter list elements
624  *
625  * Example:
626  *  # od -x ibm,max-sync-cop
627  *  0000000 0000 0001 0000 1000 0000 01fe 0000 0001
628  *  0000020 0000 1000 0000 01fe
629  *
630  *  In this example, compression supports 0x1000 (4,096) data byte length
631  *  and 0x1fe (510) total scatter list elements.  Decompression supports
632  *  0x1000 (4,096) data byte length and 0x1f3 (510) total scatter list
633  *  elements.
634  *
635  * @devdata - struct nx842_devdata to update
636  * @prop - struct property point containing the maxsyncop for the update
637  *
638  * Returns:
639  *  0 on success
640  *  -EINVAL on failure
641  */
642 static int nx842_OF_upd_maxsyncop(struct nx842_devdata *devdata,
643                                         struct property *prop) {
644         int ret = 0;
645         unsigned int comp_data_limit, decomp_data_limit;
646         unsigned int comp_sg_limit, decomp_sg_limit;
647         const struct maxsynccop_t {
648                 __be32 comp_elements;
649                 __be32 comp_data_limit;
650                 __be32 comp_sg_limit;
651                 __be32 decomp_elements;
652                 __be32 decomp_data_limit;
653                 __be32 decomp_sg_limit;
654         } *maxsynccop;
655
656         if (prop->length != sizeof(*maxsynccop)) {
657                 dev_err(devdata->dev, "%s: unexpected format for ibm,max-sync-cop property\n", __func__);
658                 dev_dbg(devdata->dev, "%s: ibm,max-sync-cop is %d bytes long, expected %lu bytes\n", __func__, prop->length,
659                                 sizeof(*maxsynccop));
660                 ret = -EINVAL;
661                 goto out;
662         }
663
664         maxsynccop = (const struct maxsynccop_t *)prop->value;
665         comp_data_limit = be32_to_cpu(maxsynccop->comp_data_limit);
666         comp_sg_limit = be32_to_cpu(maxsynccop->comp_sg_limit);
667         decomp_data_limit = be32_to_cpu(maxsynccop->decomp_data_limit);
668         decomp_sg_limit = be32_to_cpu(maxsynccop->decomp_sg_limit);
669
670         /* Use one limit rather than separate limits for compression and
671          * decompression. Set a maximum for this so as not to exceed the
672          * size that the header can support and round the value down to
673          * the hardware page size (4K) */
674         devdata->max_sync_size = min(comp_data_limit, decomp_data_limit);
675
676         devdata->max_sync_size = min_t(unsigned int, devdata->max_sync_size,
677                                         65536);
678
679         if (devdata->max_sync_size < 4096) {
680                 dev_err(devdata->dev, "%s: hardware max data size (%u) is "
681                                 "less than the driver minimum, unable to use "
682                                 "the hardware device\n",
683                                 __func__, devdata->max_sync_size);
684                 ret = -EINVAL;
685                 goto out;
686         }
687
688         nx842_pseries_constraints.maximum = devdata->max_sync_size;
689
690         devdata->max_sync_sg = min(comp_sg_limit, decomp_sg_limit);
691         if (devdata->max_sync_sg < 1) {
692                 dev_err(devdata->dev, "%s: hardware max sg size (%u) is "
693                                 "less than the driver minimum, unable to use "
694                                 "the hardware device\n",
695                                 __func__, devdata->max_sync_sg);
696                 ret = -EINVAL;
697                 goto out;
698         }
699
700 out:
701         return ret;
702 }
703
704 /**
705  *
706  * nx842_OF_upd -- Handle OF properties updates for the device.
707  *
708  * Set all properties from the OF tree.  Optionally, a new property
709  * can be provided by the @new_prop pointer to overwrite an existing value.
710  * The device will remain disabled until all values are valid, this function
711  * will return an error for updates unless all values are valid.
712  *
713  * @new_prop: If not NULL, this property is being updated.  If NULL, update
714  *  all properties from the current values in the OF tree.
715  *
716  * Returns:
717  *  0 - Success
718  *  -ENOMEM - Could not allocate memory for new devdata structure
719  *  -EINVAL - property value not found, new_prop is not a recognized
720  *      property for the device or property value is not valid.
721  *  -ENODEV - Device is not available
722  */
723 static int nx842_OF_upd(struct property *new_prop)
724 {
725         struct nx842_devdata *old_devdata = NULL;
726         struct nx842_devdata *new_devdata = NULL;
727         struct device_node *of_node = NULL;
728         struct property *status = NULL;
729         struct property *maxsglen = NULL;
730         struct property *maxsyncop = NULL;
731         int ret = 0;
732         unsigned long flags;
733
734         new_devdata = kzalloc(sizeof(*new_devdata), GFP_NOFS);
735         if (!new_devdata)
736                 return -ENOMEM;
737
738         spin_lock_irqsave(&devdata_mutex, flags);
739         old_devdata = rcu_dereference_check(devdata,
740                         lockdep_is_held(&devdata_mutex));
741         if (old_devdata)
742                 of_node = old_devdata->dev->of_node;
743
744         if (!old_devdata || !of_node) {
745                 pr_err("%s: device is not available\n", __func__);
746                 spin_unlock_irqrestore(&devdata_mutex, flags);
747                 kfree(new_devdata);
748                 return -ENODEV;
749         }
750
751         memcpy(new_devdata, old_devdata, sizeof(*old_devdata));
752         new_devdata->counters = old_devdata->counters;
753
754         /* Set ptrs for existing properties */
755         status = of_find_property(of_node, "status", NULL);
756         maxsglen = of_find_property(of_node, "ibm,max-sg-len", NULL);
757         maxsyncop = of_find_property(of_node, "ibm,max-sync-cop", NULL);
758         if (!status || !maxsglen || !maxsyncop) {
759                 dev_err(old_devdata->dev, "%s: Could not locate device properties\n", __func__);
760                 ret = -EINVAL;
761                 goto error_out;
762         }
763
764         /*
765          * If this is a property update, there are only certain properties that
766          * we care about. Bail if it isn't in the below list
767          */
768         if (new_prop && (strncmp(new_prop->name, "status", new_prop->length) ||
769                          strncmp(new_prop->name, "ibm,max-sg-len", new_prop->length) ||
770                          strncmp(new_prop->name, "ibm,max-sync-cop", new_prop->length)))
771                 goto out;
772
773         /* Perform property updates */
774         ret = nx842_OF_upd_status(status);
775         if (ret)
776                 goto error_out;
777
778         ret = nx842_OF_upd_maxsglen(new_devdata, maxsglen);
779         if (ret)
780                 goto error_out;
781
782         ret = nx842_OF_upd_maxsyncop(new_devdata, maxsyncop);
783         if (ret)
784                 goto error_out;
785
786 out:
787         dev_info(old_devdata->dev, "%s: max_sync_size new:%u old:%u\n",
788                         __func__, new_devdata->max_sync_size,
789                         old_devdata->max_sync_size);
790         dev_info(old_devdata->dev, "%s: max_sync_sg new:%u old:%u\n",
791                         __func__, new_devdata->max_sync_sg,
792                         old_devdata->max_sync_sg);
793         dev_info(old_devdata->dev, "%s: max_sg_len new:%u old:%u\n",
794                         __func__, new_devdata->max_sg_len,
795                         old_devdata->max_sg_len);
796
797         rcu_assign_pointer(devdata, new_devdata);
798         spin_unlock_irqrestore(&devdata_mutex, flags);
799         synchronize_rcu();
800         dev_set_drvdata(new_devdata->dev, new_devdata);
801         kfree(old_devdata);
802         return 0;
803
804 error_out:
805         if (new_devdata) {
806                 dev_info(old_devdata->dev, "%s: device disabled\n", __func__);
807                 nx842_OF_set_defaults(new_devdata);
808                 rcu_assign_pointer(devdata, new_devdata);
809                 spin_unlock_irqrestore(&devdata_mutex, flags);
810                 synchronize_rcu();
811                 dev_set_drvdata(new_devdata->dev, new_devdata);
812                 kfree(old_devdata);
813         } else {
814                 dev_err(old_devdata->dev, "%s: could not update driver from hardware\n", __func__);
815                 spin_unlock_irqrestore(&devdata_mutex, flags);
816         }
817
818         if (!ret)
819                 ret = -EINVAL;
820         return ret;
821 }
822
823 /**
824  * nx842_OF_notifier - Process updates to OF properties for the device
825  *
826  * @np: notifier block
827  * @action: notifier action
828  * @update: struct pSeries_reconfig_prop_update pointer if action is
829  *      PSERIES_UPDATE_PROPERTY
830  *
831  * Returns:
832  *      NOTIFY_OK on success
833  *      NOTIFY_BAD encoded with error number on failure, use
834  *              notifier_to_errno() to decode this value
835  */
836 static int nx842_OF_notifier(struct notifier_block *np, unsigned long action,
837                              void *data)
838 {
839         struct of_reconfig_data *upd = data;
840         struct nx842_devdata *local_devdata;
841         struct device_node *node = NULL;
842
843         rcu_read_lock();
844         local_devdata = rcu_dereference(devdata);
845         if (local_devdata)
846                 node = local_devdata->dev->of_node;
847
848         if (local_devdata &&
849                         action == OF_RECONFIG_UPDATE_PROPERTY &&
850                         !strcmp(upd->dn->name, node->name)) {
851                 rcu_read_unlock();
852                 nx842_OF_upd(upd->prop);
853         } else
854                 rcu_read_unlock();
855
856         return NOTIFY_OK;
857 }
858
859 static struct notifier_block nx842_of_nb = {
860         .notifier_call = nx842_OF_notifier,
861 };
862
863 #define nx842_counter_read(_name)                                       \
864 static ssize_t nx842_##_name##_show(struct device *dev,         \
865                 struct device_attribute *attr,                          \
866                 char *buf) {                                            \
867         struct nx842_devdata *local_devdata;                    \
868         int p = 0;                                                      \
869         rcu_read_lock();                                                \
870         local_devdata = rcu_dereference(devdata);                       \
871         if (local_devdata)                                              \
872                 p = snprintf(buf, PAGE_SIZE, "%ld\n",                   \
873                        atomic64_read(&local_devdata->counters->_name)); \
874         rcu_read_unlock();                                              \
875         return p;                                                       \
876 }
877
878 #define NX842DEV_COUNTER_ATTR_RO(_name)                                 \
879         nx842_counter_read(_name);                                      \
880         static struct device_attribute dev_attr_##_name = __ATTR(_name, \
881                                                 0444,                   \
882                                                 nx842_##_name##_show,\
883                                                 NULL);
884
885 NX842DEV_COUNTER_ATTR_RO(comp_complete);
886 NX842DEV_COUNTER_ATTR_RO(comp_failed);
887 NX842DEV_COUNTER_ATTR_RO(decomp_complete);
888 NX842DEV_COUNTER_ATTR_RO(decomp_failed);
889 NX842DEV_COUNTER_ATTR_RO(swdecomp);
890
891 static ssize_t nx842_timehist_show(struct device *,
892                 struct device_attribute *, char *);
893
894 static struct device_attribute dev_attr_comp_times = __ATTR(comp_times, 0444,
895                 nx842_timehist_show, NULL);
896 static struct device_attribute dev_attr_decomp_times = __ATTR(decomp_times,
897                 0444, nx842_timehist_show, NULL);
898
899 static ssize_t nx842_timehist_show(struct device *dev,
900                 struct device_attribute *attr, char *buf) {
901         char *p = buf;
902         struct nx842_devdata *local_devdata;
903         atomic64_t *times;
904         int bytes_remain = PAGE_SIZE;
905         int bytes;
906         int i;
907
908         rcu_read_lock();
909         local_devdata = rcu_dereference(devdata);
910         if (!local_devdata) {
911                 rcu_read_unlock();
912                 return 0;
913         }
914
915         if (attr == &dev_attr_comp_times)
916                 times = local_devdata->counters->comp_times;
917         else if (attr == &dev_attr_decomp_times)
918                 times = local_devdata->counters->decomp_times;
919         else {
920                 rcu_read_unlock();
921                 return 0;
922         }
923
924         for (i = 0; i < (NX842_HIST_SLOTS - 2); i++) {
925                 bytes = snprintf(p, bytes_remain, "%u-%uus:\t%ld\n",
926                                i ? (2<<(i-1)) : 0, (2<<i)-1,
927                                atomic64_read(&times[i]));
928                 bytes_remain -= bytes;
929                 p += bytes;
930         }
931         /* The last bucket holds everything over
932          * 2<<(NX842_HIST_SLOTS - 2) us */
933         bytes = snprintf(p, bytes_remain, "%uus - :\t%ld\n",
934                         2<<(NX842_HIST_SLOTS - 2),
935                         atomic64_read(&times[(NX842_HIST_SLOTS - 1)]));
936         p += bytes;
937
938         rcu_read_unlock();
939         return p - buf;
940 }
941
942 static struct attribute *nx842_sysfs_entries[] = {
943         &dev_attr_comp_complete.attr,
944         &dev_attr_comp_failed.attr,
945         &dev_attr_decomp_complete.attr,
946         &dev_attr_decomp_failed.attr,
947         &dev_attr_swdecomp.attr,
948         &dev_attr_comp_times.attr,
949         &dev_attr_decomp_times.attr,
950         NULL,
951 };
952
953 static struct attribute_group nx842_attribute_group = {
954         .name = NULL,           /* put in device directory */
955         .attrs = nx842_sysfs_entries,
956 };
957
958 static struct nx842_driver nx842_pseries_driver = {
959         .name =         KBUILD_MODNAME,
960         .owner =        THIS_MODULE,
961         .workmem_size = sizeof(struct nx842_workmem),
962         .constraints =  &nx842_pseries_constraints,
963         .compress =     nx842_pseries_compress,
964         .decompress =   nx842_pseries_decompress,
965 };
966
967 static int nx842_pseries_crypto_init(struct crypto_tfm *tfm)
968 {
969         return nx842_crypto_init(tfm, &nx842_pseries_driver);
970 }
971
972 static struct crypto_alg nx842_pseries_alg = {
973         .cra_name               = "842",
974         .cra_driver_name        = "842-nx",
975         .cra_priority           = 300,
976         .cra_flags              = CRYPTO_ALG_TYPE_COMPRESS,
977         .cra_ctxsize            = sizeof(struct nx842_crypto_ctx),
978         .cra_module             = THIS_MODULE,
979         .cra_init               = nx842_pseries_crypto_init,
980         .cra_exit               = nx842_crypto_exit,
981         .cra_u                  = { .compress = {
982         .coa_compress           = nx842_crypto_compress,
983         .coa_decompress         = nx842_crypto_decompress } }
984 };
985
986 static int nx842_probe(struct vio_dev *viodev,
987                        const struct vio_device_id *id)
988 {
989         struct nx842_devdata *old_devdata, *new_devdata = NULL;
990         unsigned long flags;
991         int ret = 0;
992
993         new_devdata = kzalloc(sizeof(*new_devdata), GFP_NOFS);
994         if (!new_devdata)
995                 return -ENOMEM;
996
997         new_devdata->counters = kzalloc(sizeof(*new_devdata->counters),
998                         GFP_NOFS);
999         if (!new_devdata->counters) {
1000                 kfree(new_devdata);
1001                 return -ENOMEM;
1002         }
1003
1004         spin_lock_irqsave(&devdata_mutex, flags);
1005         old_devdata = rcu_dereference_check(devdata,
1006                         lockdep_is_held(&devdata_mutex));
1007
1008         if (old_devdata && old_devdata->vdev != NULL) {
1009                 dev_err(&viodev->dev, "%s: Attempt to register more than one instance of the hardware\n", __func__);
1010                 ret = -1;
1011                 goto error_unlock;
1012         }
1013
1014         dev_set_drvdata(&viodev->dev, NULL);
1015
1016         new_devdata->vdev = viodev;
1017         new_devdata->dev = &viodev->dev;
1018         nx842_OF_set_defaults(new_devdata);
1019
1020         rcu_assign_pointer(devdata, new_devdata);
1021         spin_unlock_irqrestore(&devdata_mutex, flags);
1022         synchronize_rcu();
1023         kfree(old_devdata);
1024
1025         of_reconfig_notifier_register(&nx842_of_nb);
1026
1027         ret = nx842_OF_upd(NULL);
1028         if (ret)
1029                 goto error;
1030
1031         ret = crypto_register_alg(&nx842_pseries_alg);
1032         if (ret) {
1033                 dev_err(&viodev->dev, "could not register comp alg: %d\n", ret);
1034                 goto error;
1035         }
1036
1037         rcu_read_lock();
1038         dev_set_drvdata(&viodev->dev, rcu_dereference(devdata));
1039         rcu_read_unlock();
1040
1041         if (sysfs_create_group(&viodev->dev.kobj, &nx842_attribute_group)) {
1042                 dev_err(&viodev->dev, "could not create sysfs device attributes\n");
1043                 ret = -1;
1044                 goto error;
1045         }
1046
1047         return 0;
1048
1049 error_unlock:
1050         spin_unlock_irqrestore(&devdata_mutex, flags);
1051         if (new_devdata)
1052                 kfree(new_devdata->counters);
1053         kfree(new_devdata);
1054 error:
1055         return ret;
1056 }
1057
1058 static int nx842_remove(struct vio_dev *viodev)
1059 {
1060         struct nx842_devdata *old_devdata;
1061         unsigned long flags;
1062
1063         pr_info("Removing IBM Power 842 compression device\n");
1064         sysfs_remove_group(&viodev->dev.kobj, &nx842_attribute_group);
1065
1066         crypto_unregister_alg(&nx842_pseries_alg);
1067
1068         spin_lock_irqsave(&devdata_mutex, flags);
1069         old_devdata = rcu_dereference_check(devdata,
1070                         lockdep_is_held(&devdata_mutex));
1071         of_reconfig_notifier_unregister(&nx842_of_nb);
1072         RCU_INIT_POINTER(devdata, NULL);
1073         spin_unlock_irqrestore(&devdata_mutex, flags);
1074         synchronize_rcu();
1075         dev_set_drvdata(&viodev->dev, NULL);
1076         if (old_devdata)
1077                 kfree(old_devdata->counters);
1078         kfree(old_devdata);
1079
1080         return 0;
1081 }
1082
1083 static const struct vio_device_id nx842_vio_driver_ids[] = {
1084         {"ibm,compression-v1", "ibm,compression"},
1085         {"", ""},
1086 };
1087
1088 static struct vio_driver nx842_vio_driver = {
1089         .name = KBUILD_MODNAME,
1090         .probe = nx842_probe,
1091         .remove = nx842_remove,
1092         .get_desired_dma = nx842_get_desired_dma,
1093         .id_table = nx842_vio_driver_ids,
1094 };
1095
1096 static int __init nx842_pseries_init(void)
1097 {
1098         struct nx842_devdata *new_devdata;
1099         int ret;
1100
1101         if (!of_find_compatible_node(NULL, NULL, "ibm,compression"))
1102                 return -ENODEV;
1103
1104         RCU_INIT_POINTER(devdata, NULL);
1105         new_devdata = kzalloc(sizeof(*new_devdata), GFP_KERNEL);
1106         if (!new_devdata)
1107                 return -ENOMEM;
1108
1109         RCU_INIT_POINTER(devdata, new_devdata);
1110
1111         ret = vio_register_driver(&nx842_vio_driver);
1112         if (ret) {
1113                 pr_err("Could not register VIO driver %d\n", ret);
1114
1115                 kfree(new_devdata);
1116                 return ret;
1117         }
1118
1119         return 0;
1120 }
1121
1122 module_init(nx842_pseries_init);
1123
1124 static void __exit nx842_pseries_exit(void)
1125 {
1126         struct nx842_devdata *old_devdata;
1127         unsigned long flags;
1128
1129         crypto_unregister_alg(&nx842_pseries_alg);
1130
1131         spin_lock_irqsave(&devdata_mutex, flags);
1132         old_devdata = rcu_dereference_check(devdata,
1133                         lockdep_is_held(&devdata_mutex));
1134         RCU_INIT_POINTER(devdata, NULL);
1135         spin_unlock_irqrestore(&devdata_mutex, flags);
1136         synchronize_rcu();
1137         if (old_devdata && old_devdata->dev)
1138                 dev_set_drvdata(old_devdata->dev, NULL);
1139         kfree(old_devdata);
1140         vio_unregister_driver(&nx842_vio_driver);
1141 }
1142
1143 module_exit(nx842_pseries_exit);
1144