xref: /petsc/src/mat/impls/aij/seq/seqcusparse/aijcusparse.cu (revision 0ce8acde5d9c3c86bc1b2082dfaed4e1ee92a172)
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);
40470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSETriFactors_Destroy(Mat_SeqAIJCUSPARSETriFactors**);
41470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSE_Destroy(Mat_SeqAIJCUSPARSE**);
427f756511SDominic Meiser 
43b06137fdSPaul Mullowney PetscErrorCode MatCUSPARSESetStream(Mat A,const cudaStream_t stream)
44b06137fdSPaul Mullowney {
45b06137fdSPaul Mullowney   cusparseStatus_t   stat;
46b06137fdSPaul Mullowney   Mat_SeqAIJCUSPARSE *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
47b06137fdSPaul Mullowney 
48b06137fdSPaul Mullowney   PetscFunctionBegin;
49b06137fdSPaul Mullowney   cusparsestruct->stream = stream;
5057d48284SJunchao Zhang   stat = cusparseSetStream(cusparsestruct->handle,cusparsestruct->stream);CHKERRCUSPARSE(stat);
51b06137fdSPaul Mullowney   PetscFunctionReturn(0);
52b06137fdSPaul Mullowney }
53b06137fdSPaul Mullowney 
54b06137fdSPaul Mullowney PetscErrorCode MatCUSPARSESetHandle(Mat A,const cusparseHandle_t handle)
55b06137fdSPaul Mullowney {
56b06137fdSPaul Mullowney   cusparseStatus_t   stat;
57b06137fdSPaul Mullowney   Mat_SeqAIJCUSPARSE *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
58b06137fdSPaul Mullowney 
59b06137fdSPaul Mullowney   PetscFunctionBegin;
606b1cf21dSAlejandro Lamas Daviña   if (cusparsestruct->handle != handle) {
6116a2e217SAlejandro Lamas Daviña     if (cusparsestruct->handle) {
6257d48284SJunchao Zhang       stat = cusparseDestroy(cusparsestruct->handle);CHKERRCUSPARSE(stat);
6316a2e217SAlejandro Lamas Daviña     }
64b06137fdSPaul Mullowney     cusparsestruct->handle = handle;
656b1cf21dSAlejandro Lamas Daviña   }
6657d48284SJunchao Zhang   stat = cusparseSetPointerMode(cusparsestruct->handle, CUSPARSE_POINTER_MODE_DEVICE);CHKERRCUSPARSE(stat);
67b06137fdSPaul Mullowney   PetscFunctionReturn(0);
68b06137fdSPaul Mullowney }
69b06137fdSPaul Mullowney 
70b06137fdSPaul Mullowney PetscErrorCode MatCUSPARSEClearHandle(Mat A)
71b06137fdSPaul Mullowney {
72b06137fdSPaul Mullowney   Mat_SeqAIJCUSPARSE *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
73b06137fdSPaul Mullowney   PetscFunctionBegin;
74b06137fdSPaul Mullowney   if (cusparsestruct->handle)
75b06137fdSPaul Mullowney     cusparsestruct->handle = 0;
76b06137fdSPaul Mullowney   PetscFunctionReturn(0);
77b06137fdSPaul Mullowney }
78b06137fdSPaul Mullowney 
79ea799195SBarry Smith PetscErrorCode MatFactorGetSolverType_seqaij_cusparse(Mat A,MatSolverType *type)
809ae82921SPaul Mullowney {
819ae82921SPaul Mullowney   PetscFunctionBegin;
829ae82921SPaul Mullowney   *type = MATSOLVERCUSPARSE;
839ae82921SPaul Mullowney   PetscFunctionReturn(0);
849ae82921SPaul Mullowney }
859ae82921SPaul Mullowney 
86c708e6cdSJed Brown /*MC
87087f3262SPaul Mullowney   MATSOLVERCUSPARSE = "cusparse" - A matrix type providing triangular solvers for seq matrices
88087f3262SPaul Mullowney   on a single GPU of type, seqaijcusparse, aijcusparse, or seqaijcusp, aijcusp. Currently supported
89087f3262SPaul Mullowney   algorithms are ILU(k) and ICC(k). Typically, deeper factorizations (larger k) results in poorer
90087f3262SPaul Mullowney   performance in the triangular solves. Full LU, and Cholesky decompositions can be solved through the
91087f3262SPaul Mullowney   CUSPARSE triangular solve algorithm. However, the performance can be quite poor and thus these
92087f3262SPaul Mullowney   algorithms are not recommended. This class does NOT support direct solver operations.
93c708e6cdSJed Brown 
949ae82921SPaul Mullowney   Level: beginner
95c708e6cdSJed Brown 
963ca39a21SBarry Smith .seealso: PCFactorSetMatSolverType(), MatSolverType, MatCreateSeqAIJCUSPARSE(), MATAIJCUSPARSE, MatCreateAIJCUSPARSE(), MatCUSPARSESetFormat(), MatCUSPARSEStorageFormat, MatCUSPARSEFormatOperation
97c708e6cdSJed Brown M*/
989ae82921SPaul Mullowney 
9942c9c57cSBarry Smith PETSC_EXTERN PetscErrorCode MatGetFactor_seqaijcusparse_cusparse(Mat A,MatFactorType ftype,Mat *B)
1009ae82921SPaul Mullowney {
1019ae82921SPaul Mullowney   PetscErrorCode ierr;
102bc3f50f2SPaul Mullowney   PetscInt       n = A->rmap->n;
1039ae82921SPaul Mullowney 
1049ae82921SPaul Mullowney   PetscFunctionBegin;
105bc3f50f2SPaul Mullowney   ierr = MatCreate(PetscObjectComm((PetscObject)A),B);CHKERRQ(ierr);
106404133a2SPaul Mullowney   (*B)->factortype = ftype;
107bc3f50f2SPaul Mullowney   ierr = MatSetSizes(*B,n,n,n,n);CHKERRQ(ierr);
1089ae82921SPaul Mullowney   ierr = MatSetType(*B,MATSEQAIJCUSPARSE);CHKERRQ(ierr);
1092205254eSKarl Rupp 
110087f3262SPaul Mullowney   if (ftype == MAT_FACTOR_LU || ftype == MAT_FACTOR_ILU || ftype == MAT_FACTOR_ILUDT) {
11133d57670SJed Brown     ierr = MatSetBlockSizesFromMats(*B,A,A);CHKERRQ(ierr);
1129ae82921SPaul Mullowney     (*B)->ops->ilufactorsymbolic = MatILUFactorSymbolic_SeqAIJCUSPARSE;
1139ae82921SPaul Mullowney     (*B)->ops->lufactorsymbolic  = MatLUFactorSymbolic_SeqAIJCUSPARSE;
114087f3262SPaul Mullowney   } else if (ftype == MAT_FACTOR_CHOLESKY || ftype == MAT_FACTOR_ICC) {
115087f3262SPaul Mullowney     (*B)->ops->iccfactorsymbolic      = MatICCFactorSymbolic_SeqAIJCUSPARSE;
116087f3262SPaul Mullowney     (*B)->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_SeqAIJCUSPARSE;
1179ae82921SPaul Mullowney   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Factor type not supported for CUSPARSE Matrix Types");
118bc3f50f2SPaul Mullowney 
119fa03d054SJed Brown   ierr = MatSeqAIJSetPreallocation(*B,MAT_SKIP_ALLOCATION,NULL);CHKERRQ(ierr);
1203ca39a21SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)(*B),"MatFactorGetSolverType_C",MatFactorGetSolverType_seqaij_cusparse);CHKERRQ(ierr);
1219ae82921SPaul Mullowney   PetscFunctionReturn(0);
1229ae82921SPaul Mullowney }
1239ae82921SPaul Mullowney 
124bc3f50f2SPaul Mullowney PETSC_INTERN PetscErrorCode MatCUSPARSESetFormat_SeqAIJCUSPARSE(Mat A,MatCUSPARSEFormatOperation op,MatCUSPARSEStorageFormat format)
125ca45077fSPaul Mullowney {
126aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
1276e111a19SKarl Rupp 
128ca45077fSPaul Mullowney   PetscFunctionBegin;
129ca45077fSPaul Mullowney   switch (op) {
130e057df02SPaul Mullowney   case MAT_CUSPARSE_MULT:
131aa372e3fSPaul Mullowney     cusparsestruct->format = format;
132ca45077fSPaul Mullowney     break;
133e057df02SPaul Mullowney   case MAT_CUSPARSE_ALL:
134aa372e3fSPaul Mullowney     cusparsestruct->format = format;
135ca45077fSPaul Mullowney     break;
136ca45077fSPaul Mullowney   default:
13736d62e41SPaul Mullowney     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"unsupported operation %d for MatCUSPARSEFormatOperation. MAT_CUSPARSE_MULT and MAT_CUSPARSE_ALL are currently supported.",op);
138ca45077fSPaul Mullowney   }
139ca45077fSPaul Mullowney   PetscFunctionReturn(0);
140ca45077fSPaul Mullowney }
1419ae82921SPaul Mullowney 
142e057df02SPaul Mullowney /*@
143e057df02SPaul Mullowney    MatCUSPARSESetFormat - Sets the storage format of CUSPARSE matrices for a particular
144e057df02SPaul Mullowney    operation. Only the MatMult operation can use different GPU storage formats
145aa372e3fSPaul Mullowney    for MPIAIJCUSPARSE matrices.
146e057df02SPaul Mullowney    Not Collective
147e057df02SPaul Mullowney 
148e057df02SPaul Mullowney    Input Parameters:
1498468deeeSKarl Rupp +  A - Matrix of type SEQAIJCUSPARSE
15036d62e41SPaul 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.
1512692e278SPaul Mullowney -  format - MatCUSPARSEStorageFormat (one of MAT_CUSPARSE_CSR, MAT_CUSPARSE_ELL, MAT_CUSPARSE_HYB. The latter two require CUDA 4.2)
152e057df02SPaul Mullowney 
153e057df02SPaul Mullowney    Output Parameter:
154e057df02SPaul Mullowney 
155e057df02SPaul Mullowney    Level: intermediate
156e057df02SPaul Mullowney 
1578468deeeSKarl Rupp .seealso: MatCUSPARSEStorageFormat, MatCUSPARSEFormatOperation
158e057df02SPaul Mullowney @*/
159e057df02SPaul Mullowney PetscErrorCode MatCUSPARSESetFormat(Mat A,MatCUSPARSEFormatOperation op,MatCUSPARSEStorageFormat format)
160e057df02SPaul Mullowney {
161e057df02SPaul Mullowney   PetscErrorCode ierr;
1626e111a19SKarl Rupp 
163e057df02SPaul Mullowney   PetscFunctionBegin;
164e057df02SPaul Mullowney   PetscValidHeaderSpecific(A, MAT_CLASSID,1);
165e057df02SPaul Mullowney   ierr = PetscTryMethod(A, "MatCUSPARSESetFormat_C",(Mat,MatCUSPARSEFormatOperation,MatCUSPARSEStorageFormat),(A,op,format));CHKERRQ(ierr);
166e057df02SPaul Mullowney   PetscFunctionReturn(0);
167e057df02SPaul Mullowney }
168e057df02SPaul Mullowney 
1694416b707SBarry Smith static PetscErrorCode MatSetFromOptions_SeqAIJCUSPARSE(PetscOptionItems *PetscOptionsObject,Mat A)
1709ae82921SPaul Mullowney {
1719ae82921SPaul Mullowney   PetscErrorCode           ierr;
172e057df02SPaul Mullowney   MatCUSPARSEStorageFormat format;
1739ae82921SPaul Mullowney   PetscBool                flg;
174a183c035SDominic Meiser   Mat_SeqAIJCUSPARSE       *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
1756e111a19SKarl Rupp 
1769ae82921SPaul Mullowney   PetscFunctionBegin;
177e55864a3SBarry Smith   ierr = PetscOptionsHead(PetscOptionsObject,"SeqAIJCUSPARSE options");CHKERRQ(ierr);
1789ae82921SPaul Mullowney   if (A->factortype==MAT_FACTOR_NONE) {
179e057df02SPaul Mullowney     ierr = PetscOptionsEnum("-mat_cusparse_mult_storage_format","sets storage format of (seq)aijcusparse gpu matrices for SpMV",
180a183c035SDominic Meiser                             "MatCUSPARSESetFormat",MatCUSPARSEStorageFormats,(PetscEnum)cusparsestruct->format,(PetscEnum*)&format,&flg);CHKERRQ(ierr);
181e057df02SPaul Mullowney     if (flg) {
182e057df02SPaul Mullowney       ierr = MatCUSPARSESetFormat(A,MAT_CUSPARSE_MULT,format);CHKERRQ(ierr);
183045c96e1SPaul Mullowney     }
1849ae82921SPaul Mullowney   }
1854c87dfd4SPaul Mullowney   ierr = PetscOptionsEnum("-mat_cusparse_storage_format","sets storage format of (seq)aijcusparse gpu matrices for SpMV and TriSolve",
186a183c035SDominic Meiser                           "MatCUSPARSESetFormat",MatCUSPARSEStorageFormats,(PetscEnum)cusparsestruct->format,(PetscEnum*)&format,&flg);CHKERRQ(ierr);
1874c87dfd4SPaul Mullowney   if (flg) {
1884c87dfd4SPaul Mullowney     ierr = MatCUSPARSESetFormat(A,MAT_CUSPARSE_ALL,format);CHKERRQ(ierr);
1894c87dfd4SPaul Mullowney   }
1900af67c1bSStefano Zampini   ierr = PetscOptionsTail();CHKERRQ(ierr);
1919ae82921SPaul Mullowney   PetscFunctionReturn(0);
1929ae82921SPaul Mullowney 
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;
452087f3262SPaul Mullowney   ierr = MatSeqAIJCUSPARSEBuildILULowerTriMatrix(A);CHKERRQ(ierr);
453087f3262SPaul Mullowney   ierr = MatSeqAIJCUSPARSEBuildILUUpperTriMatrix(A);CHKERRQ(ierr);
4542205254eSKarl Rupp 
455e65717acSKarl Rupp   cusparseTriFactors->workVector = new THRUSTARRAY(n);
456aa372e3fSPaul Mullowney   cusparseTriFactors->nnz=a->nz;
4579ae82921SPaul Mullowney 
458c70f7ee4SJunchao Zhang   A->offloadmask = PETSC_OFFLOAD_BOTH;
459e057df02SPaul Mullowney   /* lower triangular indices */
4609ae82921SPaul Mullowney   ierr = ISGetIndices(isrow,&r);CHKERRQ(ierr);
4619ae82921SPaul Mullowney   ierr = ISIdentity(isrow,&row_identity);CHKERRQ(ierr);
4622205254eSKarl Rupp   if (!row_identity) {
463aa372e3fSPaul Mullowney     cusparseTriFactors->rpermIndices = new THRUSTINTARRAY(n);
464aa372e3fSPaul Mullowney     cusparseTriFactors->rpermIndices->assign(r, r+n);
4652205254eSKarl Rupp   }
4669ae82921SPaul Mullowney   ierr = ISRestoreIndices(isrow,&r);CHKERRQ(ierr);
4679ae82921SPaul Mullowney 
468e057df02SPaul Mullowney   /* upper triangular indices */
4699ae82921SPaul Mullowney   ierr = ISGetIndices(iscol,&c);CHKERRQ(ierr);
4709ae82921SPaul Mullowney   ierr = ISIdentity(iscol,&col_identity);CHKERRQ(ierr);
4712205254eSKarl Rupp   if (!col_identity) {
472aa372e3fSPaul Mullowney     cusparseTriFactors->cpermIndices = new THRUSTINTARRAY(n);
473aa372e3fSPaul Mullowney     cusparseTriFactors->cpermIndices->assign(c, c+n);
4742205254eSKarl Rupp   }
4754863603aSSatish Balay 
4764863603aSSatish Balay   if (!row_identity && !col_identity) {
4774863603aSSatish Balay     ierr = PetscLogCpuToGpu(2*n*sizeof(PetscInt));CHKERRQ(ierr);
4784863603aSSatish Balay   } else if(!row_identity) {
4794863603aSSatish Balay     ierr = PetscLogCpuToGpu(n*sizeof(PetscInt));CHKERRQ(ierr);
4804863603aSSatish Balay   } else if(!col_identity) {
4814863603aSSatish Balay     ierr = PetscLogCpuToGpu(n*sizeof(PetscInt));CHKERRQ(ierr);
4824863603aSSatish Balay   }
4834863603aSSatish Balay 
4849ae82921SPaul Mullowney   ierr = ISRestoreIndices(iscol,&c);CHKERRQ(ierr);
4859ae82921SPaul Mullowney   PetscFunctionReturn(0);
4869ae82921SPaul Mullowney }
4879ae82921SPaul Mullowney 
488087f3262SPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEBuildICCTriMatrices(Mat A)
489087f3262SPaul Mullowney {
490087f3262SPaul Mullowney   Mat_SeqAIJ                        *a = (Mat_SeqAIJ*)A->data;
491087f3262SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
492aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
493aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
494087f3262SPaul Mullowney   cusparseStatus_t                  stat;
495087f3262SPaul Mullowney   PetscErrorCode                    ierr;
49657d48284SJunchao Zhang   cudaError_t                       cerr;
497087f3262SPaul Mullowney   PetscInt                          *AiUp, *AjUp;
498087f3262SPaul Mullowney   PetscScalar                       *AAUp;
499087f3262SPaul Mullowney   PetscScalar                       *AALo;
500087f3262SPaul Mullowney   PetscInt                          nzUpper = a->nz,n = A->rmap->n,i,offset,nz,j;
501087f3262SPaul Mullowney   Mat_SeqSBAIJ                      *b = (Mat_SeqSBAIJ*)A->data;
502087f3262SPaul Mullowney   const PetscInt                    *ai = b->i,*aj = b->j,*vj;
503087f3262SPaul Mullowney   const MatScalar                   *aa = b->a,*v;
504087f3262SPaul Mullowney 
505087f3262SPaul Mullowney   PetscFunctionBegin;
506cf00fe3bSKarl Rupp   if (!n) PetscFunctionReturn(0);
507c70f7ee4SJunchao Zhang   if (A->offloadmask == PETSC_OFFLOAD_UNALLOCATED || A->offloadmask == PETSC_OFFLOAD_CPU) {
508087f3262SPaul Mullowney     try {
509087f3262SPaul Mullowney       /* Allocate Space for the upper triangular matrix */
51057d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AiUp, (n+1)*sizeof(PetscInt));CHKERRCUDA(cerr);
51157d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AjUp, nzUpper*sizeof(PetscInt));CHKERRCUDA(cerr);
51257d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AAUp, nzUpper*sizeof(PetscScalar));CHKERRCUDA(cerr);
51357d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AALo, nzUpper*sizeof(PetscScalar));CHKERRCUDA(cerr);
514087f3262SPaul Mullowney 
515087f3262SPaul Mullowney       /* Fill the upper triangular matrix */
516087f3262SPaul Mullowney       AiUp[0]=(PetscInt) 0;
517087f3262SPaul Mullowney       AiUp[n]=nzUpper;
518087f3262SPaul Mullowney       offset = 0;
519087f3262SPaul Mullowney       for (i=0; i<n; i++) {
520087f3262SPaul Mullowney         /* set the pointers */
521087f3262SPaul Mullowney         v  = aa + ai[i];
522087f3262SPaul Mullowney         vj = aj + ai[i];
523087f3262SPaul Mullowney         nz = ai[i+1] - ai[i] - 1; /* exclude diag[i] */
524087f3262SPaul Mullowney 
525087f3262SPaul Mullowney         /* first, set the diagonal elements */
526087f3262SPaul Mullowney         AjUp[offset] = (PetscInt) i;
52709f51544SAlejandro Lamas Daviña         AAUp[offset] = (MatScalar)1.0/v[nz];
528087f3262SPaul Mullowney         AiUp[i]      = offset;
52909f51544SAlejandro Lamas Daviña         AALo[offset] = (MatScalar)1.0/v[nz];
530087f3262SPaul Mullowney 
531087f3262SPaul Mullowney         offset+=1;
532087f3262SPaul Mullowney         if (nz>0) {
533f22e0265SBarry Smith           ierr = PetscArraycpy(&(AjUp[offset]), vj, nz);CHKERRQ(ierr);
534580bdb30SBarry Smith           ierr = PetscArraycpy(&(AAUp[offset]), v, nz);CHKERRQ(ierr);
535087f3262SPaul Mullowney           for (j=offset; j<offset+nz; j++) {
536087f3262SPaul Mullowney             AAUp[j] = -AAUp[j];
537087f3262SPaul Mullowney             AALo[j] = AAUp[j]/v[nz];
538087f3262SPaul Mullowney           }
539087f3262SPaul Mullowney           offset+=nz;
540087f3262SPaul Mullowney         }
541087f3262SPaul Mullowney       }
542087f3262SPaul Mullowney 
543aa372e3fSPaul Mullowney       /* allocate space for the triangular factor information */
544aa372e3fSPaul Mullowney       upTriFactor = new Mat_SeqAIJCUSPARSETriFactorStruct;
545087f3262SPaul Mullowney 
546aa372e3fSPaul Mullowney       /* Create the matrix description */
54757d48284SJunchao Zhang       stat = cusparseCreateMatDescr(&upTriFactor->descr);CHKERRCUSPARSE(stat);
54857d48284SJunchao Zhang       stat = cusparseSetMatIndexBase(upTriFactor->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
54957d48284SJunchao Zhang       stat = cusparseSetMatType(upTriFactor->descr, CUSPARSE_MATRIX_TYPE_TRIANGULAR);CHKERRCUSPARSE(stat);
55057d48284SJunchao Zhang       stat = cusparseSetMatFillMode(upTriFactor->descr, CUSPARSE_FILL_MODE_UPPER);CHKERRCUSPARSE(stat);
55157d48284SJunchao Zhang       stat = cusparseSetMatDiagType(upTriFactor->descr, CUSPARSE_DIAG_TYPE_UNIT);CHKERRCUSPARSE(stat);
552087f3262SPaul Mullowney 
553aa372e3fSPaul Mullowney       /* Create the solve analysis information */
55457d48284SJunchao Zhang       stat = cusparseCreateSolveAnalysisInfo(&upTriFactor->solveInfo);CHKERRCUSPARSE(stat);
555aa372e3fSPaul Mullowney 
556aa372e3fSPaul Mullowney       /* set the operation */
557aa372e3fSPaul Mullowney       upTriFactor->solveOp = CUSPARSE_OPERATION_NON_TRANSPOSE;
558aa372e3fSPaul Mullowney 
559aa372e3fSPaul Mullowney       /* set the matrix */
560aa372e3fSPaul Mullowney       upTriFactor->csrMat = new CsrMatrix;
561aa372e3fSPaul Mullowney       upTriFactor->csrMat->num_rows = A->rmap->n;
562aa372e3fSPaul Mullowney       upTriFactor->csrMat->num_cols = A->cmap->n;
563aa372e3fSPaul Mullowney       upTriFactor->csrMat->num_entries = a->nz;
564aa372e3fSPaul Mullowney 
565aa372e3fSPaul Mullowney       upTriFactor->csrMat->row_offsets = new THRUSTINTARRAY32(A->rmap->n+1);
566aa372e3fSPaul Mullowney       upTriFactor->csrMat->row_offsets->assign(AiUp, AiUp+A->rmap->n+1);
567aa372e3fSPaul Mullowney 
568aa372e3fSPaul Mullowney       upTriFactor->csrMat->column_indices = new THRUSTINTARRAY32(a->nz);
569aa372e3fSPaul Mullowney       upTriFactor->csrMat->column_indices->assign(AjUp, AjUp+a->nz);
570aa372e3fSPaul Mullowney 
571aa372e3fSPaul Mullowney       upTriFactor->csrMat->values = new THRUSTARRAY(a->nz);
572aa372e3fSPaul Mullowney       upTriFactor->csrMat->values->assign(AAUp, AAUp+a->nz);
573aa372e3fSPaul Mullowney 
574aa372e3fSPaul Mullowney       /* perform the solve analysis */
575aa372e3fSPaul Mullowney       stat = cusparse_analysis(cusparseTriFactors->handle, upTriFactor->solveOp,
576aa372e3fSPaul Mullowney                                upTriFactor->csrMat->num_rows, upTriFactor->csrMat->num_entries, upTriFactor->descr,
577aa372e3fSPaul Mullowney                                upTriFactor->csrMat->values->data().get(), upTriFactor->csrMat->row_offsets->data().get(),
57857d48284SJunchao Zhang                                upTriFactor->csrMat->column_indices->data().get(), upTriFactor->solveInfo);CHKERRCUSPARSE(stat);
579aa372e3fSPaul Mullowney 
580aa372e3fSPaul Mullowney       /* assign the pointer. Is this really necessary? */
581aa372e3fSPaul Mullowney       ((Mat_SeqAIJCUSPARSETriFactors*)A->spptr)->upTriFactorPtr = upTriFactor;
582aa372e3fSPaul Mullowney 
583aa372e3fSPaul Mullowney       /* allocate space for the triangular factor information */
584aa372e3fSPaul Mullowney       loTriFactor = new Mat_SeqAIJCUSPARSETriFactorStruct;
585aa372e3fSPaul Mullowney 
586aa372e3fSPaul Mullowney       /* Create the matrix description */
58757d48284SJunchao Zhang       stat = cusparseCreateMatDescr(&loTriFactor->descr);CHKERRCUSPARSE(stat);
58857d48284SJunchao Zhang       stat = cusparseSetMatIndexBase(loTriFactor->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
58957d48284SJunchao Zhang       stat = cusparseSetMatType(loTriFactor->descr, CUSPARSE_MATRIX_TYPE_TRIANGULAR);CHKERRCUSPARSE(stat);
59057d48284SJunchao Zhang       stat = cusparseSetMatFillMode(loTriFactor->descr, CUSPARSE_FILL_MODE_UPPER);CHKERRCUSPARSE(stat);
59157d48284SJunchao Zhang       stat = cusparseSetMatDiagType(loTriFactor->descr, CUSPARSE_DIAG_TYPE_NON_UNIT);CHKERRCUSPARSE(stat);
592aa372e3fSPaul Mullowney 
593aa372e3fSPaul Mullowney       /* Create the solve analysis information */
59457d48284SJunchao Zhang       stat = cusparseCreateSolveAnalysisInfo(&loTriFactor->solveInfo);CHKERRCUSPARSE(stat);
595aa372e3fSPaul Mullowney 
596aa372e3fSPaul Mullowney       /* set the operation */
597aa372e3fSPaul Mullowney       loTriFactor->solveOp = CUSPARSE_OPERATION_TRANSPOSE;
598aa372e3fSPaul Mullowney 
599aa372e3fSPaul Mullowney       /* set the matrix */
600aa372e3fSPaul Mullowney       loTriFactor->csrMat = new CsrMatrix;
601aa372e3fSPaul Mullowney       loTriFactor->csrMat->num_rows = A->rmap->n;
602aa372e3fSPaul Mullowney       loTriFactor->csrMat->num_cols = A->cmap->n;
603aa372e3fSPaul Mullowney       loTriFactor->csrMat->num_entries = a->nz;
604aa372e3fSPaul Mullowney 
605aa372e3fSPaul Mullowney       loTriFactor->csrMat->row_offsets = new THRUSTINTARRAY32(A->rmap->n+1);
606aa372e3fSPaul Mullowney       loTriFactor->csrMat->row_offsets->assign(AiUp, AiUp+A->rmap->n+1);
607aa372e3fSPaul Mullowney 
608aa372e3fSPaul Mullowney       loTriFactor->csrMat->column_indices = new THRUSTINTARRAY32(a->nz);
609aa372e3fSPaul Mullowney       loTriFactor->csrMat->column_indices->assign(AjUp, AjUp+a->nz);
610aa372e3fSPaul Mullowney 
611aa372e3fSPaul Mullowney       loTriFactor->csrMat->values = new THRUSTARRAY(a->nz);
612aa372e3fSPaul Mullowney       loTriFactor->csrMat->values->assign(AALo, AALo+a->nz);
6134863603aSSatish Balay       ierr = PetscLogCpuToGpu(2*(((A->rmap->n+1)+(a->nz))*sizeof(int)+(a->nz)*sizeof(PetscScalar)));CHKERRQ(ierr);
614aa372e3fSPaul Mullowney 
615aa372e3fSPaul Mullowney       /* perform the solve analysis */
616aa372e3fSPaul Mullowney       stat = cusparse_analysis(cusparseTriFactors->handle, loTriFactor->solveOp,
617aa372e3fSPaul Mullowney                                loTriFactor->csrMat->num_rows, loTriFactor->csrMat->num_entries, loTriFactor->descr,
618aa372e3fSPaul Mullowney                                loTriFactor->csrMat->values->data().get(), loTriFactor->csrMat->row_offsets->data().get(),
61957d48284SJunchao Zhang                                loTriFactor->csrMat->column_indices->data().get(), loTriFactor->solveInfo);CHKERRCUSPARSE(stat);
620aa372e3fSPaul Mullowney 
621aa372e3fSPaul Mullowney       /* assign the pointer. Is this really necessary? */
622aa372e3fSPaul Mullowney       ((Mat_SeqAIJCUSPARSETriFactors*)A->spptr)->loTriFactorPtr = loTriFactor;
623087f3262SPaul Mullowney 
624c70f7ee4SJunchao Zhang       A->offloadmask = PETSC_OFFLOAD_BOTH;
62557d48284SJunchao Zhang       cerr = cudaFreeHost(AiUp);CHKERRCUDA(cerr);
62657d48284SJunchao Zhang       cerr = cudaFreeHost(AjUp);CHKERRCUDA(cerr);
62757d48284SJunchao Zhang       cerr = cudaFreeHost(AAUp);CHKERRCUDA(cerr);
62857d48284SJunchao Zhang       cerr = cudaFreeHost(AALo);CHKERRCUDA(cerr);
629087f3262SPaul Mullowney     } catch(char *ex) {
630087f3262SPaul Mullowney       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
631087f3262SPaul Mullowney     }
632087f3262SPaul Mullowney   }
633087f3262SPaul Mullowney   PetscFunctionReturn(0);
634087f3262SPaul Mullowney }
635087f3262SPaul Mullowney 
636087f3262SPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEICCAnalysisAndCopyToGPU(Mat A)
6379ae82921SPaul Mullowney {
6389ae82921SPaul Mullowney   PetscErrorCode               ierr;
639087f3262SPaul Mullowney   Mat_SeqAIJ                   *a                  = (Mat_SeqAIJ*)A->data;
640087f3262SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
641087f3262SPaul Mullowney   IS                           ip = a->row;
642087f3262SPaul Mullowney   const PetscInt               *rip;
643087f3262SPaul Mullowney   PetscBool                    perm_identity;
644087f3262SPaul Mullowney   PetscInt                     n = A->rmap->n;
645087f3262SPaul Mullowney 
646087f3262SPaul Mullowney   PetscFunctionBegin;
647087f3262SPaul Mullowney   ierr = MatSeqAIJCUSPARSEBuildICCTriMatrices(A);CHKERRQ(ierr);
648e65717acSKarl Rupp   cusparseTriFactors->workVector = new THRUSTARRAY(n);
649aa372e3fSPaul Mullowney   cusparseTriFactors->nnz=(a->nz-n)*2 + n;
650aa372e3fSPaul Mullowney 
651087f3262SPaul Mullowney   /* lower triangular indices */
652087f3262SPaul Mullowney   ierr = ISGetIndices(ip,&rip);CHKERRQ(ierr);
653087f3262SPaul Mullowney   ierr = ISIdentity(ip,&perm_identity);CHKERRQ(ierr);
654087f3262SPaul Mullowney   if (!perm_identity) {
6554e4bbfaaSStefano Zampini     IS             iip;
6564e4bbfaaSStefano Zampini     const PetscInt *irip;
6574e4bbfaaSStefano Zampini 
6584e4bbfaaSStefano Zampini     ierr = ISInvertPermutation(ip,PETSC_DECIDE,&iip);CHKERRQ(ierr);
6594e4bbfaaSStefano Zampini     ierr = ISGetIndices(iip,&irip);CHKERRQ(ierr);
660aa372e3fSPaul Mullowney     cusparseTriFactors->rpermIndices = new THRUSTINTARRAY(n);
661aa372e3fSPaul Mullowney     cusparseTriFactors->rpermIndices->assign(rip, rip+n);
662aa372e3fSPaul Mullowney     cusparseTriFactors->cpermIndices = new THRUSTINTARRAY(n);
6634e4bbfaaSStefano Zampini     cusparseTriFactors->cpermIndices->assign(irip, irip+n);
6644e4bbfaaSStefano Zampini     ierr = ISRestoreIndices(iip,&irip);CHKERRQ(ierr);
6654e4bbfaaSStefano Zampini     ierr = ISDestroy(&iip);CHKERRQ(ierr);
6664863603aSSatish Balay     ierr = PetscLogCpuToGpu(2*n*sizeof(PetscInt));CHKERRQ(ierr);
667087f3262SPaul Mullowney   }
668087f3262SPaul Mullowney   ierr = ISRestoreIndices(ip,&rip);CHKERRQ(ierr);
669087f3262SPaul Mullowney   PetscFunctionReturn(0);
670087f3262SPaul Mullowney }
671087f3262SPaul Mullowney 
6726fa9248bSJed Brown static PetscErrorCode MatLUFactorNumeric_SeqAIJCUSPARSE(Mat B,Mat A,const MatFactorInfo *info)
6739ae82921SPaul Mullowney {
6749ae82921SPaul Mullowney   Mat_SeqAIJ     *b = (Mat_SeqAIJ*)B->data;
6759ae82921SPaul Mullowney   IS             isrow = b->row,iscol = b->col;
6769ae82921SPaul Mullowney   PetscBool      row_identity,col_identity;
677b175d8bbSPaul Mullowney   PetscErrorCode ierr;
6789ae82921SPaul Mullowney 
6799ae82921SPaul Mullowney   PetscFunctionBegin;
6809ae82921SPaul Mullowney   ierr = MatLUFactorNumeric_SeqAIJ(B,A,info);CHKERRQ(ierr);
681e057df02SPaul Mullowney   /* determine which version of MatSolve needs to be used. */
6829ae82921SPaul Mullowney   ierr = ISIdentity(isrow,&row_identity);CHKERRQ(ierr);
6839ae82921SPaul Mullowney   ierr = ISIdentity(iscol,&col_identity);CHKERRQ(ierr);
684bda325fcSPaul Mullowney   if (row_identity && col_identity) {
685bda325fcSPaul Mullowney     B->ops->solve = MatSolve_SeqAIJCUSPARSE_NaturalOrdering;
686bda325fcSPaul Mullowney     B->ops->solvetranspose = MatSolveTranspose_SeqAIJCUSPARSE_NaturalOrdering;
6874e4bbfaaSStefano Zampini     B->ops->matsolve = NULL;
6884e4bbfaaSStefano Zampini     B->ops->matsolvetranspose = NULL;
689bda325fcSPaul Mullowney   } else {
690bda325fcSPaul Mullowney     B->ops->solve = MatSolve_SeqAIJCUSPARSE;
691bda325fcSPaul Mullowney     B->ops->solvetranspose = MatSolveTranspose_SeqAIJCUSPARSE;
6924e4bbfaaSStefano Zampini     B->ops->matsolve = NULL;
6934e4bbfaaSStefano Zampini     B->ops->matsolvetranspose = NULL;
694bda325fcSPaul Mullowney   }
6958dc1d2a3SPaul Mullowney 
696e057df02SPaul Mullowney   /* get the triangular factors */
697087f3262SPaul Mullowney   ierr = MatSeqAIJCUSPARSEILUAnalysisAndCopyToGPU(B);CHKERRQ(ierr);
6989ae82921SPaul Mullowney   PetscFunctionReturn(0);
6999ae82921SPaul Mullowney }
7009ae82921SPaul Mullowney 
701087f3262SPaul Mullowney static PetscErrorCode MatCholeskyFactorNumeric_SeqAIJCUSPARSE(Mat B,Mat A,const MatFactorInfo *info)
702087f3262SPaul Mullowney {
703087f3262SPaul Mullowney   Mat_SeqAIJ     *b = (Mat_SeqAIJ*)B->data;
704087f3262SPaul Mullowney   IS             ip = b->row;
705087f3262SPaul Mullowney   PetscBool      perm_identity;
706b175d8bbSPaul Mullowney   PetscErrorCode ierr;
707087f3262SPaul Mullowney 
708087f3262SPaul Mullowney   PetscFunctionBegin;
709087f3262SPaul Mullowney   ierr = MatCholeskyFactorNumeric_SeqAIJ(B,A,info);CHKERRQ(ierr);
710087f3262SPaul Mullowney 
711087f3262SPaul Mullowney   /* determine which version of MatSolve needs to be used. */
712087f3262SPaul Mullowney   ierr = ISIdentity(ip,&perm_identity);CHKERRQ(ierr);
713087f3262SPaul Mullowney   if (perm_identity) {
714087f3262SPaul Mullowney     B->ops->solve = MatSolve_SeqAIJCUSPARSE_NaturalOrdering;
715087f3262SPaul Mullowney     B->ops->solvetranspose = MatSolveTranspose_SeqAIJCUSPARSE_NaturalOrdering;
7164e4bbfaaSStefano Zampini     B->ops->matsolve = NULL;
7174e4bbfaaSStefano Zampini     B->ops->matsolvetranspose = NULL;
718087f3262SPaul Mullowney   } else {
719087f3262SPaul Mullowney     B->ops->solve = MatSolve_SeqAIJCUSPARSE;
720087f3262SPaul Mullowney     B->ops->solvetranspose = MatSolveTranspose_SeqAIJCUSPARSE;
7214e4bbfaaSStefano Zampini     B->ops->matsolve = NULL;
7224e4bbfaaSStefano Zampini     B->ops->matsolvetranspose = NULL;
723087f3262SPaul Mullowney   }
724087f3262SPaul Mullowney 
725087f3262SPaul Mullowney   /* get the triangular factors */
726087f3262SPaul Mullowney   ierr = MatSeqAIJCUSPARSEICCAnalysisAndCopyToGPU(B);CHKERRQ(ierr);
727087f3262SPaul Mullowney   PetscFunctionReturn(0);
728087f3262SPaul Mullowney }
7299ae82921SPaul Mullowney 
730b175d8bbSPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEAnalyzeTransposeForSolve(Mat A)
731bda325fcSPaul Mullowney {
732bda325fcSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
733aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
734aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
735aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
736aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
737bda325fcSPaul Mullowney   cusparseStatus_t                  stat;
738aa372e3fSPaul Mullowney   cusparseIndexBase_t               indexBase;
739aa372e3fSPaul Mullowney   cusparseMatrixType_t              matrixType;
740aa372e3fSPaul Mullowney   cusparseFillMode_t                fillMode;
741aa372e3fSPaul Mullowney   cusparseDiagType_t                diagType;
742b175d8bbSPaul Mullowney 
743bda325fcSPaul Mullowney   PetscFunctionBegin;
744bda325fcSPaul Mullowney 
745aa372e3fSPaul Mullowney   /*********************************************/
746aa372e3fSPaul Mullowney   /* Now the Transpose of the Lower Tri Factor */
747aa372e3fSPaul Mullowney   /*********************************************/
748aa372e3fSPaul Mullowney 
749aa372e3fSPaul Mullowney   /* allocate space for the transpose of the lower triangular factor */
750aa372e3fSPaul Mullowney   loTriFactorT = new Mat_SeqAIJCUSPARSETriFactorStruct;
751aa372e3fSPaul Mullowney 
752aa372e3fSPaul Mullowney   /* set the matrix descriptors of the lower triangular factor */
753aa372e3fSPaul Mullowney   matrixType = cusparseGetMatType(loTriFactor->descr);
754aa372e3fSPaul Mullowney   indexBase = cusparseGetMatIndexBase(loTriFactor->descr);
755aa372e3fSPaul Mullowney   fillMode = cusparseGetMatFillMode(loTriFactor->descr)==CUSPARSE_FILL_MODE_UPPER ?
756aa372e3fSPaul Mullowney     CUSPARSE_FILL_MODE_LOWER : CUSPARSE_FILL_MODE_UPPER;
757aa372e3fSPaul Mullowney   diagType = cusparseGetMatDiagType(loTriFactor->descr);
758aa372e3fSPaul Mullowney 
759aa372e3fSPaul Mullowney   /* Create the matrix description */
76057d48284SJunchao Zhang   stat = cusparseCreateMatDescr(&loTriFactorT->descr);CHKERRCUSPARSE(stat);
76157d48284SJunchao Zhang   stat = cusparseSetMatIndexBase(loTriFactorT->descr, indexBase);CHKERRCUSPARSE(stat);
76257d48284SJunchao Zhang   stat = cusparseSetMatType(loTriFactorT->descr, matrixType);CHKERRCUSPARSE(stat);
76357d48284SJunchao Zhang   stat = cusparseSetMatFillMode(loTriFactorT->descr, fillMode);CHKERRCUSPARSE(stat);
76457d48284SJunchao Zhang   stat = cusparseSetMatDiagType(loTriFactorT->descr, diagType);CHKERRCUSPARSE(stat);
765aa372e3fSPaul Mullowney 
766aa372e3fSPaul Mullowney   /* Create the solve analysis information */
76757d48284SJunchao Zhang   stat = cusparseCreateSolveAnalysisInfo(&loTriFactorT->solveInfo);CHKERRCUSPARSE(stat);
768aa372e3fSPaul Mullowney 
769aa372e3fSPaul Mullowney   /* set the operation */
770aa372e3fSPaul Mullowney   loTriFactorT->solveOp = CUSPARSE_OPERATION_NON_TRANSPOSE;
771aa372e3fSPaul Mullowney 
772aa372e3fSPaul Mullowney   /* allocate GPU space for the CSC of the lower triangular factor*/
773aa372e3fSPaul Mullowney   loTriFactorT->csrMat = new CsrMatrix;
774aa372e3fSPaul Mullowney   loTriFactorT->csrMat->num_rows = loTriFactor->csrMat->num_rows;
775aa372e3fSPaul Mullowney   loTriFactorT->csrMat->num_cols = loTriFactor->csrMat->num_cols;
776aa372e3fSPaul Mullowney   loTriFactorT->csrMat->num_entries = loTriFactor->csrMat->num_entries;
777aa372e3fSPaul Mullowney   loTriFactorT->csrMat->row_offsets = new THRUSTINTARRAY32(loTriFactor->csrMat->num_rows+1);
778aa372e3fSPaul Mullowney   loTriFactorT->csrMat->column_indices = new THRUSTINTARRAY32(loTriFactor->csrMat->num_entries);
779aa372e3fSPaul Mullowney   loTriFactorT->csrMat->values = new THRUSTARRAY(loTriFactor->csrMat->num_entries);
780aa372e3fSPaul Mullowney 
781aa372e3fSPaul Mullowney   /* compute the transpose of the lower triangular factor, i.e. the CSC */
782aa372e3fSPaul Mullowney   stat = cusparse_csr2csc(cusparseTriFactors->handle, loTriFactor->csrMat->num_rows,
783aa372e3fSPaul Mullowney                           loTriFactor->csrMat->num_cols, loTriFactor->csrMat->num_entries,
784aa372e3fSPaul Mullowney                           loTriFactor->csrMat->values->data().get(),
785aa372e3fSPaul Mullowney                           loTriFactor->csrMat->row_offsets->data().get(),
786aa372e3fSPaul Mullowney                           loTriFactor->csrMat->column_indices->data().get(),
787aa372e3fSPaul Mullowney                           loTriFactorT->csrMat->values->data().get(),
788aa372e3fSPaul Mullowney                           loTriFactorT->csrMat->column_indices->data().get(),
789aa372e3fSPaul Mullowney                           loTriFactorT->csrMat->row_offsets->data().get(),
79057d48284SJunchao Zhang                           CUSPARSE_ACTION_NUMERIC, indexBase);CHKERRCUSPARSE(stat);
791aa372e3fSPaul Mullowney 
792aa372e3fSPaul Mullowney   /* perform the solve analysis on the transposed matrix */
793aa372e3fSPaul Mullowney   stat = cusparse_analysis(cusparseTriFactors->handle, loTriFactorT->solveOp,
794aa372e3fSPaul Mullowney                            loTriFactorT->csrMat->num_rows, loTriFactorT->csrMat->num_entries,
795aa372e3fSPaul Mullowney                            loTriFactorT->descr, loTriFactorT->csrMat->values->data().get(),
796aa372e3fSPaul Mullowney                            loTriFactorT->csrMat->row_offsets->data().get(), loTriFactorT->csrMat->column_indices->data().get(),
79757d48284SJunchao Zhang                            loTriFactorT->solveInfo);CHKERRCUSPARSE(stat);
798aa372e3fSPaul Mullowney 
799aa372e3fSPaul Mullowney   /* assign the pointer. Is this really necessary? */
800aa372e3fSPaul Mullowney   ((Mat_SeqAIJCUSPARSETriFactors*)A->spptr)->loTriFactorPtrTranspose = loTriFactorT;
801aa372e3fSPaul Mullowney 
802aa372e3fSPaul Mullowney   /*********************************************/
803aa372e3fSPaul Mullowney   /* Now the Transpose of the Upper Tri Factor */
804aa372e3fSPaul Mullowney   /*********************************************/
805aa372e3fSPaul Mullowney 
806aa372e3fSPaul Mullowney   /* allocate space for the transpose of the upper triangular factor */
807aa372e3fSPaul Mullowney   upTriFactorT = new Mat_SeqAIJCUSPARSETriFactorStruct;
808aa372e3fSPaul Mullowney 
809aa372e3fSPaul Mullowney   /* set the matrix descriptors of the upper triangular factor */
810aa372e3fSPaul Mullowney   matrixType = cusparseGetMatType(upTriFactor->descr);
811aa372e3fSPaul Mullowney   indexBase = cusparseGetMatIndexBase(upTriFactor->descr);
812aa372e3fSPaul Mullowney   fillMode = cusparseGetMatFillMode(upTriFactor->descr)==CUSPARSE_FILL_MODE_UPPER ?
813aa372e3fSPaul Mullowney     CUSPARSE_FILL_MODE_LOWER : CUSPARSE_FILL_MODE_UPPER;
814aa372e3fSPaul Mullowney   diagType = cusparseGetMatDiagType(upTriFactor->descr);
815aa372e3fSPaul Mullowney 
816aa372e3fSPaul Mullowney   /* Create the matrix description */
81757d48284SJunchao Zhang   stat = cusparseCreateMatDescr(&upTriFactorT->descr);CHKERRCUSPARSE(stat);
81857d48284SJunchao Zhang   stat = cusparseSetMatIndexBase(upTriFactorT->descr, indexBase);CHKERRCUSPARSE(stat);
81957d48284SJunchao Zhang   stat = cusparseSetMatType(upTriFactorT->descr, matrixType);CHKERRCUSPARSE(stat);
82057d48284SJunchao Zhang   stat = cusparseSetMatFillMode(upTriFactorT->descr, fillMode);CHKERRCUSPARSE(stat);
82157d48284SJunchao Zhang   stat = cusparseSetMatDiagType(upTriFactorT->descr, diagType);CHKERRCUSPARSE(stat);
822aa372e3fSPaul Mullowney 
823aa372e3fSPaul Mullowney   /* Create the solve analysis information */
82457d48284SJunchao Zhang   stat = cusparseCreateSolveAnalysisInfo(&upTriFactorT->solveInfo);CHKERRCUSPARSE(stat);
825aa372e3fSPaul Mullowney 
826aa372e3fSPaul Mullowney   /* set the operation */
827aa372e3fSPaul Mullowney   upTriFactorT->solveOp = CUSPARSE_OPERATION_NON_TRANSPOSE;
828aa372e3fSPaul Mullowney 
829aa372e3fSPaul Mullowney   /* allocate GPU space for the CSC of the upper triangular factor*/
830aa372e3fSPaul Mullowney   upTriFactorT->csrMat = new CsrMatrix;
831aa372e3fSPaul Mullowney   upTriFactorT->csrMat->num_rows = upTriFactor->csrMat->num_rows;
832aa372e3fSPaul Mullowney   upTriFactorT->csrMat->num_cols = upTriFactor->csrMat->num_cols;
833aa372e3fSPaul Mullowney   upTriFactorT->csrMat->num_entries = upTriFactor->csrMat->num_entries;
834aa372e3fSPaul Mullowney   upTriFactorT->csrMat->row_offsets = new THRUSTINTARRAY32(upTriFactor->csrMat->num_rows+1);
835aa372e3fSPaul Mullowney   upTriFactorT->csrMat->column_indices = new THRUSTINTARRAY32(upTriFactor->csrMat->num_entries);
836aa372e3fSPaul Mullowney   upTriFactorT->csrMat->values = new THRUSTARRAY(upTriFactor->csrMat->num_entries);
837aa372e3fSPaul Mullowney 
838aa372e3fSPaul Mullowney   /* compute the transpose of the upper triangular factor, i.e. the CSC */
839aa372e3fSPaul Mullowney   stat = cusparse_csr2csc(cusparseTriFactors->handle, upTriFactor->csrMat->num_rows,
840aa372e3fSPaul Mullowney                           upTriFactor->csrMat->num_cols, upTriFactor->csrMat->num_entries,
841aa372e3fSPaul Mullowney                           upTriFactor->csrMat->values->data().get(),
842aa372e3fSPaul Mullowney                           upTriFactor->csrMat->row_offsets->data().get(),
843aa372e3fSPaul Mullowney                           upTriFactor->csrMat->column_indices->data().get(),
844aa372e3fSPaul Mullowney                           upTriFactorT->csrMat->values->data().get(),
845aa372e3fSPaul Mullowney                           upTriFactorT->csrMat->column_indices->data().get(),
846aa372e3fSPaul Mullowney                           upTriFactorT->csrMat->row_offsets->data().get(),
84757d48284SJunchao Zhang                           CUSPARSE_ACTION_NUMERIC, indexBase);CHKERRCUSPARSE(stat);
848aa372e3fSPaul Mullowney 
849aa372e3fSPaul Mullowney   /* perform the solve analysis on the transposed matrix */
850aa372e3fSPaul Mullowney   stat = cusparse_analysis(cusparseTriFactors->handle, upTriFactorT->solveOp,
851aa372e3fSPaul Mullowney                            upTriFactorT->csrMat->num_rows, upTriFactorT->csrMat->num_entries,
852aa372e3fSPaul Mullowney                            upTriFactorT->descr, upTriFactorT->csrMat->values->data().get(),
853aa372e3fSPaul Mullowney                            upTriFactorT->csrMat->row_offsets->data().get(), upTriFactorT->csrMat->column_indices->data().get(),
85457d48284SJunchao Zhang                            upTriFactorT->solveInfo);CHKERRCUSPARSE(stat);
855aa372e3fSPaul Mullowney 
856aa372e3fSPaul Mullowney   /* assign the pointer. Is this really necessary? */
857aa372e3fSPaul Mullowney   ((Mat_SeqAIJCUSPARSETriFactors*)A->spptr)->upTriFactorPtrTranspose = upTriFactorT;
858bda325fcSPaul Mullowney   PetscFunctionReturn(0);
859bda325fcSPaul Mullowney }
860bda325fcSPaul Mullowney 
861b175d8bbSPaul Mullowney static PetscErrorCode MatSeqAIJCUSPARSEGenerateTransposeForMult(Mat A)
862bda325fcSPaul Mullowney {
863aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
864aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSEMultStruct *matstruct = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->mat;
865aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSEMultStruct *matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
866bda325fcSPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
867bda325fcSPaul Mullowney   cusparseStatus_t             stat;
868aa372e3fSPaul Mullowney   cusparseIndexBase_t          indexBase;
869b06137fdSPaul Mullowney   cudaError_t                  err;
8704863603aSSatish Balay   PetscErrorCode               ierr;
871b175d8bbSPaul Mullowney 
872bda325fcSPaul Mullowney   PetscFunctionBegin;
873aa372e3fSPaul Mullowney 
874aa372e3fSPaul Mullowney   /* allocate space for the triangular factor information */
875aa372e3fSPaul Mullowney   matstructT = new Mat_SeqAIJCUSPARSEMultStruct;
87657d48284SJunchao Zhang   stat = cusparseCreateMatDescr(&matstructT->descr);CHKERRCUSPARSE(stat);
877aa372e3fSPaul Mullowney   indexBase = cusparseGetMatIndexBase(matstruct->descr);
87857d48284SJunchao Zhang   stat = cusparseSetMatIndexBase(matstructT->descr, indexBase);CHKERRCUSPARSE(stat);
87957d48284SJunchao Zhang   stat = cusparseSetMatType(matstructT->descr, CUSPARSE_MATRIX_TYPE_GENERAL);CHKERRCUSPARSE(stat);
880aa372e3fSPaul Mullowney 
881b06137fdSPaul Mullowney   /* set alpha and beta */
882c41cb2e2SAlejandro Lamas Daviña   err = cudaMalloc((void **)&(matstructT->alpha),    sizeof(PetscScalar));CHKERRCUDA(err);
8837656d835SStefano Zampini   err = cudaMalloc((void **)&(matstructT->beta_zero),sizeof(PetscScalar));CHKERRCUDA(err);
8847656d835SStefano Zampini   err = cudaMalloc((void **)&(matstructT->beta_one), sizeof(PetscScalar));CHKERRCUDA(err);
8857656d835SStefano Zampini   err = cudaMemcpy(matstructT->alpha,    &PETSC_CUSPARSE_ONE, sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
8867656d835SStefano Zampini   err = cudaMemcpy(matstructT->beta_zero,&PETSC_CUSPARSE_ZERO,sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
8877656d835SStefano Zampini   err = cudaMemcpy(matstructT->beta_one, &PETSC_CUSPARSE_ONE, sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
88857d48284SJunchao Zhang   stat = cusparseSetPointerMode(cusparsestruct->handle, CUSPARSE_POINTER_MODE_DEVICE);CHKERRCUSPARSE(stat);
889b06137fdSPaul Mullowney 
890aa372e3fSPaul Mullowney   if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
891aa372e3fSPaul Mullowney     CsrMatrix *matrix = (CsrMatrix*)matstruct->mat;
892aa372e3fSPaul Mullowney     CsrMatrix *matrixT= new CsrMatrix;
893554b8892SKarl Rupp     matrixT->num_rows = A->cmap->n;
894554b8892SKarl Rupp     matrixT->num_cols = A->rmap->n;
895aa372e3fSPaul Mullowney     matrixT->num_entries = a->nz;
896a8bd5306SMark Adams     matrixT->row_offsets = new THRUSTINTARRAY32(matrixT->num_rows+1);
897aa372e3fSPaul Mullowney     matrixT->column_indices = new THRUSTINTARRAY32(a->nz);
898aa372e3fSPaul Mullowney     matrixT->values = new THRUSTARRAY(a->nz);
899a3fdcf43SKarl Rupp 
90081902715SJunchao Zhang     cusparsestruct->rowoffsets_gpu = new THRUSTINTARRAY32(A->rmap->n+1);
90181902715SJunchao Zhang     cusparsestruct->rowoffsets_gpu->assign(a->i,a->i+A->rmap->n+1);
90281902715SJunchao Zhang     /* compute the transpose, i.e. the CSC */
903aa372e3fSPaul Mullowney     indexBase = cusparseGetMatIndexBase(matstruct->descr);
904a3fdcf43SKarl Rupp     stat = cusparse_csr2csc(cusparsestruct->handle, A->rmap->n,
905a3fdcf43SKarl Rupp                             A->cmap->n, matrix->num_entries,
906aa372e3fSPaul Mullowney                             matrix->values->data().get(),
90781902715SJunchao Zhang                             cusparsestruct->rowoffsets_gpu->data().get(),
908aa372e3fSPaul Mullowney                             matrix->column_indices->data().get(),
909aa372e3fSPaul Mullowney                             matrixT->values->data().get(),
910aa372e3fSPaul Mullowney                             matrixT->column_indices->data().get(),
911aa372e3fSPaul Mullowney                             matrixT->row_offsets->data().get(),
91257d48284SJunchao Zhang                             CUSPARSE_ACTION_NUMERIC, indexBase);CHKERRCUSPARSE(stat);
913aa372e3fSPaul Mullowney     /* assign the pointer */
914aa372e3fSPaul Mullowney     matstructT->mat = matrixT;
9154863603aSSatish Balay     ierr = PetscLogCpuToGpu(((A->rmap->n+1)+(a->nz))*sizeof(int)+(3+a->nz)*sizeof(PetscScalar));CHKERRQ(ierr);
916aa372e3fSPaul Mullowney   } else if (cusparsestruct->format==MAT_CUSPARSE_ELL || cusparsestruct->format==MAT_CUSPARSE_HYB) {
917aa372e3fSPaul Mullowney     /* First convert HYB to CSR */
918aa372e3fSPaul Mullowney     CsrMatrix *temp= new CsrMatrix;
919aa372e3fSPaul Mullowney     temp->num_rows = A->rmap->n;
920aa372e3fSPaul Mullowney     temp->num_cols = A->cmap->n;
921aa372e3fSPaul Mullowney     temp->num_entries = a->nz;
922aa372e3fSPaul Mullowney     temp->row_offsets = new THRUSTINTARRAY32(A->rmap->n+1);
923aa372e3fSPaul Mullowney     temp->column_indices = new THRUSTINTARRAY32(a->nz);
924aa372e3fSPaul Mullowney     temp->values = new THRUSTARRAY(a->nz);
925aa372e3fSPaul Mullowney 
9262692e278SPaul Mullowney 
927aa372e3fSPaul Mullowney     stat = cusparse_hyb2csr(cusparsestruct->handle,
928aa372e3fSPaul Mullowney                             matstruct->descr, (cusparseHybMat_t)matstruct->mat,
929aa372e3fSPaul Mullowney                             temp->values->data().get(),
930aa372e3fSPaul Mullowney                             temp->row_offsets->data().get(),
93157d48284SJunchao Zhang                             temp->column_indices->data().get());CHKERRCUSPARSE(stat);
932aa372e3fSPaul Mullowney 
933aa372e3fSPaul Mullowney     /* Next, convert CSR to CSC (i.e. the matrix transpose) */
934aa372e3fSPaul Mullowney     CsrMatrix *tempT= new CsrMatrix;
935aa372e3fSPaul Mullowney     tempT->num_rows = A->rmap->n;
936aa372e3fSPaul Mullowney     tempT->num_cols = A->cmap->n;
937aa372e3fSPaul Mullowney     tempT->num_entries = a->nz;
938aa372e3fSPaul Mullowney     tempT->row_offsets = new THRUSTINTARRAY32(A->rmap->n+1);
939aa372e3fSPaul Mullowney     tempT->column_indices = new THRUSTINTARRAY32(a->nz);
940aa372e3fSPaul Mullowney     tempT->values = new THRUSTARRAY(a->nz);
941aa372e3fSPaul Mullowney 
942aa372e3fSPaul Mullowney     stat = cusparse_csr2csc(cusparsestruct->handle, temp->num_rows,
943aa372e3fSPaul Mullowney                             temp->num_cols, temp->num_entries,
944aa372e3fSPaul Mullowney                             temp->values->data().get(),
945aa372e3fSPaul Mullowney                             temp->row_offsets->data().get(),
946aa372e3fSPaul Mullowney                             temp->column_indices->data().get(),
947aa372e3fSPaul Mullowney                             tempT->values->data().get(),
948aa372e3fSPaul Mullowney                             tempT->column_indices->data().get(),
949aa372e3fSPaul Mullowney                             tempT->row_offsets->data().get(),
95057d48284SJunchao Zhang                             CUSPARSE_ACTION_NUMERIC, indexBase);CHKERRCUSPARSE(stat);
951aa372e3fSPaul Mullowney 
952aa372e3fSPaul Mullowney     /* Last, convert CSC to HYB */
953aa372e3fSPaul Mullowney     cusparseHybMat_t hybMat;
95457d48284SJunchao Zhang     stat = cusparseCreateHybMat(&hybMat);CHKERRCUSPARSE(stat);
955aa372e3fSPaul Mullowney     cusparseHybPartition_t partition = cusparsestruct->format==MAT_CUSPARSE_ELL ?
956aa372e3fSPaul Mullowney       CUSPARSE_HYB_PARTITION_MAX : CUSPARSE_HYB_PARTITION_AUTO;
957aa372e3fSPaul Mullowney     stat = cusparse_csr2hyb(cusparsestruct->handle, A->rmap->n, A->cmap->n,
958aa372e3fSPaul Mullowney                             matstructT->descr, tempT->values->data().get(),
959aa372e3fSPaul Mullowney                             tempT->row_offsets->data().get(),
960aa372e3fSPaul Mullowney                             tempT->column_indices->data().get(),
96157d48284SJunchao Zhang                             hybMat, 0, partition);CHKERRCUSPARSE(stat);
962aa372e3fSPaul Mullowney 
963aa372e3fSPaul Mullowney     /* assign the pointer */
964aa372e3fSPaul Mullowney     matstructT->mat = hybMat;
9654863603aSSatish Balay     ierr = PetscLogCpuToGpu((2*(((A->rmap->n+1)+(a->nz))*sizeof(int)+(a->nz)*sizeof(PetscScalar)))+3*sizeof(PetscScalar));CHKERRQ(ierr);
966aa372e3fSPaul Mullowney 
967aa372e3fSPaul Mullowney     /* delete temporaries */
968aa372e3fSPaul Mullowney     if (tempT) {
969aa372e3fSPaul Mullowney       if (tempT->values) delete (THRUSTARRAY*) tempT->values;
970aa372e3fSPaul Mullowney       if (tempT->column_indices) delete (THRUSTINTARRAY32*) tempT->column_indices;
971aa372e3fSPaul Mullowney       if (tempT->row_offsets) delete (THRUSTINTARRAY32*) tempT->row_offsets;
972aa372e3fSPaul Mullowney       delete (CsrMatrix*) tempT;
973087f3262SPaul Mullowney     }
974aa372e3fSPaul Mullowney     if (temp) {
975aa372e3fSPaul Mullowney       if (temp->values) delete (THRUSTARRAY*) temp->values;
976aa372e3fSPaul Mullowney       if (temp->column_indices) delete (THRUSTINTARRAY32*) temp->column_indices;
977aa372e3fSPaul Mullowney       if (temp->row_offsets) delete (THRUSTINTARRAY32*) temp->row_offsets;
978aa372e3fSPaul Mullowney       delete (CsrMatrix*) temp;
979aa372e3fSPaul Mullowney     }
980aa372e3fSPaul Mullowney   }
981213423ffSJunchao Zhang   /* the compressed row indices is not used for matTranspose */
982213423ffSJunchao Zhang   matstructT->cprowIndices = NULL;
983aa372e3fSPaul Mullowney   /* assign the pointer */
984aa372e3fSPaul Mullowney   ((Mat_SeqAIJCUSPARSE*)A->spptr)->matTranspose = matstructT;
985bda325fcSPaul Mullowney   PetscFunctionReturn(0);
986bda325fcSPaul Mullowney }
987bda325fcSPaul Mullowney 
9884e4bbfaaSStefano Zampini /* Why do we need to analyze the tranposed matrix again? Can't we just use op(A) = CUSPARSE_OPERATION_TRANSPOSE in MatSolve_SeqAIJCUSPARSE? */
9896fa9248bSJed Brown static PetscErrorCode MatSolveTranspose_SeqAIJCUSPARSE(Mat A,Vec bb,Vec xx)
990bda325fcSPaul Mullowney {
991c41cb2e2SAlejandro Lamas Daviña   PetscInt                              n = xx->map->n;
992465f34aeSAlejandro Lamas Daviña   const PetscScalar                     *barray;
993465f34aeSAlejandro Lamas Daviña   PetscScalar                           *xarray;
994465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<const PetscScalar> bGPU;
995465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<PetscScalar>       xGPU;
996bda325fcSPaul Mullowney   cusparseStatus_t                      stat;
997bda325fcSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors          *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
998aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *loTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
999aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *upTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1000aa372e3fSPaul Mullowney   THRUSTARRAY                           *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1001b175d8bbSPaul Mullowney   PetscErrorCode                        ierr;
100257d48284SJunchao Zhang   cudaError_t                           cerr;
1003bda325fcSPaul Mullowney 
1004bda325fcSPaul Mullowney   PetscFunctionBegin;
1005aa372e3fSPaul Mullowney   /* Analyze the matrix and create the transpose ... on the fly */
1006aa372e3fSPaul Mullowney   if (!loTriFactorT && !upTriFactorT) {
1007bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEAnalyzeTransposeForSolve(A);CHKERRQ(ierr);
1008aa372e3fSPaul Mullowney     loTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1009aa372e3fSPaul Mullowney     upTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1010bda325fcSPaul Mullowney   }
1011bda325fcSPaul Mullowney 
1012bda325fcSPaul Mullowney   /* Get the GPU pointers */
1013c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1014c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
1015c41cb2e2SAlejandro Lamas Daviña   xGPU = thrust::device_pointer_cast(xarray);
1016c41cb2e2SAlejandro Lamas Daviña   bGPU = thrust::device_pointer_cast(barray);
1017bda325fcSPaul Mullowney 
10187a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1019aa372e3fSPaul Mullowney   /* First, reorder with the row permutation */
1020c41cb2e2SAlejandro Lamas Daviña   thrust::copy(thrust::make_permutation_iterator(bGPU, cusparseTriFactors->rpermIndices->begin()),
1021c41cb2e2SAlejandro Lamas Daviña                thrust::make_permutation_iterator(bGPU+n, cusparseTriFactors->rpermIndices->end()),
1022c41cb2e2SAlejandro Lamas Daviña                xGPU);
1023aa372e3fSPaul Mullowney 
1024aa372e3fSPaul Mullowney   /* First, solve U */
1025aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactorT->solveOp,
10267656d835SStefano Zampini                         upTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactorT->descr,
1027aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->values->data().get(),
1028aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->row_offsets->data().get(),
1029aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->column_indices->data().get(),
1030aa372e3fSPaul Mullowney                         upTriFactorT->solveInfo,
103157d48284SJunchao Zhang                         xarray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1032aa372e3fSPaul Mullowney 
1033aa372e3fSPaul Mullowney   /* Then, solve L */
1034aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactorT->solveOp,
10357656d835SStefano Zampini                         loTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactorT->descr,
1036aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->values->data().get(),
1037aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->row_offsets->data().get(),
1038aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->column_indices->data().get(),
1039aa372e3fSPaul Mullowney                         loTriFactorT->solveInfo,
104057d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
1041aa372e3fSPaul Mullowney 
1042aa372e3fSPaul Mullowney   /* Last, copy the solution, xGPU, into a temporary with the column permutation ... can't be done in place. */
1043c41cb2e2SAlejandro Lamas Daviña   thrust::copy(thrust::make_permutation_iterator(xGPU, cusparseTriFactors->cpermIndices->begin()),
1044c41cb2e2SAlejandro Lamas Daviña                thrust::make_permutation_iterator(xGPU+n, cusparseTriFactors->cpermIndices->end()),
1045aa372e3fSPaul Mullowney                tempGPU->begin());
1046aa372e3fSPaul Mullowney 
1047aa372e3fSPaul Mullowney   /* Copy the temporary to the full solution. */
1048c41cb2e2SAlejandro Lamas Daviña   thrust::copy(tempGPU->begin(), tempGPU->end(), xGPU);
1049bda325fcSPaul Mullowney 
1050bda325fcSPaul Mullowney   /* restore */
1051c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1052c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
105357d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1054661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1055958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
1056bda325fcSPaul Mullowney   PetscFunctionReturn(0);
1057bda325fcSPaul Mullowney }
1058bda325fcSPaul Mullowney 
10596fa9248bSJed Brown static PetscErrorCode MatSolveTranspose_SeqAIJCUSPARSE_NaturalOrdering(Mat A,Vec bb,Vec xx)
1060bda325fcSPaul Mullowney {
1061465f34aeSAlejandro Lamas Daviña   const PetscScalar                 *barray;
1062465f34aeSAlejandro Lamas Daviña   PetscScalar                       *xarray;
1063bda325fcSPaul Mullowney   cusparseStatus_t                  stat;
1064bda325fcSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1065aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1066aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1067aa372e3fSPaul Mullowney   THRUSTARRAY                       *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1068b175d8bbSPaul Mullowney   PetscErrorCode                    ierr;
106957d48284SJunchao Zhang   cudaError_t                       cerr;
1070bda325fcSPaul Mullowney 
1071bda325fcSPaul Mullowney   PetscFunctionBegin;
1072aa372e3fSPaul Mullowney   /* Analyze the matrix and create the transpose ... on the fly */
1073aa372e3fSPaul Mullowney   if (!loTriFactorT && !upTriFactorT) {
1074bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEAnalyzeTransposeForSolve(A);CHKERRQ(ierr);
1075aa372e3fSPaul Mullowney     loTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1076aa372e3fSPaul Mullowney     upTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1077bda325fcSPaul Mullowney   }
1078bda325fcSPaul Mullowney 
1079bda325fcSPaul Mullowney   /* Get the GPU pointers */
1080c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1081c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
1082bda325fcSPaul Mullowney 
10837a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1084aa372e3fSPaul Mullowney   /* First, solve U */
1085aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactorT->solveOp,
10867656d835SStefano Zampini                         upTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactorT->descr,
1087aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->values->data().get(),
1088aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->row_offsets->data().get(),
1089aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->column_indices->data().get(),
1090aa372e3fSPaul Mullowney                         upTriFactorT->solveInfo,
109157d48284SJunchao Zhang                         barray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1092aa372e3fSPaul Mullowney 
1093aa372e3fSPaul Mullowney   /* Then, solve L */
1094aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactorT->solveOp,
10957656d835SStefano Zampini                         loTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactorT->descr,
1096aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->values->data().get(),
1097aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->row_offsets->data().get(),
1098aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->column_indices->data().get(),
1099aa372e3fSPaul Mullowney                         loTriFactorT->solveInfo,
110057d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
1101bda325fcSPaul Mullowney 
1102bda325fcSPaul Mullowney   /* restore */
1103c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1104c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
110557d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1106661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1107958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
1108bda325fcSPaul Mullowney   PetscFunctionReturn(0);
1109bda325fcSPaul Mullowney }
1110bda325fcSPaul Mullowney 
11116fa9248bSJed Brown static PetscErrorCode MatSolve_SeqAIJCUSPARSE(Mat A,Vec bb,Vec xx)
11129ae82921SPaul Mullowney {
1113465f34aeSAlejandro Lamas Daviña   const PetscScalar                     *barray;
1114465f34aeSAlejandro Lamas Daviña   PetscScalar                           *xarray;
1115465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<const PetscScalar> bGPU;
1116465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<PetscScalar>       xGPU;
11179ae82921SPaul Mullowney   cusparseStatus_t                      stat;
11189ae82921SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors          *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1119aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
1120aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
1121aa372e3fSPaul Mullowney   THRUSTARRAY                           *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1122b175d8bbSPaul Mullowney   PetscErrorCode                        ierr;
112357d48284SJunchao Zhang   cudaError_t                           cerr;
11249ae82921SPaul Mullowney 
11259ae82921SPaul Mullowney   PetscFunctionBegin;
1126ebc8f436SDominic Meiser 
1127e057df02SPaul Mullowney   /* Get the GPU pointers */
1128c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1129c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
1130c41cb2e2SAlejandro Lamas Daviña   xGPU = thrust::device_pointer_cast(xarray);
1131c41cb2e2SAlejandro Lamas Daviña   bGPU = thrust::device_pointer_cast(barray);
11329ae82921SPaul Mullowney 
11337a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1134aa372e3fSPaul Mullowney   /* First, reorder with the row permutation */
1135c41cb2e2SAlejandro Lamas Daviña   thrust::copy(thrust::make_permutation_iterator(bGPU, cusparseTriFactors->rpermIndices->begin()),
1136c41cb2e2SAlejandro Lamas Daviña                thrust::make_permutation_iterator(bGPU, cusparseTriFactors->rpermIndices->end()),
11374e4bbfaaSStefano Zampini                tempGPU->begin());
1138aa372e3fSPaul Mullowney 
1139aa372e3fSPaul Mullowney   /* Next, solve L */
1140aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactor->solveOp,
11417656d835SStefano Zampini                         loTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactor->descr,
1142aa372e3fSPaul Mullowney                         loTriFactor->csrMat->values->data().get(),
1143aa372e3fSPaul Mullowney                         loTriFactor->csrMat->row_offsets->data().get(),
1144aa372e3fSPaul Mullowney                         loTriFactor->csrMat->column_indices->data().get(),
1145aa372e3fSPaul Mullowney                         loTriFactor->solveInfo,
114657d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
1147aa372e3fSPaul Mullowney 
1148aa372e3fSPaul Mullowney   /* Then, solve U */
1149aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactor->solveOp,
11507656d835SStefano Zampini                         upTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactor->descr,
1151aa372e3fSPaul Mullowney                         upTriFactor->csrMat->values->data().get(),
1152aa372e3fSPaul Mullowney                         upTriFactor->csrMat->row_offsets->data().get(),
1153aa372e3fSPaul Mullowney                         upTriFactor->csrMat->column_indices->data().get(),
1154aa372e3fSPaul Mullowney                         upTriFactor->solveInfo,
115557d48284SJunchao Zhang                         xarray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1156aa372e3fSPaul Mullowney 
11574e4bbfaaSStefano Zampini   /* Last, reorder with the column permutation */
11584e4bbfaaSStefano Zampini   thrust::copy(thrust::make_permutation_iterator(tempGPU->begin(), cusparseTriFactors->cpermIndices->begin()),
11594e4bbfaaSStefano Zampini                thrust::make_permutation_iterator(tempGPU->begin(), cusparseTriFactors->cpermIndices->end()),
11604e4bbfaaSStefano Zampini                xGPU);
11619ae82921SPaul Mullowney 
1162c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1163c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
116457d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1165661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1166958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
11679ae82921SPaul Mullowney   PetscFunctionReturn(0);
11689ae82921SPaul Mullowney }
11699ae82921SPaul Mullowney 
11706fa9248bSJed Brown static PetscErrorCode MatSolve_SeqAIJCUSPARSE_NaturalOrdering(Mat A,Vec bb,Vec xx)
11719ae82921SPaul Mullowney {
1172465f34aeSAlejandro Lamas Daviña   const PetscScalar                 *barray;
1173465f34aeSAlejandro Lamas Daviña   PetscScalar                       *xarray;
11749ae82921SPaul Mullowney   cusparseStatus_t                  stat;
11759ae82921SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1176aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
1177aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
1178aa372e3fSPaul Mullowney   THRUSTARRAY                       *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1179b175d8bbSPaul Mullowney   PetscErrorCode                    ierr;
118057d48284SJunchao Zhang   cudaError_t                       cerr;
11819ae82921SPaul Mullowney 
11829ae82921SPaul Mullowney   PetscFunctionBegin;
1183e057df02SPaul Mullowney   /* Get the GPU pointers */
1184c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1185c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
11869ae82921SPaul Mullowney 
11877a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1188aa372e3fSPaul Mullowney   /* First, solve L */
1189aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactor->solveOp,
11907656d835SStefano Zampini                         loTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactor->descr,
1191aa372e3fSPaul Mullowney                         loTriFactor->csrMat->values->data().get(),
1192aa372e3fSPaul Mullowney                         loTriFactor->csrMat->row_offsets->data().get(),
1193aa372e3fSPaul Mullowney                         loTriFactor->csrMat->column_indices->data().get(),
1194aa372e3fSPaul Mullowney                         loTriFactor->solveInfo,
119557d48284SJunchao Zhang                         barray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1196aa372e3fSPaul Mullowney 
1197aa372e3fSPaul Mullowney   /* Next, solve U */
1198aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactor->solveOp,
11997656d835SStefano Zampini                         upTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactor->descr,
1200aa372e3fSPaul Mullowney                         upTriFactor->csrMat->values->data().get(),
1201aa372e3fSPaul Mullowney                         upTriFactor->csrMat->row_offsets->data().get(),
1202aa372e3fSPaul Mullowney                         upTriFactor->csrMat->column_indices->data().get(),
1203aa372e3fSPaul Mullowney                         upTriFactor->solveInfo,
120457d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
12059ae82921SPaul Mullowney 
1206c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1207c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
120857d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1209661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1210958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
12119ae82921SPaul Mullowney   PetscFunctionReturn(0);
12129ae82921SPaul Mullowney }
12139ae82921SPaul Mullowney 
12146fa9248bSJed Brown static PetscErrorCode MatSeqAIJCUSPARSECopyToGPU(Mat A)
12159ae82921SPaul Mullowney {
1216aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
12177c700b8dSJunchao Zhang   Mat_SeqAIJCUSPARSEMultStruct *matstruct = cusparsestruct->mat;
12189ae82921SPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
1219213423ffSJunchao Zhang   PetscInt                     m = A->rmap->n,*ii,*ridx,tmp;
12209ae82921SPaul Mullowney   PetscErrorCode               ierr;
1221aa372e3fSPaul Mullowney   cusparseStatus_t             stat;
1222b06137fdSPaul Mullowney   cudaError_t                  err;
12239ae82921SPaul Mullowney 
12249ae82921SPaul Mullowney   PetscFunctionBegin;
122595639643SRichard Tran Mills   if (A->boundtocpu) PetscFunctionReturn(0);
1226c70f7ee4SJunchao Zhang   if (A->offloadmask == PETSC_OFFLOAD_UNALLOCATED || A->offloadmask == PETSC_OFFLOAD_CPU) {
12279ae82921SPaul Mullowney     ierr = PetscLogEventBegin(MAT_CUSPARSECopyToGPU,A,0,0,0);CHKERRQ(ierr);
122881902715SJunchao Zhang     if (A->was_assembled && A->nonzerostate == cusparsestruct->nonzerostate && cusparsestruct->format == MAT_CUSPARSE_CSR) {
122981902715SJunchao Zhang       /* Copy values only */
123081902715SJunchao Zhang       CsrMatrix *mat,*matT;
123181902715SJunchao Zhang       mat  = (CsrMatrix*)cusparsestruct->mat->mat;
123281902715SJunchao Zhang       mat->values->assign(a->a, a->a+a->nz);
12334863603aSSatish Balay       ierr = PetscLogCpuToGpu((a->nz)*sizeof(PetscScalar));CHKERRQ(ierr);
123481902715SJunchao Zhang 
123581902715SJunchao Zhang       /* Update matT when it was built before */
123681902715SJunchao Zhang       if (cusparsestruct->matTranspose) {
123781902715SJunchao Zhang         cusparseIndexBase_t indexBase = cusparseGetMatIndexBase(cusparsestruct->mat->descr);
123881902715SJunchao Zhang         matT = (CsrMatrix*)cusparsestruct->matTranspose->mat;
123981902715SJunchao Zhang         stat = cusparse_csr2csc(cusparsestruct->handle, A->rmap->n,
124081902715SJunchao Zhang                                  A->cmap->n, mat->num_entries,
124181902715SJunchao Zhang                                  mat->values->data().get(),
124281902715SJunchao Zhang                                  cusparsestruct->rowoffsets_gpu->data().get(),
124381902715SJunchao Zhang                                  mat->column_indices->data().get(),
124481902715SJunchao Zhang                                  matT->values->data().get(),
124581902715SJunchao Zhang                                  matT->column_indices->data().get(),
124681902715SJunchao Zhang                                  matT->row_offsets->data().get(),
12479f74ec24SSatish Balay                                  CUSPARSE_ACTION_NUMERIC,indexBase);CHKERRCUSPARSE(stat);
124881902715SJunchao Zhang       }
124934d6c7a5SJose E. Roman     } else {
12507c700b8dSJunchao Zhang       ierr = MatSeqAIJCUSPARSEMultStruct_Destroy(&cusparsestruct->mat,cusparsestruct->format);CHKERRQ(ierr);
12517c700b8dSJunchao Zhang       ierr = MatSeqAIJCUSPARSEMultStruct_Destroy(&cusparsestruct->matTranspose,cusparsestruct->format);CHKERRQ(ierr);
12527c700b8dSJunchao Zhang       delete cusparsestruct->workVector;
125381902715SJunchao Zhang       delete cusparsestruct->rowoffsets_gpu;
12549ae82921SPaul Mullowney       try {
12559ae82921SPaul Mullowney         if (a->compressedrow.use) {
12569ae82921SPaul Mullowney           m    = a->compressedrow.nrows;
12579ae82921SPaul Mullowney           ii   = a->compressedrow.i;
12589ae82921SPaul Mullowney           ridx = a->compressedrow.rindex;
12599ae82921SPaul Mullowney         } else {
1260213423ffSJunchao Zhang           m    = A->rmap->n;
1261213423ffSJunchao Zhang           ii   = a->i;
1262213423ffSJunchao Zhang           ridx = NULL; /* In this case, one should not dereference ridx */
12639ae82921SPaul Mullowney         }
1264213423ffSJunchao Zhang         cusparsestruct->nrows = m;
12659ae82921SPaul Mullowney 
1266aa372e3fSPaul Mullowney         /* allocate space for the triangular factor information */
1267aa372e3fSPaul Mullowney         matstruct = new Mat_SeqAIJCUSPARSEMultStruct;
126857d48284SJunchao Zhang         stat = cusparseCreateMatDescr(&matstruct->descr);CHKERRCUSPARSE(stat);
126957d48284SJunchao Zhang         stat = cusparseSetMatIndexBase(matstruct->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
127057d48284SJunchao Zhang         stat = cusparseSetMatType(matstruct->descr, CUSPARSE_MATRIX_TYPE_GENERAL);CHKERRCUSPARSE(stat);
12719ae82921SPaul Mullowney 
1272c41cb2e2SAlejandro Lamas Daviña         err = cudaMalloc((void **)&(matstruct->alpha),    sizeof(PetscScalar));CHKERRCUDA(err);
12737656d835SStefano Zampini         err = cudaMalloc((void **)&(matstruct->beta_zero),sizeof(PetscScalar));CHKERRCUDA(err);
12747656d835SStefano Zampini         err = cudaMalloc((void **)&(matstruct->beta_one), sizeof(PetscScalar));CHKERRCUDA(err);
12757656d835SStefano Zampini         err = cudaMemcpy(matstruct->alpha,    &PETSC_CUSPARSE_ONE, sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
12767656d835SStefano Zampini         err = cudaMemcpy(matstruct->beta_zero,&PETSC_CUSPARSE_ZERO,sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
12777656d835SStefano Zampini         err = cudaMemcpy(matstruct->beta_one, &PETSC_CUSPARSE_ONE, sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
127857d48284SJunchao Zhang         stat = cusparseSetPointerMode(cusparsestruct->handle, CUSPARSE_POINTER_MODE_DEVICE);CHKERRCUSPARSE(stat);
1279b06137fdSPaul Mullowney 
1280aa372e3fSPaul Mullowney         /* Build a hybrid/ellpack matrix if this option is chosen for the storage */
1281aa372e3fSPaul Mullowney         if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
1282aa372e3fSPaul Mullowney           /* set the matrix */
1283aa372e3fSPaul Mullowney           CsrMatrix *matrix= new CsrMatrix;
1284a65300a6SPaul Mullowney           matrix->num_rows = m;
1285aa372e3fSPaul Mullowney           matrix->num_cols = A->cmap->n;
1286aa372e3fSPaul Mullowney           matrix->num_entries = a->nz;
1287a65300a6SPaul Mullowney           matrix->row_offsets = new THRUSTINTARRAY32(m+1);
1288a65300a6SPaul Mullowney           matrix->row_offsets->assign(ii, ii + m+1);
12899ae82921SPaul Mullowney 
1290aa372e3fSPaul Mullowney           matrix->column_indices = new THRUSTINTARRAY32(a->nz);
1291aa372e3fSPaul Mullowney           matrix->column_indices->assign(a->j, a->j+a->nz);
1292aa372e3fSPaul Mullowney 
1293aa372e3fSPaul Mullowney           matrix->values = new THRUSTARRAY(a->nz);
1294aa372e3fSPaul Mullowney           matrix->values->assign(a->a, a->a+a->nz);
1295aa372e3fSPaul Mullowney 
1296aa372e3fSPaul Mullowney           /* assign the pointer */
1297aa372e3fSPaul Mullowney           matstruct->mat = matrix;
1298aa372e3fSPaul Mullowney 
1299aa372e3fSPaul Mullowney         } else if (cusparsestruct->format==MAT_CUSPARSE_ELL || cusparsestruct->format==MAT_CUSPARSE_HYB) {
1300aa372e3fSPaul Mullowney           CsrMatrix *matrix= new CsrMatrix;
1301a65300a6SPaul Mullowney           matrix->num_rows = m;
1302aa372e3fSPaul Mullowney           matrix->num_cols = A->cmap->n;
1303aa372e3fSPaul Mullowney           matrix->num_entries = a->nz;
1304a65300a6SPaul Mullowney           matrix->row_offsets = new THRUSTINTARRAY32(m+1);
1305a65300a6SPaul Mullowney           matrix->row_offsets->assign(ii, ii + m+1);
1306aa372e3fSPaul Mullowney 
1307aa372e3fSPaul Mullowney           matrix->column_indices = new THRUSTINTARRAY32(a->nz);
1308aa372e3fSPaul Mullowney           matrix->column_indices->assign(a->j, a->j+a->nz);
1309aa372e3fSPaul Mullowney 
1310aa372e3fSPaul Mullowney           matrix->values = new THRUSTARRAY(a->nz);
1311aa372e3fSPaul Mullowney           matrix->values->assign(a->a, a->a+a->nz);
1312aa372e3fSPaul Mullowney 
1313aa372e3fSPaul Mullowney           cusparseHybMat_t hybMat;
131457d48284SJunchao Zhang           stat = cusparseCreateHybMat(&hybMat);CHKERRCUSPARSE(stat);
1315aa372e3fSPaul Mullowney           cusparseHybPartition_t partition = cusparsestruct->format==MAT_CUSPARSE_ELL ?
1316aa372e3fSPaul Mullowney             CUSPARSE_HYB_PARTITION_MAX : CUSPARSE_HYB_PARTITION_AUTO;
1317a65300a6SPaul Mullowney           stat = cusparse_csr2hyb(cusparsestruct->handle, matrix->num_rows, matrix->num_cols,
1318aa372e3fSPaul Mullowney               matstruct->descr, matrix->values->data().get(),
1319aa372e3fSPaul Mullowney               matrix->row_offsets->data().get(),
1320aa372e3fSPaul Mullowney               matrix->column_indices->data().get(),
132157d48284SJunchao Zhang               hybMat, 0, partition);CHKERRCUSPARSE(stat);
1322aa372e3fSPaul Mullowney           /* assign the pointer */
1323aa372e3fSPaul Mullowney           matstruct->mat = hybMat;
1324aa372e3fSPaul Mullowney 
1325aa372e3fSPaul Mullowney           if (matrix) {
1326aa372e3fSPaul Mullowney             if (matrix->values) delete (THRUSTARRAY*)matrix->values;
1327aa372e3fSPaul Mullowney             if (matrix->column_indices) delete (THRUSTINTARRAY32*)matrix->column_indices;
1328aa372e3fSPaul Mullowney             if (matrix->row_offsets) delete (THRUSTINTARRAY32*)matrix->row_offsets;
1329aa372e3fSPaul Mullowney             delete (CsrMatrix*)matrix;
1330087f3262SPaul Mullowney           }
1331087f3262SPaul Mullowney         }
1332ca45077fSPaul Mullowney 
1333aa372e3fSPaul Mullowney         /* assign the compressed row indices */
1334213423ffSJunchao Zhang         if (a->compressedrow.use) {
1335213423ffSJunchao Zhang           cusparsestruct->workVector = new THRUSTARRAY(m);
1336aa372e3fSPaul Mullowney           matstruct->cprowIndices    = new THRUSTINTARRAY(m);
1337aa372e3fSPaul Mullowney           matstruct->cprowIndices->assign(ridx,ridx+m);
1338213423ffSJunchao Zhang           tmp = m;
1339213423ffSJunchao Zhang         } else {
1340213423ffSJunchao Zhang           cusparsestruct->workVector = NULL;
1341213423ffSJunchao Zhang           matstruct->cprowIndices    = NULL;
1342213423ffSJunchao Zhang           tmp = 0;
1343213423ffSJunchao Zhang         }
1344213423ffSJunchao Zhang         ierr = PetscLogCpuToGpu(((m+1)+(a->nz))*sizeof(int)+tmp*sizeof(PetscInt)+(3+(a->nz))*sizeof(PetscScalar));CHKERRQ(ierr);
1345aa372e3fSPaul Mullowney 
1346aa372e3fSPaul Mullowney         /* assign the pointer */
1347aa372e3fSPaul Mullowney         cusparsestruct->mat = matstruct;
13489ae82921SPaul Mullowney       } catch(char *ex) {
13499ae82921SPaul Mullowney         SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
13509ae82921SPaul Mullowney       }
135134d6c7a5SJose E. Roman       cusparsestruct->nonzerostate = A->nonzerostate;
135234d6c7a5SJose E. Roman     }
135357d48284SJunchao Zhang     err  = WaitForGPU();CHKERRCUDA(err);
1354c70f7ee4SJunchao Zhang     A->offloadmask = PETSC_OFFLOAD_BOTH;
13559ae82921SPaul Mullowney     ierr = PetscLogEventEnd(MAT_CUSPARSECopyToGPU,A,0,0,0);CHKERRQ(ierr);
13569ae82921SPaul Mullowney   }
13579ae82921SPaul Mullowney   PetscFunctionReturn(0);
13589ae82921SPaul Mullowney }
13599ae82921SPaul Mullowney 
1360c41cb2e2SAlejandro Lamas Daviña struct VecCUDAPlusEquals
1361aa372e3fSPaul Mullowney {
1362aa372e3fSPaul Mullowney   template <typename Tuple>
1363aa372e3fSPaul Mullowney   __host__ __device__
1364aa372e3fSPaul Mullowney   void operator()(Tuple t)
1365aa372e3fSPaul Mullowney   {
1366aa372e3fSPaul Mullowney     thrust::get<1>(t) = thrust::get<1>(t) + thrust::get<0>(t);
1367aa372e3fSPaul Mullowney   }
1368aa372e3fSPaul Mullowney };
1369aa372e3fSPaul Mullowney 
13706fa9248bSJed Brown static PetscErrorCode MatMult_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy)
13719ae82921SPaul Mullowney {
1372b175d8bbSPaul Mullowney   PetscErrorCode ierr;
13739ae82921SPaul Mullowney 
13749ae82921SPaul Mullowney   PetscFunctionBegin;
13757656d835SStefano Zampini   ierr = MatMultAdd_SeqAIJCUSPARSE(A,xx,NULL,yy);CHKERRQ(ierr);
13769ae82921SPaul Mullowney   PetscFunctionReturn(0);
13779ae82921SPaul Mullowney }
13789ae82921SPaul Mullowney 
13796fa9248bSJed Brown static PetscErrorCode MatMultTranspose_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy)
1380ca45077fSPaul Mullowney {
1381ca45077fSPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
1382aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
13839ff858a8SKarl Rupp   Mat_SeqAIJCUSPARSEMultStruct *matstructT;
1384465f34aeSAlejandro Lamas Daviña   const PetscScalar            *xarray;
1385465f34aeSAlejandro Lamas Daviña   PetscScalar                  *yarray;
1386b175d8bbSPaul Mullowney   PetscErrorCode               ierr;
138757d48284SJunchao Zhang   cudaError_t                  cerr;
1388aa372e3fSPaul Mullowney   cusparseStatus_t             stat;
1389ca45077fSPaul Mullowney 
1390ca45077fSPaul Mullowney   PetscFunctionBegin;
139134d6c7a5SJose E. Roman   /* The line below is necessary due to the operations that modify the matrix on the CPU (axpy, scale, etc) */
139234d6c7a5SJose E. Roman   ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
13939ff858a8SKarl Rupp   matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1394aa372e3fSPaul Mullowney   if (!matstructT) {
1395bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEGenerateTransposeForMult(A);CHKERRQ(ierr);
1396aa372e3fSPaul Mullowney     matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1397bda325fcSPaul Mullowney   }
1398c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(xx,&xarray);CHKERRQ(ierr);
1399c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(yy,&yarray);CHKERRQ(ierr);
1400f6ae8131SMark   if (yy->map->n) {
1401f6ae8131SMark     PetscInt                     n = yy->map->n;
1402f6ae8131SMark     cudaError_t                  err;
1403f6ae8131SMark     err = cudaMemset(yarray,0,n*sizeof(PetscScalar));CHKERRCUDA(err); /* hack to fix numerical errors from reading output vector yy, apparently */
1404f6ae8131SMark   }
1405aa372e3fSPaul Mullowney 
14067a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1407aa372e3fSPaul Mullowney   if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
1408aa372e3fSPaul Mullowney     CsrMatrix *mat = (CsrMatrix*)matstructT->mat;
1409aa372e3fSPaul Mullowney     stat = cusparse_csr_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1410aa372e3fSPaul Mullowney                              mat->num_rows, mat->num_cols,
1411b06137fdSPaul Mullowney                              mat->num_entries, matstructT->alpha, matstructT->descr,
1412aa372e3fSPaul Mullowney                              mat->values->data().get(), mat->row_offsets->data().get(),
14137656d835SStefano Zampini                              mat->column_indices->data().get(), xarray, matstructT->beta_zero,
141457d48284SJunchao Zhang                              yarray);CHKERRCUSPARSE(stat);
1415aa372e3fSPaul Mullowney   } else {
1416aa372e3fSPaul Mullowney     cusparseHybMat_t hybMat = (cusparseHybMat_t)matstructT->mat;
1417aa372e3fSPaul Mullowney     stat = cusparse_hyb_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1418b06137fdSPaul Mullowney                              matstructT->alpha, matstructT->descr, hybMat,
14197656d835SStefano Zampini                              xarray, matstructT->beta_zero,
142057d48284SJunchao Zhang                              yarray);CHKERRCUSPARSE(stat);
1421ca45077fSPaul Mullowney   }
1422c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(xx,&xarray);CHKERRQ(ierr);
1423c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(yy,&yarray);CHKERRQ(ierr);
142457d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1425661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1426213423ffSJunchao Zhang   ierr = PetscLogGpuFlops(2.0*a->nz);CHKERRQ(ierr);
1427ca45077fSPaul Mullowney   PetscFunctionReturn(0);
1428ca45077fSPaul Mullowney }
1429ca45077fSPaul Mullowney 
1430aa372e3fSPaul Mullowney 
14316fa9248bSJed Brown static PetscErrorCode MatMultAdd_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy,Vec zz)
14329ae82921SPaul Mullowney {
14339ae82921SPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
1434aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
14359ff858a8SKarl Rupp   Mat_SeqAIJCUSPARSEMultStruct *matstruct;
1436465f34aeSAlejandro Lamas Daviña   const PetscScalar            *xarray;
14377656d835SStefano Zampini   PetscScalar                  *zarray,*dptr,*beta;
1438b175d8bbSPaul Mullowney   PetscErrorCode               ierr;
143957d48284SJunchao Zhang   cudaError_t                  cerr;
1440aa372e3fSPaul Mullowney   cusparseStatus_t             stat;
1441213423ffSJunchao Zhang   PetscBool                    compressed = a->compressedrow.use; /* Does the matrix use compressed rows (i.e., drop zero rows)? */
14426e111a19SKarl Rupp 
14439ae82921SPaul Mullowney   PetscFunctionBegin;
144434d6c7a5SJose E. Roman   /* The line below is necessary due to the operations that modify the matrix on the CPU (axpy, scale, etc) */
144534d6c7a5SJose E. Roman   ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
14469ff858a8SKarl Rupp   matstruct = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->mat;
14479ae82921SPaul Mullowney   try {
1448c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDAGetArrayRead(xx,&xarray);CHKERRQ(ierr);
1449213423ffSJunchao Zhang 
1450213423ffSJunchao Zhang     if (yy == zz) {ierr = VecCUDAGetArray(zz,&zarray);CHKERRQ(ierr);} /* read & write zz, so need to get uptodate zarray on GPU */
1451213423ffSJunchao Zhang     else {ierr = VecCUDAGetArrayWrite(zz,&zarray);CHKERRQ(ierr);} /* write zz, so no need to init zarray on GPU */
1452213423ffSJunchao Zhang 
1453213423ffSJunchao Zhang     dptr = compressed ? cusparsestruct->workVector->data().get() : zarray; /* Use a work vector for SpMv result if compressed */
1454213423ffSJunchao Zhang     beta = (yy == zz && !compressed) ? matstruct->beta_one : matstruct->beta_zero;
14559ae82921SPaul Mullowney 
14567a052e47Shannah_mairs     ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1457213423ffSJunchao Zhang     /* csr_spmv does y = alpha*Ax + beta*y */
1458aa372e3fSPaul Mullowney     if (cusparsestruct->format == MAT_CUSPARSE_CSR) {
1459b06137fdSPaul Mullowney       /* here we need to be careful to set the number of rows in the multiply to the
1460b06137fdSPaul Mullowney          number of compressed rows in the matrix ... which is equivalent to the
1461b06137fdSPaul Mullowney          size of the workVector */
14627656d835SStefano Zampini       CsrMatrix *mat = (CsrMatrix*)matstruct->mat;
1463aa372e3fSPaul Mullowney       stat = cusparse_csr_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1464a65300a6SPaul Mullowney                                mat->num_rows, mat->num_cols,
1465b06137fdSPaul Mullowney                                mat->num_entries, matstruct->alpha, matstruct->descr,
1466aa372e3fSPaul Mullowney                                mat->values->data().get(), mat->row_offsets->data().get(),
14677656d835SStefano Zampini                                mat->column_indices->data().get(), xarray, beta,
146857d48284SJunchao Zhang                                dptr);CHKERRCUSPARSE(stat);
1469aa372e3fSPaul Mullowney     } else {
1470213423ffSJunchao Zhang       if (cusparsestruct->nrows) {
1471301298b4SMark Adams         cusparseHybMat_t hybMat = (cusparseHybMat_t)matstruct->mat;
1472aa372e3fSPaul Mullowney         stat = cusparse_hyb_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1473b06137fdSPaul Mullowney                                  matstruct->alpha, matstruct->descr, hybMat,
14747656d835SStefano Zampini                                  xarray, beta,
147557d48284SJunchao Zhang                                  dptr);CHKERRCUSPARSE(stat);
1476a65300a6SPaul Mullowney       }
1477aa372e3fSPaul Mullowney     }
1478958c4211Shannah_mairs     ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1479aa372e3fSPaul Mullowney 
1480213423ffSJunchao Zhang     if (yy) { /* MatMultAdd: zz = A*xx + yy */
1481213423ffSJunchao Zhang       if (compressed) { /* A is compressed. We first copy yy to zz, then ScatterAdd the work vector to zz */
1482213423ffSJunchao Zhang         ierr = VecCopy_SeqCUDA(yy,zz);CHKERRQ(ierr); /* zz = yy */
1483213423ffSJunchao Zhang       } else if (zz != yy) { /* A's not compreseed. zz already contains A*xx, and we just need to add yy */
1484213423ffSJunchao Zhang         ierr = VecAXPY_SeqCUDA(zz,1.0,yy);CHKERRQ(ierr); /* zz += yy */
14857656d835SStefano Zampini       }
1486213423ffSJunchao Zhang     } else if (compressed) { /* MatMult: zz = A*xx. A is compressed, so we zero zz first, then ScatterAdd the work vector to zz */
1487c1fb3f03SStefano Zampini       ierr = VecSet_SeqCUDA(zz,0);CHKERRQ(ierr);
14887656d835SStefano Zampini     }
14897656d835SStefano Zampini 
1490213423ffSJunchao Zhang     /* ScatterAdd the result from work vector into the full vector when A is compressed */
1491213423ffSJunchao Zhang     ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1492213423ffSJunchao Zhang     if (compressed) {
1493213423ffSJunchao Zhang       thrust::device_ptr<PetscScalar> zptr = thrust::device_pointer_cast(zarray);
1494c41cb2e2SAlejandro Lamas Daviña       thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple(cusparsestruct->workVector->begin(), thrust::make_permutation_iterator(zptr, matstruct->cprowIndices->begin()))),
1495c41cb2e2SAlejandro Lamas Daviña                        thrust::make_zip_iterator(thrust::make_tuple(cusparsestruct->workVector->begin(), thrust::make_permutation_iterator(zptr, matstruct->cprowIndices->begin()))) + cusparsestruct->workVector->size(),
1496c41cb2e2SAlejandro Lamas Daviña                        VecCUDAPlusEquals());
14977656d835SStefano Zampini     }
1498958c4211Shannah_mairs     ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1499c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDARestoreArrayRead(xx,&xarray);CHKERRQ(ierr);
1500213423ffSJunchao Zhang     if (yy == zz) {ierr = VecCUDARestoreArray(zz,&zarray);CHKERRQ(ierr);}
1501213423ffSJunchao Zhang     else {ierr = VecCUDARestoreArrayWrite(zz,&zarray);CHKERRQ(ierr);}
15029ae82921SPaul Mullowney   } catch(char *ex) {
15039ae82921SPaul Mullowney     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
15049ae82921SPaul Mullowney   }
150557d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1506958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*a->nz);CHKERRQ(ierr);
15079ae82921SPaul Mullowney   PetscFunctionReturn(0);
15089ae82921SPaul Mullowney }
15099ae82921SPaul Mullowney 
15106fa9248bSJed Brown static PetscErrorCode MatMultTransposeAdd_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy,Vec zz)
1511ca45077fSPaul Mullowney {
1512ca45077fSPaul Mullowney   Mat_SeqAIJ                      *a = (Mat_SeqAIJ*)A->data;
1513aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE              *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
15149ff858a8SKarl Rupp   Mat_SeqAIJCUSPARSEMultStruct    *matstructT;
1515465f34aeSAlejandro Lamas Daviña   const PetscScalar               *xarray;
151620291eb5SJunchao Zhang   PetscScalar                     *zarray,*beta;
1517b175d8bbSPaul Mullowney   PetscErrorCode                  ierr;
151857d48284SJunchao Zhang   cudaError_t                     cerr;
1519aa372e3fSPaul Mullowney   cusparseStatus_t                stat;
15206e111a19SKarl Rupp 
1521ca45077fSPaul Mullowney   PetscFunctionBegin;
152234d6c7a5SJose E. Roman   /* The line below is necessary due to the operations that modify the matrix on the CPU (axpy, scale, etc) */
152334d6c7a5SJose E. Roman   ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
15249ff858a8SKarl Rupp   matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1525aa372e3fSPaul Mullowney   if (!matstructT) {
1526bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEGenerateTransposeForMult(A);CHKERRQ(ierr);
1527aa372e3fSPaul Mullowney     matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1528bda325fcSPaul Mullowney   }
1529aa372e3fSPaul Mullowney 
153020291eb5SJunchao Zhang   /* Note unlike Mat, MatTranspose uses non-compressed row storage */
1531ca45077fSPaul Mullowney   try {
1532c41cb2e2SAlejandro Lamas Daviña     ierr = VecCopy_SeqCUDA(yy,zz);CHKERRQ(ierr);
1533c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDAGetArrayRead(xx,&xarray);CHKERRQ(ierr);
1534f2d70e9dSBarry Smith     ierr = VecCUDAGetArray(zz,&zarray);CHKERRQ(ierr);
153520291eb5SJunchao Zhang     beta = (yy == zz) ? matstructT->beta_one : matstructT->beta_zero;
1536ca45077fSPaul Mullowney 
15377a052e47Shannah_mairs     ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1538e057df02SPaul Mullowney     /* multiply add with matrix transpose */
1539aa372e3fSPaul Mullowney     if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
1540aa372e3fSPaul Mullowney       CsrMatrix *mat = (CsrMatrix*)matstructT->mat;
1541aa372e3fSPaul Mullowney       stat = cusparse_csr_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1542a65300a6SPaul Mullowney                                mat->num_rows, mat->num_cols,
1543b06137fdSPaul Mullowney                                mat->num_entries, matstructT->alpha, matstructT->descr,
1544aa372e3fSPaul Mullowney                                mat->values->data().get(), mat->row_offsets->data().get(),
1545a3fdcf43SKarl Rupp                                mat->column_indices->data().get(), xarray, beta,
15469f74ec24SSatish Balay                                zarray);CHKERRCUSPARSE(stat);
1547aa372e3fSPaul Mullowney     } else {
1548aa372e3fSPaul Mullowney       cusparseHybMat_t hybMat = (cusparseHybMat_t)matstructT->mat;
1549213423ffSJunchao Zhang       if (cusparsestruct->nrows) {
1550aa372e3fSPaul Mullowney         stat = cusparse_hyb_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1551b06137fdSPaul Mullowney                                  matstructT->alpha, matstructT->descr, hybMat,
1552a3fdcf43SKarl Rupp                                  xarray, beta,
15539f74ec24SSatish Balay                                  zarray);CHKERRCUSPARSE(stat);
1554a65300a6SPaul Mullowney       }
1555aa372e3fSPaul Mullowney     }
1556a3fdcf43SKarl Rupp     ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1557a3fdcf43SKarl Rupp 
155820291eb5SJunchao Zhang     if (zz != yy) {ierr = VecAXPY_SeqCUDA(zz,1.0,yy);CHKERRQ(ierr);}
1559c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDARestoreArrayRead(xx,&xarray);CHKERRQ(ierr);
1560f2d70e9dSBarry Smith     ierr = VecCUDARestoreArray(zz,&zarray);CHKERRQ(ierr);
1561ca45077fSPaul Mullowney   } catch(char *ex) {
1562ca45077fSPaul Mullowney     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
1563661c2d29Shannah_mairs   }
15649f74ec24SSatish Balay   cerr = WaitForGPU();CHKERRCUDA(cerr);
1565958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*a->nz);CHKERRQ(ierr);
1566ca45077fSPaul Mullowney   PetscFunctionReturn(0);
1567ca45077fSPaul Mullowney }
1568ca45077fSPaul Mullowney 
15696fa9248bSJed Brown static PetscErrorCode MatAssemblyEnd_SeqAIJCUSPARSE(Mat A,MatAssemblyType mode)
15709ae82921SPaul Mullowney {
15719ae82921SPaul Mullowney   PetscErrorCode ierr;
15726e111a19SKarl Rupp 
15739ae82921SPaul Mullowney   PetscFunctionBegin;
15749ae82921SPaul Mullowney   ierr = MatAssemblyEnd_SeqAIJ(A,mode);CHKERRQ(ierr);
157595639643SRichard Tran Mills   if (mode == MAT_FLUSH_ASSEMBLY || A->boundtocpu) PetscFunctionReturn(0);
1576bc3f50f2SPaul Mullowney   if (A->factortype == MAT_FACTOR_NONE) {
1577e057df02SPaul Mullowney     ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
1578bc3f50f2SPaul Mullowney   }
1579bbf3fe20SPaul Mullowney   A->ops->mult             = MatMult_SeqAIJCUSPARSE;
1580bbf3fe20SPaul Mullowney   A->ops->multadd          = MatMultAdd_SeqAIJCUSPARSE;
1581bbf3fe20SPaul Mullowney   A->ops->multtranspose    = MatMultTranspose_SeqAIJCUSPARSE;
1582bbf3fe20SPaul Mullowney   A->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJCUSPARSE;
15839ae82921SPaul Mullowney   PetscFunctionReturn(0);
15849ae82921SPaul Mullowney }
15859ae82921SPaul Mullowney 
15869ae82921SPaul Mullowney /* --------------------------------------------------------------------------------*/
1587e057df02SPaul Mullowney /*@
15889ae82921SPaul Mullowney    MatCreateSeqAIJCUSPARSE - Creates a sparse matrix in AIJ (compressed row) format
1589e057df02SPaul Mullowney    (the default parallel PETSc format). This matrix will ultimately pushed down
1590e057df02SPaul Mullowney    to NVidia GPUs and use the CUSPARSE library for calculations. For good matrix
1591e057df02SPaul Mullowney    assembly performance the user should preallocate the matrix storage by setting
1592e057df02SPaul Mullowney    the parameter nz (or the array nnz).  By setting these parameters accurately,
1593e057df02SPaul Mullowney    performance during matrix assembly can be increased by more than a factor of 50.
15949ae82921SPaul Mullowney 
1595d083f849SBarry Smith    Collective
15969ae82921SPaul Mullowney 
15979ae82921SPaul Mullowney    Input Parameters:
15989ae82921SPaul Mullowney +  comm - MPI communicator, set to PETSC_COMM_SELF
15999ae82921SPaul Mullowney .  m - number of rows
16009ae82921SPaul Mullowney .  n - number of columns
16019ae82921SPaul Mullowney .  nz - number of nonzeros per row (same for all rows)
16029ae82921SPaul Mullowney -  nnz - array containing the number of nonzeros in the various rows
16030298fd71SBarry Smith          (possibly different for each row) or NULL
16049ae82921SPaul Mullowney 
16059ae82921SPaul Mullowney    Output Parameter:
16069ae82921SPaul Mullowney .  A - the matrix
16079ae82921SPaul Mullowney 
16089ae82921SPaul Mullowney    It is recommended that one use the MatCreate(), MatSetType() and/or MatSetFromOptions(),
16099ae82921SPaul Mullowney    MatXXXXSetPreallocation() paradgm instead of this routine directly.
16109ae82921SPaul Mullowney    [MatXXXXSetPreallocation() is, for example, MatSeqAIJSetPreallocation]
16119ae82921SPaul Mullowney 
16129ae82921SPaul Mullowney    Notes:
16139ae82921SPaul Mullowney    If nnz is given then nz is ignored
16149ae82921SPaul Mullowney 
16159ae82921SPaul Mullowney    The AIJ format (also called the Yale sparse matrix format or
16169ae82921SPaul Mullowney    compressed row storage), is fully compatible with standard Fortran 77
16179ae82921SPaul Mullowney    storage.  That is, the stored row and column indices can begin at
16189ae82921SPaul Mullowney    either one (as in Fortran) or zero.  See the users' manual for details.
16199ae82921SPaul Mullowney 
16209ae82921SPaul Mullowney    Specify the preallocated storage with either nz or nnz (not both).
16210298fd71SBarry Smith    Set nz=PETSC_DEFAULT and nnz=NULL for PETSc to control dynamic memory
16229ae82921SPaul Mullowney    allocation.  For large problems you MUST preallocate memory or you
16239ae82921SPaul Mullowney    will get TERRIBLE performance, see the users' manual chapter on matrices.
16249ae82921SPaul Mullowney 
16259ae82921SPaul Mullowney    By default, this format uses inodes (identical nodes) when possible, to
16269ae82921SPaul Mullowney    improve numerical efficiency of matrix-vector products and solves. We
16279ae82921SPaul Mullowney    search for consecutive rows with the same nonzero structure, thereby
16289ae82921SPaul Mullowney    reusing matrix information to achieve increased efficiency.
16299ae82921SPaul Mullowney 
16309ae82921SPaul Mullowney    Level: intermediate
16319ae82921SPaul Mullowney 
1632e057df02SPaul Mullowney .seealso: MatCreate(), MatCreateAIJ(), MatSetValues(), MatSeqAIJSetColumnIndices(), MatCreateSeqAIJWithArrays(), MatCreateAIJ(), MATSEQAIJCUSPARSE, MATAIJCUSPARSE
16339ae82921SPaul Mullowney @*/
16349ae82921SPaul Mullowney PetscErrorCode  MatCreateSeqAIJCUSPARSE(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt nz,const PetscInt nnz[],Mat *A)
16359ae82921SPaul Mullowney {
16369ae82921SPaul Mullowney   PetscErrorCode ierr;
16379ae82921SPaul Mullowney 
16389ae82921SPaul Mullowney   PetscFunctionBegin;
16399ae82921SPaul Mullowney   ierr = MatCreate(comm,A);CHKERRQ(ierr);
16409ae82921SPaul Mullowney   ierr = MatSetSizes(*A,m,n,m,n);CHKERRQ(ierr);
16419ae82921SPaul Mullowney   ierr = MatSetType(*A,MATSEQAIJCUSPARSE);CHKERRQ(ierr);
16429ae82921SPaul Mullowney   ierr = MatSeqAIJSetPreallocation_SeqAIJ(*A,nz,(PetscInt*)nnz);CHKERRQ(ierr);
16439ae82921SPaul Mullowney   PetscFunctionReturn(0);
16449ae82921SPaul Mullowney }
16459ae82921SPaul Mullowney 
16466fa9248bSJed Brown static PetscErrorCode MatDestroy_SeqAIJCUSPARSE(Mat A)
16479ae82921SPaul Mullowney {
16489ae82921SPaul Mullowney   PetscErrorCode   ierr;
1649ab25e6cbSDominic Meiser 
16509ae82921SPaul Mullowney   PetscFunctionBegin;
16519ae82921SPaul Mullowney   if (A->factortype==MAT_FACTOR_NONE) {
1652c70f7ee4SJunchao Zhang     if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) {
1653470880abSPatrick Sanan       ierr = MatSeqAIJCUSPARSE_Destroy((Mat_SeqAIJCUSPARSE**)&A->spptr);CHKERRQ(ierr);
16549ae82921SPaul Mullowney     }
16559ae82921SPaul Mullowney   } else {
1656470880abSPatrick Sanan     ierr = MatSeqAIJCUSPARSETriFactors_Destroy((Mat_SeqAIJCUSPARSETriFactors**)&A->spptr);CHKERRQ(ierr);
1657aa372e3fSPaul Mullowney   }
16589ae82921SPaul Mullowney   ierr = MatDestroy_SeqAIJ(A);CHKERRQ(ierr);
16599ae82921SPaul Mullowney   PetscFunctionReturn(0);
16609ae82921SPaul Mullowney }
16619ae82921SPaul Mullowney 
166295639643SRichard Tran Mills static PetscErrorCode MatBindToCPU_SeqAIJCUSPARSE(Mat,PetscBool);
16639ff858a8SKarl Rupp static PetscErrorCode MatDuplicate_SeqAIJCUSPARSE(Mat A,MatDuplicateOption cpvalues,Mat *B)
16649ff858a8SKarl Rupp {
16659ff858a8SKarl Rupp   PetscErrorCode ierr;
16669ff858a8SKarl Rupp   Mat C;
16679ff858a8SKarl Rupp   cusparseStatus_t stat;
16689ff858a8SKarl Rupp   cusparseHandle_t handle=0;
16699ff858a8SKarl Rupp 
16709ff858a8SKarl Rupp   PetscFunctionBegin;
16719ff858a8SKarl Rupp   ierr = MatDuplicate_SeqAIJ(A,cpvalues,B);CHKERRQ(ierr);
16729ff858a8SKarl Rupp   C    = *B;
167334136279SStefano Zampini   ierr = PetscFree(C->defaultvectype);CHKERRQ(ierr);
167434136279SStefano Zampini   ierr = PetscStrallocpy(VECCUDA,&C->defaultvectype);CHKERRQ(ierr);
167534136279SStefano Zampini 
16769ff858a8SKarl Rupp   /* inject CUSPARSE-specific stuff */
16779ff858a8SKarl Rupp   if (C->factortype==MAT_FACTOR_NONE) {
16789ff858a8SKarl Rupp     /* you cannot check the inode.use flag here since the matrix was just created.
16799ff858a8SKarl Rupp        now build a GPU matrix data structure */
16809ff858a8SKarl Rupp     C->spptr = new Mat_SeqAIJCUSPARSE;
16819ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->mat            = 0;
16829ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->matTranspose   = 0;
16839ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->workVector     = 0;
168481902715SJunchao Zhang     ((Mat_SeqAIJCUSPARSE*)C->spptr)->rowoffsets_gpu = 0;
16859ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->format         = MAT_CUSPARSE_CSR;
16869ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->stream         = 0;
168757d48284SJunchao Zhang     stat = cusparseCreate(&handle);CHKERRCUSPARSE(stat);
16889ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->handle         = handle;
16899ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->nonzerostate   = 0;
16909ff858a8SKarl Rupp   } else {
16919ff858a8SKarl Rupp     /* NEXT, set the pointers to the triangular factors */
16929ff858a8SKarl Rupp     C->spptr = new Mat_SeqAIJCUSPARSETriFactors;
16939ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->loTriFactorPtr          = 0;
16949ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->upTriFactorPtr          = 0;
16959ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->loTriFactorPtrTranspose = 0;
16969ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->upTriFactorPtrTranspose = 0;
16979ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->rpermIndices            = 0;
16989ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->cpermIndices            = 0;
16999ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->workVector              = 0;
17009ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->handle                  = 0;
170157d48284SJunchao Zhang     stat = cusparseCreate(&handle);CHKERRCUSPARSE(stat);
17029ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->handle                  = handle;
17039ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->nnz                     = 0;
17049ff858a8SKarl Rupp   }
17059ff858a8SKarl Rupp 
17069ff858a8SKarl Rupp   C->ops->assemblyend      = MatAssemblyEnd_SeqAIJCUSPARSE;
17079ff858a8SKarl Rupp   C->ops->destroy          = MatDestroy_SeqAIJCUSPARSE;
17089ff858a8SKarl Rupp   C->ops->setfromoptions   = MatSetFromOptions_SeqAIJCUSPARSE;
17099ff858a8SKarl Rupp   C->ops->mult             = MatMult_SeqAIJCUSPARSE;
17109ff858a8SKarl Rupp   C->ops->multadd          = MatMultAdd_SeqAIJCUSPARSE;
17119ff858a8SKarl Rupp   C->ops->multtranspose    = MatMultTranspose_SeqAIJCUSPARSE;
17129ff858a8SKarl Rupp   C->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJCUSPARSE;
17139ff858a8SKarl Rupp   C->ops->duplicate        = MatDuplicate_SeqAIJCUSPARSE;
171495639643SRichard Tran Mills   C->ops->bindtocpu        = MatBindToCPU_SeqAIJCUSPARSE;
17159ff858a8SKarl Rupp 
17169ff858a8SKarl Rupp   ierr = PetscObjectChangeTypeName((PetscObject)C,MATSEQAIJCUSPARSE);CHKERRQ(ierr);
17179ff858a8SKarl Rupp 
171895639643SRichard Tran Mills   C->boundtocpu  = PETSC_FALSE;
1719c70f7ee4SJunchao Zhang   C->offloadmask = PETSC_OFFLOAD_UNALLOCATED;
17209ff858a8SKarl Rupp 
17219ff858a8SKarl Rupp   ierr = PetscObjectComposeFunction((PetscObject)C, "MatCUSPARSESetFormat_C", MatCUSPARSESetFormat_SeqAIJCUSPARSE);CHKERRQ(ierr);
17229ff858a8SKarl Rupp   PetscFunctionReturn(0);
17239ff858a8SKarl Rupp }
17249ff858a8SKarl Rupp 
172595639643SRichard Tran Mills 
172695639643SRichard Tran Mills static PetscErrorCode MatBindToCPU_SeqAIJCUSPARSE(Mat A,PetscBool flg)
172795639643SRichard Tran Mills {
172895639643SRichard Tran Mills   PetscFunctionBegin;
1729c34f1ff0SRichard Tran Mills   /* Currently, there is no case in which an AIJCUSPARSE matrix ever has its offloadmask set to PETS_OFFLOAD_GPU.
173095639643SRichard Tran Mills      If this changes, we need to implement a routine to update the CPU (host) version of the matrix from the GPU one.
173195639643SRichard Tran Mills      Right now, for safety we simply check for PETSC_OFFLOAD_GPU and have MatBindToCPU() do nothing in this case.
173295639643SRichard Tran Mills      TODO: Add MatAIJCUSPARSECopyFromGPU() and make MatBindToCPU() functional for AIJCUSPARSE matries;
173395639643SRichard Tran Mills            can follow the example of MatBindToCPU_SeqAIJViennaCL(). */
173495639643SRichard Tran Mills   if (A->offloadmask == PETSC_OFFLOAD_GPU) PetscFunctionReturn(0);
173595639643SRichard Tran Mills   if (flg) {
173695639643SRichard Tran Mills     A->ops->mult             = MatMult_SeqAIJ;
173795639643SRichard Tran Mills     A->ops->multadd          = MatMultAdd_SeqAIJ;
1738c34f1ff0SRichard Tran Mills     A->ops->multtranspose    = MatMultTranspose_SeqAIJ;
1739c34f1ff0SRichard Tran Mills     A->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJ;
174095639643SRichard Tran Mills     A->ops->assemblyend      = MatAssemblyEnd_SeqAIJ;
174195639643SRichard Tran Mills     A->ops->duplicate        = MatDuplicate_SeqAIJ;
174295639643SRichard Tran Mills   } else {
174395639643SRichard Tran Mills     A->ops->mult             = MatMult_SeqAIJCUSPARSE;
174495639643SRichard Tran Mills     A->ops->multadd          = MatMultAdd_SeqAIJCUSPARSE;
174595639643SRichard Tran Mills     A->ops->multtranspose    = MatMultTranspose_SeqAIJCUSPARSE;
174695639643SRichard Tran Mills     A->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJCUSPARSE;
174795639643SRichard Tran Mills     A->ops->assemblyend      = MatAssemblyEnd_SeqAIJCUSPARSE;
174895639643SRichard Tran Mills     A->ops->destroy          = MatDestroy_SeqAIJCUSPARSE;
174995639643SRichard Tran Mills     A->ops->duplicate        = MatDuplicate_SeqAIJCUSPARSE;
175095639643SRichard Tran Mills   }
175195639643SRichard Tran Mills   A->boundtocpu = flg;
175295639643SRichard Tran Mills   PetscFunctionReturn(0);
175395639643SRichard Tran Mills }
175495639643SRichard Tran Mills 
1755*0ce8acdeSStefano Zampini PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCUSPARSE(Mat B, MatType mtype, MatReuse reuse, Mat* newmat)
17569ae82921SPaul Mullowney {
17579ae82921SPaul Mullowney   PetscErrorCode ierr;
1758aa372e3fSPaul Mullowney   cusparseStatus_t stat;
1759aa372e3fSPaul Mullowney   cusparseHandle_t handle=0;
17609ae82921SPaul Mullowney 
17619ae82921SPaul Mullowney   PetscFunctionBegin;
1762*0ce8acdeSStefano Zampini   if (reuse != MAT_INPLACE_MATRIX) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not yet supported");
176334136279SStefano Zampini   ierr = PetscFree(B->defaultvectype);CHKERRQ(ierr);
176434136279SStefano Zampini   ierr = PetscStrallocpy(VECCUDA,&B->defaultvectype);CHKERRQ(ierr);
176534136279SStefano Zampini 
17669ae82921SPaul Mullowney   if (B->factortype==MAT_FACTOR_NONE) {
1767e057df02SPaul Mullowney     /* you cannot check the inode.use flag here since the matrix was just created.
1768e057df02SPaul Mullowney        now build a GPU matrix data structure */
17699ae82921SPaul Mullowney     B->spptr = new Mat_SeqAIJCUSPARSE;
17709ae82921SPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->mat            = 0;
1771aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->matTranspose   = 0;
1772aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->workVector     = 0;
177381902715SJunchao Zhang     ((Mat_SeqAIJCUSPARSE*)B->spptr)->rowoffsets_gpu = 0;
1774e057df02SPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->format         = MAT_CUSPARSE_CSR;
1775aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->stream         = 0;
177657d48284SJunchao Zhang     stat = cusparseCreate(&handle);CHKERRCUSPARSE(stat);
1777aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->handle         = handle;
17789ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)B->spptr)->nonzerostate   = 0;
17799ae82921SPaul Mullowney   } else {
17809ae82921SPaul Mullowney     /* NEXT, set the pointers to the triangular factors */
1781debe9ee2SPaul Mullowney     B->spptr = new Mat_SeqAIJCUSPARSETriFactors;
17829ae82921SPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->loTriFactorPtr          = 0;
17839ae82921SPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->upTriFactorPtr          = 0;
1784aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->loTriFactorPtrTranspose = 0;
1785aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->upTriFactorPtrTranspose = 0;
1786aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->rpermIndices            = 0;
1787aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->cpermIndices            = 0;
1788aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->workVector              = 0;
178957d48284SJunchao Zhang     stat = cusparseCreate(&handle);CHKERRCUSPARSE(stat);
1790aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->handle                  = handle;
1791aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSETriFactors*)B->spptr)->nnz                     = 0;
17929ae82921SPaul Mullowney   }
1793aa372e3fSPaul Mullowney 
17949ae82921SPaul Mullowney   B->ops->assemblyend      = MatAssemblyEnd_SeqAIJCUSPARSE;
17959ae82921SPaul Mullowney   B->ops->destroy          = MatDestroy_SeqAIJCUSPARSE;
17969ae82921SPaul Mullowney   B->ops->setfromoptions   = MatSetFromOptions_SeqAIJCUSPARSE;
1797ca45077fSPaul Mullowney   B->ops->mult             = MatMult_SeqAIJCUSPARSE;
1798ca45077fSPaul Mullowney   B->ops->multadd          = MatMultAdd_SeqAIJCUSPARSE;
1799ca45077fSPaul Mullowney   B->ops->multtranspose    = MatMultTranspose_SeqAIJCUSPARSE;
1800ca45077fSPaul Mullowney   B->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJCUSPARSE;
18019ff858a8SKarl Rupp   B->ops->duplicate        = MatDuplicate_SeqAIJCUSPARSE;
180295639643SRichard Tran Mills   B->ops->bindtocpu        = MatBindToCPU_SeqAIJCUSPARSE;
18032205254eSKarl Rupp 
18049ae82921SPaul Mullowney   ierr = PetscObjectChangeTypeName((PetscObject)B,MATSEQAIJCUSPARSE);CHKERRQ(ierr);
18052205254eSKarl Rupp 
180695639643SRichard Tran Mills   B->boundtocpu  = PETSC_FALSE;
1807c70f7ee4SJunchao Zhang   B->offloadmask = PETSC_OFFLOAD_UNALLOCATED;
18082205254eSKarl Rupp 
1809bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatCUSPARSESetFormat_C",MatCUSPARSESetFormat_SeqAIJCUSPARSE);CHKERRQ(ierr);
18109ae82921SPaul Mullowney   PetscFunctionReturn(0);
18119ae82921SPaul Mullowney }
18129ae82921SPaul Mullowney 
181302fe1965SBarry Smith PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJCUSPARSE(Mat B)
181402fe1965SBarry Smith {
181502fe1965SBarry Smith   PetscErrorCode ierr;
181602fe1965SBarry Smith 
181702fe1965SBarry Smith   PetscFunctionBegin;
181802fe1965SBarry Smith   ierr = MatCreate_SeqAIJ(B);CHKERRQ(ierr);
1819*0ce8acdeSStefano Zampini   ierr = MatConvert_SeqAIJ_SeqAIJCUSPARSE(B,MATSEQAIJCUSPARSE,MAT_INPLACE_MATRIX,&B);CHKERRQ(ierr);
182002fe1965SBarry Smith   PetscFunctionReturn(0);
182102fe1965SBarry Smith }
182202fe1965SBarry Smith 
18233ca39a21SBarry Smith /*MC
1824e057df02SPaul Mullowney    MATSEQAIJCUSPARSE - MATAIJCUSPARSE = "(seq)aijcusparse" - A matrix type to be used for sparse matrices.
1825e057df02SPaul Mullowney 
1826e057df02SPaul Mullowney    A matrix type type whose data resides on Nvidia GPUs. These matrices can be in either
18272692e278SPaul Mullowney    CSR, ELL, or Hybrid format. The ELL and HYB formats require CUDA 4.2 or later.
18282692e278SPaul Mullowney    All matrix calculations are performed on Nvidia GPUs using the CUSPARSE library.
1829e057df02SPaul Mullowney 
1830e057df02SPaul Mullowney    Options Database Keys:
1831e057df02SPaul Mullowney +  -mat_type aijcusparse - sets the matrix type to "seqaijcusparse" during a call to MatSetFromOptions()
1832aa372e3fSPaul 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).
1833a2b725a8SWilliam 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).
1834e057df02SPaul Mullowney 
1835e057df02SPaul Mullowney   Level: beginner
1836e057df02SPaul Mullowney 
18378468deeeSKarl Rupp .seealso: MatCreateSeqAIJCUSPARSE(), MATAIJCUSPARSE, MatCreateAIJCUSPARSE(), MatCUSPARSESetFormat(), MatCUSPARSEStorageFormat, MatCUSPARSEFormatOperation
1838e057df02SPaul Mullowney M*/
18397f756511SDominic Meiser 
184042c9c57cSBarry Smith PETSC_EXTERN PetscErrorCode MatGetFactor_seqaijcusparse_cusparse(Mat,MatFactorType,Mat*);
184142c9c57cSBarry Smith 
18420f39cd5aSBarry Smith 
18433ca39a21SBarry Smith PETSC_EXTERN PetscErrorCode MatSolverTypeRegister_CUSPARSE(void)
184442c9c57cSBarry Smith {
184542c9c57cSBarry Smith   PetscErrorCode ierr;
184642c9c57cSBarry Smith 
184742c9c57cSBarry Smith   PetscFunctionBegin;
18483ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_LU,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
18493ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_CHOLESKY,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
18503ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_ILU,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
18513ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_ICC,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
185242c9c57cSBarry Smith   PetscFunctionReturn(0);
185342c9c57cSBarry Smith }
185429b38603SBarry Smith 
185581e08676SBarry Smith 
1856470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSE_Destroy(Mat_SeqAIJCUSPARSE **cusparsestruct)
18577f756511SDominic Meiser {
18587f756511SDominic Meiser   cusparseStatus_t stat;
18597f756511SDominic Meiser   cusparseHandle_t handle;
18607f756511SDominic Meiser 
18617f756511SDominic Meiser   PetscFunctionBegin;
18627f756511SDominic Meiser   if (*cusparsestruct) {
1863470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*cusparsestruct)->mat,(*cusparsestruct)->format);
1864470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*cusparsestruct)->matTranspose,(*cusparsestruct)->format);
18657f756511SDominic Meiser     delete (*cusparsestruct)->workVector;
186681902715SJunchao Zhang     delete (*cusparsestruct)->rowoffsets_gpu;
18677f756511SDominic Meiser     if (handle = (*cusparsestruct)->handle) {
186857d48284SJunchao Zhang       stat = cusparseDestroy(handle);CHKERRCUSPARSE(stat);
18697f756511SDominic Meiser     }
18707f756511SDominic Meiser     delete *cusparsestruct;
18717f756511SDominic Meiser     *cusparsestruct = 0;
18727f756511SDominic Meiser   }
18737f756511SDominic Meiser   PetscFunctionReturn(0);
18747f756511SDominic Meiser }
18757f756511SDominic Meiser 
18767f756511SDominic Meiser static PetscErrorCode CsrMatrix_Destroy(CsrMatrix **mat)
18777f756511SDominic Meiser {
18787f756511SDominic Meiser   PetscFunctionBegin;
18797f756511SDominic Meiser   if (*mat) {
18807f756511SDominic Meiser     delete (*mat)->values;
18817f756511SDominic Meiser     delete (*mat)->column_indices;
18827f756511SDominic Meiser     delete (*mat)->row_offsets;
18837f756511SDominic Meiser     delete *mat;
18847f756511SDominic Meiser     *mat = 0;
18857f756511SDominic Meiser   }
18867f756511SDominic Meiser   PetscFunctionReturn(0);
18877f756511SDominic Meiser }
18887f756511SDominic Meiser 
1889470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSEMultStruct_Destroy(Mat_SeqAIJCUSPARSETriFactorStruct **trifactor)
18907f756511SDominic Meiser {
18917f756511SDominic Meiser   cusparseStatus_t stat;
18927f756511SDominic Meiser   PetscErrorCode   ierr;
18937f756511SDominic Meiser 
18947f756511SDominic Meiser   PetscFunctionBegin;
18957f756511SDominic Meiser   if (*trifactor) {
189657d48284SJunchao Zhang     if ((*trifactor)->descr) { stat = cusparseDestroyMatDescr((*trifactor)->descr);CHKERRCUSPARSE(stat); }
189757d48284SJunchao Zhang     if ((*trifactor)->solveInfo) { stat = cusparseDestroySolveAnalysisInfo((*trifactor)->solveInfo);CHKERRCUSPARSE(stat); }
18987f756511SDominic Meiser     ierr = CsrMatrix_Destroy(&(*trifactor)->csrMat);CHKERRQ(ierr);
18997f756511SDominic Meiser     delete *trifactor;
19007f756511SDominic Meiser     *trifactor = 0;
19017f756511SDominic Meiser   }
19027f756511SDominic Meiser   PetscFunctionReturn(0);
19037f756511SDominic Meiser }
19047f756511SDominic Meiser 
1905470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSEMultStruct_Destroy(Mat_SeqAIJCUSPARSEMultStruct **matstruct,MatCUSPARSEStorageFormat format)
19067f756511SDominic Meiser {
19077f756511SDominic Meiser   CsrMatrix        *mat;
19087f756511SDominic Meiser   cusparseStatus_t stat;
19097f756511SDominic Meiser   cudaError_t      err;
19107f756511SDominic Meiser 
19117f756511SDominic Meiser   PetscFunctionBegin;
19127f756511SDominic Meiser   if (*matstruct) {
19137f756511SDominic Meiser     if ((*matstruct)->mat) {
19147f756511SDominic Meiser       if (format==MAT_CUSPARSE_ELL || format==MAT_CUSPARSE_HYB) {
19157f756511SDominic Meiser         cusparseHybMat_t hybMat = (cusparseHybMat_t)(*matstruct)->mat;
191657d48284SJunchao Zhang         stat = cusparseDestroyHybMat(hybMat);CHKERRCUSPARSE(stat);
19177f756511SDominic Meiser       } else {
19187f756511SDominic Meiser         mat = (CsrMatrix*)(*matstruct)->mat;
19197f756511SDominic Meiser         CsrMatrix_Destroy(&mat);
19207f756511SDominic Meiser       }
19217f756511SDominic Meiser     }
192257d48284SJunchao Zhang     if ((*matstruct)->descr) { stat = cusparseDestroyMatDescr((*matstruct)->descr);CHKERRCUSPARSE(stat); }
19237f756511SDominic Meiser     delete (*matstruct)->cprowIndices;
1924c41cb2e2SAlejandro Lamas Daviña     if ((*matstruct)->alpha)     { err=cudaFree((*matstruct)->alpha);CHKERRCUDA(err); }
19257656d835SStefano Zampini     if ((*matstruct)->beta_zero) { err=cudaFree((*matstruct)->beta_zero);CHKERRCUDA(err); }
19267656d835SStefano Zampini     if ((*matstruct)->beta_one)  { err=cudaFree((*matstruct)->beta_one);CHKERRCUDA(err); }
19277f756511SDominic Meiser     delete *matstruct;
19287f756511SDominic Meiser     *matstruct = 0;
19297f756511SDominic Meiser   }
19307f756511SDominic Meiser   PetscFunctionReturn(0);
19317f756511SDominic Meiser }
19327f756511SDominic Meiser 
1933470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSETriFactors_Destroy(Mat_SeqAIJCUSPARSETriFactors** trifactors)
19347f756511SDominic Meiser {
19357f756511SDominic Meiser   cusparseHandle_t handle;
19367f756511SDominic Meiser   cusparseStatus_t stat;
19377f756511SDominic Meiser 
19387f756511SDominic Meiser   PetscFunctionBegin;
19397f756511SDominic Meiser   if (*trifactors) {
1940470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->loTriFactorPtr);
1941470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->upTriFactorPtr);
1942470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->loTriFactorPtrTranspose);
1943470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->upTriFactorPtrTranspose);
19447f756511SDominic Meiser     delete (*trifactors)->rpermIndices;
19457f756511SDominic Meiser     delete (*trifactors)->cpermIndices;
19467f756511SDominic Meiser     delete (*trifactors)->workVector;
19477f756511SDominic Meiser     if (handle = (*trifactors)->handle) {
194857d48284SJunchao Zhang       stat = cusparseDestroy(handle);CHKERRCUSPARSE(stat);
19497f756511SDominic Meiser     }
19507f756511SDominic Meiser     delete *trifactors;
19517f756511SDominic Meiser     *trifactors = 0;
19527f756511SDominic Meiser   }
19537f756511SDominic Meiser   PetscFunctionReturn(0);
19547f756511SDominic Meiser }
19557f756511SDominic Meiser 
1956