xref: /petsc/src/mat/impls/aij/seq/seqcusparse/aijcusparse.cu (revision c8378d121935c10cdcb3f94beda699f12b8f5d13)
19ae82921SPaul Mullowney /*
29ae82921SPaul Mullowney   Defines the basic matrix operations for the AIJ (compressed row)
3bc3f50f2SPaul Mullowney   matrix storage format using the CUSPARSE library,
49ae82921SPaul Mullowney */
5dced61a5SBarry Smith #define PETSC_SKIP_SPINLOCK
653800007SKarl Rupp #define PETSC_SKIP_CXX_COMPLEX_FIX
799acd6aaSStefano Zampini #define PETSC_SKIP_IMMINTRIN_H_CUDAWORKAROUND 1
89ae82921SPaul Mullowney 
93d13b8fdSMatthew G. Knepley #include <petscconf.h>
103d13b8fdSMatthew G. Knepley #include <../src/mat/impls/aij/seq/aij.h>          /*I "petscmat.h" I*/
11087f3262SPaul Mullowney #include <../src/mat/impls/sbaij/seq/sbaij.h>
123d13b8fdSMatthew G. Knepley #include <../src/vec/vec/impls/dvecimpl.h>
13af0996ceSBarry Smith #include <petsc/private/vecimpl.h>
149ae82921SPaul Mullowney #undef VecType
153d13b8fdSMatthew G. Knepley #include <../src/mat/impls/aij/seq/seqcusparse/cusparsematimpl.h>
16bc3f50f2SPaul Mullowney 
17e057df02SPaul Mullowney const char *const MatCUSPARSEStorageFormats[] = {"CSR","ELL","HYB","MatCUSPARSEStorageFormat","MAT_CUSPARSE_",0};
189ae82921SPaul Mullowney 
19087f3262SPaul Mullowney static PetscErrorCode MatICCFactorSymbolic_SeqAIJCUSPARSE(Mat,Mat,IS,const MatFactorInfo*);
20087f3262SPaul Mullowney static PetscErrorCode MatCholeskyFactorSymbolic_SeqAIJCUSPARSE(Mat,Mat,IS,const MatFactorInfo*);
21087f3262SPaul Mullowney static PetscErrorCode MatCholeskyFactorNumeric_SeqAIJCUSPARSE(Mat,Mat,const MatFactorInfo*);
22087f3262SPaul Mullowney 
236fa9248bSJed Brown static PetscErrorCode MatILUFactorSymbolic_SeqAIJCUSPARSE(Mat,Mat,IS,IS,const MatFactorInfo*);
246fa9248bSJed Brown static PetscErrorCode MatLUFactorSymbolic_SeqAIJCUSPARSE(Mat,Mat,IS,IS,const MatFactorInfo*);
256fa9248bSJed Brown static PetscErrorCode MatLUFactorNumeric_SeqAIJCUSPARSE(Mat,Mat,const MatFactorInfo*);
26087f3262SPaul Mullowney 
276fa9248bSJed Brown static PetscErrorCode MatSolve_SeqAIJCUSPARSE(Mat,Vec,Vec);
286fa9248bSJed Brown static PetscErrorCode MatSolve_SeqAIJCUSPARSE_NaturalOrdering(Mat,Vec,Vec);
296fa9248bSJed Brown static PetscErrorCode MatSolveTranspose_SeqAIJCUSPARSE(Mat,Vec,Vec);
306fa9248bSJed Brown static PetscErrorCode MatSolveTranspose_SeqAIJCUSPARSE_NaturalOrdering(Mat,Vec,Vec);
314416b707SBarry Smith static PetscErrorCode MatSetFromOptions_SeqAIJCUSPARSE(PetscOptionItems *PetscOptionsObject,Mat);
326fa9248bSJed Brown static PetscErrorCode MatMult_SeqAIJCUSPARSE(Mat,Vec,Vec);
336fa9248bSJed Brown static PetscErrorCode MatMultAdd_SeqAIJCUSPARSE(Mat,Vec,Vec,Vec);
346fa9248bSJed Brown static PetscErrorCode MatMultTranspose_SeqAIJCUSPARSE(Mat,Vec,Vec);
356fa9248bSJed Brown static PetscErrorCode MatMultTransposeAdd_SeqAIJCUSPARSE(Mat,Vec,Vec,Vec);
369ae82921SPaul Mullowney 
377f756511SDominic Meiser static PetscErrorCode CsrMatrix_Destroy(CsrMatrix**);
38470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSEMultStruct_Destroy(Mat_SeqAIJCUSPARSETriFactorStruct**);
39470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSEMultStruct_Destroy(Mat_SeqAIJCUSPARSEMultStruct**,MatCUSPARSEStorageFormat);
40ccdfe979SStefano Zampini static PetscErrorCode MatSeqAIJCUSPARSETriFactors_Reset(Mat_SeqAIJCUSPARSETriFactors**);
41470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSETriFactors_Destroy(Mat_SeqAIJCUSPARSETriFactors**);
42470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSE_Destroy(Mat_SeqAIJCUSPARSE**);
437f756511SDominic Meiser 
44b06137fdSPaul Mullowney PetscErrorCode MatCUSPARSESetStream(Mat A,const cudaStream_t stream)
45b06137fdSPaul Mullowney {
46b06137fdSPaul Mullowney   cusparseStatus_t   stat;
47b06137fdSPaul Mullowney   Mat_SeqAIJCUSPARSE *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
48b06137fdSPaul Mullowney 
49b06137fdSPaul Mullowney   PetscFunctionBegin;
50b06137fdSPaul Mullowney   cusparsestruct->stream = stream;
5157d48284SJunchao Zhang   stat = cusparseSetStream(cusparsestruct->handle,cusparsestruct->stream);CHKERRCUSPARSE(stat);
52b06137fdSPaul Mullowney   PetscFunctionReturn(0);
53b06137fdSPaul Mullowney }
54b06137fdSPaul Mullowney 
55b06137fdSPaul Mullowney PetscErrorCode MatCUSPARSESetHandle(Mat A,const cusparseHandle_t handle)
56b06137fdSPaul Mullowney {
57b06137fdSPaul Mullowney   cusparseStatus_t   stat;
58b06137fdSPaul Mullowney   Mat_SeqAIJCUSPARSE *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
59b06137fdSPaul Mullowney 
60b06137fdSPaul Mullowney   PetscFunctionBegin;
616b1cf21dSAlejandro Lamas Daviña   if (cusparsestruct->handle != handle) {
6216a2e217SAlejandro Lamas Daviña     if (cusparsestruct->handle) {
6357d48284SJunchao Zhang       stat = cusparseDestroy(cusparsestruct->handle);CHKERRCUSPARSE(stat);
6416a2e217SAlejandro Lamas Daviña     }
65b06137fdSPaul Mullowney     cusparsestruct->handle = handle;
666b1cf21dSAlejandro Lamas Daviña   }
6757d48284SJunchao Zhang   stat = cusparseSetPointerMode(cusparsestruct->handle, CUSPARSE_POINTER_MODE_DEVICE);CHKERRCUSPARSE(stat);
68b06137fdSPaul Mullowney   PetscFunctionReturn(0);
69b06137fdSPaul Mullowney }
70b06137fdSPaul Mullowney 
71b06137fdSPaul Mullowney PetscErrorCode MatCUSPARSEClearHandle(Mat A)
72b06137fdSPaul Mullowney {
73b06137fdSPaul Mullowney   Mat_SeqAIJCUSPARSE *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
74ccdfe979SStefano Zampini 
75b06137fdSPaul Mullowney   PetscFunctionBegin;
76ccdfe979SStefano Zampini   if (cusparsestruct->handle) cusparsestruct->handle = 0;
77b06137fdSPaul Mullowney   PetscFunctionReturn(0);
78b06137fdSPaul Mullowney }
79b06137fdSPaul Mullowney 
80ea799195SBarry Smith PetscErrorCode MatFactorGetSolverType_seqaij_cusparse(Mat A,MatSolverType *type)
819ae82921SPaul Mullowney {
829ae82921SPaul Mullowney   PetscFunctionBegin;
839ae82921SPaul Mullowney   *type = MATSOLVERCUSPARSE;
849ae82921SPaul Mullowney   PetscFunctionReturn(0);
859ae82921SPaul Mullowney }
869ae82921SPaul Mullowney 
87c708e6cdSJed Brown /*MC
88087f3262SPaul Mullowney   MATSOLVERCUSPARSE = "cusparse" - A matrix type providing triangular solvers for seq matrices
89087f3262SPaul Mullowney   on a single GPU of type, seqaijcusparse, aijcusparse, or seqaijcusp, aijcusp. Currently supported
90087f3262SPaul Mullowney   algorithms are ILU(k) and ICC(k). Typically, deeper factorizations (larger k) results in poorer
91087f3262SPaul Mullowney   performance in the triangular solves. Full LU, and Cholesky decompositions can be solved through the
92087f3262SPaul Mullowney   CUSPARSE triangular solve algorithm. However, the performance can be quite poor and thus these
93087f3262SPaul Mullowney   algorithms are not recommended. This class does NOT support direct solver operations.
94c708e6cdSJed Brown 
959ae82921SPaul Mullowney   Level: beginner
96c708e6cdSJed Brown 
973ca39a21SBarry Smith .seealso: PCFactorSetMatSolverType(), MatSolverType, MatCreateSeqAIJCUSPARSE(), MATAIJCUSPARSE, MatCreateAIJCUSPARSE(), MatCUSPARSESetFormat(), MatCUSPARSEStorageFormat, MatCUSPARSEFormatOperation
98c708e6cdSJed Brown M*/
999ae82921SPaul Mullowney 
10042c9c57cSBarry Smith PETSC_EXTERN PetscErrorCode MatGetFactor_seqaijcusparse_cusparse(Mat A,MatFactorType ftype,Mat *B)
1019ae82921SPaul Mullowney {
1029ae82921SPaul Mullowney   PetscErrorCode ierr;
103bc3f50f2SPaul Mullowney   PetscInt       n = A->rmap->n;
1049ae82921SPaul Mullowney 
1059ae82921SPaul Mullowney   PetscFunctionBegin;
106bc3f50f2SPaul Mullowney   ierr = MatCreate(PetscObjectComm((PetscObject)A),B);CHKERRQ(ierr);
107404133a2SPaul Mullowney   (*B)->factortype = ftype;
108bc3f50f2SPaul Mullowney   ierr = MatSetSizes(*B,n,n,n,n);CHKERRQ(ierr);
1099ae82921SPaul Mullowney   ierr = MatSetType(*B,MATSEQAIJCUSPARSE);CHKERRQ(ierr);
1102205254eSKarl Rupp 
111087f3262SPaul Mullowney   if (ftype == MAT_FACTOR_LU || ftype == MAT_FACTOR_ILU || ftype == MAT_FACTOR_ILUDT) {
11233d57670SJed Brown     ierr = MatSetBlockSizesFromMats(*B,A,A);CHKERRQ(ierr);
1139ae82921SPaul Mullowney     (*B)->ops->ilufactorsymbolic = MatILUFactorSymbolic_SeqAIJCUSPARSE;
1149ae82921SPaul Mullowney     (*B)->ops->lufactorsymbolic  = MatLUFactorSymbolic_SeqAIJCUSPARSE;
115087f3262SPaul Mullowney   } else if (ftype == MAT_FACTOR_CHOLESKY || ftype == MAT_FACTOR_ICC) {
116087f3262SPaul Mullowney     (*B)->ops->iccfactorsymbolic      = MatICCFactorSymbolic_SeqAIJCUSPARSE;
117087f3262SPaul Mullowney     (*B)->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_SeqAIJCUSPARSE;
1189ae82921SPaul Mullowney   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Factor type not supported for CUSPARSE Matrix Types");
119bc3f50f2SPaul Mullowney 
120fa03d054SJed Brown   ierr = MatSeqAIJSetPreallocation(*B,MAT_SKIP_ALLOCATION,NULL);CHKERRQ(ierr);
1213ca39a21SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)(*B),"MatFactorGetSolverType_C",MatFactorGetSolverType_seqaij_cusparse);CHKERRQ(ierr);
1229ae82921SPaul Mullowney   PetscFunctionReturn(0);
1239ae82921SPaul Mullowney }
1249ae82921SPaul Mullowney 
125bc3f50f2SPaul Mullowney PETSC_INTERN PetscErrorCode MatCUSPARSESetFormat_SeqAIJCUSPARSE(Mat A,MatCUSPARSEFormatOperation op,MatCUSPARSEStorageFormat format)
126ca45077fSPaul Mullowney {
127aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
1286e111a19SKarl Rupp 
129ca45077fSPaul Mullowney   PetscFunctionBegin;
130ca45077fSPaul Mullowney   switch (op) {
131e057df02SPaul Mullowney   case MAT_CUSPARSE_MULT:
132aa372e3fSPaul Mullowney     cusparsestruct->format = format;
133ca45077fSPaul Mullowney     break;
134e057df02SPaul Mullowney   case MAT_CUSPARSE_ALL:
135aa372e3fSPaul Mullowney     cusparsestruct->format = format;
136ca45077fSPaul Mullowney     break;
137ca45077fSPaul Mullowney   default:
13836d62e41SPaul Mullowney     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"unsupported operation %d for MatCUSPARSEFormatOperation. MAT_CUSPARSE_MULT and MAT_CUSPARSE_ALL are currently supported.",op);
139ca45077fSPaul Mullowney   }
140ca45077fSPaul Mullowney   PetscFunctionReturn(0);
141ca45077fSPaul Mullowney }
1429ae82921SPaul Mullowney 
143e057df02SPaul Mullowney /*@
144e057df02SPaul Mullowney    MatCUSPARSESetFormat - Sets the storage format of CUSPARSE matrices for a particular
145e057df02SPaul Mullowney    operation. Only the MatMult operation can use different GPU storage formats
146aa372e3fSPaul Mullowney    for MPIAIJCUSPARSE matrices.
147e057df02SPaul Mullowney    Not Collective
148e057df02SPaul Mullowney 
149e057df02SPaul Mullowney    Input Parameters:
1508468deeeSKarl Rupp +  A - Matrix of type SEQAIJCUSPARSE
15136d62e41SPaul Mullowney .  op - MatCUSPARSEFormatOperation. SEQAIJCUSPARSE matrices support MAT_CUSPARSE_MULT and MAT_CUSPARSE_ALL. MPIAIJCUSPARSE matrices support MAT_CUSPARSE_MULT_DIAG, MAT_CUSPARSE_MULT_OFFDIAG, and MAT_CUSPARSE_ALL.
1522692e278SPaul Mullowney -  format - MatCUSPARSEStorageFormat (one of MAT_CUSPARSE_CSR, MAT_CUSPARSE_ELL, MAT_CUSPARSE_HYB. The latter two require CUDA 4.2)
153e057df02SPaul Mullowney 
154e057df02SPaul Mullowney    Output Parameter:
155e057df02SPaul Mullowney 
156e057df02SPaul Mullowney    Level: intermediate
157e057df02SPaul Mullowney 
1588468deeeSKarl Rupp .seealso: MatCUSPARSEStorageFormat, MatCUSPARSEFormatOperation
159e057df02SPaul Mullowney @*/
160e057df02SPaul Mullowney PetscErrorCode MatCUSPARSESetFormat(Mat A,MatCUSPARSEFormatOperation op,MatCUSPARSEStorageFormat format)
161e057df02SPaul Mullowney {
162e057df02SPaul Mullowney   PetscErrorCode ierr;
1636e111a19SKarl Rupp 
164e057df02SPaul Mullowney   PetscFunctionBegin;
165e057df02SPaul Mullowney   PetscValidHeaderSpecific(A, MAT_CLASSID,1);
166e057df02SPaul Mullowney   ierr = PetscTryMethod(A,"MatCUSPARSESetFormat_C",(Mat,MatCUSPARSEFormatOperation,MatCUSPARSEStorageFormat),(A,op,format));CHKERRQ(ierr);
167e057df02SPaul Mullowney   PetscFunctionReturn(0);
168e057df02SPaul Mullowney }
169e057df02SPaul Mullowney 
1704416b707SBarry Smith static PetscErrorCode MatSetFromOptions_SeqAIJCUSPARSE(PetscOptionItems *PetscOptionsObject,Mat A)
1719ae82921SPaul Mullowney {
1729ae82921SPaul Mullowney   PetscErrorCode           ierr;
173e057df02SPaul Mullowney   MatCUSPARSEStorageFormat format;
1749ae82921SPaul Mullowney   PetscBool                flg;
175a183c035SDominic Meiser   Mat_SeqAIJCUSPARSE       *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
1766e111a19SKarl Rupp 
1779ae82921SPaul Mullowney   PetscFunctionBegin;
178e55864a3SBarry Smith   ierr = PetscOptionsHead(PetscOptionsObject,"SeqAIJCUSPARSE options");CHKERRQ(ierr);
1799ae82921SPaul Mullowney   if (A->factortype==MAT_FACTOR_NONE) {
180e057df02SPaul Mullowney     ierr = PetscOptionsEnum("-mat_cusparse_mult_storage_format","sets storage format of (seq)aijcusparse gpu matrices for SpMV",
181a183c035SDominic Meiser                             "MatCUSPARSESetFormat",MatCUSPARSEStorageFormats,(PetscEnum)cusparsestruct->format,(PetscEnum*)&format,&flg);CHKERRQ(ierr);
182e057df02SPaul Mullowney     if (flg) {
183e057df02SPaul Mullowney       ierr = MatCUSPARSESetFormat(A,MAT_CUSPARSE_MULT,format);CHKERRQ(ierr);
184045c96e1SPaul Mullowney     }
1859ae82921SPaul Mullowney   }
1864c87dfd4SPaul Mullowney   ierr = PetscOptionsEnum("-mat_cusparse_storage_format","sets storage format of (seq)aijcusparse gpu matrices for SpMV and TriSolve",
187a183c035SDominic Meiser                           "MatCUSPARSESetFormat",MatCUSPARSEStorageFormats,(PetscEnum)cusparsestruct->format,(PetscEnum*)&format,&flg);CHKERRQ(ierr);
1884c87dfd4SPaul Mullowney   if (flg) {
1894c87dfd4SPaul Mullowney     ierr = MatCUSPARSESetFormat(A,MAT_CUSPARSE_ALL,format);CHKERRQ(ierr);
1904c87dfd4SPaul Mullowney   }
1910af67c1bSStefano Zampini   ierr = PetscOptionsTail();CHKERRQ(ierr);
1929ae82921SPaul Mullowney   PetscFunctionReturn(0);
1939ae82921SPaul Mullowney }
1949ae82921SPaul Mullowney 
1956fa9248bSJed Brown static PetscErrorCode MatILUFactorSymbolic_SeqAIJCUSPARSE(Mat B,Mat A,IS isrow,IS iscol,const MatFactorInfo *info)
1969ae82921SPaul Mullowney {
1979ae82921SPaul Mullowney   PetscErrorCode ierr;
1989ae82921SPaul Mullowney 
1999ae82921SPaul Mullowney   PetscFunctionBegin;
2009ae82921SPaul Mullowney   ierr = MatILUFactorSymbolic_SeqAIJ(B,A,isrow,iscol,info);CHKERRQ(ierr);
2019ae82921SPaul Mullowney   B->ops->lufactornumeric = MatLUFactorNumeric_SeqAIJCUSPARSE;
2029ae82921SPaul Mullowney   PetscFunctionReturn(0);
2039ae82921SPaul Mullowney }
2049ae82921SPaul Mullowney 
2056fa9248bSJed Brown static PetscErrorCode MatLUFactorSymbolic_SeqAIJCUSPARSE(Mat B,Mat A,IS isrow,IS iscol,const MatFactorInfo *info)
2069ae82921SPaul Mullowney {
2079ae82921SPaul Mullowney   PetscErrorCode ierr;
2089ae82921SPaul Mullowney 
2099ae82921SPaul Mullowney   PetscFunctionBegin;
2109ae82921SPaul Mullowney   ierr = MatLUFactorSymbolic_SeqAIJ(B,A,isrow,iscol,info);CHKERRQ(ierr);
2119ae82921SPaul Mullowney   B->ops->lufactornumeric = MatLUFactorNumeric_SeqAIJCUSPARSE;
2129ae82921SPaul Mullowney   PetscFunctionReturn(0);
2139ae82921SPaul Mullowney }
2149ae82921SPaul Mullowney 
215087f3262SPaul Mullowney static PetscErrorCode MatICCFactorSymbolic_SeqAIJCUSPARSE(Mat B,Mat A,IS perm,const MatFactorInfo *info)
216087f3262SPaul Mullowney {
217087f3262SPaul Mullowney   PetscErrorCode ierr;
218087f3262SPaul Mullowney 
219087f3262SPaul Mullowney   PetscFunctionBegin;
220087f3262SPaul Mullowney   ierr = MatICCFactorSymbolic_SeqAIJ(B,A,perm,info);CHKERRQ(ierr);
221087f3262SPaul Mullowney   B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqAIJCUSPARSE;
222087f3262SPaul Mullowney   PetscFunctionReturn(0);
223087f3262SPaul Mullowney }
224087f3262SPaul Mullowney 
225087f3262SPaul Mullowney static PetscErrorCode MatCholeskyFactorSymbolic_SeqAIJCUSPARSE(Mat B,Mat A,IS perm,const MatFactorInfo *info)
226087f3262SPaul Mullowney {
227087f3262SPaul Mullowney   PetscErrorCode ierr;
228087f3262SPaul Mullowney 
229087f3262SPaul Mullowney   PetscFunctionBegin;
230087f3262SPaul Mullowney   ierr = MatCholeskyFactorSymbolic_SeqAIJ(B,A,perm,info);CHKERRQ(ierr);
231087f3262SPaul Mullowney   B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqAIJCUSPARSE;
232087f3262SPaul Mullowney   PetscFunctionReturn(0);
233087f3262SPaul Mullowney }
234087f3262SPaul Mullowney 
235087f3262SPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEBuildILULowerTriMatrix(Mat A)
2369ae82921SPaul Mullowney {
2379ae82921SPaul Mullowney   Mat_SeqAIJ                        *a = (Mat_SeqAIJ*)A->data;
2389ae82921SPaul Mullowney   PetscInt                          n = A->rmap->n;
2399ae82921SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
240aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
2419ae82921SPaul Mullowney   cusparseStatus_t                  stat;
2429ae82921SPaul Mullowney   const PetscInt                    *ai = a->i,*aj = a->j,*vi;
2439ae82921SPaul Mullowney   const MatScalar                   *aa = a->a,*v;
2449ae82921SPaul Mullowney   PetscInt                          *AiLo, *AjLo;
2459ae82921SPaul Mullowney   PetscScalar                       *AALo;
2469ae82921SPaul Mullowney   PetscInt                          i,nz, nzLower, offset, rowOffset;
247b175d8bbSPaul Mullowney   PetscErrorCode                    ierr;
24857d48284SJunchao Zhang   cudaError_t                       cerr;
2499ae82921SPaul Mullowney 
2509ae82921SPaul Mullowney   PetscFunctionBegin;
251cf00fe3bSKarl Rupp   if (!n) PetscFunctionReturn(0);
252c70f7ee4SJunchao Zhang   if (A->offloadmask == PETSC_OFFLOAD_UNALLOCATED || A->offloadmask == PETSC_OFFLOAD_CPU) {
2539ae82921SPaul Mullowney     try {
2549ae82921SPaul Mullowney       /* first figure out the number of nonzeros in the lower triangular matrix including 1's on the diagonal. */
2559ae82921SPaul Mullowney       nzLower=n+ai[n]-ai[1];
2569ae82921SPaul Mullowney 
2579ae82921SPaul Mullowney       /* Allocate Space for the lower triangular matrix */
25857d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AiLo, (n+1)*sizeof(PetscInt));CHKERRCUDA(cerr);
25957d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AjLo, nzLower*sizeof(PetscInt));CHKERRCUDA(cerr);
26057d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AALo, nzLower*sizeof(PetscScalar));CHKERRCUDA(cerr);
2619ae82921SPaul Mullowney 
2629ae82921SPaul Mullowney       /* Fill the lower triangular matrix */
2639ae82921SPaul Mullowney       AiLo[0]  = (PetscInt) 0;
2649ae82921SPaul Mullowney       AiLo[n]  = nzLower;
2659ae82921SPaul Mullowney       AjLo[0]  = (PetscInt) 0;
2669ae82921SPaul Mullowney       AALo[0]  = (MatScalar) 1.0;
2679ae82921SPaul Mullowney       v        = aa;
2689ae82921SPaul Mullowney       vi       = aj;
2699ae82921SPaul Mullowney       offset   = 1;
2709ae82921SPaul Mullowney       rowOffset= 1;
2719ae82921SPaul Mullowney       for (i=1; i<n; i++) {
2729ae82921SPaul Mullowney         nz = ai[i+1] - ai[i];
273e057df02SPaul Mullowney         /* additional 1 for the term on the diagonal */
2749ae82921SPaul Mullowney         AiLo[i]    = rowOffset;
2759ae82921SPaul Mullowney         rowOffset += nz+1;
2769ae82921SPaul Mullowney 
277580bdb30SBarry Smith         ierr = PetscArraycpy(&(AjLo[offset]), vi, nz);CHKERRQ(ierr);
278580bdb30SBarry Smith         ierr = PetscArraycpy(&(AALo[offset]), v, nz);CHKERRQ(ierr);
2799ae82921SPaul Mullowney 
2809ae82921SPaul Mullowney         offset      += nz;
2819ae82921SPaul Mullowney         AjLo[offset] = (PetscInt) i;
2829ae82921SPaul Mullowney         AALo[offset] = (MatScalar) 1.0;
2839ae82921SPaul Mullowney         offset      += 1;
2849ae82921SPaul Mullowney 
2859ae82921SPaul Mullowney         v  += nz;
2869ae82921SPaul Mullowney         vi += nz;
2879ae82921SPaul Mullowney       }
2882205254eSKarl Rupp 
289aa372e3fSPaul Mullowney       /* allocate space for the triangular factor information */
290aa372e3fSPaul Mullowney       loTriFactor = new Mat_SeqAIJCUSPARSETriFactorStruct;
2912205254eSKarl Rupp 
292aa372e3fSPaul Mullowney       /* Create the matrix description */
29357d48284SJunchao Zhang       stat = cusparseCreateMatDescr(&loTriFactor->descr);CHKERRCUSPARSE(stat);
29457d48284SJunchao Zhang       stat = cusparseSetMatIndexBase(loTriFactor->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
29557d48284SJunchao Zhang       stat = cusparseSetMatType(loTriFactor->descr, CUSPARSE_MATRIX_TYPE_TRIANGULAR);CHKERRCUSPARSE(stat);
29657d48284SJunchao Zhang       stat = cusparseSetMatFillMode(loTriFactor->descr, CUSPARSE_FILL_MODE_LOWER);CHKERRCUSPARSE(stat);
29757d48284SJunchao Zhang       stat = cusparseSetMatDiagType(loTriFactor->descr, CUSPARSE_DIAG_TYPE_UNIT);CHKERRCUSPARSE(stat);
298aa372e3fSPaul Mullowney 
299aa372e3fSPaul Mullowney       /* Create the solve analysis information */
30057d48284SJunchao Zhang       stat = cusparseCreateSolveAnalysisInfo(&loTriFactor->solveInfo);CHKERRCUSPARSE(stat);
301aa372e3fSPaul Mullowney 
302aa372e3fSPaul Mullowney       /* set the operation */
303aa372e3fSPaul Mullowney       loTriFactor->solveOp = CUSPARSE_OPERATION_NON_TRANSPOSE;
304aa372e3fSPaul Mullowney 
305aa372e3fSPaul Mullowney       /* set the matrix */
306aa372e3fSPaul Mullowney       loTriFactor->csrMat = new CsrMatrix;
307aa372e3fSPaul Mullowney       loTriFactor->csrMat->num_rows = n;
308aa372e3fSPaul Mullowney       loTriFactor->csrMat->num_cols = n;
309aa372e3fSPaul Mullowney       loTriFactor->csrMat->num_entries = nzLower;
310aa372e3fSPaul Mullowney 
311aa372e3fSPaul Mullowney       loTriFactor->csrMat->row_offsets = new THRUSTINTARRAY32(n+1);
312aa372e3fSPaul Mullowney       loTriFactor->csrMat->row_offsets->assign(AiLo, AiLo+n+1);
313aa372e3fSPaul Mullowney 
314aa372e3fSPaul Mullowney       loTriFactor->csrMat->column_indices = new THRUSTINTARRAY32(nzLower);
315aa372e3fSPaul Mullowney       loTriFactor->csrMat->column_indices->assign(AjLo, AjLo+nzLower);
316aa372e3fSPaul Mullowney 
317aa372e3fSPaul Mullowney       loTriFactor->csrMat->values = new THRUSTARRAY(nzLower);
318aa372e3fSPaul Mullowney       loTriFactor->csrMat->values->assign(AALo, AALo+nzLower);
319aa372e3fSPaul Mullowney 
320aa372e3fSPaul Mullowney       /* perform the solve analysis */
321aa372e3fSPaul Mullowney       stat = cusparse_analysis(cusparseTriFactors->handle, loTriFactor->solveOp,
322aa372e3fSPaul Mullowney                                loTriFactor->csrMat->num_rows, loTriFactor->csrMat->num_entries, loTriFactor->descr,
323aa372e3fSPaul Mullowney                                loTriFactor->csrMat->values->data().get(), loTriFactor->csrMat->row_offsets->data().get(),
32457d48284SJunchao Zhang                                loTriFactor->csrMat->column_indices->data().get(), loTriFactor->solveInfo);CHKERRCUSPARSE(stat);
325aa372e3fSPaul Mullowney 
326aa372e3fSPaul Mullowney       /* assign the pointer. Is this really necessary? */
327aa372e3fSPaul Mullowney       ((Mat_SeqAIJCUSPARSETriFactors*)A->spptr)->loTriFactorPtr = loTriFactor;
3282205254eSKarl Rupp 
32957d48284SJunchao Zhang       cerr = cudaFreeHost(AiLo);CHKERRCUDA(cerr);
33057d48284SJunchao Zhang       cerr = cudaFreeHost(AjLo);CHKERRCUDA(cerr);
33157d48284SJunchao Zhang       cerr = cudaFreeHost(AALo);CHKERRCUDA(cerr);
3324863603aSSatish Balay       ierr = PetscLogCpuToGpu((n+1+nzLower)*sizeof(int)+nzLower*sizeof(PetscScalar));CHKERRQ(ierr);
3339ae82921SPaul Mullowney     } catch(char *ex) {
3349ae82921SPaul Mullowney       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
3359ae82921SPaul Mullowney     }
3369ae82921SPaul Mullowney   }
3379ae82921SPaul Mullowney   PetscFunctionReturn(0);
3389ae82921SPaul Mullowney }
3399ae82921SPaul Mullowney 
340087f3262SPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEBuildILUUpperTriMatrix(Mat A)
3419ae82921SPaul Mullowney {
3429ae82921SPaul Mullowney   Mat_SeqAIJ                        *a = (Mat_SeqAIJ*)A->data;
3439ae82921SPaul Mullowney   PetscInt                          n = A->rmap->n;
3449ae82921SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
345aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
3469ae82921SPaul Mullowney   cusparseStatus_t                  stat;
3479ae82921SPaul Mullowney   const PetscInt                    *aj = a->j,*adiag = a->diag,*vi;
3489ae82921SPaul Mullowney   const MatScalar                   *aa = a->a,*v;
3499ae82921SPaul Mullowney   PetscInt                          *AiUp, *AjUp;
3509ae82921SPaul Mullowney   PetscScalar                       *AAUp;
3519ae82921SPaul Mullowney   PetscInt                          i,nz, nzUpper, offset;
3529ae82921SPaul Mullowney   PetscErrorCode                    ierr;
35357d48284SJunchao Zhang   cudaError_t                       cerr;
3549ae82921SPaul Mullowney 
3559ae82921SPaul Mullowney   PetscFunctionBegin;
356cf00fe3bSKarl Rupp   if (!n) PetscFunctionReturn(0);
357c70f7ee4SJunchao Zhang   if (A->offloadmask == PETSC_OFFLOAD_UNALLOCATED || A->offloadmask == PETSC_OFFLOAD_CPU) {
3589ae82921SPaul Mullowney     try {
3599ae82921SPaul Mullowney       /* next, figure out the number of nonzeros in the upper triangular matrix. */
3609ae82921SPaul Mullowney       nzUpper = adiag[0]-adiag[n];
3619ae82921SPaul Mullowney 
3629ae82921SPaul Mullowney       /* Allocate Space for the upper triangular matrix */
36357d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AiUp, (n+1)*sizeof(PetscInt));CHKERRCUDA(cerr);
36457d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AjUp, nzUpper*sizeof(PetscInt));CHKERRCUDA(cerr);
36557d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AAUp, nzUpper*sizeof(PetscScalar));CHKERRCUDA(cerr);
3669ae82921SPaul Mullowney 
3679ae82921SPaul Mullowney       /* Fill the upper triangular matrix */
3689ae82921SPaul Mullowney       AiUp[0]=(PetscInt) 0;
3699ae82921SPaul Mullowney       AiUp[n]=nzUpper;
3709ae82921SPaul Mullowney       offset = nzUpper;
3719ae82921SPaul Mullowney       for (i=n-1; i>=0; i--) {
3729ae82921SPaul Mullowney         v  = aa + adiag[i+1] + 1;
3739ae82921SPaul Mullowney         vi = aj + adiag[i+1] + 1;
3749ae82921SPaul Mullowney 
375e057df02SPaul Mullowney         /* number of elements NOT on the diagonal */
3769ae82921SPaul Mullowney         nz = adiag[i] - adiag[i+1]-1;
3779ae82921SPaul Mullowney 
378e057df02SPaul Mullowney         /* decrement the offset */
3799ae82921SPaul Mullowney         offset -= (nz+1);
3809ae82921SPaul Mullowney 
381e057df02SPaul Mullowney         /* first, set the diagonal elements */
3829ae82921SPaul Mullowney         AjUp[offset] = (PetscInt) i;
38309f51544SAlejandro Lamas Daviña         AAUp[offset] = (MatScalar)1./v[nz];
3849ae82921SPaul Mullowney         AiUp[i]      = AiUp[i+1] - (nz+1);
3859ae82921SPaul Mullowney 
386580bdb30SBarry Smith         ierr = PetscArraycpy(&(AjUp[offset+1]), vi, nz);CHKERRQ(ierr);
387580bdb30SBarry Smith         ierr = PetscArraycpy(&(AAUp[offset+1]), v, nz);CHKERRQ(ierr);
3889ae82921SPaul Mullowney       }
3892205254eSKarl Rupp 
390aa372e3fSPaul Mullowney       /* allocate space for the triangular factor information */
391aa372e3fSPaul Mullowney       upTriFactor = new Mat_SeqAIJCUSPARSETriFactorStruct;
3922205254eSKarl Rupp 
393aa372e3fSPaul Mullowney       /* Create the matrix description */
39457d48284SJunchao Zhang       stat = cusparseCreateMatDescr(&upTriFactor->descr);CHKERRCUSPARSE(stat);
39557d48284SJunchao Zhang       stat = cusparseSetMatIndexBase(upTriFactor->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
39657d48284SJunchao Zhang       stat = cusparseSetMatType(upTriFactor->descr, CUSPARSE_MATRIX_TYPE_TRIANGULAR);CHKERRCUSPARSE(stat);
39757d48284SJunchao Zhang       stat = cusparseSetMatFillMode(upTriFactor->descr, CUSPARSE_FILL_MODE_UPPER);CHKERRCUSPARSE(stat);
39857d48284SJunchao Zhang       stat = cusparseSetMatDiagType(upTriFactor->descr, CUSPARSE_DIAG_TYPE_NON_UNIT);CHKERRCUSPARSE(stat);
399aa372e3fSPaul Mullowney 
400aa372e3fSPaul Mullowney       /* Create the solve analysis information */
40157d48284SJunchao Zhang       stat = cusparseCreateSolveAnalysisInfo(&upTriFactor->solveInfo);CHKERRCUSPARSE(stat);
402aa372e3fSPaul Mullowney 
403aa372e3fSPaul Mullowney       /* set the operation */
404aa372e3fSPaul Mullowney       upTriFactor->solveOp = CUSPARSE_OPERATION_NON_TRANSPOSE;
405aa372e3fSPaul Mullowney 
406aa372e3fSPaul Mullowney       /* set the matrix */
407aa372e3fSPaul Mullowney       upTriFactor->csrMat = new CsrMatrix;
408aa372e3fSPaul Mullowney       upTriFactor->csrMat->num_rows = n;
409aa372e3fSPaul Mullowney       upTriFactor->csrMat->num_cols = n;
410aa372e3fSPaul Mullowney       upTriFactor->csrMat->num_entries = nzUpper;
411aa372e3fSPaul Mullowney 
412aa372e3fSPaul Mullowney       upTriFactor->csrMat->row_offsets = new THRUSTINTARRAY32(n+1);
413aa372e3fSPaul Mullowney       upTriFactor->csrMat->row_offsets->assign(AiUp, AiUp+n+1);
414aa372e3fSPaul Mullowney 
415aa372e3fSPaul Mullowney       upTriFactor->csrMat->column_indices = new THRUSTINTARRAY32(nzUpper);
416aa372e3fSPaul Mullowney       upTriFactor->csrMat->column_indices->assign(AjUp, AjUp+nzUpper);
417aa372e3fSPaul Mullowney 
418aa372e3fSPaul Mullowney       upTriFactor->csrMat->values = new THRUSTARRAY(nzUpper);
419aa372e3fSPaul Mullowney       upTriFactor->csrMat->values->assign(AAUp, AAUp+nzUpper);
420aa372e3fSPaul Mullowney 
421aa372e3fSPaul Mullowney       /* perform the solve analysis */
422aa372e3fSPaul Mullowney       stat = cusparse_analysis(cusparseTriFactors->handle, upTriFactor->solveOp,
423aa372e3fSPaul Mullowney                                upTriFactor->csrMat->num_rows, upTriFactor->csrMat->num_entries, upTriFactor->descr,
424aa372e3fSPaul Mullowney                                upTriFactor->csrMat->values->data().get(), upTriFactor->csrMat->row_offsets->data().get(),
42557d48284SJunchao Zhang                                upTriFactor->csrMat->column_indices->data().get(), upTriFactor->solveInfo);CHKERRCUSPARSE(stat);
426aa372e3fSPaul Mullowney 
427aa372e3fSPaul Mullowney       /* assign the pointer. Is this really necessary? */
428aa372e3fSPaul Mullowney       ((Mat_SeqAIJCUSPARSETriFactors*)A->spptr)->upTriFactorPtr = upTriFactor;
4292205254eSKarl Rupp 
43057d48284SJunchao Zhang       cerr = cudaFreeHost(AiUp);CHKERRCUDA(cerr);
43157d48284SJunchao Zhang       cerr = cudaFreeHost(AjUp);CHKERRCUDA(cerr);
43257d48284SJunchao Zhang       cerr = cudaFreeHost(AAUp);CHKERRCUDA(cerr);
4334863603aSSatish Balay       ierr = PetscLogCpuToGpu((n+1+nzUpper)*sizeof(int)+nzUpper*sizeof(PetscScalar));CHKERRQ(ierr);
4349ae82921SPaul Mullowney     } catch(char *ex) {
4359ae82921SPaul Mullowney       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
4369ae82921SPaul Mullowney     }
4379ae82921SPaul Mullowney   }
4389ae82921SPaul Mullowney   PetscFunctionReturn(0);
4399ae82921SPaul Mullowney }
4409ae82921SPaul Mullowney 
441087f3262SPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEILUAnalysisAndCopyToGPU(Mat A)
4429ae82921SPaul Mullowney {
4439ae82921SPaul Mullowney   PetscErrorCode               ierr;
4449ae82921SPaul Mullowney   Mat_SeqAIJ                   *a                  = (Mat_SeqAIJ*)A->data;
4459ae82921SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
4469ae82921SPaul Mullowney   IS                           isrow = a->row,iscol = a->icol;
4479ae82921SPaul Mullowney   PetscBool                    row_identity,col_identity;
4489ae82921SPaul Mullowney   const PetscInt               *r,*c;
4499ae82921SPaul Mullowney   PetscInt                     n = A->rmap->n;
4509ae82921SPaul Mullowney 
4519ae82921SPaul Mullowney   PetscFunctionBegin;
452ccdfe979SStefano Zampini   ierr = MatSeqAIJCUSPARSETriFactors_Reset(&cusparseTriFactors);CHKERRQ(ierr);
453087f3262SPaul Mullowney   ierr = MatSeqAIJCUSPARSEBuildILULowerTriMatrix(A);CHKERRQ(ierr);
454087f3262SPaul Mullowney   ierr = MatSeqAIJCUSPARSEBuildILUUpperTriMatrix(A);CHKERRQ(ierr);
4552205254eSKarl Rupp 
456e65717acSKarl Rupp   cusparseTriFactors->workVector = new THRUSTARRAY(n);
457aa372e3fSPaul Mullowney   cusparseTriFactors->nnz=a->nz;
4589ae82921SPaul Mullowney 
459c70f7ee4SJunchao Zhang   A->offloadmask = PETSC_OFFLOAD_BOTH;
460e057df02SPaul Mullowney   /* lower triangular indices */
4619ae82921SPaul Mullowney   ierr = ISGetIndices(isrow,&r);CHKERRQ(ierr);
4629ae82921SPaul Mullowney   ierr = ISIdentity(isrow,&row_identity);CHKERRQ(ierr);
4632205254eSKarl Rupp   if (!row_identity) {
464aa372e3fSPaul Mullowney     cusparseTriFactors->rpermIndices = new THRUSTINTARRAY(n);
465aa372e3fSPaul Mullowney     cusparseTriFactors->rpermIndices->assign(r, r+n);
4662205254eSKarl Rupp   }
4679ae82921SPaul Mullowney   ierr = ISRestoreIndices(isrow,&r);CHKERRQ(ierr);
4689ae82921SPaul Mullowney 
469e057df02SPaul Mullowney   /* upper triangular indices */
4709ae82921SPaul Mullowney   ierr = ISGetIndices(iscol,&c);CHKERRQ(ierr);
4719ae82921SPaul Mullowney   ierr = ISIdentity(iscol,&col_identity);CHKERRQ(ierr);
4722205254eSKarl Rupp   if (!col_identity) {
473aa372e3fSPaul Mullowney     cusparseTriFactors->cpermIndices = new THRUSTINTARRAY(n);
474aa372e3fSPaul Mullowney     cusparseTriFactors->cpermIndices->assign(c, c+n);
4752205254eSKarl Rupp   }
4764863603aSSatish Balay 
4774863603aSSatish Balay   if (!row_identity && !col_identity) {
4784863603aSSatish Balay     ierr = PetscLogCpuToGpu(2*n*sizeof(PetscInt));CHKERRQ(ierr);
4794863603aSSatish Balay   } else if(!row_identity) {
4804863603aSSatish Balay     ierr = PetscLogCpuToGpu(n*sizeof(PetscInt));CHKERRQ(ierr);
4814863603aSSatish Balay   } else if(!col_identity) {
4824863603aSSatish Balay     ierr = PetscLogCpuToGpu(n*sizeof(PetscInt));CHKERRQ(ierr);
4834863603aSSatish Balay   }
4844863603aSSatish Balay 
4859ae82921SPaul Mullowney   ierr = ISRestoreIndices(iscol,&c);CHKERRQ(ierr);
4869ae82921SPaul Mullowney   PetscFunctionReturn(0);
4879ae82921SPaul Mullowney }
4889ae82921SPaul Mullowney 
489087f3262SPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEBuildICCTriMatrices(Mat A)
490087f3262SPaul Mullowney {
491087f3262SPaul Mullowney   Mat_SeqAIJ                        *a = (Mat_SeqAIJ*)A->data;
492087f3262SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
493aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
494aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
495087f3262SPaul Mullowney   cusparseStatus_t                  stat;
496087f3262SPaul Mullowney   PetscErrorCode                    ierr;
49757d48284SJunchao Zhang   cudaError_t                       cerr;
498087f3262SPaul Mullowney   PetscInt                          *AiUp, *AjUp;
499087f3262SPaul Mullowney   PetscScalar                       *AAUp;
500087f3262SPaul Mullowney   PetscScalar                       *AALo;
501087f3262SPaul Mullowney   PetscInt                          nzUpper = a->nz,n = A->rmap->n,i,offset,nz,j;
502087f3262SPaul Mullowney   Mat_SeqSBAIJ                      *b = (Mat_SeqSBAIJ*)A->data;
503087f3262SPaul Mullowney   const PetscInt                    *ai = b->i,*aj = b->j,*vj;
504087f3262SPaul Mullowney   const MatScalar                   *aa = b->a,*v;
505087f3262SPaul Mullowney 
506087f3262SPaul Mullowney   PetscFunctionBegin;
507cf00fe3bSKarl Rupp   if (!n) PetscFunctionReturn(0);
508c70f7ee4SJunchao Zhang   if (A->offloadmask == PETSC_OFFLOAD_UNALLOCATED || A->offloadmask == PETSC_OFFLOAD_CPU) {
509087f3262SPaul Mullowney     try {
510087f3262SPaul Mullowney       /* Allocate Space for the upper triangular matrix */
51157d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AiUp, (n+1)*sizeof(PetscInt));CHKERRCUDA(cerr);
51257d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AjUp, nzUpper*sizeof(PetscInt));CHKERRCUDA(cerr);
51357d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AAUp, nzUpper*sizeof(PetscScalar));CHKERRCUDA(cerr);
51457d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AALo, nzUpper*sizeof(PetscScalar));CHKERRCUDA(cerr);
515087f3262SPaul Mullowney 
516087f3262SPaul Mullowney       /* Fill the upper triangular matrix */
517087f3262SPaul Mullowney       AiUp[0]=(PetscInt) 0;
518087f3262SPaul Mullowney       AiUp[n]=nzUpper;
519087f3262SPaul Mullowney       offset = 0;
520087f3262SPaul Mullowney       for (i=0; i<n; i++) {
521087f3262SPaul Mullowney         /* set the pointers */
522087f3262SPaul Mullowney         v  = aa + ai[i];
523087f3262SPaul Mullowney         vj = aj + ai[i];
524087f3262SPaul Mullowney         nz = ai[i+1] - ai[i] - 1; /* exclude diag[i] */
525087f3262SPaul Mullowney 
526087f3262SPaul Mullowney         /* first, set the diagonal elements */
527087f3262SPaul Mullowney         AjUp[offset] = (PetscInt) i;
52809f51544SAlejandro Lamas Daviña         AAUp[offset] = (MatScalar)1.0/v[nz];
529087f3262SPaul Mullowney         AiUp[i]      = offset;
53009f51544SAlejandro Lamas Daviña         AALo[offset] = (MatScalar)1.0/v[nz];
531087f3262SPaul Mullowney 
532087f3262SPaul Mullowney         offset+=1;
533087f3262SPaul Mullowney         if (nz>0) {
534f22e0265SBarry Smith           ierr = PetscArraycpy(&(AjUp[offset]), vj, nz);CHKERRQ(ierr);
535580bdb30SBarry Smith           ierr = PetscArraycpy(&(AAUp[offset]), v, nz);CHKERRQ(ierr);
536087f3262SPaul Mullowney           for (j=offset; j<offset+nz; j++) {
537087f3262SPaul Mullowney             AAUp[j] = -AAUp[j];
538087f3262SPaul Mullowney             AALo[j] = AAUp[j]/v[nz];
539087f3262SPaul Mullowney           }
540087f3262SPaul Mullowney           offset+=nz;
541087f3262SPaul Mullowney         }
542087f3262SPaul Mullowney       }
543087f3262SPaul Mullowney 
544aa372e3fSPaul Mullowney       /* allocate space for the triangular factor information */
545aa372e3fSPaul Mullowney       upTriFactor = new Mat_SeqAIJCUSPARSETriFactorStruct;
546087f3262SPaul Mullowney 
547aa372e3fSPaul Mullowney       /* Create the matrix description */
54857d48284SJunchao Zhang       stat = cusparseCreateMatDescr(&upTriFactor->descr);CHKERRCUSPARSE(stat);
54957d48284SJunchao Zhang       stat = cusparseSetMatIndexBase(upTriFactor->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
55057d48284SJunchao Zhang       stat = cusparseSetMatType(upTriFactor->descr, CUSPARSE_MATRIX_TYPE_TRIANGULAR);CHKERRCUSPARSE(stat);
55157d48284SJunchao Zhang       stat = cusparseSetMatFillMode(upTriFactor->descr, CUSPARSE_FILL_MODE_UPPER);CHKERRCUSPARSE(stat);
55257d48284SJunchao Zhang       stat = cusparseSetMatDiagType(upTriFactor->descr, CUSPARSE_DIAG_TYPE_UNIT);CHKERRCUSPARSE(stat);
553087f3262SPaul Mullowney 
554aa372e3fSPaul Mullowney       /* Create the solve analysis information */
55557d48284SJunchao Zhang       stat = cusparseCreateSolveAnalysisInfo(&upTriFactor->solveInfo);CHKERRCUSPARSE(stat);
556aa372e3fSPaul Mullowney 
557aa372e3fSPaul Mullowney       /* set the operation */
558aa372e3fSPaul Mullowney       upTriFactor->solveOp = CUSPARSE_OPERATION_NON_TRANSPOSE;
559aa372e3fSPaul Mullowney 
560aa372e3fSPaul Mullowney       /* set the matrix */
561aa372e3fSPaul Mullowney       upTriFactor->csrMat = new CsrMatrix;
562aa372e3fSPaul Mullowney       upTriFactor->csrMat->num_rows = A->rmap->n;
563aa372e3fSPaul Mullowney       upTriFactor->csrMat->num_cols = A->cmap->n;
564aa372e3fSPaul Mullowney       upTriFactor->csrMat->num_entries = a->nz;
565aa372e3fSPaul Mullowney 
566aa372e3fSPaul Mullowney       upTriFactor->csrMat->row_offsets = new THRUSTINTARRAY32(A->rmap->n+1);
567aa372e3fSPaul Mullowney       upTriFactor->csrMat->row_offsets->assign(AiUp, AiUp+A->rmap->n+1);
568aa372e3fSPaul Mullowney 
569aa372e3fSPaul Mullowney       upTriFactor->csrMat->column_indices = new THRUSTINTARRAY32(a->nz);
570aa372e3fSPaul Mullowney       upTriFactor->csrMat->column_indices->assign(AjUp, AjUp+a->nz);
571aa372e3fSPaul Mullowney 
572aa372e3fSPaul Mullowney       upTriFactor->csrMat->values = new THRUSTARRAY(a->nz);
573aa372e3fSPaul Mullowney       upTriFactor->csrMat->values->assign(AAUp, AAUp+a->nz);
574aa372e3fSPaul Mullowney 
575aa372e3fSPaul Mullowney       /* perform the solve analysis */
576aa372e3fSPaul Mullowney       stat = cusparse_analysis(cusparseTriFactors->handle, upTriFactor->solveOp,
577aa372e3fSPaul Mullowney                                upTriFactor->csrMat->num_rows, upTriFactor->csrMat->num_entries, upTriFactor->descr,
578aa372e3fSPaul Mullowney                                upTriFactor->csrMat->values->data().get(), upTriFactor->csrMat->row_offsets->data().get(),
57957d48284SJunchao Zhang                                upTriFactor->csrMat->column_indices->data().get(), upTriFactor->solveInfo);CHKERRCUSPARSE(stat);
580aa372e3fSPaul Mullowney 
581aa372e3fSPaul Mullowney       /* assign the pointer. Is this really necessary? */
582aa372e3fSPaul Mullowney       ((Mat_SeqAIJCUSPARSETriFactors*)A->spptr)->upTriFactorPtr = upTriFactor;
583aa372e3fSPaul Mullowney 
584aa372e3fSPaul Mullowney       /* allocate space for the triangular factor information */
585aa372e3fSPaul Mullowney       loTriFactor = new Mat_SeqAIJCUSPARSETriFactorStruct;
586aa372e3fSPaul Mullowney 
587aa372e3fSPaul Mullowney       /* Create the matrix description */
58857d48284SJunchao Zhang       stat = cusparseCreateMatDescr(&loTriFactor->descr);CHKERRCUSPARSE(stat);
58957d48284SJunchao Zhang       stat = cusparseSetMatIndexBase(loTriFactor->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
59057d48284SJunchao Zhang       stat = cusparseSetMatType(loTriFactor->descr, CUSPARSE_MATRIX_TYPE_TRIANGULAR);CHKERRCUSPARSE(stat);
59157d48284SJunchao Zhang       stat = cusparseSetMatFillMode(loTriFactor->descr, CUSPARSE_FILL_MODE_UPPER);CHKERRCUSPARSE(stat);
59257d48284SJunchao Zhang       stat = cusparseSetMatDiagType(loTriFactor->descr, CUSPARSE_DIAG_TYPE_NON_UNIT);CHKERRCUSPARSE(stat);
593aa372e3fSPaul Mullowney 
594aa372e3fSPaul Mullowney       /* Create the solve analysis information */
59557d48284SJunchao Zhang       stat = cusparseCreateSolveAnalysisInfo(&loTriFactor->solveInfo);CHKERRCUSPARSE(stat);
596aa372e3fSPaul Mullowney 
597aa372e3fSPaul Mullowney       /* set the operation */
598aa372e3fSPaul Mullowney       loTriFactor->solveOp = CUSPARSE_OPERATION_TRANSPOSE;
599aa372e3fSPaul Mullowney 
600aa372e3fSPaul Mullowney       /* set the matrix */
601aa372e3fSPaul Mullowney       loTriFactor->csrMat = new CsrMatrix;
602aa372e3fSPaul Mullowney       loTriFactor->csrMat->num_rows = A->rmap->n;
603aa372e3fSPaul Mullowney       loTriFactor->csrMat->num_cols = A->cmap->n;
604aa372e3fSPaul Mullowney       loTriFactor->csrMat->num_entries = a->nz;
605aa372e3fSPaul Mullowney 
606aa372e3fSPaul Mullowney       loTriFactor->csrMat->row_offsets = new THRUSTINTARRAY32(A->rmap->n+1);
607aa372e3fSPaul Mullowney       loTriFactor->csrMat->row_offsets->assign(AiUp, AiUp+A->rmap->n+1);
608aa372e3fSPaul Mullowney 
609aa372e3fSPaul Mullowney       loTriFactor->csrMat->column_indices = new THRUSTINTARRAY32(a->nz);
610aa372e3fSPaul Mullowney       loTriFactor->csrMat->column_indices->assign(AjUp, AjUp+a->nz);
611aa372e3fSPaul Mullowney 
612aa372e3fSPaul Mullowney       loTriFactor->csrMat->values = new THRUSTARRAY(a->nz);
613aa372e3fSPaul Mullowney       loTriFactor->csrMat->values->assign(AALo, AALo+a->nz);
6144863603aSSatish Balay       ierr = PetscLogCpuToGpu(2*(((A->rmap->n+1)+(a->nz))*sizeof(int)+(a->nz)*sizeof(PetscScalar)));CHKERRQ(ierr);
615aa372e3fSPaul Mullowney 
616aa372e3fSPaul Mullowney       /* perform the solve analysis */
617aa372e3fSPaul Mullowney       stat = cusparse_analysis(cusparseTriFactors->handle, loTriFactor->solveOp,
618aa372e3fSPaul Mullowney                                loTriFactor->csrMat->num_rows, loTriFactor->csrMat->num_entries, loTriFactor->descr,
619aa372e3fSPaul Mullowney                                loTriFactor->csrMat->values->data().get(), loTriFactor->csrMat->row_offsets->data().get(),
62057d48284SJunchao Zhang                                loTriFactor->csrMat->column_indices->data().get(), loTriFactor->solveInfo);CHKERRCUSPARSE(stat);
621aa372e3fSPaul Mullowney 
622aa372e3fSPaul Mullowney       /* assign the pointer. Is this really necessary? */
623aa372e3fSPaul Mullowney       ((Mat_SeqAIJCUSPARSETriFactors*)A->spptr)->loTriFactorPtr = loTriFactor;
624087f3262SPaul Mullowney 
625c70f7ee4SJunchao Zhang       A->offloadmask = PETSC_OFFLOAD_BOTH;
62657d48284SJunchao Zhang       cerr = cudaFreeHost(AiUp);CHKERRCUDA(cerr);
62757d48284SJunchao Zhang       cerr = cudaFreeHost(AjUp);CHKERRCUDA(cerr);
62857d48284SJunchao Zhang       cerr = cudaFreeHost(AAUp);CHKERRCUDA(cerr);
62957d48284SJunchao Zhang       cerr = cudaFreeHost(AALo);CHKERRCUDA(cerr);
630087f3262SPaul Mullowney     } catch(char *ex) {
631087f3262SPaul Mullowney       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
632087f3262SPaul Mullowney     }
633087f3262SPaul Mullowney   }
634087f3262SPaul Mullowney   PetscFunctionReturn(0);
635087f3262SPaul Mullowney }
636087f3262SPaul Mullowney 
637087f3262SPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEICCAnalysisAndCopyToGPU(Mat A)
6389ae82921SPaul Mullowney {
6399ae82921SPaul Mullowney   PetscErrorCode               ierr;
640087f3262SPaul Mullowney   Mat_SeqAIJ                   *a                  = (Mat_SeqAIJ*)A->data;
641087f3262SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
642087f3262SPaul Mullowney   IS                           ip = a->row;
643087f3262SPaul Mullowney   const PetscInt               *rip;
644087f3262SPaul Mullowney   PetscBool                    perm_identity;
645087f3262SPaul Mullowney   PetscInt                     n = A->rmap->n;
646087f3262SPaul Mullowney 
647087f3262SPaul Mullowney   PetscFunctionBegin;
648ccdfe979SStefano Zampini   ierr = MatSeqAIJCUSPARSETriFactors_Reset(&cusparseTriFactors);CHKERRQ(ierr);
649087f3262SPaul Mullowney   ierr = MatSeqAIJCUSPARSEBuildICCTriMatrices(A);CHKERRQ(ierr);
650e65717acSKarl Rupp   cusparseTriFactors->workVector = new THRUSTARRAY(n);
651aa372e3fSPaul Mullowney   cusparseTriFactors->nnz=(a->nz-n)*2 + n;
652aa372e3fSPaul Mullowney 
653087f3262SPaul Mullowney   /* lower triangular indices */
654087f3262SPaul Mullowney   ierr = ISGetIndices(ip,&rip);CHKERRQ(ierr);
655087f3262SPaul Mullowney   ierr = ISIdentity(ip,&perm_identity);CHKERRQ(ierr);
656087f3262SPaul Mullowney   if (!perm_identity) {
6574e4bbfaaSStefano Zampini     IS             iip;
6584e4bbfaaSStefano Zampini     const PetscInt *irip;
6594e4bbfaaSStefano Zampini 
6604e4bbfaaSStefano Zampini     ierr = ISInvertPermutation(ip,PETSC_DECIDE,&iip);CHKERRQ(ierr);
6614e4bbfaaSStefano Zampini     ierr = ISGetIndices(iip,&irip);CHKERRQ(ierr);
662aa372e3fSPaul Mullowney     cusparseTriFactors->rpermIndices = new THRUSTINTARRAY(n);
663aa372e3fSPaul Mullowney     cusparseTriFactors->rpermIndices->assign(rip, rip+n);
664aa372e3fSPaul Mullowney     cusparseTriFactors->cpermIndices = new THRUSTINTARRAY(n);
6654e4bbfaaSStefano Zampini     cusparseTriFactors->cpermIndices->assign(irip, irip+n);
6664e4bbfaaSStefano Zampini     ierr = ISRestoreIndices(iip,&irip);CHKERRQ(ierr);
6674e4bbfaaSStefano Zampini     ierr = ISDestroy(&iip);CHKERRQ(ierr);
6684863603aSSatish Balay     ierr = PetscLogCpuToGpu(2*n*sizeof(PetscInt));CHKERRQ(ierr);
669087f3262SPaul Mullowney   }
670087f3262SPaul Mullowney   ierr = ISRestoreIndices(ip,&rip);CHKERRQ(ierr);
671087f3262SPaul Mullowney   PetscFunctionReturn(0);
672087f3262SPaul Mullowney }
673087f3262SPaul Mullowney 
6746fa9248bSJed Brown static PetscErrorCode MatLUFactorNumeric_SeqAIJCUSPARSE(Mat B,Mat A,const MatFactorInfo *info)
6759ae82921SPaul Mullowney {
6769ae82921SPaul Mullowney   Mat_SeqAIJ     *b = (Mat_SeqAIJ*)B->data;
6779ae82921SPaul Mullowney   IS             isrow = b->row,iscol = b->col;
6789ae82921SPaul Mullowney   PetscBool      row_identity,col_identity;
679b175d8bbSPaul Mullowney   PetscErrorCode ierr;
6809ae82921SPaul Mullowney 
6819ae82921SPaul Mullowney   PetscFunctionBegin;
6829ae82921SPaul Mullowney   ierr = MatLUFactorNumeric_SeqAIJ(B,A,info);CHKERRQ(ierr);
683ccdfe979SStefano Zampini   B->offloadmask = PETSC_OFFLOAD_CPU;
684e057df02SPaul Mullowney   /* determine which version of MatSolve needs to be used. */
6859ae82921SPaul Mullowney   ierr = ISIdentity(isrow,&row_identity);CHKERRQ(ierr);
6869ae82921SPaul Mullowney   ierr = ISIdentity(iscol,&col_identity);CHKERRQ(ierr);
687bda325fcSPaul Mullowney   if (row_identity && col_identity) {
688bda325fcSPaul Mullowney     B->ops->solve = MatSolve_SeqAIJCUSPARSE_NaturalOrdering;
689bda325fcSPaul Mullowney     B->ops->solvetranspose = MatSolveTranspose_SeqAIJCUSPARSE_NaturalOrdering;
6904e4bbfaaSStefano Zampini     B->ops->matsolve = NULL;
6914e4bbfaaSStefano Zampini     B->ops->matsolvetranspose = NULL;
692bda325fcSPaul Mullowney   } else {
693bda325fcSPaul Mullowney     B->ops->solve = MatSolve_SeqAIJCUSPARSE;
694bda325fcSPaul Mullowney     B->ops->solvetranspose = MatSolveTranspose_SeqAIJCUSPARSE;
6954e4bbfaaSStefano Zampini     B->ops->matsolve = NULL;
6964e4bbfaaSStefano Zampini     B->ops->matsolvetranspose = NULL;
697bda325fcSPaul Mullowney   }
6988dc1d2a3SPaul Mullowney 
699e057df02SPaul Mullowney   /* get the triangular factors */
700087f3262SPaul Mullowney   ierr = MatSeqAIJCUSPARSEILUAnalysisAndCopyToGPU(B);CHKERRQ(ierr);
7019ae82921SPaul Mullowney   PetscFunctionReturn(0);
7029ae82921SPaul Mullowney }
7039ae82921SPaul Mullowney 
704087f3262SPaul Mullowney static PetscErrorCode MatCholeskyFactorNumeric_SeqAIJCUSPARSE(Mat B,Mat A,const MatFactorInfo *info)
705087f3262SPaul Mullowney {
706087f3262SPaul Mullowney   Mat_SeqAIJ     *b = (Mat_SeqAIJ*)B->data;
707087f3262SPaul Mullowney   IS             ip = b->row;
708087f3262SPaul Mullowney   PetscBool      perm_identity;
709b175d8bbSPaul Mullowney   PetscErrorCode ierr;
710087f3262SPaul Mullowney 
711087f3262SPaul Mullowney   PetscFunctionBegin;
712087f3262SPaul Mullowney   ierr = MatCholeskyFactorNumeric_SeqAIJ(B,A,info);CHKERRQ(ierr);
713ccdfe979SStefano Zampini   B->offloadmask = PETSC_OFFLOAD_CPU;
714087f3262SPaul Mullowney   /* determine which version of MatSolve needs to be used. */
715087f3262SPaul Mullowney   ierr = ISIdentity(ip,&perm_identity);CHKERRQ(ierr);
716087f3262SPaul Mullowney   if (perm_identity) {
717087f3262SPaul Mullowney     B->ops->solve = MatSolve_SeqAIJCUSPARSE_NaturalOrdering;
718087f3262SPaul Mullowney     B->ops->solvetranspose = MatSolveTranspose_SeqAIJCUSPARSE_NaturalOrdering;
7194e4bbfaaSStefano Zampini     B->ops->matsolve = NULL;
7204e4bbfaaSStefano Zampini     B->ops->matsolvetranspose = NULL;
721087f3262SPaul Mullowney   } else {
722087f3262SPaul Mullowney     B->ops->solve = MatSolve_SeqAIJCUSPARSE;
723087f3262SPaul Mullowney     B->ops->solvetranspose = MatSolveTranspose_SeqAIJCUSPARSE;
7244e4bbfaaSStefano Zampini     B->ops->matsolve = NULL;
7254e4bbfaaSStefano Zampini     B->ops->matsolvetranspose = NULL;
726087f3262SPaul Mullowney   }
727087f3262SPaul Mullowney 
728087f3262SPaul Mullowney   /* get the triangular factors */
729087f3262SPaul Mullowney   ierr = MatSeqAIJCUSPARSEICCAnalysisAndCopyToGPU(B);CHKERRQ(ierr);
730087f3262SPaul Mullowney   PetscFunctionReturn(0);
731087f3262SPaul Mullowney }
7329ae82921SPaul Mullowney 
733b175d8bbSPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEAnalyzeTransposeForSolve(Mat A)
734bda325fcSPaul Mullowney {
735bda325fcSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
736aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
737aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
738aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
739aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
740bda325fcSPaul Mullowney   cusparseStatus_t                  stat;
741aa372e3fSPaul Mullowney   cusparseIndexBase_t               indexBase;
742aa372e3fSPaul Mullowney   cusparseMatrixType_t              matrixType;
743aa372e3fSPaul Mullowney   cusparseFillMode_t                fillMode;
744aa372e3fSPaul Mullowney   cusparseDiagType_t                diagType;
745b175d8bbSPaul Mullowney 
746bda325fcSPaul Mullowney   PetscFunctionBegin;
747bda325fcSPaul Mullowney 
748aa372e3fSPaul Mullowney   /*********************************************/
749aa372e3fSPaul Mullowney   /* Now the Transpose of the Lower Tri Factor */
750aa372e3fSPaul Mullowney   /*********************************************/
751aa372e3fSPaul Mullowney 
752aa372e3fSPaul Mullowney   /* allocate space for the transpose of the lower triangular factor */
753aa372e3fSPaul Mullowney   loTriFactorT = new Mat_SeqAIJCUSPARSETriFactorStruct;
754aa372e3fSPaul Mullowney 
755aa372e3fSPaul Mullowney   /* set the matrix descriptors of the lower triangular factor */
756aa372e3fSPaul Mullowney   matrixType = cusparseGetMatType(loTriFactor->descr);
757aa372e3fSPaul Mullowney   indexBase = cusparseGetMatIndexBase(loTriFactor->descr);
758aa372e3fSPaul Mullowney   fillMode = cusparseGetMatFillMode(loTriFactor->descr)==CUSPARSE_FILL_MODE_UPPER ?
759aa372e3fSPaul Mullowney     CUSPARSE_FILL_MODE_LOWER : CUSPARSE_FILL_MODE_UPPER;
760aa372e3fSPaul Mullowney   diagType = cusparseGetMatDiagType(loTriFactor->descr);
761aa372e3fSPaul Mullowney 
762aa372e3fSPaul Mullowney   /* Create the matrix description */
76357d48284SJunchao Zhang   stat = cusparseCreateMatDescr(&loTriFactorT->descr);CHKERRCUSPARSE(stat);
76457d48284SJunchao Zhang   stat = cusparseSetMatIndexBase(loTriFactorT->descr, indexBase);CHKERRCUSPARSE(stat);
76557d48284SJunchao Zhang   stat = cusparseSetMatType(loTriFactorT->descr, matrixType);CHKERRCUSPARSE(stat);
76657d48284SJunchao Zhang   stat = cusparseSetMatFillMode(loTriFactorT->descr, fillMode);CHKERRCUSPARSE(stat);
76757d48284SJunchao Zhang   stat = cusparseSetMatDiagType(loTriFactorT->descr, diagType);CHKERRCUSPARSE(stat);
768aa372e3fSPaul Mullowney 
769aa372e3fSPaul Mullowney   /* Create the solve analysis information */
77057d48284SJunchao Zhang   stat = cusparseCreateSolveAnalysisInfo(&loTriFactorT->solveInfo);CHKERRCUSPARSE(stat);
771aa372e3fSPaul Mullowney 
772aa372e3fSPaul Mullowney   /* set the operation */
773aa372e3fSPaul Mullowney   loTriFactorT->solveOp = CUSPARSE_OPERATION_NON_TRANSPOSE;
774aa372e3fSPaul Mullowney 
775aa372e3fSPaul Mullowney   /* allocate GPU space for the CSC of the lower triangular factor*/
776aa372e3fSPaul Mullowney   loTriFactorT->csrMat = new CsrMatrix;
777aa372e3fSPaul Mullowney   loTriFactorT->csrMat->num_rows = loTriFactor->csrMat->num_rows;
778aa372e3fSPaul Mullowney   loTriFactorT->csrMat->num_cols = loTriFactor->csrMat->num_cols;
779aa372e3fSPaul Mullowney   loTriFactorT->csrMat->num_entries = loTriFactor->csrMat->num_entries;
780aa372e3fSPaul Mullowney   loTriFactorT->csrMat->row_offsets = new THRUSTINTARRAY32(loTriFactor->csrMat->num_rows+1);
781aa372e3fSPaul Mullowney   loTriFactorT->csrMat->column_indices = new THRUSTINTARRAY32(loTriFactor->csrMat->num_entries);
782aa372e3fSPaul Mullowney   loTriFactorT->csrMat->values = new THRUSTARRAY(loTriFactor->csrMat->num_entries);
783aa372e3fSPaul Mullowney 
784aa372e3fSPaul Mullowney   /* compute the transpose of the lower triangular factor, i.e. the CSC */
785aa372e3fSPaul Mullowney   stat = cusparse_csr2csc(cusparseTriFactors->handle, loTriFactor->csrMat->num_rows,
786aa372e3fSPaul Mullowney                           loTriFactor->csrMat->num_cols, loTriFactor->csrMat->num_entries,
787aa372e3fSPaul Mullowney                           loTriFactor->csrMat->values->data().get(),
788aa372e3fSPaul Mullowney                           loTriFactor->csrMat->row_offsets->data().get(),
789aa372e3fSPaul Mullowney                           loTriFactor->csrMat->column_indices->data().get(),
790aa372e3fSPaul Mullowney                           loTriFactorT->csrMat->values->data().get(),
791aa372e3fSPaul Mullowney                           loTriFactorT->csrMat->column_indices->data().get(),
792aa372e3fSPaul Mullowney                           loTriFactorT->csrMat->row_offsets->data().get(),
79357d48284SJunchao Zhang                           CUSPARSE_ACTION_NUMERIC, indexBase);CHKERRCUSPARSE(stat);
794aa372e3fSPaul Mullowney 
795aa372e3fSPaul Mullowney   /* perform the solve analysis on the transposed matrix */
796aa372e3fSPaul Mullowney   stat = cusparse_analysis(cusparseTriFactors->handle, loTriFactorT->solveOp,
797aa372e3fSPaul Mullowney                            loTriFactorT->csrMat->num_rows, loTriFactorT->csrMat->num_entries,
798aa372e3fSPaul Mullowney                            loTriFactorT->descr, loTriFactorT->csrMat->values->data().get(),
799aa372e3fSPaul Mullowney                            loTriFactorT->csrMat->row_offsets->data().get(), loTriFactorT->csrMat->column_indices->data().get(),
80057d48284SJunchao Zhang                            loTriFactorT->solveInfo);CHKERRCUSPARSE(stat);
801aa372e3fSPaul Mullowney 
802aa372e3fSPaul Mullowney   /* assign the pointer. Is this really necessary? */
803aa372e3fSPaul Mullowney   ((Mat_SeqAIJCUSPARSETriFactors*)A->spptr)->loTriFactorPtrTranspose = loTriFactorT;
804aa372e3fSPaul Mullowney 
805aa372e3fSPaul Mullowney   /*********************************************/
806aa372e3fSPaul Mullowney   /* Now the Transpose of the Upper Tri Factor */
807aa372e3fSPaul Mullowney   /*********************************************/
808aa372e3fSPaul Mullowney 
809aa372e3fSPaul Mullowney   /* allocate space for the transpose of the upper triangular factor */
810aa372e3fSPaul Mullowney   upTriFactorT = new Mat_SeqAIJCUSPARSETriFactorStruct;
811aa372e3fSPaul Mullowney 
812aa372e3fSPaul Mullowney   /* set the matrix descriptors of the upper triangular factor */
813aa372e3fSPaul Mullowney   matrixType = cusparseGetMatType(upTriFactor->descr);
814aa372e3fSPaul Mullowney   indexBase = cusparseGetMatIndexBase(upTriFactor->descr);
815aa372e3fSPaul Mullowney   fillMode = cusparseGetMatFillMode(upTriFactor->descr)==CUSPARSE_FILL_MODE_UPPER ?
816aa372e3fSPaul Mullowney     CUSPARSE_FILL_MODE_LOWER : CUSPARSE_FILL_MODE_UPPER;
817aa372e3fSPaul Mullowney   diagType = cusparseGetMatDiagType(upTriFactor->descr);
818aa372e3fSPaul Mullowney 
819aa372e3fSPaul Mullowney   /* Create the matrix description */
82057d48284SJunchao Zhang   stat = cusparseCreateMatDescr(&upTriFactorT->descr);CHKERRCUSPARSE(stat);
82157d48284SJunchao Zhang   stat = cusparseSetMatIndexBase(upTriFactorT->descr, indexBase);CHKERRCUSPARSE(stat);
82257d48284SJunchao Zhang   stat = cusparseSetMatType(upTriFactorT->descr, matrixType);CHKERRCUSPARSE(stat);
82357d48284SJunchao Zhang   stat = cusparseSetMatFillMode(upTriFactorT->descr, fillMode);CHKERRCUSPARSE(stat);
82457d48284SJunchao Zhang   stat = cusparseSetMatDiagType(upTriFactorT->descr, diagType);CHKERRCUSPARSE(stat);
825aa372e3fSPaul Mullowney 
826aa372e3fSPaul Mullowney   /* Create the solve analysis information */
82757d48284SJunchao Zhang   stat = cusparseCreateSolveAnalysisInfo(&upTriFactorT->solveInfo);CHKERRCUSPARSE(stat);
828aa372e3fSPaul Mullowney 
829aa372e3fSPaul Mullowney   /* set the operation */
830aa372e3fSPaul Mullowney   upTriFactorT->solveOp = CUSPARSE_OPERATION_NON_TRANSPOSE;
831aa372e3fSPaul Mullowney 
832aa372e3fSPaul Mullowney   /* allocate GPU space for the CSC of the upper triangular factor*/
833aa372e3fSPaul Mullowney   upTriFactorT->csrMat = new CsrMatrix;
834aa372e3fSPaul Mullowney   upTriFactorT->csrMat->num_rows = upTriFactor->csrMat->num_rows;
835aa372e3fSPaul Mullowney   upTriFactorT->csrMat->num_cols = upTriFactor->csrMat->num_cols;
836aa372e3fSPaul Mullowney   upTriFactorT->csrMat->num_entries = upTriFactor->csrMat->num_entries;
837aa372e3fSPaul Mullowney   upTriFactorT->csrMat->row_offsets = new THRUSTINTARRAY32(upTriFactor->csrMat->num_rows+1);
838aa372e3fSPaul Mullowney   upTriFactorT->csrMat->column_indices = new THRUSTINTARRAY32(upTriFactor->csrMat->num_entries);
839aa372e3fSPaul Mullowney   upTriFactorT->csrMat->values = new THRUSTARRAY(upTriFactor->csrMat->num_entries);
840aa372e3fSPaul Mullowney 
841aa372e3fSPaul Mullowney   /* compute the transpose of the upper triangular factor, i.e. the CSC */
842aa372e3fSPaul Mullowney   stat = cusparse_csr2csc(cusparseTriFactors->handle, upTriFactor->csrMat->num_rows,
843aa372e3fSPaul Mullowney                           upTriFactor->csrMat->num_cols, upTriFactor->csrMat->num_entries,
844aa372e3fSPaul Mullowney                           upTriFactor->csrMat->values->data().get(),
845aa372e3fSPaul Mullowney                           upTriFactor->csrMat->row_offsets->data().get(),
846aa372e3fSPaul Mullowney                           upTriFactor->csrMat->column_indices->data().get(),
847aa372e3fSPaul Mullowney                           upTriFactorT->csrMat->values->data().get(),
848aa372e3fSPaul Mullowney                           upTriFactorT->csrMat->column_indices->data().get(),
849aa372e3fSPaul Mullowney                           upTriFactorT->csrMat->row_offsets->data().get(),
85057d48284SJunchao Zhang                           CUSPARSE_ACTION_NUMERIC, indexBase);CHKERRCUSPARSE(stat);
851aa372e3fSPaul Mullowney 
852aa372e3fSPaul Mullowney   /* perform the solve analysis on the transposed matrix */
853aa372e3fSPaul Mullowney   stat = cusparse_analysis(cusparseTriFactors->handle, upTriFactorT->solveOp,
854aa372e3fSPaul Mullowney                            upTriFactorT->csrMat->num_rows, upTriFactorT->csrMat->num_entries,
855aa372e3fSPaul Mullowney                            upTriFactorT->descr, upTriFactorT->csrMat->values->data().get(),
856aa372e3fSPaul Mullowney                            upTriFactorT->csrMat->row_offsets->data().get(), upTriFactorT->csrMat->column_indices->data().get(),
85757d48284SJunchao Zhang                            upTriFactorT->solveInfo);CHKERRCUSPARSE(stat);
858aa372e3fSPaul Mullowney 
859aa372e3fSPaul Mullowney   /* assign the pointer. Is this really necessary? */
860aa372e3fSPaul Mullowney   ((Mat_SeqAIJCUSPARSETriFactors*)A->spptr)->upTriFactorPtrTranspose = upTriFactorT;
861bda325fcSPaul Mullowney   PetscFunctionReturn(0);
862bda325fcSPaul Mullowney }
863bda325fcSPaul Mullowney 
864b175d8bbSPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEGenerateTransposeForMult(Mat A)
865bda325fcSPaul Mullowney {
866aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
867aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSEMultStruct *matstruct = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->mat;
868aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSEMultStruct *matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
869bda325fcSPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
870bda325fcSPaul Mullowney   cusparseStatus_t             stat;
871aa372e3fSPaul Mullowney   cusparseIndexBase_t          indexBase;
872b06137fdSPaul Mullowney   cudaError_t                  err;
8734863603aSSatish Balay   PetscErrorCode               ierr;
874b175d8bbSPaul Mullowney 
875bda325fcSPaul Mullowney   PetscFunctionBegin;
876aa372e3fSPaul Mullowney 
877aa372e3fSPaul Mullowney   /* allocate space for the triangular factor information */
878aa372e3fSPaul Mullowney   matstructT = new Mat_SeqAIJCUSPARSEMultStruct;
87957d48284SJunchao Zhang   stat = cusparseCreateMatDescr(&matstructT->descr);CHKERRCUSPARSE(stat);
880aa372e3fSPaul Mullowney   indexBase = cusparseGetMatIndexBase(matstruct->descr);
88157d48284SJunchao Zhang   stat = cusparseSetMatIndexBase(matstructT->descr, indexBase);CHKERRCUSPARSE(stat);
88257d48284SJunchao Zhang   stat = cusparseSetMatType(matstructT->descr, CUSPARSE_MATRIX_TYPE_GENERAL);CHKERRCUSPARSE(stat);
883aa372e3fSPaul Mullowney 
884b06137fdSPaul Mullowney   /* set alpha and beta */
885c41cb2e2SAlejandro Lamas Daviña   err = cudaMalloc((void **)&(matstructT->alpha),    sizeof(PetscScalar));CHKERRCUDA(err);
8867656d835SStefano Zampini   err = cudaMalloc((void **)&(matstructT->beta_zero),sizeof(PetscScalar));CHKERRCUDA(err);
8877656d835SStefano Zampini   err = cudaMalloc((void **)&(matstructT->beta_one), sizeof(PetscScalar));CHKERRCUDA(err);
8887656d835SStefano Zampini   err = cudaMemcpy(matstructT->alpha,    &PETSC_CUSPARSE_ONE, sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
8897656d835SStefano Zampini   err = cudaMemcpy(matstructT->beta_zero,&PETSC_CUSPARSE_ZERO,sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
8907656d835SStefano Zampini   err = cudaMemcpy(matstructT->beta_one, &PETSC_CUSPARSE_ONE, sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
89157d48284SJunchao Zhang   stat = cusparseSetPointerMode(cusparsestruct->handle, CUSPARSE_POINTER_MODE_DEVICE);CHKERRCUSPARSE(stat);
892b06137fdSPaul Mullowney 
893aa372e3fSPaul Mullowney   if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
894aa372e3fSPaul Mullowney     CsrMatrix *matrix = (CsrMatrix*)matstruct->mat;
895aa372e3fSPaul Mullowney     CsrMatrix *matrixT= new CsrMatrix;
896554b8892SKarl Rupp     matrixT->num_rows = A->cmap->n;
897554b8892SKarl Rupp     matrixT->num_cols = A->rmap->n;
898aa372e3fSPaul Mullowney     matrixT->num_entries = a->nz;
899a8bd5306SMark Adams     matrixT->row_offsets = new THRUSTINTARRAY32(matrixT->num_rows+1);
900aa372e3fSPaul Mullowney     matrixT->column_indices = new THRUSTINTARRAY32(a->nz);
901aa372e3fSPaul Mullowney     matrixT->values = new THRUSTARRAY(a->nz);
902a3fdcf43SKarl Rupp 
90381902715SJunchao Zhang     cusparsestruct->rowoffsets_gpu = new THRUSTINTARRAY32(A->rmap->n+1);
90481902715SJunchao Zhang     cusparsestruct->rowoffsets_gpu->assign(a->i,a->i+A->rmap->n+1);
90581902715SJunchao Zhang     /* compute the transpose, i.e. the CSC */
906aa372e3fSPaul Mullowney     indexBase = cusparseGetMatIndexBase(matstruct->descr);
907a3fdcf43SKarl Rupp     stat = cusparse_csr2csc(cusparsestruct->handle, A->rmap->n,
908a3fdcf43SKarl Rupp                             A->cmap->n, matrix->num_entries,
909aa372e3fSPaul Mullowney                             matrix->values->data().get(),
91081902715SJunchao Zhang                             cusparsestruct->rowoffsets_gpu->data().get(),
911aa372e3fSPaul Mullowney                             matrix->column_indices->data().get(),
912aa372e3fSPaul Mullowney                             matrixT->values->data().get(),
913aa372e3fSPaul Mullowney                             matrixT->column_indices->data().get(),
914aa372e3fSPaul Mullowney                             matrixT->row_offsets->data().get(),
91557d48284SJunchao Zhang                             CUSPARSE_ACTION_NUMERIC, indexBase);CHKERRCUSPARSE(stat);
916aa372e3fSPaul Mullowney     /* assign the pointer */
917aa372e3fSPaul Mullowney     matstructT->mat = matrixT;
9184863603aSSatish Balay     ierr = PetscLogCpuToGpu(((A->rmap->n+1)+(a->nz))*sizeof(int)+(3+a->nz)*sizeof(PetscScalar));CHKERRQ(ierr);
919aa372e3fSPaul Mullowney   } else if (cusparsestruct->format==MAT_CUSPARSE_ELL || cusparsestruct->format==MAT_CUSPARSE_HYB) {
920aa372e3fSPaul Mullowney     /* First convert HYB to CSR */
921aa372e3fSPaul Mullowney     CsrMatrix *temp= new CsrMatrix;
922aa372e3fSPaul Mullowney     temp->num_rows = A->rmap->n;
923aa372e3fSPaul Mullowney     temp->num_cols = A->cmap->n;
924aa372e3fSPaul Mullowney     temp->num_entries = a->nz;
925aa372e3fSPaul Mullowney     temp->row_offsets = new THRUSTINTARRAY32(A->rmap->n+1);
926aa372e3fSPaul Mullowney     temp->column_indices = new THRUSTINTARRAY32(a->nz);
927aa372e3fSPaul Mullowney     temp->values = new THRUSTARRAY(a->nz);
928aa372e3fSPaul Mullowney 
9292692e278SPaul Mullowney 
930aa372e3fSPaul Mullowney     stat = cusparse_hyb2csr(cusparsestruct->handle,
931aa372e3fSPaul Mullowney                             matstruct->descr, (cusparseHybMat_t)matstruct->mat,
932aa372e3fSPaul Mullowney                             temp->values->data().get(),
933aa372e3fSPaul Mullowney                             temp->row_offsets->data().get(),
93457d48284SJunchao Zhang                             temp->column_indices->data().get());CHKERRCUSPARSE(stat);
935aa372e3fSPaul Mullowney 
936aa372e3fSPaul Mullowney     /* Next, convert CSR to CSC (i.e. the matrix transpose) */
937aa372e3fSPaul Mullowney     CsrMatrix *tempT= new CsrMatrix;
938aa372e3fSPaul Mullowney     tempT->num_rows = A->rmap->n;
939aa372e3fSPaul Mullowney     tempT->num_cols = A->cmap->n;
940aa372e3fSPaul Mullowney     tempT->num_entries = a->nz;
941aa372e3fSPaul Mullowney     tempT->row_offsets = new THRUSTINTARRAY32(A->rmap->n+1);
942aa372e3fSPaul Mullowney     tempT->column_indices = new THRUSTINTARRAY32(a->nz);
943aa372e3fSPaul Mullowney     tempT->values = new THRUSTARRAY(a->nz);
944aa372e3fSPaul Mullowney 
945aa372e3fSPaul Mullowney     stat = cusparse_csr2csc(cusparsestruct->handle, temp->num_rows,
946aa372e3fSPaul Mullowney                             temp->num_cols, temp->num_entries,
947aa372e3fSPaul Mullowney                             temp->values->data().get(),
948aa372e3fSPaul Mullowney                             temp->row_offsets->data().get(),
949aa372e3fSPaul Mullowney                             temp->column_indices->data().get(),
950aa372e3fSPaul Mullowney                             tempT->values->data().get(),
951aa372e3fSPaul Mullowney                             tempT->column_indices->data().get(),
952aa372e3fSPaul Mullowney                             tempT->row_offsets->data().get(),
95357d48284SJunchao Zhang                             CUSPARSE_ACTION_NUMERIC, indexBase);CHKERRCUSPARSE(stat);
954aa372e3fSPaul Mullowney 
955aa372e3fSPaul Mullowney     /* Last, convert CSC to HYB */
956aa372e3fSPaul Mullowney     cusparseHybMat_t hybMat;
95757d48284SJunchao Zhang     stat = cusparseCreateHybMat(&hybMat);CHKERRCUSPARSE(stat);
958aa372e3fSPaul Mullowney     cusparseHybPartition_t partition = cusparsestruct->format==MAT_CUSPARSE_ELL ?
959aa372e3fSPaul Mullowney       CUSPARSE_HYB_PARTITION_MAX : CUSPARSE_HYB_PARTITION_AUTO;
960aa372e3fSPaul Mullowney     stat = cusparse_csr2hyb(cusparsestruct->handle, A->rmap->n, A->cmap->n,
961aa372e3fSPaul Mullowney                             matstructT->descr, tempT->values->data().get(),
962aa372e3fSPaul Mullowney                             tempT->row_offsets->data().get(),
963aa372e3fSPaul Mullowney                             tempT->column_indices->data().get(),
96457d48284SJunchao Zhang                             hybMat, 0, partition);CHKERRCUSPARSE(stat);
965aa372e3fSPaul Mullowney 
966aa372e3fSPaul Mullowney     /* assign the pointer */
967aa372e3fSPaul Mullowney     matstructT->mat = hybMat;
9684863603aSSatish Balay     ierr = PetscLogCpuToGpu((2*(((A->rmap->n+1)+(a->nz))*sizeof(int)+(a->nz)*sizeof(PetscScalar)))+3*sizeof(PetscScalar));CHKERRQ(ierr);
969aa372e3fSPaul Mullowney 
970aa372e3fSPaul Mullowney     /* delete temporaries */
971aa372e3fSPaul Mullowney     if (tempT) {
972aa372e3fSPaul Mullowney       if (tempT->values) delete (THRUSTARRAY*) tempT->values;
973aa372e3fSPaul Mullowney       if (tempT->column_indices) delete (THRUSTINTARRAY32*) tempT->column_indices;
974aa372e3fSPaul Mullowney       if (tempT->row_offsets) delete (THRUSTINTARRAY32*) tempT->row_offsets;
975aa372e3fSPaul Mullowney       delete (CsrMatrix*) tempT;
976087f3262SPaul Mullowney     }
977aa372e3fSPaul Mullowney     if (temp) {
978aa372e3fSPaul Mullowney       if (temp->values) delete (THRUSTARRAY*) temp->values;
979aa372e3fSPaul Mullowney       if (temp->column_indices) delete (THRUSTINTARRAY32*) temp->column_indices;
980aa372e3fSPaul Mullowney       if (temp->row_offsets) delete (THRUSTINTARRAY32*) temp->row_offsets;
981aa372e3fSPaul Mullowney       delete (CsrMatrix*) temp;
982aa372e3fSPaul Mullowney     }
983aa372e3fSPaul Mullowney   }
984213423ffSJunchao Zhang   /* the compressed row indices is not used for matTranspose */
985213423ffSJunchao Zhang   matstructT->cprowIndices = NULL;
986aa372e3fSPaul Mullowney   /* assign the pointer */
987aa372e3fSPaul Mullowney   ((Mat_SeqAIJCUSPARSE*)A->spptr)->matTranspose = matstructT;
988bda325fcSPaul Mullowney   PetscFunctionReturn(0);
989bda325fcSPaul Mullowney }
990bda325fcSPaul Mullowney 
9914e4bbfaaSStefano Zampini /* Why do we need to analyze the tranposed matrix again? Can't we just use op(A) = CUSPARSE_OPERATION_TRANSPOSE in MatSolve_SeqAIJCUSPARSE? */
9926fa9248bSJed Brown static PetscErrorCode MatSolveTranspose_SeqAIJCUSPARSE(Mat A,Vec bb,Vec xx)
993bda325fcSPaul Mullowney {
994c41cb2e2SAlejandro Lamas Daviña   PetscInt                              n = xx->map->n;
995465f34aeSAlejandro Lamas Daviña   const PetscScalar                     *barray;
996465f34aeSAlejandro Lamas Daviña   PetscScalar                           *xarray;
997465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<const PetscScalar> bGPU;
998465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<PetscScalar>       xGPU;
999bda325fcSPaul Mullowney   cusparseStatus_t                      stat;
1000bda325fcSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors          *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1001aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *loTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1002aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *upTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1003aa372e3fSPaul Mullowney   THRUSTARRAY                           *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1004b175d8bbSPaul Mullowney   PetscErrorCode                        ierr;
100557d48284SJunchao Zhang   cudaError_t                           cerr;
1006bda325fcSPaul Mullowney 
1007bda325fcSPaul Mullowney   PetscFunctionBegin;
1008aa372e3fSPaul Mullowney   /* Analyze the matrix and create the transpose ... on the fly */
1009aa372e3fSPaul Mullowney   if (!loTriFactorT && !upTriFactorT) {
1010bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEAnalyzeTransposeForSolve(A);CHKERRQ(ierr);
1011aa372e3fSPaul Mullowney     loTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1012aa372e3fSPaul Mullowney     upTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1013bda325fcSPaul Mullowney   }
1014bda325fcSPaul Mullowney 
1015bda325fcSPaul Mullowney   /* Get the GPU pointers */
1016c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1017c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
1018c41cb2e2SAlejandro Lamas Daviña   xGPU = thrust::device_pointer_cast(xarray);
1019c41cb2e2SAlejandro Lamas Daviña   bGPU = thrust::device_pointer_cast(barray);
1020bda325fcSPaul Mullowney 
10217a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1022aa372e3fSPaul Mullowney   /* First, reorder with the row permutation */
1023c41cb2e2SAlejandro Lamas Daviña   thrust::copy(thrust::make_permutation_iterator(bGPU, cusparseTriFactors->rpermIndices->begin()),
1024c41cb2e2SAlejandro Lamas Daviña                thrust::make_permutation_iterator(bGPU+n, cusparseTriFactors->rpermIndices->end()),
1025c41cb2e2SAlejandro Lamas Daviña                xGPU);
1026aa372e3fSPaul Mullowney 
1027aa372e3fSPaul Mullowney   /* First, solve U */
1028aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactorT->solveOp,
10297656d835SStefano Zampini                         upTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactorT->descr,
1030aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->values->data().get(),
1031aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->row_offsets->data().get(),
1032aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->column_indices->data().get(),
1033aa372e3fSPaul Mullowney                         upTriFactorT->solveInfo,
103457d48284SJunchao Zhang                         xarray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1035aa372e3fSPaul Mullowney 
1036aa372e3fSPaul Mullowney   /* Then, solve L */
1037aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactorT->solveOp,
10387656d835SStefano Zampini                         loTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactorT->descr,
1039aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->values->data().get(),
1040aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->row_offsets->data().get(),
1041aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->column_indices->data().get(),
1042aa372e3fSPaul Mullowney                         loTriFactorT->solveInfo,
104357d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
1044aa372e3fSPaul Mullowney 
1045aa372e3fSPaul Mullowney   /* Last, copy the solution, xGPU, into a temporary with the column permutation ... can't be done in place. */
1046c41cb2e2SAlejandro Lamas Daviña   thrust::copy(thrust::make_permutation_iterator(xGPU, cusparseTriFactors->cpermIndices->begin()),
1047c41cb2e2SAlejandro Lamas Daviña                thrust::make_permutation_iterator(xGPU+n, cusparseTriFactors->cpermIndices->end()),
1048aa372e3fSPaul Mullowney                tempGPU->begin());
1049aa372e3fSPaul Mullowney 
1050aa372e3fSPaul Mullowney   /* Copy the temporary to the full solution. */
1051c41cb2e2SAlejandro Lamas Daviña   thrust::copy(tempGPU->begin(), tempGPU->end(), xGPU);
1052bda325fcSPaul Mullowney 
1053bda325fcSPaul Mullowney   /* restore */
1054c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1055c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
105657d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1057661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1058958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
1059bda325fcSPaul Mullowney   PetscFunctionReturn(0);
1060bda325fcSPaul Mullowney }
1061bda325fcSPaul Mullowney 
10626fa9248bSJed Brown static PetscErrorCode MatSolveTranspose_SeqAIJCUSPARSE_NaturalOrdering(Mat A,Vec bb,Vec xx)
1063bda325fcSPaul Mullowney {
1064465f34aeSAlejandro Lamas Daviña   const PetscScalar                 *barray;
1065465f34aeSAlejandro Lamas Daviña   PetscScalar                       *xarray;
1066bda325fcSPaul Mullowney   cusparseStatus_t                  stat;
1067bda325fcSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1068aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1069aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1070aa372e3fSPaul Mullowney   THRUSTARRAY                       *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1071b175d8bbSPaul Mullowney   PetscErrorCode                    ierr;
107257d48284SJunchao Zhang   cudaError_t                       cerr;
1073bda325fcSPaul Mullowney 
1074bda325fcSPaul Mullowney   PetscFunctionBegin;
1075aa372e3fSPaul Mullowney   /* Analyze the matrix and create the transpose ... on the fly */
1076aa372e3fSPaul Mullowney   if (!loTriFactorT && !upTriFactorT) {
1077bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEAnalyzeTransposeForSolve(A);CHKERRQ(ierr);
1078aa372e3fSPaul Mullowney     loTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1079aa372e3fSPaul Mullowney     upTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1080bda325fcSPaul Mullowney   }
1081bda325fcSPaul Mullowney 
1082bda325fcSPaul Mullowney   /* Get the GPU pointers */
1083c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1084c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
1085bda325fcSPaul Mullowney 
10867a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1087aa372e3fSPaul Mullowney   /* First, solve U */
1088aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactorT->solveOp,
10897656d835SStefano Zampini                         upTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactorT->descr,
1090aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->values->data().get(),
1091aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->row_offsets->data().get(),
1092aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->column_indices->data().get(),
1093aa372e3fSPaul Mullowney                         upTriFactorT->solveInfo,
109457d48284SJunchao Zhang                         barray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1095aa372e3fSPaul Mullowney 
1096aa372e3fSPaul Mullowney   /* Then, solve L */
1097aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactorT->solveOp,
10987656d835SStefano Zampini                         loTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactorT->descr,
1099aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->values->data().get(),
1100aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->row_offsets->data().get(),
1101aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->column_indices->data().get(),
1102aa372e3fSPaul Mullowney                         loTriFactorT->solveInfo,
110357d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
1104bda325fcSPaul Mullowney 
1105bda325fcSPaul Mullowney   /* restore */
1106c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1107c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
110857d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1109661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1110958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
1111bda325fcSPaul Mullowney   PetscFunctionReturn(0);
1112bda325fcSPaul Mullowney }
1113bda325fcSPaul Mullowney 
11146fa9248bSJed Brown static PetscErrorCode MatSolve_SeqAIJCUSPARSE(Mat A,Vec bb,Vec xx)
11159ae82921SPaul Mullowney {
1116465f34aeSAlejandro Lamas Daviña   const PetscScalar                     *barray;
1117465f34aeSAlejandro Lamas Daviña   PetscScalar                           *xarray;
1118465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<const PetscScalar> bGPU;
1119465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<PetscScalar>       xGPU;
11209ae82921SPaul Mullowney   cusparseStatus_t                      stat;
11219ae82921SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors          *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1122aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
1123aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
1124aa372e3fSPaul Mullowney   THRUSTARRAY                           *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1125b175d8bbSPaul Mullowney   PetscErrorCode                        ierr;
112657d48284SJunchao Zhang   cudaError_t                           cerr;
11279ae82921SPaul Mullowney 
11289ae82921SPaul Mullowney   PetscFunctionBegin;
1129ebc8f436SDominic Meiser 
1130e057df02SPaul Mullowney   /* Get the GPU pointers */
1131c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1132c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
1133c41cb2e2SAlejandro Lamas Daviña   xGPU = thrust::device_pointer_cast(xarray);
1134c41cb2e2SAlejandro Lamas Daviña   bGPU = thrust::device_pointer_cast(barray);
11359ae82921SPaul Mullowney 
11367a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1137aa372e3fSPaul Mullowney   /* First, reorder with the row permutation */
1138c41cb2e2SAlejandro Lamas Daviña   thrust::copy(thrust::make_permutation_iterator(bGPU, cusparseTriFactors->rpermIndices->begin()),
1139c41cb2e2SAlejandro Lamas Daviña                thrust::make_permutation_iterator(bGPU, cusparseTriFactors->rpermIndices->end()),
11404e4bbfaaSStefano Zampini                tempGPU->begin());
1141aa372e3fSPaul Mullowney 
1142aa372e3fSPaul Mullowney   /* Next, solve L */
1143aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactor->solveOp,
11447656d835SStefano Zampini                         loTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactor->descr,
1145aa372e3fSPaul Mullowney                         loTriFactor->csrMat->values->data().get(),
1146aa372e3fSPaul Mullowney                         loTriFactor->csrMat->row_offsets->data().get(),
1147aa372e3fSPaul Mullowney                         loTriFactor->csrMat->column_indices->data().get(),
1148aa372e3fSPaul Mullowney                         loTriFactor->solveInfo,
114957d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
1150aa372e3fSPaul Mullowney 
1151aa372e3fSPaul Mullowney   /* Then, solve U */
1152aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactor->solveOp,
11537656d835SStefano Zampini                         upTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactor->descr,
1154aa372e3fSPaul Mullowney                         upTriFactor->csrMat->values->data().get(),
1155aa372e3fSPaul Mullowney                         upTriFactor->csrMat->row_offsets->data().get(),
1156aa372e3fSPaul Mullowney                         upTriFactor->csrMat->column_indices->data().get(),
1157aa372e3fSPaul Mullowney                         upTriFactor->solveInfo,
115857d48284SJunchao Zhang                         xarray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1159aa372e3fSPaul Mullowney 
11604e4bbfaaSStefano Zampini   /* Last, reorder with the column permutation */
11614e4bbfaaSStefano Zampini   thrust::copy(thrust::make_permutation_iterator(tempGPU->begin(), cusparseTriFactors->cpermIndices->begin()),
11624e4bbfaaSStefano Zampini                thrust::make_permutation_iterator(tempGPU->begin(), cusparseTriFactors->cpermIndices->end()),
11634e4bbfaaSStefano Zampini                xGPU);
11649ae82921SPaul Mullowney 
1165c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1166c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
116757d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1168661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1169958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
11709ae82921SPaul Mullowney   PetscFunctionReturn(0);
11719ae82921SPaul Mullowney }
11729ae82921SPaul Mullowney 
11736fa9248bSJed Brown static PetscErrorCode MatSolve_SeqAIJCUSPARSE_NaturalOrdering(Mat A,Vec bb,Vec xx)
11749ae82921SPaul Mullowney {
1175465f34aeSAlejandro Lamas Daviña   const PetscScalar                 *barray;
1176465f34aeSAlejandro Lamas Daviña   PetscScalar                       *xarray;
11779ae82921SPaul Mullowney   cusparseStatus_t                  stat;
11789ae82921SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1179aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
1180aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
1181aa372e3fSPaul Mullowney   THRUSTARRAY                       *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1182b175d8bbSPaul Mullowney   PetscErrorCode                    ierr;
118357d48284SJunchao Zhang   cudaError_t                       cerr;
11849ae82921SPaul Mullowney 
11859ae82921SPaul Mullowney   PetscFunctionBegin;
1186e057df02SPaul Mullowney   /* Get the GPU pointers */
1187c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1188c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
11899ae82921SPaul Mullowney 
11907a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1191aa372e3fSPaul Mullowney   /* First, solve L */
1192aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactor->solveOp,
11937656d835SStefano Zampini                         loTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactor->descr,
1194aa372e3fSPaul Mullowney                         loTriFactor->csrMat->values->data().get(),
1195aa372e3fSPaul Mullowney                         loTriFactor->csrMat->row_offsets->data().get(),
1196aa372e3fSPaul Mullowney                         loTriFactor->csrMat->column_indices->data().get(),
1197aa372e3fSPaul Mullowney                         loTriFactor->solveInfo,
119857d48284SJunchao Zhang                         barray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1199aa372e3fSPaul Mullowney 
1200aa372e3fSPaul Mullowney   /* Next, solve U */
1201aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactor->solveOp,
12027656d835SStefano Zampini                         upTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactor->descr,
1203aa372e3fSPaul Mullowney                         upTriFactor->csrMat->values->data().get(),
1204aa372e3fSPaul Mullowney                         upTriFactor->csrMat->row_offsets->data().get(),
1205aa372e3fSPaul Mullowney                         upTriFactor->csrMat->column_indices->data().get(),
1206aa372e3fSPaul Mullowney                         upTriFactor->solveInfo,
120757d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
12089ae82921SPaul Mullowney 
1209c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1210c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
121157d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1212661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1213958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
12149ae82921SPaul Mullowney   PetscFunctionReturn(0);
12159ae82921SPaul Mullowney }
12169ae82921SPaul Mullowney 
12176fa9248bSJed Brown static PetscErrorCode MatSeqAIJCUSPARSECopyToGPU(Mat A)
12189ae82921SPaul Mullowney {
1219aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
12207c700b8dSJunchao Zhang   Mat_SeqAIJCUSPARSEMultStruct *matstruct = cusparsestruct->mat;
12219ae82921SPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
1222213423ffSJunchao Zhang   PetscInt                     m = A->rmap->n,*ii,*ridx,tmp;
12239ae82921SPaul Mullowney   PetscErrorCode               ierr;
1224aa372e3fSPaul Mullowney   cusparseStatus_t             stat;
1225b06137fdSPaul Mullowney   cudaError_t                  err;
12269ae82921SPaul Mullowney 
12279ae82921SPaul Mullowney   PetscFunctionBegin;
122895639643SRichard Tran Mills   if (A->boundtocpu) PetscFunctionReturn(0);
1229c70f7ee4SJunchao Zhang   if (A->offloadmask == PETSC_OFFLOAD_UNALLOCATED || A->offloadmask == PETSC_OFFLOAD_CPU) {
12309ae82921SPaul Mullowney     ierr = PetscLogEventBegin(MAT_CUSPARSECopyToGPU,A,0,0,0);CHKERRQ(ierr);
123181902715SJunchao Zhang     if (A->was_assembled && A->nonzerostate == cusparsestruct->nonzerostate && cusparsestruct->format == MAT_CUSPARSE_CSR) {
123281902715SJunchao Zhang       /* Copy values only */
123381902715SJunchao Zhang       CsrMatrix *mat,*matT;
123481902715SJunchao Zhang       mat  = (CsrMatrix*)cusparsestruct->mat->mat;
123581902715SJunchao Zhang       mat->values->assign(a->a, a->a+a->nz);
12364863603aSSatish Balay       ierr = PetscLogCpuToGpu((a->nz)*sizeof(PetscScalar));CHKERRQ(ierr);
123781902715SJunchao Zhang 
123881902715SJunchao Zhang       /* Update matT when it was built before */
123981902715SJunchao Zhang       if (cusparsestruct->matTranspose) {
124081902715SJunchao Zhang         cusparseIndexBase_t indexBase = cusparseGetMatIndexBase(cusparsestruct->mat->descr);
124181902715SJunchao Zhang         matT = (CsrMatrix*)cusparsestruct->matTranspose->mat;
124281902715SJunchao Zhang         stat = cusparse_csr2csc(cusparsestruct->handle, A->rmap->n,
124381902715SJunchao Zhang                                  A->cmap->n, mat->num_entries,
124481902715SJunchao Zhang                                  mat->values->data().get(),
124581902715SJunchao Zhang                                  cusparsestruct->rowoffsets_gpu->data().get(),
124681902715SJunchao Zhang                                  mat->column_indices->data().get(),
124781902715SJunchao Zhang                                  matT->values->data().get(),
124881902715SJunchao Zhang                                  matT->column_indices->data().get(),
124981902715SJunchao Zhang                                  matT->row_offsets->data().get(),
12509f74ec24SSatish Balay                                  CUSPARSE_ACTION_NUMERIC,indexBase);CHKERRCUSPARSE(stat);
125181902715SJunchao Zhang       }
125234d6c7a5SJose E. Roman     } else {
12537c700b8dSJunchao Zhang       ierr = MatSeqAIJCUSPARSEMultStruct_Destroy(&cusparsestruct->mat,cusparsestruct->format);CHKERRQ(ierr);
12547c700b8dSJunchao Zhang       ierr = MatSeqAIJCUSPARSEMultStruct_Destroy(&cusparsestruct->matTranspose,cusparsestruct->format);CHKERRQ(ierr);
12557c700b8dSJunchao Zhang       delete cusparsestruct->workVector;
125681902715SJunchao Zhang       delete cusparsestruct->rowoffsets_gpu;
12579ae82921SPaul Mullowney       try {
12589ae82921SPaul Mullowney         if (a->compressedrow.use) {
12599ae82921SPaul Mullowney           m    = a->compressedrow.nrows;
12609ae82921SPaul Mullowney           ii   = a->compressedrow.i;
12619ae82921SPaul Mullowney           ridx = a->compressedrow.rindex;
12629ae82921SPaul Mullowney         } else {
1263213423ffSJunchao Zhang           m    = A->rmap->n;
1264213423ffSJunchao Zhang           ii   = a->i;
1265213423ffSJunchao Zhang           ridx = NULL; /* In this case, one should not dereference ridx */
12669ae82921SPaul Mullowney         }
1267213423ffSJunchao Zhang         cusparsestruct->nrows = m;
12689ae82921SPaul Mullowney 
1269aa372e3fSPaul Mullowney         /* allocate space for the triangular factor information */
1270aa372e3fSPaul Mullowney         matstruct = new Mat_SeqAIJCUSPARSEMultStruct;
127157d48284SJunchao Zhang         stat = cusparseCreateMatDescr(&matstruct->descr);CHKERRCUSPARSE(stat);
127257d48284SJunchao Zhang         stat = cusparseSetMatIndexBase(matstruct->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
127357d48284SJunchao Zhang         stat = cusparseSetMatType(matstruct->descr, CUSPARSE_MATRIX_TYPE_GENERAL);CHKERRCUSPARSE(stat);
12749ae82921SPaul Mullowney 
1275c41cb2e2SAlejandro Lamas Daviña         err = cudaMalloc((void **)&(matstruct->alpha),    sizeof(PetscScalar));CHKERRCUDA(err);
12767656d835SStefano Zampini         err = cudaMalloc((void **)&(matstruct->beta_zero),sizeof(PetscScalar));CHKERRCUDA(err);
12777656d835SStefano Zampini         err = cudaMalloc((void **)&(matstruct->beta_one), sizeof(PetscScalar));CHKERRCUDA(err);
12787656d835SStefano Zampini         err = cudaMemcpy(matstruct->alpha,    &PETSC_CUSPARSE_ONE, sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
12797656d835SStefano Zampini         err = cudaMemcpy(matstruct->beta_zero,&PETSC_CUSPARSE_ZERO,sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
12807656d835SStefano Zampini         err = cudaMemcpy(matstruct->beta_one, &PETSC_CUSPARSE_ONE, sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
128157d48284SJunchao Zhang         stat = cusparseSetPointerMode(cusparsestruct->handle, CUSPARSE_POINTER_MODE_DEVICE);CHKERRCUSPARSE(stat);
1282b06137fdSPaul Mullowney 
1283aa372e3fSPaul Mullowney         /* Build a hybrid/ellpack matrix if this option is chosen for the storage */
1284aa372e3fSPaul Mullowney         if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
1285aa372e3fSPaul Mullowney           /* set the matrix */
1286aa372e3fSPaul Mullowney           CsrMatrix *matrix= new CsrMatrix;
1287a65300a6SPaul Mullowney           matrix->num_rows = m;
1288aa372e3fSPaul Mullowney           matrix->num_cols = A->cmap->n;
1289aa372e3fSPaul Mullowney           matrix->num_entries = a->nz;
1290a65300a6SPaul Mullowney           matrix->row_offsets = new THRUSTINTARRAY32(m+1);
1291a65300a6SPaul Mullowney           matrix->row_offsets->assign(ii, ii + m+1);
12929ae82921SPaul Mullowney 
1293aa372e3fSPaul Mullowney           matrix->column_indices = new THRUSTINTARRAY32(a->nz);
1294aa372e3fSPaul Mullowney           matrix->column_indices->assign(a->j, a->j+a->nz);
1295aa372e3fSPaul Mullowney 
1296aa372e3fSPaul Mullowney           matrix->values = new THRUSTARRAY(a->nz);
1297aa372e3fSPaul Mullowney           matrix->values->assign(a->a, a->a+a->nz);
1298aa372e3fSPaul Mullowney 
1299aa372e3fSPaul Mullowney           /* assign the pointer */
1300aa372e3fSPaul Mullowney           matstruct->mat = matrix;
1301aa372e3fSPaul Mullowney 
1302aa372e3fSPaul Mullowney         } else if (cusparsestruct->format==MAT_CUSPARSE_ELL || cusparsestruct->format==MAT_CUSPARSE_HYB) {
1303aa372e3fSPaul Mullowney           CsrMatrix *matrix= new CsrMatrix;
1304a65300a6SPaul Mullowney           matrix->num_rows = m;
1305aa372e3fSPaul Mullowney           matrix->num_cols = A->cmap->n;
1306aa372e3fSPaul Mullowney           matrix->num_entries = a->nz;
1307a65300a6SPaul Mullowney           matrix->row_offsets = new THRUSTINTARRAY32(m+1);
1308a65300a6SPaul Mullowney           matrix->row_offsets->assign(ii, ii + m+1);
1309aa372e3fSPaul Mullowney 
1310aa372e3fSPaul Mullowney           matrix->column_indices = new THRUSTINTARRAY32(a->nz);
1311aa372e3fSPaul Mullowney           matrix->column_indices->assign(a->j, a->j+a->nz);
1312aa372e3fSPaul Mullowney 
1313aa372e3fSPaul Mullowney           matrix->values = new THRUSTARRAY(a->nz);
1314aa372e3fSPaul Mullowney           matrix->values->assign(a->a, a->a+a->nz);
1315aa372e3fSPaul Mullowney 
1316aa372e3fSPaul Mullowney           cusparseHybMat_t hybMat;
131757d48284SJunchao Zhang           stat = cusparseCreateHybMat(&hybMat);CHKERRCUSPARSE(stat);
1318aa372e3fSPaul Mullowney           cusparseHybPartition_t partition = cusparsestruct->format==MAT_CUSPARSE_ELL ?
1319aa372e3fSPaul Mullowney             CUSPARSE_HYB_PARTITION_MAX : CUSPARSE_HYB_PARTITION_AUTO;
1320a65300a6SPaul Mullowney           stat = cusparse_csr2hyb(cusparsestruct->handle, matrix->num_rows, matrix->num_cols,
1321aa372e3fSPaul Mullowney               matstruct->descr, matrix->values->data().get(),
1322aa372e3fSPaul Mullowney               matrix->row_offsets->data().get(),
1323aa372e3fSPaul Mullowney               matrix->column_indices->data().get(),
132457d48284SJunchao Zhang               hybMat, 0, partition);CHKERRCUSPARSE(stat);
1325aa372e3fSPaul Mullowney           /* assign the pointer */
1326aa372e3fSPaul Mullowney           matstruct->mat = hybMat;
1327aa372e3fSPaul Mullowney 
1328aa372e3fSPaul Mullowney           if (matrix) {
1329aa372e3fSPaul Mullowney             if (matrix->values) delete (THRUSTARRAY*)matrix->values;
1330aa372e3fSPaul Mullowney             if (matrix->column_indices) delete (THRUSTINTARRAY32*)matrix->column_indices;
1331aa372e3fSPaul Mullowney             if (matrix->row_offsets) delete (THRUSTINTARRAY32*)matrix->row_offsets;
1332aa372e3fSPaul Mullowney             delete (CsrMatrix*)matrix;
1333087f3262SPaul Mullowney           }
1334087f3262SPaul Mullowney         }
1335ca45077fSPaul Mullowney 
1336aa372e3fSPaul Mullowney         /* assign the compressed row indices */
1337213423ffSJunchao Zhang         if (a->compressedrow.use) {
1338213423ffSJunchao Zhang           cusparsestruct->workVector = new THRUSTARRAY(m);
1339aa372e3fSPaul Mullowney           matstruct->cprowIndices    = new THRUSTINTARRAY(m);
1340aa372e3fSPaul Mullowney           matstruct->cprowIndices->assign(ridx,ridx+m);
1341213423ffSJunchao Zhang           tmp = m;
1342213423ffSJunchao Zhang         } else {
1343213423ffSJunchao Zhang           cusparsestruct->workVector = NULL;
1344213423ffSJunchao Zhang           matstruct->cprowIndices    = NULL;
1345213423ffSJunchao Zhang           tmp = 0;
1346213423ffSJunchao Zhang         }
1347213423ffSJunchao Zhang         ierr = PetscLogCpuToGpu(((m+1)+(a->nz))*sizeof(int)+tmp*sizeof(PetscInt)+(3+(a->nz))*sizeof(PetscScalar));CHKERRQ(ierr);
1348aa372e3fSPaul Mullowney 
1349aa372e3fSPaul Mullowney         /* assign the pointer */
1350aa372e3fSPaul Mullowney         cusparsestruct->mat = matstruct;
13519ae82921SPaul Mullowney       } catch(char *ex) {
13529ae82921SPaul Mullowney         SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
13539ae82921SPaul Mullowney       }
135434d6c7a5SJose E. Roman       cusparsestruct->nonzerostate = A->nonzerostate;
135534d6c7a5SJose E. Roman     }
135657d48284SJunchao Zhang     err  = WaitForGPU();CHKERRCUDA(err);
1357c70f7ee4SJunchao Zhang     A->offloadmask = PETSC_OFFLOAD_BOTH;
13589ae82921SPaul Mullowney     ierr = PetscLogEventEnd(MAT_CUSPARSECopyToGPU,A,0,0,0);CHKERRQ(ierr);
13599ae82921SPaul Mullowney   }
13609ae82921SPaul Mullowney   PetscFunctionReturn(0);
13619ae82921SPaul Mullowney }
13629ae82921SPaul Mullowney 
1363c41cb2e2SAlejandro Lamas Daviña struct VecCUDAPlusEquals
1364aa372e3fSPaul Mullowney {
1365aa372e3fSPaul Mullowney   template <typename Tuple>
1366aa372e3fSPaul Mullowney   __host__ __device__
1367aa372e3fSPaul Mullowney   void operator()(Tuple t)
1368aa372e3fSPaul Mullowney   {
1369aa372e3fSPaul Mullowney     thrust::get<1>(t) = thrust::get<1>(t) + thrust::get<0>(t);
1370aa372e3fSPaul Mullowney   }
1371aa372e3fSPaul Mullowney };
1372aa372e3fSPaul Mullowney 
1373ccdfe979SStefano Zampini typedef struct {
1374ccdfe979SStefano Zampini   PetscBool   cisdense;
1375ccdfe979SStefano Zampini   PetscScalar *Bt;
1376ccdfe979SStefano Zampini   Mat         X;
1377ccdfe979SStefano Zampini } MatMatCusparse;
1378ccdfe979SStefano Zampini 
1379ccdfe979SStefano Zampini static PetscErrorCode MatDestroy_MatMatCusparse(void *data)
1380ccdfe979SStefano Zampini {
1381ccdfe979SStefano Zampini   PetscErrorCode ierr;
1382ccdfe979SStefano Zampini   MatMatCusparse *mmdata = (MatMatCusparse *)data;
1383ccdfe979SStefano Zampini   cudaError_t    cerr;
1384ccdfe979SStefano Zampini 
1385ccdfe979SStefano Zampini   PetscFunctionBegin;
1386ccdfe979SStefano Zampini   cerr = cudaFree(mmdata->Bt);CHKERRCUDA(cerr);
1387ccdfe979SStefano Zampini   ierr = MatDestroy(&mmdata->X);CHKERRQ(ierr);
1388ccdfe979SStefano Zampini   ierr = PetscFree(data);CHKERRQ(ierr);
1389ccdfe979SStefano Zampini   PetscFunctionReturn(0);
1390ccdfe979SStefano Zampini }
1391ccdfe979SStefano Zampini 
1392ccdfe979SStefano Zampini PETSC_INTERN PetscErrorCode MatMatMultNumeric_SeqDenseCUDA_SeqDenseCUDA_Private(Mat,Mat,Mat,PetscBool,PetscBool);
1393ccdfe979SStefano Zampini 
1394ccdfe979SStefano Zampini static PetscErrorCode MatProductNumeric_SeqAIJCUSPARSE_SeqDENSECUDA(Mat C)
1395ccdfe979SStefano Zampini {
1396ccdfe979SStefano Zampini   Mat_Product                  *product = C->product;
1397ccdfe979SStefano Zampini   Mat                          A,B;
1398ccdfe979SStefano Zampini   PetscInt                     m,n,k,blda,clda;
1399ccdfe979SStefano Zampini   PetscBool                    flg,biscuda;
1400ccdfe979SStefano Zampini   Mat_SeqAIJCUSPARSE           *cusp;
1401ccdfe979SStefano Zampini   cusparseStatus_t             stat;
1402ccdfe979SStefano Zampini   cusparseOperation_t          opA;
1403ccdfe979SStefano Zampini   cusparseMatDescr_t           matA;
1404ccdfe979SStefano Zampini   const PetscScalar            *barray;
1405ccdfe979SStefano Zampini   PetscScalar                  *carray;
1406ccdfe979SStefano Zampini   PetscErrorCode               ierr;
1407ccdfe979SStefano Zampini   MatMatCusparse               *mmdata;
1408ccdfe979SStefano Zampini   Mat_SeqAIJCUSPARSEMultStruct *mat;
1409ccdfe979SStefano Zampini   CsrMatrix                    *csrmat;
1410*c8378d12SStefano Zampini   cudaError_t                  cuer;
1411ccdfe979SStefano Zampini 
1412ccdfe979SStefano Zampini   PetscFunctionBegin;
1413ccdfe979SStefano Zampini   MatCheckProduct(C,1);
1414ccdfe979SStefano Zampini   if (!C->product->data) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Product data empty");
1415ccdfe979SStefano Zampini   mmdata = (MatMatCusparse*)product->data;
1416ccdfe979SStefano Zampini   A    = product->A;
1417ccdfe979SStefano Zampini   B    = product->B;
1418ccdfe979SStefano Zampini   ierr = PetscObjectTypeCompare((PetscObject)A,MATSEQAIJCUSPARSE,&flg);CHKERRQ(ierr);
1419ccdfe979SStefano Zampini   if (!flg) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_PLIB,"Not for type %s",((PetscObject)A)->type_name);
1420ccdfe979SStefano Zampini   /* currently CopyToGpu does not copy if the matrix is bound to CPU
1421ccdfe979SStefano Zampini      Instead of silently accepting the wrong answer, I prefer to raise the error */
1422ccdfe979SStefano Zampini   if (A->boundtocpu) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Cannot bind to CPU a CUSPARSE matrix between MatProductSymbolic and MatProductNumeric phases");
1423ccdfe979SStefano Zampini   ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
1424ccdfe979SStefano Zampini   cusp = (Mat_SeqAIJCUSPARSE*)A->spptr;
1425ccdfe979SStefano Zampini   switch (product->type) {
1426ccdfe979SStefano Zampini   case MATPRODUCT_AB:
1427ccdfe979SStefano Zampini   case MATPRODUCT_PtAP:
1428ccdfe979SStefano Zampini     mat = cusp->mat;
1429ccdfe979SStefano Zampini     opA = CUSPARSE_OPERATION_NON_TRANSPOSE;
1430ccdfe979SStefano Zampini     m   = A->rmap->n;
1431ccdfe979SStefano Zampini     k   = A->cmap->n;
1432ccdfe979SStefano Zampini     n   = B->cmap->n;
1433ccdfe979SStefano Zampini     break;
1434ccdfe979SStefano Zampini   case MATPRODUCT_AtB:
1435ccdfe979SStefano Zampini     if (!cusp->matTranspose) {
1436ccdfe979SStefano Zampini       ierr = MatSeqAIJCUSPARSEGenerateTransposeForMult(A);CHKERRQ(ierr);
1437ccdfe979SStefano Zampini     }
1438ccdfe979SStefano Zampini     mat = cusp->matTranspose;
1439ccdfe979SStefano Zampini     opA = CUSPARSE_OPERATION_NON_TRANSPOSE;
1440ccdfe979SStefano Zampini     m   = A->cmap->n;
1441ccdfe979SStefano Zampini     k   = A->rmap->n;
1442ccdfe979SStefano Zampini     n   = B->cmap->n;
1443ccdfe979SStefano Zampini     break;
1444ccdfe979SStefano Zampini   case MATPRODUCT_ABt:
1445ccdfe979SStefano Zampini   case MATPRODUCT_RARt:
1446ccdfe979SStefano Zampini     mat = cusp->mat;
1447ccdfe979SStefano Zampini     opA = CUSPARSE_OPERATION_NON_TRANSPOSE;
1448ccdfe979SStefano Zampini     m   = A->rmap->n;
1449ccdfe979SStefano Zampini     k   = B->cmap->n;
1450ccdfe979SStefano Zampini     n   = B->rmap->n;
1451ccdfe979SStefano Zampini     break;
1452ccdfe979SStefano Zampini   default:
1453ccdfe979SStefano Zampini     SETERRQ1(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Unsupported product type %s",MatProductTypes[product->type]);
1454ccdfe979SStefano Zampini   }
1455ccdfe979SStefano Zampini   if (!mat) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Missing Mat_SeqAIJCUSPARSEMultStruct");
1456ccdfe979SStefano Zampini   matA   = mat->descr;
1457ccdfe979SStefano Zampini   csrmat = (CsrMatrix*)mat->mat;
1458ccdfe979SStefano Zampini   /* if the user passed a CPU matrix, copy the data to the GPU */
1459ccdfe979SStefano Zampini   ierr = PetscObjectTypeCompare((PetscObject)B,MATSEQDENSECUDA,&biscuda);CHKERRQ(ierr);
1460ccdfe979SStefano Zampini   if (!biscuda) {
1461ccdfe979SStefano Zampini     ierr = MatConvert(B,MATSEQDENSECUDA,MAT_INPLACE_MATRIX,&B);CHKERRQ(ierr);
1462ccdfe979SStefano Zampini   }
1463ccdfe979SStefano Zampini   ierr = MatDenseCUDAGetArrayRead(B,&barray);CHKERRQ(ierr);
1464ccdfe979SStefano Zampini   ierr = MatDenseGetLDA(B,&blda);CHKERRQ(ierr);
1465*c8378d12SStefano Zampini   if (product->type == MATPRODUCT_RARt || product->type == MATPRODUCT_PtAP) {
1466*c8378d12SStefano Zampini     ierr = MatDenseCUDAGetArrayWrite(mmdata->X,&carray);CHKERRQ(ierr);
1467*c8378d12SStefano Zampini     ierr = MatDenseGetLDA(mmdata->X,&clda);CHKERRQ(ierr);
1468*c8378d12SStefano Zampini   } else {
1469*c8378d12SStefano Zampini     ierr = MatDenseCUDAGetArrayWrite(C,&carray);CHKERRQ(ierr);
1470*c8378d12SStefano Zampini     ierr = MatDenseGetLDA(C,&clda);CHKERRQ(ierr);
1471*c8378d12SStefano Zampini   }
1472*c8378d12SStefano Zampini 
1473*c8378d12SStefano Zampini   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1474*c8378d12SStefano Zampini 
1475ccdfe979SStefano Zampini   /* cusparse spmm does not support transpose on B */
1476ccdfe979SStefano Zampini   if (product->type == MATPRODUCT_ABt || product->type == MATPRODUCT_RARt) {
1477ccdfe979SStefano Zampini     cublasHandle_t cublasv2handle;
1478ccdfe979SStefano Zampini     cublasStatus_t cerr;
1479ccdfe979SStefano Zampini 
1480ccdfe979SStefano Zampini     ierr = PetscCUBLASGetHandle(&cublasv2handle);CHKERRQ(ierr);
1481ccdfe979SStefano Zampini     cerr = cublasXgeam(cublasv2handle,CUBLAS_OP_T,CUBLAS_OP_T,
1482ccdfe979SStefano Zampini                        B->cmap->n,B->rmap->n,
1483ccdfe979SStefano Zampini                        &PETSC_CUSPARSE_ONE ,barray,blda,
1484ccdfe979SStefano Zampini                        &PETSC_CUSPARSE_ZERO,barray,blda,
1485ccdfe979SStefano Zampini                        mmdata->Bt,B->cmap->n);CHKERRCUBLAS(cerr);
1486ccdfe979SStefano Zampini     blda = B->cmap->n;
1487ccdfe979SStefano Zampini   }
1488ccdfe979SStefano Zampini 
1489ccdfe979SStefano Zampini   /* perform the MatMat operation */
1490ccdfe979SStefano Zampini   stat = cusparse_csr_spmm(cusp->handle,opA,m,n,k,
1491ccdfe979SStefano Zampini                            csrmat->num_entries,mat->alpha,matA,
1492ccdfe979SStefano Zampini                            csrmat->values->data().get(),
1493ccdfe979SStefano Zampini                            csrmat->row_offsets->data().get(),
1494ccdfe979SStefano Zampini                            csrmat->column_indices->data().get(),
1495ccdfe979SStefano Zampini                            mmdata->Bt ? mmdata->Bt : barray,blda,mat->beta_zero,
1496ccdfe979SStefano Zampini                            carray,clda);CHKERRCUSPARSE(stat);
1497*c8378d12SStefano Zampini   cuer = WaitForGPU();CHKERRCUDA(cuer);
1498*c8378d12SStefano Zampini   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1499*c8378d12SStefano Zampini   ierr = PetscLogGpuFlops(n*2.0*csrmat->num_entries);CHKERRQ(ierr);
1500ccdfe979SStefano Zampini   ierr = MatDenseCUDARestoreArrayRead(B,&barray);CHKERRQ(ierr);
1501ccdfe979SStefano Zampini   if (product->type == MATPRODUCT_RARt) {
1502ccdfe979SStefano Zampini     ierr = MatDenseCUDARestoreArrayWrite(mmdata->X,&carray);CHKERRQ(ierr);
1503ccdfe979SStefano Zampini     ierr = MatMatMultNumeric_SeqDenseCUDA_SeqDenseCUDA_Private(B,mmdata->X,C,PETSC_FALSE,PETSC_FALSE);CHKERRQ(ierr);
1504ccdfe979SStefano Zampini   } else if (product->type == MATPRODUCT_PtAP) {
1505ccdfe979SStefano Zampini     ierr = MatDenseCUDARestoreArrayWrite(mmdata->X,&carray);CHKERRQ(ierr);
1506ccdfe979SStefano Zampini     ierr = MatMatMultNumeric_SeqDenseCUDA_SeqDenseCUDA_Private(B,mmdata->X,C,PETSC_TRUE,PETSC_FALSE);CHKERRQ(ierr);
1507ccdfe979SStefano Zampini   } else {
1508ccdfe979SStefano Zampini     ierr = MatDenseCUDARestoreArrayWrite(C,&carray);CHKERRQ(ierr);
1509ccdfe979SStefano Zampini   }
1510ccdfe979SStefano Zampini   if (mmdata->cisdense) {
1511ccdfe979SStefano Zampini     ierr = MatConvert(C,MATSEQDENSE,MAT_INPLACE_MATRIX,&C);CHKERRQ(ierr);
1512ccdfe979SStefano Zampini   }
1513ccdfe979SStefano Zampini   if (!biscuda) {
1514ccdfe979SStefano Zampini     ierr = MatConvert(B,MATSEQDENSE,MAT_INPLACE_MATRIX,&B);CHKERRQ(ierr);
1515ccdfe979SStefano Zampini   }
1516ccdfe979SStefano Zampini   PetscFunctionReturn(0);
1517ccdfe979SStefano Zampini }
1518ccdfe979SStefano Zampini 
1519ccdfe979SStefano Zampini static PetscErrorCode MatProductSymbolic_SeqAIJCUSPARSE_SeqDENSECUDA(Mat C)
1520ccdfe979SStefano Zampini {
1521ccdfe979SStefano Zampini   Mat_Product        *product = C->product;
1522ccdfe979SStefano Zampini   Mat                A,B;
1523ccdfe979SStefano Zampini   PetscInt           m,n;
1524ccdfe979SStefano Zampini   PetscBool          cisdense,flg;
1525ccdfe979SStefano Zampini   PetscErrorCode     ierr;
1526ccdfe979SStefano Zampini   MatMatCusparse     *mmdata;
1527ccdfe979SStefano Zampini   Mat_SeqAIJCUSPARSE *cusp;
1528ccdfe979SStefano Zampini 
1529ccdfe979SStefano Zampini   PetscFunctionBegin;
1530ccdfe979SStefano Zampini   MatCheckProduct(C,1);
1531ccdfe979SStefano Zampini   if (C->product->data) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Product data not empty");
1532ccdfe979SStefano Zampini   A    = product->A;
1533ccdfe979SStefano Zampini   B    = product->B;
1534ccdfe979SStefano Zampini   ierr = PetscObjectTypeCompare((PetscObject)A,MATSEQAIJCUSPARSE,&flg);CHKERRQ(ierr);
1535ccdfe979SStefano Zampini   if (!flg) SETERRQ1(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Not for type %s",((PetscObject)A)->type_name);
1536ccdfe979SStefano Zampini   cusp = (Mat_SeqAIJCUSPARSE*)A->spptr;
1537ccdfe979SStefano Zampini   if (cusp->format != MAT_CUSPARSE_CSR) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Only for MAT_CUSPARSE_CSR format");
1538ccdfe979SStefano Zampini   switch (product->type) {
1539ccdfe979SStefano Zampini   case MATPRODUCT_AB:
1540ccdfe979SStefano Zampini     m = A->rmap->n;
1541ccdfe979SStefano Zampini     n = B->cmap->n;
1542ccdfe979SStefano Zampini     break;
1543ccdfe979SStefano Zampini   case MATPRODUCT_AtB:
1544ccdfe979SStefano Zampini     m = A->cmap->n;
1545ccdfe979SStefano Zampini     n = B->cmap->n;
1546ccdfe979SStefano Zampini     break;
1547ccdfe979SStefano Zampini   case MATPRODUCT_ABt:
1548ccdfe979SStefano Zampini     m = A->rmap->n;
1549ccdfe979SStefano Zampini     n = B->rmap->n;
1550ccdfe979SStefano Zampini     break;
1551ccdfe979SStefano Zampini   case MATPRODUCT_PtAP:
1552ccdfe979SStefano Zampini     m = B->cmap->n;
1553ccdfe979SStefano Zampini     n = B->cmap->n;
1554ccdfe979SStefano Zampini     break;
1555ccdfe979SStefano Zampini   case MATPRODUCT_RARt:
1556ccdfe979SStefano Zampini     m = B->rmap->n;
1557ccdfe979SStefano Zampini     n = B->rmap->n;
1558ccdfe979SStefano Zampini     break;
1559ccdfe979SStefano Zampini   default:
1560ccdfe979SStefano Zampini     SETERRQ1(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Unsupported product type %s",MatProductTypes[product->type]);
1561ccdfe979SStefano Zampini   }
1562ccdfe979SStefano Zampini   ierr = MatSetSizes(C,m,n,m,n);CHKERRQ(ierr);
1563ccdfe979SStefano Zampini   /* if C is of type MATSEQDENSE (CPU), perform the operation on the GPU and then copy on the CPU */
1564ccdfe979SStefano Zampini   ierr = PetscObjectTypeCompare((PetscObject)C,MATSEQDENSE,&cisdense);CHKERRQ(ierr);
1565ccdfe979SStefano Zampini   ierr = MatSetType(C,MATSEQDENSECUDA);CHKERRQ(ierr);
1566ccdfe979SStefano Zampini 
1567ccdfe979SStefano Zampini   /* product data */
1568ccdfe979SStefano Zampini   ierr = PetscNew(&mmdata);CHKERRQ(ierr);
1569ccdfe979SStefano Zampini   mmdata->cisdense = cisdense;
1570ccdfe979SStefano Zampini   /* cusparse spmm does not support transpose on B */
1571ccdfe979SStefano Zampini   if (product->type == MATPRODUCT_ABt || product->type == MATPRODUCT_RARt) {
1572ccdfe979SStefano Zampini     cudaError_t cerr;
1573ccdfe979SStefano Zampini 
1574ccdfe979SStefano Zampini     cerr = cudaMalloc((void**)&mmdata->Bt,(size_t)B->rmap->n*(size_t)B->cmap->n*sizeof(PetscScalar));CHKERRCUDA(cerr);
1575ccdfe979SStefano Zampini   }
1576ccdfe979SStefano Zampini   /* for these products we need intermediate storage */
1577ccdfe979SStefano Zampini   if (product->type == MATPRODUCT_RARt || product->type == MATPRODUCT_PtAP) {
1578ccdfe979SStefano Zampini     ierr = MatCreate(PetscObjectComm((PetscObject)C),&mmdata->X);CHKERRQ(ierr);
1579ccdfe979SStefano Zampini     ierr = MatSetType(mmdata->X,MATSEQDENSECUDA);CHKERRQ(ierr);
1580ccdfe979SStefano Zampini     if (product->type == MATPRODUCT_RARt) { /* do not preallocate, since the first call to MatDenseCUDAGetArray will preallocate on the GPU for us */
1581ccdfe979SStefano Zampini       ierr = MatSetSizes(mmdata->X,A->rmap->n,B->rmap->n,A->rmap->n,B->rmap->n);CHKERRQ(ierr);
1582ccdfe979SStefano Zampini     } else {
1583ccdfe979SStefano Zampini       ierr = MatSetSizes(mmdata->X,A->rmap->n,B->cmap->n,A->rmap->n,B->cmap->n);CHKERRQ(ierr);
1584ccdfe979SStefano Zampini     }
1585ccdfe979SStefano Zampini   }
1586ccdfe979SStefano Zampini   C->product->data    = mmdata;
1587ccdfe979SStefano Zampini   C->product->destroy = MatDestroy_MatMatCusparse;
1588ccdfe979SStefano Zampini 
1589ccdfe979SStefano Zampini   C->ops->productnumeric = MatProductNumeric_SeqAIJCUSPARSE_SeqDENSECUDA;
1590ccdfe979SStefano Zampini   PetscFunctionReturn(0);
1591ccdfe979SStefano Zampini }
1592ccdfe979SStefano Zampini 
1593ccdfe979SStefano Zampini PETSC_INTERN PetscErrorCode MatProductSetFromOptions_SeqAIJ_SeqDense(Mat);
1594ccdfe979SStefano Zampini 
1595ccdfe979SStefano Zampini /* handles dense B */
1596ccdfe979SStefano Zampini static PetscErrorCode MatProductSetFromOptions_SeqAIJCUSPARSE(Mat C)
1597ccdfe979SStefano Zampini {
1598ccdfe979SStefano Zampini   Mat_Product    *product = C->product;
1599ccdfe979SStefano Zampini   PetscErrorCode ierr;
1600ccdfe979SStefano Zampini 
1601ccdfe979SStefano Zampini   PetscFunctionBegin;
1602ccdfe979SStefano Zampini   MatCheckProduct(C,1);
1603ccdfe979SStefano Zampini   if (!product->A) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Missing A");
1604ccdfe979SStefano Zampini   if (product->A->boundtocpu) {
1605ccdfe979SStefano Zampini     ierr = MatProductSetFromOptions_SeqAIJ_SeqDense(C);CHKERRQ(ierr);
1606ccdfe979SStefano Zampini     PetscFunctionReturn(0);
1607ccdfe979SStefano Zampini   }
1608ccdfe979SStefano Zampini   switch (product->type) {
1609ccdfe979SStefano Zampini   case MATPRODUCT_AB:
1610ccdfe979SStefano Zampini   case MATPRODUCT_AtB:
1611ccdfe979SStefano Zampini   case MATPRODUCT_ABt:
1612ccdfe979SStefano Zampini   case MATPRODUCT_PtAP:
1613ccdfe979SStefano Zampini   case MATPRODUCT_RARt:
1614ccdfe979SStefano Zampini     C->ops->productsymbolic = MatProductSymbolic_SeqAIJCUSPARSE_SeqDENSECUDA;
1615ccdfe979SStefano Zampini   default:
1616ccdfe979SStefano Zampini     break;
1617ccdfe979SStefano Zampini   }
1618ccdfe979SStefano Zampini   PetscFunctionReturn(0);
1619ccdfe979SStefano Zampini }
1620ccdfe979SStefano Zampini 
16216fa9248bSJed Brown static PetscErrorCode MatMult_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy)
16229ae82921SPaul Mullowney {
1623b175d8bbSPaul Mullowney   PetscErrorCode ierr;
16249ae82921SPaul Mullowney 
16259ae82921SPaul Mullowney   PetscFunctionBegin;
16267656d835SStefano Zampini   ierr = MatMultAdd_SeqAIJCUSPARSE(A,xx,NULL,yy);CHKERRQ(ierr);
16279ae82921SPaul Mullowney   PetscFunctionReturn(0);
16289ae82921SPaul Mullowney }
16299ae82921SPaul Mullowney 
16306fa9248bSJed Brown static PetscErrorCode MatMultTranspose_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy)
1631ca45077fSPaul Mullowney {
1632ca45077fSPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
1633aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
16349ff858a8SKarl Rupp   Mat_SeqAIJCUSPARSEMultStruct *matstructT;
1635465f34aeSAlejandro Lamas Daviña   const PetscScalar            *xarray;
1636465f34aeSAlejandro Lamas Daviña   PetscScalar                  *yarray;
1637b175d8bbSPaul Mullowney   PetscErrorCode               ierr;
163857d48284SJunchao Zhang   cudaError_t                  cerr;
1639aa372e3fSPaul Mullowney   cusparseStatus_t             stat;
1640ca45077fSPaul Mullowney 
1641ca45077fSPaul Mullowney   PetscFunctionBegin;
164234d6c7a5SJose E. Roman   /* The line below is necessary due to the operations that modify the matrix on the CPU (axpy, scale, etc) */
164334d6c7a5SJose E. Roman   ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
16449ff858a8SKarl Rupp   matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1645aa372e3fSPaul Mullowney   if (!matstructT) {
1646bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEGenerateTransposeForMult(A);CHKERRQ(ierr);
1647aa372e3fSPaul Mullowney     matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1648bda325fcSPaul Mullowney   }
1649c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(xx,&xarray);CHKERRQ(ierr);
1650c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(yy,&yarray);CHKERRQ(ierr);
1651f6ae8131SMark   if (yy->map->n) {
1652f6ae8131SMark     PetscInt                     n = yy->map->n;
1653f6ae8131SMark     cudaError_t                  err;
1654f6ae8131SMark     err = cudaMemset(yarray,0,n*sizeof(PetscScalar));CHKERRCUDA(err); /* hack to fix numerical errors from reading output vector yy, apparently */
1655f6ae8131SMark   }
1656aa372e3fSPaul Mullowney 
16577a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1658aa372e3fSPaul Mullowney   if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
1659aa372e3fSPaul Mullowney     CsrMatrix *mat = (CsrMatrix*)matstructT->mat;
1660aa372e3fSPaul Mullowney     stat = cusparse_csr_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1661aa372e3fSPaul Mullowney                              mat->num_rows, mat->num_cols,
1662b06137fdSPaul Mullowney                              mat->num_entries, matstructT->alpha, matstructT->descr,
1663aa372e3fSPaul Mullowney                              mat->values->data().get(), mat->row_offsets->data().get(),
16647656d835SStefano Zampini                              mat->column_indices->data().get(), xarray, matstructT->beta_zero,
166557d48284SJunchao Zhang                              yarray);CHKERRCUSPARSE(stat);
1666aa372e3fSPaul Mullowney   } else {
1667aa372e3fSPaul Mullowney     cusparseHybMat_t hybMat = (cusparseHybMat_t)matstructT->mat;
1668aa372e3fSPaul Mullowney     stat = cusparse_hyb_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1669b06137fdSPaul Mullowney                              matstructT->alpha, matstructT->descr, hybMat,
16707656d835SStefano Zampini                              xarray, matstructT->beta_zero,
167157d48284SJunchao Zhang                              yarray);CHKERRCUSPARSE(stat);
1672ca45077fSPaul Mullowney   }
1673c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(xx,&xarray);CHKERRQ(ierr);
1674c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(yy,&yarray);CHKERRQ(ierr);
167557d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1676661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1677213423ffSJunchao Zhang   ierr = PetscLogGpuFlops(2.0*a->nz);CHKERRQ(ierr);
1678ca45077fSPaul Mullowney   PetscFunctionReturn(0);
1679ca45077fSPaul Mullowney }
1680ca45077fSPaul Mullowney 
1681aa372e3fSPaul Mullowney 
16826fa9248bSJed Brown static PetscErrorCode MatMultAdd_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy,Vec zz)
16839ae82921SPaul Mullowney {
16849ae82921SPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
1685aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
16869ff858a8SKarl Rupp   Mat_SeqAIJCUSPARSEMultStruct *matstruct;
1687465f34aeSAlejandro Lamas Daviña   const PetscScalar            *xarray;
16887656d835SStefano Zampini   PetscScalar                  *zarray,*dptr,*beta;
1689b175d8bbSPaul Mullowney   PetscErrorCode               ierr;
169057d48284SJunchao Zhang   cudaError_t                  cerr;
1691aa372e3fSPaul Mullowney   cusparseStatus_t             stat;
1692213423ffSJunchao Zhang   PetscBool                    compressed = a->compressedrow.use; /* Does the matrix use compressed rows (i.e., drop zero rows)? */
16936e111a19SKarl Rupp 
16949ae82921SPaul Mullowney   PetscFunctionBegin;
169534d6c7a5SJose E. Roman   /* The line below is necessary due to the operations that modify the matrix on the CPU (axpy, scale, etc) */
169634d6c7a5SJose E. Roman   ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
16979ff858a8SKarl Rupp   matstruct = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->mat;
16989ae82921SPaul Mullowney   try {
1699c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDAGetArrayRead(xx,&xarray);CHKERRQ(ierr);
1700213423ffSJunchao Zhang 
1701213423ffSJunchao Zhang     if (yy == zz) {ierr = VecCUDAGetArray(zz,&zarray);CHKERRQ(ierr);} /* read & write zz, so need to get uptodate zarray on GPU */
1702213423ffSJunchao Zhang     else {ierr = VecCUDAGetArrayWrite(zz,&zarray);CHKERRQ(ierr);} /* write zz, so no need to init zarray on GPU */
1703213423ffSJunchao Zhang 
1704213423ffSJunchao Zhang     dptr = compressed ? cusparsestruct->workVector->data().get() : zarray; /* Use a work vector for SpMv result if compressed */
1705213423ffSJunchao Zhang     beta = (yy == zz && !compressed) ? matstruct->beta_one : matstruct->beta_zero;
17069ae82921SPaul Mullowney 
17077a052e47Shannah_mairs     ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1708213423ffSJunchao Zhang     /* csr_spmv does y = alpha*Ax + beta*y */
1709aa372e3fSPaul Mullowney     if (cusparsestruct->format == MAT_CUSPARSE_CSR) {
1710b06137fdSPaul Mullowney       /* here we need to be careful to set the number of rows in the multiply to the
1711b06137fdSPaul Mullowney          number of compressed rows in the matrix ... which is equivalent to the
1712b06137fdSPaul Mullowney          size of the workVector */
17137656d835SStefano Zampini       CsrMatrix *mat = (CsrMatrix*)matstruct->mat;
1714aa372e3fSPaul Mullowney       stat = cusparse_csr_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1715a65300a6SPaul Mullowney                                mat->num_rows, mat->num_cols,
1716b06137fdSPaul Mullowney                                mat->num_entries, matstruct->alpha, matstruct->descr,
1717aa372e3fSPaul Mullowney                                mat->values->data().get(), mat->row_offsets->data().get(),
17187656d835SStefano Zampini                                mat->column_indices->data().get(), xarray, beta,
171957d48284SJunchao Zhang                                dptr);CHKERRCUSPARSE(stat);
1720aa372e3fSPaul Mullowney     } else {
1721213423ffSJunchao Zhang       if (cusparsestruct->nrows) {
1722301298b4SMark Adams         cusparseHybMat_t hybMat = (cusparseHybMat_t)matstruct->mat;
1723aa372e3fSPaul Mullowney         stat = cusparse_hyb_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1724b06137fdSPaul Mullowney                                  matstruct->alpha, matstruct->descr, hybMat,
17257656d835SStefano Zampini                                  xarray, beta,
172657d48284SJunchao Zhang                                  dptr);CHKERRCUSPARSE(stat);
1727a65300a6SPaul Mullowney       }
1728aa372e3fSPaul Mullowney     }
1729958c4211Shannah_mairs     ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1730aa372e3fSPaul Mullowney 
1731213423ffSJunchao Zhang     if (yy) { /* MatMultAdd: zz = A*xx + yy */
1732213423ffSJunchao Zhang       if (compressed) { /* A is compressed. We first copy yy to zz, then ScatterAdd the work vector to zz */
1733213423ffSJunchao Zhang         ierr = VecCopy_SeqCUDA(yy,zz);CHKERRQ(ierr); /* zz = yy */
1734213423ffSJunchao Zhang       } else if (zz != yy) { /* A's not compreseed. zz already contains A*xx, and we just need to add yy */
1735213423ffSJunchao Zhang         ierr = VecAXPY_SeqCUDA(zz,1.0,yy);CHKERRQ(ierr); /* zz += yy */
17367656d835SStefano Zampini       }
1737213423ffSJunchao Zhang     } else if (compressed) { /* MatMult: zz = A*xx. A is compressed, so we zero zz first, then ScatterAdd the work vector to zz */
1738c1fb3f03SStefano Zampini       ierr = VecSet_SeqCUDA(zz,0);CHKERRQ(ierr);
17397656d835SStefano Zampini     }
17407656d835SStefano Zampini 
1741213423ffSJunchao Zhang     /* ScatterAdd the result from work vector into the full vector when A is compressed */
1742213423ffSJunchao Zhang     ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1743213423ffSJunchao Zhang     if (compressed) {
1744213423ffSJunchao Zhang       thrust::device_ptr<PetscScalar> zptr = thrust::device_pointer_cast(zarray);
1745c41cb2e2SAlejandro Lamas Daviña       thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple(cusparsestruct->workVector->begin(), thrust::make_permutation_iterator(zptr, matstruct->cprowIndices->begin()))),
1746c41cb2e2SAlejandro Lamas Daviña                        thrust::make_zip_iterator(thrust::make_tuple(cusparsestruct->workVector->begin(), thrust::make_permutation_iterator(zptr, matstruct->cprowIndices->begin()))) + cusparsestruct->workVector->size(),
1747c41cb2e2SAlejandro Lamas Daviña                        VecCUDAPlusEquals());
17487656d835SStefano Zampini     }
1749958c4211Shannah_mairs     ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1750c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDARestoreArrayRead(xx,&xarray);CHKERRQ(ierr);
1751213423ffSJunchao Zhang     if (yy == zz) {ierr = VecCUDARestoreArray(zz,&zarray);CHKERRQ(ierr);}
1752213423ffSJunchao Zhang     else {ierr = VecCUDARestoreArrayWrite(zz,&zarray);CHKERRQ(ierr);}
17539ae82921SPaul Mullowney   } catch(char *ex) {
17549ae82921SPaul Mullowney     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
17559ae82921SPaul Mullowney   }
175657d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1757958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*a->nz);CHKERRQ(ierr);
17589ae82921SPaul Mullowney   PetscFunctionReturn(0);
17599ae82921SPaul Mullowney }
17609ae82921SPaul Mullowney 
17616fa9248bSJed Brown static PetscErrorCode MatMultTransposeAdd_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy,Vec zz)
1762ca45077fSPaul Mullowney {
1763ca45077fSPaul Mullowney   Mat_SeqAIJ                      *a = (Mat_SeqAIJ*)A->data;
1764aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE              *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
17659ff858a8SKarl Rupp   Mat_SeqAIJCUSPARSEMultStruct    *matstructT;
1766465f34aeSAlejandro Lamas Daviña   const PetscScalar               *xarray;
176720291eb5SJunchao Zhang   PetscScalar                     *zarray,*beta;
1768b175d8bbSPaul Mullowney   PetscErrorCode                  ierr;
176957d48284SJunchao Zhang   cudaError_t                     cerr;
1770aa372e3fSPaul Mullowney   cusparseStatus_t                stat;
17716e111a19SKarl Rupp 
1772ca45077fSPaul Mullowney   PetscFunctionBegin;
177334d6c7a5SJose E. Roman   /* The line below is necessary due to the operations that modify the matrix on the CPU (axpy, scale, etc) */
177434d6c7a5SJose E. Roman   ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
17759ff858a8SKarl Rupp   matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1776aa372e3fSPaul Mullowney   if (!matstructT) {
1777bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEGenerateTransposeForMult(A);CHKERRQ(ierr);
1778aa372e3fSPaul Mullowney     matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1779bda325fcSPaul Mullowney   }
1780aa372e3fSPaul Mullowney 
178120291eb5SJunchao Zhang   /* Note unlike Mat, MatTranspose uses non-compressed row storage */
1782ca45077fSPaul Mullowney   try {
1783c41cb2e2SAlejandro Lamas Daviña     ierr = VecCopy_SeqCUDA(yy,zz);CHKERRQ(ierr);
1784c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDAGetArrayRead(xx,&xarray);CHKERRQ(ierr);
1785f2d70e9dSBarry Smith     ierr = VecCUDAGetArray(zz,&zarray);CHKERRQ(ierr);
178620291eb5SJunchao Zhang     beta = (yy == zz) ? matstructT->beta_one : matstructT->beta_zero;
1787ca45077fSPaul Mullowney 
17887a052e47Shannah_mairs     ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1789e057df02SPaul Mullowney     /* multiply add with matrix transpose */
1790aa372e3fSPaul Mullowney     if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
1791aa372e3fSPaul Mullowney       CsrMatrix *mat = (CsrMatrix*)matstructT->mat;
1792aa372e3fSPaul Mullowney       stat = cusparse_csr_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1793a65300a6SPaul Mullowney                                mat->num_rows, mat->num_cols,
1794b06137fdSPaul Mullowney                                mat->num_entries, matstructT->alpha, matstructT->descr,
1795aa372e3fSPaul Mullowney                                mat->values->data().get(), mat->row_offsets->data().get(),
1796a3fdcf43SKarl Rupp                                mat->column_indices->data().get(), xarray, beta,
17979f74ec24SSatish Balay                                zarray);CHKERRCUSPARSE(stat);
1798aa372e3fSPaul Mullowney     } else {
1799aa372e3fSPaul Mullowney       cusparseHybMat_t hybMat = (cusparseHybMat_t)matstructT->mat;
1800213423ffSJunchao Zhang       if (cusparsestruct->nrows) {
1801aa372e3fSPaul Mullowney         stat = cusparse_hyb_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1802b06137fdSPaul Mullowney                                  matstructT->alpha, matstructT->descr, hybMat,
1803a3fdcf43SKarl Rupp                                  xarray, beta,
18049f74ec24SSatish Balay                                  zarray);CHKERRCUSPARSE(stat);
1805a65300a6SPaul Mullowney       }
1806aa372e3fSPaul Mullowney     }
1807a3fdcf43SKarl Rupp     ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1808a3fdcf43SKarl Rupp 
180920291eb5SJunchao Zhang     if (zz != yy) {ierr = VecAXPY_SeqCUDA(zz,1.0,yy);CHKERRQ(ierr);}
1810c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDARestoreArrayRead(xx,&xarray);CHKERRQ(ierr);
1811f2d70e9dSBarry Smith     ierr = VecCUDARestoreArray(zz,&zarray);CHKERRQ(ierr);
1812ca45077fSPaul Mullowney   } catch(char *ex) {
1813ca45077fSPaul Mullowney     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
1814661c2d29Shannah_mairs   }
18159f74ec24SSatish Balay   cerr = WaitForGPU();CHKERRCUDA(cerr);
1816958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*a->nz);CHKERRQ(ierr);
1817ca45077fSPaul Mullowney   PetscFunctionReturn(0);
1818ca45077fSPaul Mullowney }
1819ca45077fSPaul Mullowney 
18206fa9248bSJed Brown static PetscErrorCode MatAssemblyEnd_SeqAIJCUSPARSE(Mat A,MatAssemblyType mode)
18219ae82921SPaul Mullowney {
18229ae82921SPaul Mullowney   PetscErrorCode ierr;
18236e111a19SKarl Rupp 
18249ae82921SPaul Mullowney   PetscFunctionBegin;
18259ae82921SPaul Mullowney   ierr = MatAssemblyEnd_SeqAIJ(A,mode);CHKERRQ(ierr);
182695639643SRichard Tran Mills   if (mode == MAT_FLUSH_ASSEMBLY || A->boundtocpu) PetscFunctionReturn(0);
1827bc3f50f2SPaul Mullowney   if (A->factortype == MAT_FACTOR_NONE) {
1828e057df02SPaul Mullowney     ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
1829bc3f50f2SPaul Mullowney   }
1830bbf3fe20SPaul Mullowney   A->ops->mult             = MatMult_SeqAIJCUSPARSE;
1831bbf3fe20SPaul Mullowney   A->ops->multadd          = MatMultAdd_SeqAIJCUSPARSE;
1832bbf3fe20SPaul Mullowney   A->ops->multtranspose    = MatMultTranspose_SeqAIJCUSPARSE;
1833bbf3fe20SPaul Mullowney   A->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJCUSPARSE;
18349ae82921SPaul Mullowney   PetscFunctionReturn(0);
18359ae82921SPaul Mullowney }
18369ae82921SPaul Mullowney 
18379ae82921SPaul Mullowney /* --------------------------------------------------------------------------------*/
1838e057df02SPaul Mullowney /*@
18399ae82921SPaul Mullowney    MatCreateSeqAIJCUSPARSE - Creates a sparse matrix in AIJ (compressed row) format
1840e057df02SPaul Mullowney    (the default parallel PETSc format). This matrix will ultimately pushed down
1841e057df02SPaul Mullowney    to NVidia GPUs and use the CUSPARSE library for calculations. For good matrix
1842e057df02SPaul Mullowney    assembly performance the user should preallocate the matrix storage by setting
1843e057df02SPaul Mullowney    the parameter nz (or the array nnz).  By setting these parameters accurately,
1844e057df02SPaul Mullowney    performance during matrix assembly can be increased by more than a factor of 50.
18459ae82921SPaul Mullowney 
1846d083f849SBarry Smith    Collective
18479ae82921SPaul Mullowney 
18489ae82921SPaul Mullowney    Input Parameters:
18499ae82921SPaul Mullowney +  comm - MPI communicator, set to PETSC_COMM_SELF
18509ae82921SPaul Mullowney .  m - number of rows
18519ae82921SPaul Mullowney .  n - number of columns
18529ae82921SPaul Mullowney .  nz - number of nonzeros per row (same for all rows)
18539ae82921SPaul Mullowney -  nnz - array containing the number of nonzeros in the various rows
18540298fd71SBarry Smith          (possibly different for each row) or NULL
18559ae82921SPaul Mullowney 
18569ae82921SPaul Mullowney    Output Parameter:
18579ae82921SPaul Mullowney .  A - the matrix
18589ae82921SPaul Mullowney 
18599ae82921SPaul Mullowney    It is recommended that one use the MatCreate(), MatSetType() and/or MatSetFromOptions(),
18609ae82921SPaul Mullowney    MatXXXXSetPreallocation() paradgm instead of this routine directly.
18619ae82921SPaul Mullowney    [MatXXXXSetPreallocation() is, for example, MatSeqAIJSetPreallocation]
18629ae82921SPaul Mullowney 
18639ae82921SPaul Mullowney    Notes:
18649ae82921SPaul Mullowney    If nnz is given then nz is ignored
18659ae82921SPaul Mullowney 
18669ae82921SPaul Mullowney    The AIJ format (also called the Yale sparse matrix format or
18679ae82921SPaul Mullowney    compressed row storage), is fully compatible with standard Fortran 77
18689ae82921SPaul Mullowney    storage.  That is, the stored row and column indices can begin at
18699ae82921SPaul Mullowney    either one (as in Fortran) or zero.  See the users' manual for details.
18709ae82921SPaul Mullowney 
18719ae82921SPaul Mullowney    Specify the preallocated storage with either nz or nnz (not both).
18720298fd71SBarry Smith    Set nz=PETSC_DEFAULT and nnz=NULL for PETSc to control dynamic memory
18739ae82921SPaul Mullowney    allocation.  For large problems you MUST preallocate memory or you
18749ae82921SPaul Mullowney    will get TERRIBLE performance, see the users' manual chapter on matrices.
18759ae82921SPaul Mullowney 
18769ae82921SPaul Mullowney    By default, this format uses inodes (identical nodes) when possible, to
18779ae82921SPaul Mullowney    improve numerical efficiency of matrix-vector products and solves. We
18789ae82921SPaul Mullowney    search for consecutive rows with the same nonzero structure, thereby
18799ae82921SPaul Mullowney    reusing matrix information to achieve increased efficiency.
18809ae82921SPaul Mullowney 
18819ae82921SPaul Mullowney    Level: intermediate
18829ae82921SPaul Mullowney 
1883e057df02SPaul Mullowney .seealso: MatCreate(), MatCreateAIJ(), MatSetValues(), MatSeqAIJSetColumnIndices(), MatCreateSeqAIJWithArrays(), MatCreateAIJ(), MATSEQAIJCUSPARSE, MATAIJCUSPARSE
18849ae82921SPaul Mullowney @*/
18859ae82921SPaul Mullowney PetscErrorCode  MatCreateSeqAIJCUSPARSE(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt nz,const PetscInt nnz[],Mat *A)
18869ae82921SPaul Mullowney {
18879ae82921SPaul Mullowney   PetscErrorCode ierr;
18889ae82921SPaul Mullowney 
18899ae82921SPaul Mullowney   PetscFunctionBegin;
18909ae82921SPaul Mullowney   ierr = MatCreate(comm,A);CHKERRQ(ierr);
18919ae82921SPaul Mullowney   ierr = MatSetSizes(*A,m,n,m,n);CHKERRQ(ierr);
18929ae82921SPaul Mullowney   ierr = MatSetType(*A,MATSEQAIJCUSPARSE);CHKERRQ(ierr);
18939ae82921SPaul Mullowney   ierr = MatSeqAIJSetPreallocation_SeqAIJ(*A,nz,(PetscInt*)nnz);CHKERRQ(ierr);
18949ae82921SPaul Mullowney   PetscFunctionReturn(0);
18959ae82921SPaul Mullowney }
18969ae82921SPaul Mullowney 
18976fa9248bSJed Brown static PetscErrorCode MatDestroy_SeqAIJCUSPARSE(Mat A)
18989ae82921SPaul Mullowney {
18999ae82921SPaul Mullowney   PetscErrorCode ierr;
1900ab25e6cbSDominic Meiser 
19019ae82921SPaul Mullowney   PetscFunctionBegin;
19029ae82921SPaul Mullowney   if (A->factortype == MAT_FACTOR_NONE) {
1903c70f7ee4SJunchao Zhang     if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) {
1904470880abSPatrick Sanan       ierr = MatSeqAIJCUSPARSE_Destroy((Mat_SeqAIJCUSPARSE**)&A->spptr);CHKERRQ(ierr);
19059ae82921SPaul Mullowney     }
19069ae82921SPaul Mullowney   } else {
1907470880abSPatrick Sanan     ierr = MatSeqAIJCUSPARSETriFactors_Destroy((Mat_SeqAIJCUSPARSETriFactors**)&A->spptr);CHKERRQ(ierr);
1908aa372e3fSPaul Mullowney   }
1909ccdfe979SStefano Zampini   ierr = PetscObjectComposeFunction((PetscObject)A,"MatCUSPARSESetFormat_C",NULL);CHKERRQ(ierr);
1910ccdfe979SStefano Zampini   ierr = PetscObjectComposeFunction((PetscObject)A,"MatProductSetFromOptions_seqaijcusparse_seqdensecuda_C",NULL);CHKERRQ(ierr);
1911ccdfe979SStefano Zampini   ierr = PetscObjectComposeFunction((PetscObject)A,"MatProductSetFromOptions_seqaijcusparse_seqdense_C",NULL);CHKERRQ(ierr);
1912ccdfe979SStefano Zampini   ierr = PetscObjectComposeFunction((PetscObject)A,"MatFactorGetSolverType_C",NULL);CHKERRQ(ierr);
19139ae82921SPaul Mullowney   ierr = MatDestroy_SeqAIJ(A);CHKERRQ(ierr);
19149ae82921SPaul Mullowney   PetscFunctionReturn(0);
19159ae82921SPaul Mullowney }
19169ae82921SPaul Mullowney 
1917ccdfe979SStefano Zampini PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCUSPARSE(Mat,MatType,MatReuse,Mat*);
191895639643SRichard Tran Mills static PetscErrorCode MatBindToCPU_SeqAIJCUSPARSE(Mat,PetscBool);
19199ff858a8SKarl Rupp static PetscErrorCode MatDuplicate_SeqAIJCUSPARSE(Mat A,MatDuplicateOption cpvalues,Mat *B)
19209ff858a8SKarl Rupp {
19219ff858a8SKarl Rupp   PetscErrorCode ierr;
19229ff858a8SKarl Rupp 
19239ff858a8SKarl Rupp   PetscFunctionBegin;
19249ff858a8SKarl Rupp   ierr = MatDuplicate_SeqAIJ(A,cpvalues,B);CHKERRQ(ierr);
1925ccdfe979SStefano Zampini   ierr = MatConvert_SeqAIJ_SeqAIJCUSPARSE(*B,MATSEQAIJCUSPARSE,MAT_INPLACE_MATRIX,B);CHKERRQ(ierr);
19269ff858a8SKarl Rupp   PetscFunctionReturn(0);
19279ff858a8SKarl Rupp }
19289ff858a8SKarl Rupp 
192995639643SRichard Tran Mills static PetscErrorCode MatBindToCPU_SeqAIJCUSPARSE(Mat A,PetscBool flg)
193095639643SRichard Tran Mills {
193195639643SRichard Tran Mills   PetscFunctionBegin;
1932c34f1ff0SRichard Tran Mills   /* Currently, there is no case in which an AIJCUSPARSE matrix ever has its offloadmask set to PETS_OFFLOAD_GPU.
193395639643SRichard Tran Mills      If this changes, we need to implement a routine to update the CPU (host) version of the matrix from the GPU one.
193495639643SRichard Tran Mills      Right now, for safety we simply check for PETSC_OFFLOAD_GPU and have MatBindToCPU() do nothing in this case.
193595639643SRichard Tran Mills      TODO: Add MatAIJCUSPARSECopyFromGPU() and make MatBindToCPU() functional for AIJCUSPARSE matries;
193695639643SRichard Tran Mills            can follow the example of MatBindToCPU_SeqAIJViennaCL(). */
1937ccdfe979SStefano Zampini   /* We need to take care of function composition also */
193895639643SRichard Tran Mills   if (A->offloadmask == PETSC_OFFLOAD_GPU) PetscFunctionReturn(0);
193995639643SRichard Tran Mills   if (flg) {
194095639643SRichard Tran Mills     A->ops->mult             = MatMult_SeqAIJ;
194195639643SRichard Tran Mills     A->ops->multadd          = MatMultAdd_SeqAIJ;
1942c34f1ff0SRichard Tran Mills     A->ops->multtranspose    = MatMultTranspose_SeqAIJ;
1943c34f1ff0SRichard Tran Mills     A->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJ;
194495639643SRichard Tran Mills     A->ops->assemblyend      = MatAssemblyEnd_SeqAIJ;
194595639643SRichard Tran Mills     A->ops->duplicate        = MatDuplicate_SeqAIJ;
194695639643SRichard Tran Mills   } else {
194795639643SRichard Tran Mills     A->ops->mult             = MatMult_SeqAIJCUSPARSE;
194895639643SRichard Tran Mills     A->ops->multadd          = MatMultAdd_SeqAIJCUSPARSE;
194995639643SRichard Tran Mills     A->ops->multtranspose    = MatMultTranspose_SeqAIJCUSPARSE;
195095639643SRichard Tran Mills     A->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJCUSPARSE;
195195639643SRichard Tran Mills     A->ops->assemblyend      = MatAssemblyEnd_SeqAIJCUSPARSE;
195295639643SRichard Tran Mills     A->ops->destroy          = MatDestroy_SeqAIJCUSPARSE;
195395639643SRichard Tran Mills     A->ops->duplicate        = MatDuplicate_SeqAIJCUSPARSE;
195495639643SRichard Tran Mills   }
195595639643SRichard Tran Mills   A->boundtocpu = flg;
195695639643SRichard Tran Mills   PetscFunctionReturn(0);
195795639643SRichard Tran Mills }
195895639643SRichard Tran Mills 
19590ce8acdeSStefano Zampini PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCUSPARSE(Mat B, MatType mtype, MatReuse reuse, Mat* newmat)
19609ae82921SPaul Mullowney {
19619ae82921SPaul Mullowney   PetscErrorCode ierr;
1962aa372e3fSPaul Mullowney   cusparseStatus_t stat;
1963aa372e3fSPaul Mullowney   cusparseHandle_t handle=0;
19649ae82921SPaul Mullowney 
19659ae82921SPaul Mullowney   PetscFunctionBegin;
19660ce8acdeSStefano Zampini   if (reuse != MAT_INPLACE_MATRIX) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not yet supported");
196734136279SStefano Zampini   ierr = PetscFree(B->defaultvectype);CHKERRQ(ierr);
196834136279SStefano Zampini   ierr = PetscStrallocpy(VECCUDA,&B->defaultvectype);CHKERRQ(ierr);
196934136279SStefano Zampini 
19709ae82921SPaul Mullowney   if (B->factortype == MAT_FACTOR_NONE) {
1971e057df02SPaul Mullowney     /* you cannot check the inode.use flag here since the matrix was just created.
1972e057df02SPaul Mullowney        now build a GPU matrix data structure */
19739ae82921SPaul Mullowney     B->spptr = new Mat_SeqAIJCUSPARSE;
19749ae82921SPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->mat            = 0;
1975aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->matTranspose   = 0;
1976aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->workVector     = 0;
197781902715SJunchao Zhang     ((Mat_SeqAIJCUSPARSE*)B->spptr)->rowoffsets_gpu = 0;
1978e057df02SPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->format         = MAT_CUSPARSE_CSR;
1979aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->stream         = 0;
198057d48284SJunchao Zhang     stat = cusparseCreate(&handle);CHKERRCUSPARSE(stat);
1981aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->handle         = handle;
19829ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)B->spptr)->nonzerostate   = 0;
19839ae82921SPaul Mullowney   } else {
19849ae82921SPaul Mullowney     /* NEXT, set the pointers to the triangular factors */
1985debe9ee2SPaul Mullowney     B->spptr = new Mat_SeqAIJCUSPARSETriFactors;
19869ae82921SPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->loTriFactorPtr          = 0;
19879ae82921SPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->upTriFactorPtr          = 0;
1988aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->loTriFactorPtrTranspose = 0;
1989aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->upTriFactorPtrTranspose = 0;
1990aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->rpermIndices            = 0;
1991aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->cpermIndices            = 0;
1992aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->workVector              = 0;
199357d48284SJunchao Zhang     stat = cusparseCreate(&handle);CHKERRCUSPARSE(stat);
1994aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->handle                  = handle;
1995aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->nnz                     = 0;
19969ae82921SPaul Mullowney   }
1997aa372e3fSPaul Mullowney 
19989ae82921SPaul Mullowney   B->ops->assemblyend      = MatAssemblyEnd_SeqAIJCUSPARSE;
19999ae82921SPaul Mullowney   B->ops->destroy          = MatDestroy_SeqAIJCUSPARSE;
20009ae82921SPaul Mullowney   B->ops->setfromoptions   = MatSetFromOptions_SeqAIJCUSPARSE;
2001ca45077fSPaul Mullowney   B->ops->mult             = MatMult_SeqAIJCUSPARSE;
2002ca45077fSPaul Mullowney   B->ops->multadd          = MatMultAdd_SeqAIJCUSPARSE;
2003ca45077fSPaul Mullowney   B->ops->multtranspose    = MatMultTranspose_SeqAIJCUSPARSE;
2004ca45077fSPaul Mullowney   B->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJCUSPARSE;
20059ff858a8SKarl Rupp   B->ops->duplicate        = MatDuplicate_SeqAIJCUSPARSE;
200695639643SRichard Tran Mills   B->ops->bindtocpu        = MatBindToCPU_SeqAIJCUSPARSE;
20072205254eSKarl Rupp 
20089ae82921SPaul Mullowney   ierr = PetscObjectChangeTypeName((PetscObject)B,MATSEQAIJCUSPARSE);CHKERRQ(ierr);
20092205254eSKarl Rupp 
201095639643SRichard Tran Mills   B->boundtocpu  = PETSC_FALSE;
2011c70f7ee4SJunchao Zhang   B->offloadmask = PETSC_OFFLOAD_UNALLOCATED;
20122205254eSKarl Rupp 
2013bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatCUSPARSESetFormat_C",MatCUSPARSESetFormat_SeqAIJCUSPARSE);CHKERRQ(ierr);
2014ccdfe979SStefano Zampini   ierr = PetscObjectComposeFunction((PetscObject)B,"MatProductSetFromOptions_seqaijcusparse_seqdensecuda_C",MatProductSetFromOptions_SeqAIJCUSPARSE);CHKERRQ(ierr);
2015ccdfe979SStefano Zampini   ierr = PetscObjectComposeFunction((PetscObject)B,"MatProductSetFromOptions_seqaijcusparse_seqdense_C",MatProductSetFromOptions_SeqAIJCUSPARSE);CHKERRQ(ierr);
20169ae82921SPaul Mullowney   PetscFunctionReturn(0);
20179ae82921SPaul Mullowney }
20189ae82921SPaul Mullowney 
201902fe1965SBarry Smith PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJCUSPARSE(Mat B)
202002fe1965SBarry Smith {
202102fe1965SBarry Smith   PetscErrorCode ierr;
202202fe1965SBarry Smith 
202302fe1965SBarry Smith   PetscFunctionBegin;
202402fe1965SBarry Smith   ierr = MatCreate_SeqAIJ(B);CHKERRQ(ierr);
20250ce8acdeSStefano Zampini   ierr = MatConvert_SeqAIJ_SeqAIJCUSPARSE(B,MATSEQAIJCUSPARSE,MAT_INPLACE_MATRIX,&B);CHKERRQ(ierr);
202602fe1965SBarry Smith   PetscFunctionReturn(0);
202702fe1965SBarry Smith }
202802fe1965SBarry Smith 
20293ca39a21SBarry Smith /*MC
2030e057df02SPaul Mullowney    MATSEQAIJCUSPARSE - MATAIJCUSPARSE = "(seq)aijcusparse" - A matrix type to be used for sparse matrices.
2031e057df02SPaul Mullowney 
2032e057df02SPaul Mullowney    A matrix type type whose data resides on Nvidia GPUs. These matrices can be in either
20332692e278SPaul Mullowney    CSR, ELL, or Hybrid format. The ELL and HYB formats require CUDA 4.2 or later.
20342692e278SPaul Mullowney    All matrix calculations are performed on Nvidia GPUs using the CUSPARSE library.
2035e057df02SPaul Mullowney 
2036e057df02SPaul Mullowney    Options Database Keys:
2037e057df02SPaul Mullowney +  -mat_type aijcusparse - sets the matrix type to "seqaijcusparse" during a call to MatSetFromOptions()
2038aa372e3fSPaul Mullowney .  -mat_cusparse_storage_format csr - sets the storage format of matrices (for MatMult and factors in MatSolve) during a call to MatSetFromOptions(). Other options include ell (ellpack) or hyb (hybrid).
2039a2b725a8SWilliam Gropp -  -mat_cusparse_mult_storage_format csr - sets the storage format of matrices (for MatMult) during a call to MatSetFromOptions(). Other options include ell (ellpack) or hyb (hybrid).
2040e057df02SPaul Mullowney 
2041e057df02SPaul Mullowney   Level: beginner
2042e057df02SPaul Mullowney 
20438468deeeSKarl Rupp .seealso: MatCreateSeqAIJCUSPARSE(), MATAIJCUSPARSE, MatCreateAIJCUSPARSE(), MatCUSPARSESetFormat(), MatCUSPARSEStorageFormat, MatCUSPARSEFormatOperation
2044e057df02SPaul Mullowney M*/
20457f756511SDominic Meiser 
204642c9c57cSBarry Smith PETSC_EXTERN PetscErrorCode MatGetFactor_seqaijcusparse_cusparse(Mat,MatFactorType,Mat*);
204742c9c57cSBarry Smith 
20480f39cd5aSBarry Smith 
20493ca39a21SBarry Smith PETSC_EXTERN PetscErrorCode MatSolverTypeRegister_CUSPARSE(void)
205042c9c57cSBarry Smith {
205142c9c57cSBarry Smith   PetscErrorCode ierr;
205242c9c57cSBarry Smith 
205342c9c57cSBarry Smith   PetscFunctionBegin;
20543ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_LU,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
20553ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_CHOLESKY,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
20563ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_ILU,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
20573ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_ICC,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
205842c9c57cSBarry Smith   PetscFunctionReturn(0);
205942c9c57cSBarry Smith }
206029b38603SBarry Smith 
206181e08676SBarry Smith 
2062470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSE_Destroy(Mat_SeqAIJCUSPARSE **cusparsestruct)
20637f756511SDominic Meiser {
20647f756511SDominic Meiser   cusparseStatus_t stat;
20657f756511SDominic Meiser   cusparseHandle_t handle;
20667f756511SDominic Meiser 
20677f756511SDominic Meiser   PetscFunctionBegin;
20687f756511SDominic Meiser   if (*cusparsestruct) {
2069470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*cusparsestruct)->mat,(*cusparsestruct)->format);
2070470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*cusparsestruct)->matTranspose,(*cusparsestruct)->format);
20717f756511SDominic Meiser     delete (*cusparsestruct)->workVector;
207281902715SJunchao Zhang     delete (*cusparsestruct)->rowoffsets_gpu;
20737f756511SDominic Meiser     if (handle = (*cusparsestruct)->handle) {
207457d48284SJunchao Zhang       stat = cusparseDestroy(handle);CHKERRCUSPARSE(stat);
20757f756511SDominic Meiser     }
20767f756511SDominic Meiser     delete *cusparsestruct;
20777f756511SDominic Meiser     *cusparsestruct = 0;
20787f756511SDominic Meiser   }
20797f756511SDominic Meiser   PetscFunctionReturn(0);
20807f756511SDominic Meiser }
20817f756511SDominic Meiser 
20827f756511SDominic Meiser static PetscErrorCode CsrMatrix_Destroy(CsrMatrix **mat)
20837f756511SDominic Meiser {
20847f756511SDominic Meiser   PetscFunctionBegin;
20857f756511SDominic Meiser   if (*mat) {
20867f756511SDominic Meiser     delete (*mat)->values;
20877f756511SDominic Meiser     delete (*mat)->column_indices;
20887f756511SDominic Meiser     delete (*mat)->row_offsets;
20897f756511SDominic Meiser     delete *mat;
20907f756511SDominic Meiser     *mat = 0;
20917f756511SDominic Meiser   }
20927f756511SDominic Meiser   PetscFunctionReturn(0);
20937f756511SDominic Meiser }
20947f756511SDominic Meiser 
2095470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSEMultStruct_Destroy(Mat_SeqAIJCUSPARSETriFactorStruct **trifactor)
20967f756511SDominic Meiser {
20977f756511SDominic Meiser   cusparseStatus_t stat;
20987f756511SDominic Meiser   PetscErrorCode   ierr;
20997f756511SDominic Meiser 
21007f756511SDominic Meiser   PetscFunctionBegin;
21017f756511SDominic Meiser   if (*trifactor) {
210257d48284SJunchao Zhang     if ((*trifactor)->descr) { stat = cusparseDestroyMatDescr((*trifactor)->descr);CHKERRCUSPARSE(stat); }
210357d48284SJunchao Zhang     if ((*trifactor)->solveInfo) { stat = cusparseDestroySolveAnalysisInfo((*trifactor)->solveInfo);CHKERRCUSPARSE(stat); }
21047f756511SDominic Meiser     ierr = CsrMatrix_Destroy(&(*trifactor)->csrMat);CHKERRQ(ierr);
21057f756511SDominic Meiser     delete *trifactor;
21067f756511SDominic Meiser     *trifactor = 0;
21077f756511SDominic Meiser   }
21087f756511SDominic Meiser   PetscFunctionReturn(0);
21097f756511SDominic Meiser }
21107f756511SDominic Meiser 
2111470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSEMultStruct_Destroy(Mat_SeqAIJCUSPARSEMultStruct **matstruct,MatCUSPARSEStorageFormat format)
21127f756511SDominic Meiser {
21137f756511SDominic Meiser   CsrMatrix        *mat;
21147f756511SDominic Meiser   cusparseStatus_t stat;
21157f756511SDominic Meiser   cudaError_t      err;
21167f756511SDominic Meiser 
21177f756511SDominic Meiser   PetscFunctionBegin;
21187f756511SDominic Meiser   if (*matstruct) {
21197f756511SDominic Meiser     if ((*matstruct)->mat) {
21207f756511SDominic Meiser       if (format==MAT_CUSPARSE_ELL || format==MAT_CUSPARSE_HYB) {
21217f756511SDominic Meiser         cusparseHybMat_t hybMat = (cusparseHybMat_t)(*matstruct)->mat;
212257d48284SJunchao Zhang         stat = cusparseDestroyHybMat(hybMat);CHKERRCUSPARSE(stat);
21237f756511SDominic Meiser       } else {
21247f756511SDominic Meiser         mat = (CsrMatrix*)(*matstruct)->mat;
21257f756511SDominic Meiser         CsrMatrix_Destroy(&mat);
21267f756511SDominic Meiser       }
21277f756511SDominic Meiser     }
212857d48284SJunchao Zhang     if ((*matstruct)->descr) { stat = cusparseDestroyMatDescr((*matstruct)->descr);CHKERRCUSPARSE(stat); }
21297f756511SDominic Meiser     delete (*matstruct)->cprowIndices;
2130c41cb2e2SAlejandro Lamas Daviña     if ((*matstruct)->alpha)     { err=cudaFree((*matstruct)->alpha);CHKERRCUDA(err); }
21317656d835SStefano Zampini     if ((*matstruct)->beta_zero) { err=cudaFree((*matstruct)->beta_zero);CHKERRCUDA(err); }
21327656d835SStefano Zampini     if ((*matstruct)->beta_one)  { err=cudaFree((*matstruct)->beta_one);CHKERRCUDA(err); }
21337f756511SDominic Meiser     delete *matstruct;
21347f756511SDominic Meiser     *matstruct = 0;
21357f756511SDominic Meiser   }
21367f756511SDominic Meiser   PetscFunctionReturn(0);
21377f756511SDominic Meiser }
21387f756511SDominic Meiser 
2139ccdfe979SStefano Zampini static PetscErrorCode MatSeqAIJCUSPARSETriFactors_Reset(Mat_SeqAIJCUSPARSETriFactors** trifactors)
21407f756511SDominic Meiser {
21417f756511SDominic Meiser   PetscFunctionBegin;
21427f756511SDominic Meiser   if (*trifactors) {
2143470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->loTriFactorPtr);
2144470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->upTriFactorPtr);
2145470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->loTriFactorPtrTranspose);
2146470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->upTriFactorPtrTranspose);
21477f756511SDominic Meiser     delete (*trifactors)->rpermIndices;
21487f756511SDominic Meiser     delete (*trifactors)->cpermIndices;
21497f756511SDominic Meiser     delete (*trifactors)->workVector;
2150ccdfe979SStefano Zampini     (*trifactors)->rpermIndices = 0;
2151ccdfe979SStefano Zampini     (*trifactors)->cpermIndices = 0;
2152ccdfe979SStefano Zampini     (*trifactors)->workVector = 0;
2153ccdfe979SStefano Zampini   }
2154ccdfe979SStefano Zampini   PetscFunctionReturn(0);
2155ccdfe979SStefano Zampini }
2156ccdfe979SStefano Zampini 
2157ccdfe979SStefano Zampini static PetscErrorCode MatSeqAIJCUSPARSETriFactors_Destroy(Mat_SeqAIJCUSPARSETriFactors** trifactors)
2158ccdfe979SStefano Zampini {
2159ccdfe979SStefano Zampini   cusparseHandle_t handle;
2160ccdfe979SStefano Zampini   cusparseStatus_t stat;
2161ccdfe979SStefano Zampini 
2162ccdfe979SStefano Zampini   PetscFunctionBegin;
2163ccdfe979SStefano Zampini   if (*trifactors) {
2164ccdfe979SStefano Zampini     MatSeqAIJCUSPARSETriFactors_Reset(trifactors);
21657f756511SDominic Meiser     if (handle = (*trifactors)->handle) {
216657d48284SJunchao Zhang       stat = cusparseDestroy(handle);CHKERRCUSPARSE(stat);
21677f756511SDominic Meiser     }
21687f756511SDominic Meiser     delete *trifactors;
21697f756511SDominic Meiser     *trifactors = 0;
21707f756511SDominic Meiser   }
21717f756511SDominic Meiser   PetscFunctionReturn(0);
21727f756511SDominic Meiser }
21737f756511SDominic Meiser 
2174