xref: /petsc/src/mat/impls/aij/seq/seqcusparse/aijcusparse.cu (revision 57d482846e68a47f2be4871cb6766124433582b9)
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;
50*57d48284SJunchao 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) {
62*57d48284SJunchao Zhang       stat = cusparseDestroy(cusparsestruct->handle);CHKERRCUSPARSE(stat);
6316a2e217SAlejandro Lamas Daviña     }
64b06137fdSPaul Mullowney     cusparsestruct->handle = handle;
656b1cf21dSAlejandro Lamas Daviña   }
66*57d48284SJunchao 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;
248*57d48284SJunchao 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 */
258*57d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AiLo, (n+1)*sizeof(PetscInt));CHKERRCUDA(cerr);
259*57d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AjLo, nzLower*sizeof(PetscInt));CHKERRCUDA(cerr);
260*57d48284SJunchao 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 */
293*57d48284SJunchao Zhang       stat = cusparseCreateMatDescr(&loTriFactor->descr);CHKERRCUSPARSE(stat);
294*57d48284SJunchao Zhang       stat = cusparseSetMatIndexBase(loTriFactor->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
295*57d48284SJunchao Zhang       stat = cusparseSetMatType(loTriFactor->descr, CUSPARSE_MATRIX_TYPE_TRIANGULAR);CHKERRCUSPARSE(stat);
296*57d48284SJunchao Zhang       stat = cusparseSetMatFillMode(loTriFactor->descr, CUSPARSE_FILL_MODE_LOWER);CHKERRCUSPARSE(stat);
297*57d48284SJunchao Zhang       stat = cusparseSetMatDiagType(loTriFactor->descr, CUSPARSE_DIAG_TYPE_UNIT);CHKERRCUSPARSE(stat);
298aa372e3fSPaul Mullowney 
299aa372e3fSPaul Mullowney       /* Create the solve analysis information */
300*57d48284SJunchao 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(),
324*57d48284SJunchao 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 
329*57d48284SJunchao Zhang       cerr = cudaFreeHost(AiLo);CHKERRCUDA(cerr);
330*57d48284SJunchao Zhang       cerr = cudaFreeHost(AjLo);CHKERRCUDA(cerr);
331*57d48284SJunchao 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;
353*57d48284SJunchao 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 */
363*57d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AiUp, (n+1)*sizeof(PetscInt));CHKERRCUDA(cerr);
364*57d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AjUp, nzUpper*sizeof(PetscInt));CHKERRCUDA(cerr);
365*57d48284SJunchao 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 */
394*57d48284SJunchao Zhang       stat = cusparseCreateMatDescr(&upTriFactor->descr);CHKERRCUSPARSE(stat);
395*57d48284SJunchao Zhang       stat = cusparseSetMatIndexBase(upTriFactor->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
396*57d48284SJunchao Zhang       stat = cusparseSetMatType(upTriFactor->descr, CUSPARSE_MATRIX_TYPE_TRIANGULAR);CHKERRCUSPARSE(stat);
397*57d48284SJunchao Zhang       stat = cusparseSetMatFillMode(upTriFactor->descr, CUSPARSE_FILL_MODE_UPPER);CHKERRCUSPARSE(stat);
398*57d48284SJunchao Zhang       stat = cusparseSetMatDiagType(upTriFactor->descr, CUSPARSE_DIAG_TYPE_NON_UNIT);CHKERRCUSPARSE(stat);
399aa372e3fSPaul Mullowney 
400aa372e3fSPaul Mullowney       /* Create the solve analysis information */
401*57d48284SJunchao 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(),
425*57d48284SJunchao 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 
430*57d48284SJunchao Zhang       cerr = cudaFreeHost(AiUp);CHKERRCUDA(cerr);
431*57d48284SJunchao Zhang       cerr = cudaFreeHost(AjUp);CHKERRCUDA(cerr);
432*57d48284SJunchao 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;
496*57d48284SJunchao 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 */
510*57d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AiUp, (n+1)*sizeof(PetscInt));CHKERRCUDA(cerr);
511*57d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AjUp, nzUpper*sizeof(PetscInt));CHKERRCUDA(cerr);
512*57d48284SJunchao Zhang       cerr = cudaMallocHost((void**) &AAUp, nzUpper*sizeof(PetscScalar));CHKERRCUDA(cerr);
513*57d48284SJunchao 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 */
547*57d48284SJunchao Zhang       stat = cusparseCreateMatDescr(&upTriFactor->descr);CHKERRCUSPARSE(stat);
548*57d48284SJunchao Zhang       stat = cusparseSetMatIndexBase(upTriFactor->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
549*57d48284SJunchao Zhang       stat = cusparseSetMatType(upTriFactor->descr, CUSPARSE_MATRIX_TYPE_TRIANGULAR);CHKERRCUSPARSE(stat);
550*57d48284SJunchao Zhang       stat = cusparseSetMatFillMode(upTriFactor->descr, CUSPARSE_FILL_MODE_UPPER);CHKERRCUSPARSE(stat);
551*57d48284SJunchao Zhang       stat = cusparseSetMatDiagType(upTriFactor->descr, CUSPARSE_DIAG_TYPE_UNIT);CHKERRCUSPARSE(stat);
552087f3262SPaul Mullowney 
553aa372e3fSPaul Mullowney       /* Create the solve analysis information */
554*57d48284SJunchao 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(),
578*57d48284SJunchao 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 */
587*57d48284SJunchao Zhang       stat = cusparseCreateMatDescr(&loTriFactor->descr);CHKERRCUSPARSE(stat);
588*57d48284SJunchao Zhang       stat = cusparseSetMatIndexBase(loTriFactor->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
589*57d48284SJunchao Zhang       stat = cusparseSetMatType(loTriFactor->descr, CUSPARSE_MATRIX_TYPE_TRIANGULAR);CHKERRCUSPARSE(stat);
590*57d48284SJunchao Zhang       stat = cusparseSetMatFillMode(loTriFactor->descr, CUSPARSE_FILL_MODE_UPPER);CHKERRCUSPARSE(stat);
591*57d48284SJunchao Zhang       stat = cusparseSetMatDiagType(loTriFactor->descr, CUSPARSE_DIAG_TYPE_NON_UNIT);CHKERRCUSPARSE(stat);
592aa372e3fSPaul Mullowney 
593aa372e3fSPaul Mullowney       /* Create the solve analysis information */
594*57d48284SJunchao 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(),
619*57d48284SJunchao 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;
625*57d48284SJunchao Zhang       cerr = cudaFreeHost(AiUp);CHKERRCUDA(cerr);
626*57d48284SJunchao Zhang       cerr = cudaFreeHost(AjUp);CHKERRCUDA(cerr);
627*57d48284SJunchao Zhang       cerr = cudaFreeHost(AAUp);CHKERRCUDA(cerr);
628*57d48284SJunchao 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 */
760*57d48284SJunchao Zhang   stat = cusparseCreateMatDescr(&loTriFactorT->descr);CHKERRCUSPARSE(stat);
761*57d48284SJunchao Zhang   stat = cusparseSetMatIndexBase(loTriFactorT->descr, indexBase);CHKERRCUSPARSE(stat);
762*57d48284SJunchao Zhang   stat = cusparseSetMatType(loTriFactorT->descr, matrixType);CHKERRCUSPARSE(stat);
763*57d48284SJunchao Zhang   stat = cusparseSetMatFillMode(loTriFactorT->descr, fillMode);CHKERRCUSPARSE(stat);
764*57d48284SJunchao Zhang   stat = cusparseSetMatDiagType(loTriFactorT->descr, diagType);CHKERRCUSPARSE(stat);
765aa372e3fSPaul Mullowney 
766aa372e3fSPaul Mullowney   /* Create the solve analysis information */
767*57d48284SJunchao 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(),
790*57d48284SJunchao 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(),
797*57d48284SJunchao 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 */
817*57d48284SJunchao Zhang   stat = cusparseCreateMatDescr(&upTriFactorT->descr);CHKERRCUSPARSE(stat);
818*57d48284SJunchao Zhang   stat = cusparseSetMatIndexBase(upTriFactorT->descr, indexBase);CHKERRCUSPARSE(stat);
819*57d48284SJunchao Zhang   stat = cusparseSetMatType(upTriFactorT->descr, matrixType);CHKERRCUSPARSE(stat);
820*57d48284SJunchao Zhang   stat = cusparseSetMatFillMode(upTriFactorT->descr, fillMode);CHKERRCUSPARSE(stat);
821*57d48284SJunchao Zhang   stat = cusparseSetMatDiagType(upTriFactorT->descr, diagType);CHKERRCUSPARSE(stat);
822aa372e3fSPaul Mullowney 
823aa372e3fSPaul Mullowney   /* Create the solve analysis information */
824*57d48284SJunchao 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(),
847*57d48284SJunchao 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(),
854*57d48284SJunchao 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;
876*57d48284SJunchao Zhang   stat = cusparseCreateMatDescr(&matstructT->descr);CHKERRCUSPARSE(stat);
877aa372e3fSPaul Mullowney   indexBase = cusparseGetMatIndexBase(matstruct->descr);
878*57d48284SJunchao Zhang   stat = cusparseSetMatIndexBase(matstructT->descr, indexBase);CHKERRCUSPARSE(stat);
879*57d48284SJunchao 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);
888*57d48284SJunchao 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;
893a3fdcf43SKarl Rupp     thrust::device_vector<int> *rowoffsets_gpu;
894a3fdcf43SKarl Rupp     const int ncomprow = matstruct->cprowIndices->size();
895a3fdcf43SKarl Rupp     thrust::host_vector<int> cprow(ncomprow);
896a3fdcf43SKarl Rupp     cprow = *matstruct->cprowIndices; // GPU --> CPU
897554b8892SKarl Rupp     matrixT->num_rows = A->cmap->n;
898554b8892SKarl Rupp     matrixT->num_cols = A->rmap->n;
899aa372e3fSPaul Mullowney     matrixT->num_entries = a->nz;
900a8bd5306SMark Adams     matrixT->row_offsets = new THRUSTINTARRAY32(matrixT->num_rows+1);
901aa372e3fSPaul Mullowney     matrixT->column_indices = new THRUSTINTARRAY32(a->nz);
902aa372e3fSPaul Mullowney     matrixT->values = new THRUSTARRAY(a->nz);
903a3fdcf43SKarl Rupp     PetscInt k,i;
904a3fdcf43SKarl Rupp     thrust::host_vector<int> rowst_host(A->rmap->n+1);
905a3fdcf43SKarl Rupp 
906a3fdcf43SKarl Rupp     /* expand compress rows, which is forced in constructor (MatSeqAIJCUSPARSECopyToGPU) */
907a3fdcf43SKarl Rupp     rowst_host[0] = 0;
908a3fdcf43SKarl Rupp     for (k = 0, i = 0; i < A->rmap->n ; i++) {
909a3fdcf43SKarl Rupp       if (k < ncomprow && i==cprow[k]) {
910a3fdcf43SKarl Rupp 	rowst_host[i+1] = a->i[i+1];
911a3fdcf43SKarl Rupp 	k++;
912a3fdcf43SKarl Rupp       } else rowst_host[i+1] = rowst_host[i];
913a3fdcf43SKarl Rupp     }
914a3fdcf43SKarl Rupp     if (k!=ncomprow) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_SUP,"%D != %D",k,ncomprow);
915a3fdcf43SKarl Rupp     rowoffsets_gpu = new THRUSTINTARRAY32(A->rmap->n+1);
916a3fdcf43SKarl Rupp     *rowoffsets_gpu = rowst_host; // CPU --> GPU
917aa372e3fSPaul Mullowney 
918aa372e3fSPaul Mullowney     /* compute the transpose of the upper triangular factor, i.e. the CSC */
919aa372e3fSPaul Mullowney     indexBase = cusparseGetMatIndexBase(matstruct->descr);
920a3fdcf43SKarl Rupp     stat = cusparse_csr2csc(cusparsestruct->handle, A->rmap->n,
921a3fdcf43SKarl Rupp                             A->cmap->n, matrix->num_entries,
922aa372e3fSPaul Mullowney                             matrix->values->data().get(),
923a3fdcf43SKarl Rupp                             rowoffsets_gpu->data().get(),
924aa372e3fSPaul Mullowney                             matrix->column_indices->data().get(),
925aa372e3fSPaul Mullowney                             matrixT->values->data().get(),
926aa372e3fSPaul Mullowney                             matrixT->column_indices->data().get(),
927aa372e3fSPaul Mullowney                             matrixT->row_offsets->data().get(),
928*57d48284SJunchao Zhang                             CUSPARSE_ACTION_NUMERIC, indexBase);CHKERRCUSPARSE(stat);
929aa372e3fSPaul Mullowney 
930aa372e3fSPaul Mullowney     /* assign the pointer */
931aa372e3fSPaul Mullowney     matstructT->mat = matrixT;
9324863603aSSatish Balay     ierr = PetscLogCpuToGpu(((A->rmap->n+1)+(a->nz))*sizeof(int)+(3+a->nz)*sizeof(PetscScalar));CHKERRQ(ierr);
933aa372e3fSPaul Mullowney   } else if (cusparsestruct->format==MAT_CUSPARSE_ELL || cusparsestruct->format==MAT_CUSPARSE_HYB) {
934aa372e3fSPaul Mullowney     /* First convert HYB to CSR */
935aa372e3fSPaul Mullowney     CsrMatrix *temp= new CsrMatrix;
936aa372e3fSPaul Mullowney     temp->num_rows = A->rmap->n;
937aa372e3fSPaul Mullowney     temp->num_cols = A->cmap->n;
938aa372e3fSPaul Mullowney     temp->num_entries = a->nz;
939aa372e3fSPaul Mullowney     temp->row_offsets = new THRUSTINTARRAY32(A->rmap->n+1);
940aa372e3fSPaul Mullowney     temp->column_indices = new THRUSTINTARRAY32(a->nz);
941aa372e3fSPaul Mullowney     temp->values = new THRUSTARRAY(a->nz);
942aa372e3fSPaul Mullowney 
9432692e278SPaul Mullowney 
944aa372e3fSPaul Mullowney     stat = cusparse_hyb2csr(cusparsestruct->handle,
945aa372e3fSPaul Mullowney                             matstruct->descr, (cusparseHybMat_t)matstruct->mat,
946aa372e3fSPaul Mullowney                             temp->values->data().get(),
947aa372e3fSPaul Mullowney                             temp->row_offsets->data().get(),
948*57d48284SJunchao Zhang                             temp->column_indices->data().get());CHKERRCUSPARSE(stat);
949aa372e3fSPaul Mullowney 
950aa372e3fSPaul Mullowney     /* Next, convert CSR to CSC (i.e. the matrix transpose) */
951aa372e3fSPaul Mullowney     CsrMatrix *tempT= new CsrMatrix;
952aa372e3fSPaul Mullowney     tempT->num_rows = A->rmap->n;
953aa372e3fSPaul Mullowney     tempT->num_cols = A->cmap->n;
954aa372e3fSPaul Mullowney     tempT->num_entries = a->nz;
955aa372e3fSPaul Mullowney     tempT->row_offsets = new THRUSTINTARRAY32(A->rmap->n+1);
956aa372e3fSPaul Mullowney     tempT->column_indices = new THRUSTINTARRAY32(a->nz);
957aa372e3fSPaul Mullowney     tempT->values = new THRUSTARRAY(a->nz);
958aa372e3fSPaul Mullowney 
959aa372e3fSPaul Mullowney     stat = cusparse_csr2csc(cusparsestruct->handle, temp->num_rows,
960aa372e3fSPaul Mullowney                             temp->num_cols, temp->num_entries,
961aa372e3fSPaul Mullowney                             temp->values->data().get(),
962aa372e3fSPaul Mullowney                             temp->row_offsets->data().get(),
963aa372e3fSPaul Mullowney                             temp->column_indices->data().get(),
964aa372e3fSPaul Mullowney                             tempT->values->data().get(),
965aa372e3fSPaul Mullowney                             tempT->column_indices->data().get(),
966aa372e3fSPaul Mullowney                             tempT->row_offsets->data().get(),
967*57d48284SJunchao Zhang                             CUSPARSE_ACTION_NUMERIC, indexBase);CHKERRCUSPARSE(stat);
968aa372e3fSPaul Mullowney 
969aa372e3fSPaul Mullowney     /* Last, convert CSC to HYB */
970aa372e3fSPaul Mullowney     cusparseHybMat_t hybMat;
971*57d48284SJunchao Zhang     stat = cusparseCreateHybMat(&hybMat);CHKERRCUSPARSE(stat);
972aa372e3fSPaul Mullowney     cusparseHybPartition_t partition = cusparsestruct->format==MAT_CUSPARSE_ELL ?
973aa372e3fSPaul Mullowney       CUSPARSE_HYB_PARTITION_MAX : CUSPARSE_HYB_PARTITION_AUTO;
974aa372e3fSPaul Mullowney     stat = cusparse_csr2hyb(cusparsestruct->handle, A->rmap->n, A->cmap->n,
975aa372e3fSPaul Mullowney                             matstructT->descr, tempT->values->data().get(),
976aa372e3fSPaul Mullowney                             tempT->row_offsets->data().get(),
977aa372e3fSPaul Mullowney                             tempT->column_indices->data().get(),
978*57d48284SJunchao Zhang                             hybMat, 0, partition);CHKERRCUSPARSE(stat);
979aa372e3fSPaul Mullowney 
980aa372e3fSPaul Mullowney     /* assign the pointer */
981aa372e3fSPaul Mullowney     matstructT->mat = hybMat;
9824863603aSSatish Balay     ierr = PetscLogCpuToGpu((2*(((A->rmap->n+1)+(a->nz))*sizeof(int)+(a->nz)*sizeof(PetscScalar)))+3*sizeof(PetscScalar));CHKERRQ(ierr);
983aa372e3fSPaul Mullowney 
984aa372e3fSPaul Mullowney     /* delete temporaries */
985aa372e3fSPaul Mullowney     if (tempT) {
986aa372e3fSPaul Mullowney       if (tempT->values) delete (THRUSTARRAY*) tempT->values;
987aa372e3fSPaul Mullowney       if (tempT->column_indices) delete (THRUSTINTARRAY32*) tempT->column_indices;
988aa372e3fSPaul Mullowney       if (tempT->row_offsets) delete (THRUSTINTARRAY32*) tempT->row_offsets;
989aa372e3fSPaul Mullowney       delete (CsrMatrix*) tempT;
990087f3262SPaul Mullowney     }
991aa372e3fSPaul Mullowney     if (temp) {
992aa372e3fSPaul Mullowney       if (temp->values) delete (THRUSTARRAY*) temp->values;
993aa372e3fSPaul Mullowney       if (temp->column_indices) delete (THRUSTINTARRAY32*) temp->column_indices;
994aa372e3fSPaul Mullowney       if (temp->row_offsets) delete (THRUSTINTARRAY32*) temp->row_offsets;
995aa372e3fSPaul Mullowney       delete (CsrMatrix*) temp;
996aa372e3fSPaul Mullowney     }
997aa372e3fSPaul Mullowney   }
998aa372e3fSPaul Mullowney   /* assign the compressed row indices */
999aa372e3fSPaul Mullowney   matstructT->cprowIndices = new THRUSTINTARRAY;
1000554b8892SKarl Rupp   matstructT->cprowIndices->resize(A->cmap->n);
1001554b8892SKarl Rupp   thrust::sequence(matstructT->cprowIndices->begin(), matstructT->cprowIndices->end());
1002aa372e3fSPaul Mullowney   /* assign the pointer */
1003aa372e3fSPaul Mullowney   ((Mat_SeqAIJCUSPARSE*)A->spptr)->matTranspose = matstructT;
1004bda325fcSPaul Mullowney   PetscFunctionReturn(0);
1005bda325fcSPaul Mullowney }
1006bda325fcSPaul Mullowney 
10074e4bbfaaSStefano Zampini /* Why do we need to analyze the tranposed matrix again? Can't we just use op(A) = CUSPARSE_OPERATION_TRANSPOSE in MatSolve_SeqAIJCUSPARSE? */
10086fa9248bSJed Brown static PetscErrorCode MatSolveTranspose_SeqAIJCUSPARSE(Mat A,Vec bb,Vec xx)
1009bda325fcSPaul Mullowney {
1010c41cb2e2SAlejandro Lamas Daviña   PetscInt                              n = xx->map->n;
1011465f34aeSAlejandro Lamas Daviña   const PetscScalar                     *barray;
1012465f34aeSAlejandro Lamas Daviña   PetscScalar                           *xarray;
1013465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<const PetscScalar> bGPU;
1014465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<PetscScalar>       xGPU;
1015bda325fcSPaul Mullowney   cusparseStatus_t                      stat;
1016bda325fcSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors          *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1017aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *loTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1018aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *upTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1019aa372e3fSPaul Mullowney   THRUSTARRAY                           *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1020b175d8bbSPaul Mullowney   PetscErrorCode                        ierr;
1021*57d48284SJunchao Zhang   cudaError_t                           cerr;
1022bda325fcSPaul Mullowney 
1023bda325fcSPaul Mullowney   PetscFunctionBegin;
1024aa372e3fSPaul Mullowney   /* Analyze the matrix and create the transpose ... on the fly */
1025aa372e3fSPaul Mullowney   if (!loTriFactorT && !upTriFactorT) {
1026bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEAnalyzeTransposeForSolve(A);CHKERRQ(ierr);
1027aa372e3fSPaul Mullowney     loTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1028aa372e3fSPaul Mullowney     upTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1029bda325fcSPaul Mullowney   }
1030bda325fcSPaul Mullowney 
1031bda325fcSPaul Mullowney   /* Get the GPU pointers */
1032c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1033c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
1034c41cb2e2SAlejandro Lamas Daviña   xGPU = thrust::device_pointer_cast(xarray);
1035c41cb2e2SAlejandro Lamas Daviña   bGPU = thrust::device_pointer_cast(barray);
1036bda325fcSPaul Mullowney 
10377a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1038aa372e3fSPaul Mullowney   /* First, reorder with the row permutation */
1039c41cb2e2SAlejandro Lamas Daviña   thrust::copy(thrust::make_permutation_iterator(bGPU, cusparseTriFactors->rpermIndices->begin()),
1040c41cb2e2SAlejandro Lamas Daviña                thrust::make_permutation_iterator(bGPU+n, cusparseTriFactors->rpermIndices->end()),
1041c41cb2e2SAlejandro Lamas Daviña                xGPU);
1042aa372e3fSPaul Mullowney 
1043aa372e3fSPaul Mullowney   /* First, solve U */
1044aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactorT->solveOp,
10457656d835SStefano Zampini                         upTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactorT->descr,
1046aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->values->data().get(),
1047aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->row_offsets->data().get(),
1048aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->column_indices->data().get(),
1049aa372e3fSPaul Mullowney                         upTriFactorT->solveInfo,
1050*57d48284SJunchao Zhang                         xarray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1051aa372e3fSPaul Mullowney 
1052aa372e3fSPaul Mullowney   /* Then, solve L */
1053aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactorT->solveOp,
10547656d835SStefano Zampini                         loTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactorT->descr,
1055aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->values->data().get(),
1056aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->row_offsets->data().get(),
1057aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->column_indices->data().get(),
1058aa372e3fSPaul Mullowney                         loTriFactorT->solveInfo,
1059*57d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
1060aa372e3fSPaul Mullowney 
1061aa372e3fSPaul Mullowney   /* Last, copy the solution, xGPU, into a temporary with the column permutation ... can't be done in place. */
1062c41cb2e2SAlejandro Lamas Daviña   thrust::copy(thrust::make_permutation_iterator(xGPU, cusparseTriFactors->cpermIndices->begin()),
1063c41cb2e2SAlejandro Lamas Daviña                thrust::make_permutation_iterator(xGPU+n, cusparseTriFactors->cpermIndices->end()),
1064aa372e3fSPaul Mullowney                tempGPU->begin());
1065aa372e3fSPaul Mullowney 
1066aa372e3fSPaul Mullowney   /* Copy the temporary to the full solution. */
1067c41cb2e2SAlejandro Lamas Daviña   thrust::copy(tempGPU->begin(), tempGPU->end(), xGPU);
1068bda325fcSPaul Mullowney 
1069bda325fcSPaul Mullowney   /* restore */
1070c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1071c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
1072*57d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1073661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1074958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
1075bda325fcSPaul Mullowney   PetscFunctionReturn(0);
1076bda325fcSPaul Mullowney }
1077bda325fcSPaul Mullowney 
10786fa9248bSJed Brown static PetscErrorCode MatSolveTranspose_SeqAIJCUSPARSE_NaturalOrdering(Mat A,Vec bb,Vec xx)
1079bda325fcSPaul Mullowney {
1080465f34aeSAlejandro Lamas Daviña   const PetscScalar                 *barray;
1081465f34aeSAlejandro Lamas Daviña   PetscScalar                       *xarray;
1082bda325fcSPaul Mullowney   cusparseStatus_t                  stat;
1083bda325fcSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1084aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1085aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactorT = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1086aa372e3fSPaul Mullowney   THRUSTARRAY                       *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1087b175d8bbSPaul Mullowney   PetscErrorCode                    ierr;
1088*57d48284SJunchao Zhang   cudaError_t                       cerr;
1089bda325fcSPaul Mullowney 
1090bda325fcSPaul Mullowney   PetscFunctionBegin;
1091aa372e3fSPaul Mullowney   /* Analyze the matrix and create the transpose ... on the fly */
1092aa372e3fSPaul Mullowney   if (!loTriFactorT && !upTriFactorT) {
1093bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEAnalyzeTransposeForSolve(A);CHKERRQ(ierr);
1094aa372e3fSPaul Mullowney     loTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtrTranspose;
1095aa372e3fSPaul Mullowney     upTriFactorT       = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtrTranspose;
1096bda325fcSPaul Mullowney   }
1097bda325fcSPaul Mullowney 
1098bda325fcSPaul Mullowney   /* Get the GPU pointers */
1099c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1100c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
1101bda325fcSPaul Mullowney 
11027a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1103aa372e3fSPaul Mullowney   /* First, solve U */
1104aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactorT->solveOp,
11057656d835SStefano Zampini                         upTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactorT->descr,
1106aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->values->data().get(),
1107aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->row_offsets->data().get(),
1108aa372e3fSPaul Mullowney                         upTriFactorT->csrMat->column_indices->data().get(),
1109aa372e3fSPaul Mullowney                         upTriFactorT->solveInfo,
1110*57d48284SJunchao Zhang                         barray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1111aa372e3fSPaul Mullowney 
1112aa372e3fSPaul Mullowney   /* Then, solve L */
1113aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactorT->solveOp,
11147656d835SStefano Zampini                         loTriFactorT->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactorT->descr,
1115aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->values->data().get(),
1116aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->row_offsets->data().get(),
1117aa372e3fSPaul Mullowney                         loTriFactorT->csrMat->column_indices->data().get(),
1118aa372e3fSPaul Mullowney                         loTriFactorT->solveInfo,
1119*57d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
1120bda325fcSPaul Mullowney 
1121bda325fcSPaul Mullowney   /* restore */
1122c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1123c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
1124*57d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1125661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1126958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
1127bda325fcSPaul Mullowney   PetscFunctionReturn(0);
1128bda325fcSPaul Mullowney }
1129bda325fcSPaul Mullowney 
11306fa9248bSJed Brown static PetscErrorCode MatSolve_SeqAIJCUSPARSE(Mat A,Vec bb,Vec xx)
11319ae82921SPaul Mullowney {
1132465f34aeSAlejandro Lamas Daviña   const PetscScalar                     *barray;
1133465f34aeSAlejandro Lamas Daviña   PetscScalar                           *xarray;
1134465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<const PetscScalar> bGPU;
1135465f34aeSAlejandro Lamas Daviña   thrust::device_ptr<PetscScalar>       xGPU;
11369ae82921SPaul Mullowney   cusparseStatus_t                      stat;
11379ae82921SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors          *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1138aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
1139aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct     *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
1140aa372e3fSPaul Mullowney   THRUSTARRAY                           *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1141b175d8bbSPaul Mullowney   PetscErrorCode                        ierr;
1142*57d48284SJunchao Zhang   cudaError_t                           cerr;
11439ae82921SPaul Mullowney 
11449ae82921SPaul Mullowney   PetscFunctionBegin;
1145ebc8f436SDominic Meiser 
1146e057df02SPaul Mullowney   /* Get the GPU pointers */
1147c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1148c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
1149c41cb2e2SAlejandro Lamas Daviña   xGPU = thrust::device_pointer_cast(xarray);
1150c41cb2e2SAlejandro Lamas Daviña   bGPU = thrust::device_pointer_cast(barray);
11519ae82921SPaul Mullowney 
11527a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1153aa372e3fSPaul Mullowney   /* First, reorder with the row permutation */
1154c41cb2e2SAlejandro Lamas Daviña   thrust::copy(thrust::make_permutation_iterator(bGPU, cusparseTriFactors->rpermIndices->begin()),
1155c41cb2e2SAlejandro Lamas Daviña                thrust::make_permutation_iterator(bGPU, cusparseTriFactors->rpermIndices->end()),
11564e4bbfaaSStefano Zampini                tempGPU->begin());
1157aa372e3fSPaul Mullowney 
1158aa372e3fSPaul Mullowney   /* Next, solve L */
1159aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactor->solveOp,
11607656d835SStefano Zampini                         loTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactor->descr,
1161aa372e3fSPaul Mullowney                         loTriFactor->csrMat->values->data().get(),
1162aa372e3fSPaul Mullowney                         loTriFactor->csrMat->row_offsets->data().get(),
1163aa372e3fSPaul Mullowney                         loTriFactor->csrMat->column_indices->data().get(),
1164aa372e3fSPaul Mullowney                         loTriFactor->solveInfo,
1165*57d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
1166aa372e3fSPaul Mullowney 
1167aa372e3fSPaul Mullowney   /* Then, solve U */
1168aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactor->solveOp,
11697656d835SStefano Zampini                         upTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactor->descr,
1170aa372e3fSPaul Mullowney                         upTriFactor->csrMat->values->data().get(),
1171aa372e3fSPaul Mullowney                         upTriFactor->csrMat->row_offsets->data().get(),
1172aa372e3fSPaul Mullowney                         upTriFactor->csrMat->column_indices->data().get(),
1173aa372e3fSPaul Mullowney                         upTriFactor->solveInfo,
1174*57d48284SJunchao Zhang                         xarray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1175aa372e3fSPaul Mullowney 
11764e4bbfaaSStefano Zampini   /* Last, reorder with the column permutation */
11774e4bbfaaSStefano Zampini   thrust::copy(thrust::make_permutation_iterator(tempGPU->begin(), cusparseTriFactors->cpermIndices->begin()),
11784e4bbfaaSStefano Zampini                thrust::make_permutation_iterator(tempGPU->begin(), cusparseTriFactors->cpermIndices->end()),
11794e4bbfaaSStefano Zampini                xGPU);
11809ae82921SPaul Mullowney 
1181c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1182c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
1183*57d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1184661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1185958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
11869ae82921SPaul Mullowney   PetscFunctionReturn(0);
11879ae82921SPaul Mullowney }
11889ae82921SPaul Mullowney 
11896fa9248bSJed Brown static PetscErrorCode MatSolve_SeqAIJCUSPARSE_NaturalOrdering(Mat A,Vec bb,Vec xx)
11909ae82921SPaul Mullowney {
1191465f34aeSAlejandro Lamas Daviña   const PetscScalar                 *barray;
1192465f34aeSAlejandro Lamas Daviña   PetscScalar                       *xarray;
11939ae82921SPaul Mullowney   cusparseStatus_t                  stat;
11949ae82921SPaul Mullowney   Mat_SeqAIJCUSPARSETriFactors      *cusparseTriFactors = (Mat_SeqAIJCUSPARSETriFactors*)A->spptr;
1195aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *loTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->loTriFactorPtr;
1196aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSETriFactorStruct *upTriFactor = (Mat_SeqAIJCUSPARSETriFactorStruct*)cusparseTriFactors->upTriFactorPtr;
1197aa372e3fSPaul Mullowney   THRUSTARRAY                       *tempGPU = (THRUSTARRAY*)cusparseTriFactors->workVector;
1198b175d8bbSPaul Mullowney   PetscErrorCode                    ierr;
1199*57d48284SJunchao Zhang   cudaError_t                       cerr;
12009ae82921SPaul Mullowney 
12019ae82921SPaul Mullowney   PetscFunctionBegin;
1202e057df02SPaul Mullowney   /* Get the GPU pointers */
1203c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(xx,&xarray);CHKERRQ(ierr);
1204c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(bb,&barray);CHKERRQ(ierr);
12059ae82921SPaul Mullowney 
12067a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1207aa372e3fSPaul Mullowney   /* First, solve L */
1208aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, loTriFactor->solveOp,
12097656d835SStefano Zampini                         loTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, loTriFactor->descr,
1210aa372e3fSPaul Mullowney                         loTriFactor->csrMat->values->data().get(),
1211aa372e3fSPaul Mullowney                         loTriFactor->csrMat->row_offsets->data().get(),
1212aa372e3fSPaul Mullowney                         loTriFactor->csrMat->column_indices->data().get(),
1213aa372e3fSPaul Mullowney                         loTriFactor->solveInfo,
1214*57d48284SJunchao Zhang                         barray, tempGPU->data().get());CHKERRCUSPARSE(stat);
1215aa372e3fSPaul Mullowney 
1216aa372e3fSPaul Mullowney   /* Next, solve U */
1217aa372e3fSPaul Mullowney   stat = cusparse_solve(cusparseTriFactors->handle, upTriFactor->solveOp,
12187656d835SStefano Zampini                         upTriFactor->csrMat->num_rows, &PETSC_CUSPARSE_ONE, upTriFactor->descr,
1219aa372e3fSPaul Mullowney                         upTriFactor->csrMat->values->data().get(),
1220aa372e3fSPaul Mullowney                         upTriFactor->csrMat->row_offsets->data().get(),
1221aa372e3fSPaul Mullowney                         upTriFactor->csrMat->column_indices->data().get(),
1222aa372e3fSPaul Mullowney                         upTriFactor->solveInfo,
1223*57d48284SJunchao Zhang                         tempGPU->data().get(), xarray);CHKERRCUSPARSE(stat);
12249ae82921SPaul Mullowney 
1225c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(bb,&barray);CHKERRQ(ierr);
1226c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(xx,&xarray);CHKERRQ(ierr);
1227*57d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1228661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1229958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*cusparseTriFactors->nnz - A->cmap->n);CHKERRQ(ierr);
12309ae82921SPaul Mullowney   PetscFunctionReturn(0);
12319ae82921SPaul Mullowney }
12329ae82921SPaul Mullowney 
12336fa9248bSJed Brown static PetscErrorCode MatSeqAIJCUSPARSECopyToGPU(Mat A)
12349ae82921SPaul Mullowney {
1235aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
1236aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSEMultStruct *matstruct = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->mat;
12379ae82921SPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
12389ae82921SPaul Mullowney   PetscInt                     m = A->rmap->n,*ii,*ridx;
12399ae82921SPaul Mullowney   PetscErrorCode               ierr;
1240aa372e3fSPaul Mullowney   cusparseStatus_t             stat;
1241b06137fdSPaul Mullowney   cudaError_t                  err;
12429ae82921SPaul Mullowney 
12439ae82921SPaul Mullowney   PetscFunctionBegin;
1244c70f7ee4SJunchao Zhang   if (A->offloadmask == PETSC_OFFLOAD_UNALLOCATED || A->offloadmask == PETSC_OFFLOAD_CPU) {
12459ae82921SPaul Mullowney     ierr = PetscLogEventBegin(MAT_CUSPARSECopyToGPU,A,0,0,0);CHKERRQ(ierr);
124634d6c7a5SJose E. Roman     if (A->assembled && A->nonzerostate == cusparsestruct->nonzerostate && cusparsestruct->format == MAT_CUSPARSE_CSR) {
124734d6c7a5SJose E. Roman       CsrMatrix *matrix = (CsrMatrix*)matstruct->mat;
124834d6c7a5SJose E. Roman       /* copy values only */
124934d6c7a5SJose E. Roman       matrix->values->assign(a->a, a->a+a->nz);
12504863603aSSatish Balay       ierr = PetscLogCpuToGpu((a->nz)*sizeof(PetscScalar));CHKERRQ(ierr);
125134d6c7a5SJose E. Roman     } else {
1252470880abSPatrick Sanan       MatSeqAIJCUSPARSEMultStruct_Destroy(&matstruct,cusparsestruct->format);
12539ae82921SPaul Mullowney       try {
1254aa372e3fSPaul Mullowney         cusparsestruct->nonzerorow=0;
1255aa372e3fSPaul Mullowney         for (int j = 0; j<m; j++) cusparsestruct->nonzerorow += ((a->i[j+1]-a->i[j])>0);
12569ae82921SPaul Mullowney 
12579ae82921SPaul Mullowney         if (a->compressedrow.use) {
12589ae82921SPaul Mullowney           m    = a->compressedrow.nrows;
12599ae82921SPaul Mullowney           ii   = a->compressedrow.i;
12609ae82921SPaul Mullowney           ridx = a->compressedrow.rindex;
12619ae82921SPaul Mullowney         } else {
1262b06137fdSPaul Mullowney           /* Forcing compressed row on the GPU */
12639ae82921SPaul Mullowney           int k=0;
1264854ce69bSBarry Smith           ierr = PetscMalloc1(cusparsestruct->nonzerorow+1, &ii);CHKERRQ(ierr);
1265854ce69bSBarry Smith           ierr = PetscMalloc1(cusparsestruct->nonzerorow, &ridx);CHKERRQ(ierr);
12669ae82921SPaul Mullowney           ii[0]=0;
12679ae82921SPaul Mullowney           for (int j = 0; j<m; j++) {
12689ae82921SPaul Mullowney             if ((a->i[j+1]-a->i[j])>0) {
12699ae82921SPaul Mullowney               ii[k]  = a->i[j];
12709ae82921SPaul Mullowney               ridx[k]= j;
12719ae82921SPaul Mullowney               k++;
12729ae82921SPaul Mullowney             }
12739ae82921SPaul Mullowney           }
1274aa372e3fSPaul Mullowney           ii[cusparsestruct->nonzerorow] = a->nz;
1275aa372e3fSPaul Mullowney           m = cusparsestruct->nonzerorow;
12769ae82921SPaul Mullowney         }
12779ae82921SPaul Mullowney 
1278aa372e3fSPaul Mullowney         /* allocate space for the triangular factor information */
1279aa372e3fSPaul Mullowney         matstruct = new Mat_SeqAIJCUSPARSEMultStruct;
1280*57d48284SJunchao Zhang         stat = cusparseCreateMatDescr(&matstruct->descr);CHKERRCUSPARSE(stat);
1281*57d48284SJunchao Zhang         stat = cusparseSetMatIndexBase(matstruct->descr, CUSPARSE_INDEX_BASE_ZERO);CHKERRCUSPARSE(stat);
1282*57d48284SJunchao Zhang         stat = cusparseSetMatType(matstruct->descr, CUSPARSE_MATRIX_TYPE_GENERAL);CHKERRCUSPARSE(stat);
12839ae82921SPaul Mullowney 
1284c41cb2e2SAlejandro Lamas Daviña         err = cudaMalloc((void **)&(matstruct->alpha),    sizeof(PetscScalar));CHKERRCUDA(err);
12857656d835SStefano Zampini         err = cudaMalloc((void **)&(matstruct->beta_zero),sizeof(PetscScalar));CHKERRCUDA(err);
12867656d835SStefano Zampini         err = cudaMalloc((void **)&(matstruct->beta_one), sizeof(PetscScalar));CHKERRCUDA(err);
12877656d835SStefano Zampini         err = cudaMemcpy(matstruct->alpha,    &PETSC_CUSPARSE_ONE, sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
12887656d835SStefano Zampini         err = cudaMemcpy(matstruct->beta_zero,&PETSC_CUSPARSE_ZERO,sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
12897656d835SStefano Zampini         err = cudaMemcpy(matstruct->beta_one, &PETSC_CUSPARSE_ONE, sizeof(PetscScalar),cudaMemcpyHostToDevice);CHKERRCUDA(err);
1290*57d48284SJunchao Zhang         stat = cusparseSetPointerMode(cusparsestruct->handle, CUSPARSE_POINTER_MODE_DEVICE);CHKERRCUSPARSE(stat);
1291b06137fdSPaul Mullowney 
1292aa372e3fSPaul Mullowney         /* Build a hybrid/ellpack matrix if this option is chosen for the storage */
1293aa372e3fSPaul Mullowney         if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
1294aa372e3fSPaul Mullowney           /* set the matrix */
1295aa372e3fSPaul Mullowney           CsrMatrix *matrix= new CsrMatrix;
1296a65300a6SPaul Mullowney           matrix->num_rows = m;
1297aa372e3fSPaul Mullowney           matrix->num_cols = A->cmap->n;
1298aa372e3fSPaul Mullowney           matrix->num_entries = a->nz;
1299a65300a6SPaul Mullowney           matrix->row_offsets = new THRUSTINTARRAY32(m+1);
1300a65300a6SPaul Mullowney           matrix->row_offsets->assign(ii, ii + m+1);
13019ae82921SPaul Mullowney 
1302aa372e3fSPaul Mullowney           matrix->column_indices = new THRUSTINTARRAY32(a->nz);
1303aa372e3fSPaul Mullowney           matrix->column_indices->assign(a->j, a->j+a->nz);
1304aa372e3fSPaul Mullowney 
1305aa372e3fSPaul Mullowney           matrix->values = new THRUSTARRAY(a->nz);
1306aa372e3fSPaul Mullowney           matrix->values->assign(a->a, a->a+a->nz);
1307aa372e3fSPaul Mullowney 
1308aa372e3fSPaul Mullowney           /* assign the pointer */
1309aa372e3fSPaul Mullowney           matstruct->mat = matrix;
1310aa372e3fSPaul Mullowney 
1311aa372e3fSPaul Mullowney         } else if (cusparsestruct->format==MAT_CUSPARSE_ELL || cusparsestruct->format==MAT_CUSPARSE_HYB) {
1312aa372e3fSPaul Mullowney           CsrMatrix *matrix= new CsrMatrix;
1313a65300a6SPaul Mullowney           matrix->num_rows = m;
1314aa372e3fSPaul Mullowney           matrix->num_cols = A->cmap->n;
1315aa372e3fSPaul Mullowney           matrix->num_entries = a->nz;
1316a65300a6SPaul Mullowney           matrix->row_offsets = new THRUSTINTARRAY32(m+1);
1317a65300a6SPaul Mullowney           matrix->row_offsets->assign(ii, ii + m+1);
1318aa372e3fSPaul Mullowney 
1319aa372e3fSPaul Mullowney           matrix->column_indices = new THRUSTINTARRAY32(a->nz);
1320aa372e3fSPaul Mullowney           matrix->column_indices->assign(a->j, a->j+a->nz);
1321aa372e3fSPaul Mullowney 
1322aa372e3fSPaul Mullowney           matrix->values = new THRUSTARRAY(a->nz);
1323aa372e3fSPaul Mullowney           matrix->values->assign(a->a, a->a+a->nz);
1324aa372e3fSPaul Mullowney 
1325aa372e3fSPaul Mullowney           cusparseHybMat_t hybMat;
1326*57d48284SJunchao Zhang           stat = cusparseCreateHybMat(&hybMat);CHKERRCUSPARSE(stat);
1327aa372e3fSPaul Mullowney           cusparseHybPartition_t partition = cusparsestruct->format==MAT_CUSPARSE_ELL ?
1328aa372e3fSPaul Mullowney             CUSPARSE_HYB_PARTITION_MAX : CUSPARSE_HYB_PARTITION_AUTO;
1329a65300a6SPaul Mullowney           stat = cusparse_csr2hyb(cusparsestruct->handle, matrix->num_rows, matrix->num_cols,
1330aa372e3fSPaul Mullowney               matstruct->descr, matrix->values->data().get(),
1331aa372e3fSPaul Mullowney               matrix->row_offsets->data().get(),
1332aa372e3fSPaul Mullowney               matrix->column_indices->data().get(),
1333*57d48284SJunchao Zhang               hybMat, 0, partition);CHKERRCUSPARSE(stat);
1334aa372e3fSPaul Mullowney           /* assign the pointer */
1335aa372e3fSPaul Mullowney           matstruct->mat = hybMat;
1336aa372e3fSPaul Mullowney 
1337aa372e3fSPaul Mullowney           if (matrix) {
1338aa372e3fSPaul Mullowney             if (matrix->values) delete (THRUSTARRAY*)matrix->values;
1339aa372e3fSPaul Mullowney             if (matrix->column_indices) delete (THRUSTINTARRAY32*)matrix->column_indices;
1340aa372e3fSPaul Mullowney             if (matrix->row_offsets) delete (THRUSTINTARRAY32*)matrix->row_offsets;
1341aa372e3fSPaul Mullowney             delete (CsrMatrix*)matrix;
1342087f3262SPaul Mullowney           }
1343087f3262SPaul Mullowney         }
1344ca45077fSPaul Mullowney 
1345aa372e3fSPaul Mullowney         /* assign the compressed row indices */
1346aa372e3fSPaul Mullowney         matstruct->cprowIndices = new THRUSTINTARRAY(m);
1347aa372e3fSPaul Mullowney         matstruct->cprowIndices->assign(ridx,ridx+m);
13484863603aSSatish Balay         ierr = PetscLogCpuToGpu(((m+1)+(a->nz))*sizeof(int)+m*sizeof(PetscInt)+(3+(a->nz))*sizeof(PetscScalar));CHKERRQ(ierr);
1349aa372e3fSPaul Mullowney 
1350aa372e3fSPaul Mullowney         /* assign the pointer */
1351aa372e3fSPaul Mullowney         cusparsestruct->mat = matstruct;
1352aa372e3fSPaul Mullowney 
13539ae82921SPaul Mullowney         if (!a->compressedrow.use) {
13549ae82921SPaul Mullowney           ierr = PetscFree(ii);CHKERRQ(ierr);
13559ae82921SPaul Mullowney           ierr = PetscFree(ridx);CHKERRQ(ierr);
13569ae82921SPaul Mullowney         }
1357e65717acSKarl Rupp         cusparsestruct->workVector = new THRUSTARRAY(m);
13589ae82921SPaul Mullowney       } catch(char *ex) {
13599ae82921SPaul Mullowney         SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
13609ae82921SPaul Mullowney       }
136134d6c7a5SJose E. Roman       cusparsestruct->nonzerostate = A->nonzerostate;
136234d6c7a5SJose E. Roman     }
1363*57d48284SJunchao Zhang     err  = WaitForGPU();CHKERRCUDA(err);
1364c70f7ee4SJunchao Zhang     A->offloadmask = PETSC_OFFLOAD_BOTH;
13659ae82921SPaul Mullowney     ierr = PetscLogEventEnd(MAT_CUSPARSECopyToGPU,A,0,0,0);CHKERRQ(ierr);
13669ae82921SPaul Mullowney   }
13679ae82921SPaul Mullowney   PetscFunctionReturn(0);
13689ae82921SPaul Mullowney }
13699ae82921SPaul Mullowney 
1370c41cb2e2SAlejandro Lamas Daviña struct VecCUDAPlusEquals
1371aa372e3fSPaul Mullowney {
1372aa372e3fSPaul Mullowney   template <typename Tuple>
1373aa372e3fSPaul Mullowney   __host__ __device__
1374aa372e3fSPaul Mullowney   void operator()(Tuple t)
1375aa372e3fSPaul Mullowney   {
1376aa372e3fSPaul Mullowney     thrust::get<1>(t) = thrust::get<1>(t) + thrust::get<0>(t);
1377aa372e3fSPaul Mullowney   }
1378aa372e3fSPaul Mullowney };
1379aa372e3fSPaul Mullowney 
13806fa9248bSJed Brown static PetscErrorCode MatMult_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy)
13819ae82921SPaul Mullowney {
1382b175d8bbSPaul Mullowney   PetscErrorCode ierr;
13839ae82921SPaul Mullowney 
13849ae82921SPaul Mullowney   PetscFunctionBegin;
13857656d835SStefano Zampini   ierr = MatMultAdd_SeqAIJCUSPARSE(A,xx,NULL,yy);CHKERRQ(ierr);
13869ae82921SPaul Mullowney   PetscFunctionReturn(0);
13879ae82921SPaul Mullowney }
13889ae82921SPaul Mullowney 
13896fa9248bSJed Brown static PetscErrorCode MatMultTranspose_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy)
1390ca45077fSPaul Mullowney {
1391ca45077fSPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
1392aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
13939ff858a8SKarl Rupp   Mat_SeqAIJCUSPARSEMultStruct *matstructT;
1394465f34aeSAlejandro Lamas Daviña   const PetscScalar            *xarray;
1395465f34aeSAlejandro Lamas Daviña   PetscScalar                  *yarray;
1396b175d8bbSPaul Mullowney   PetscErrorCode               ierr;
1397*57d48284SJunchao Zhang   cudaError_t                  cerr;
1398aa372e3fSPaul Mullowney   cusparseStatus_t             stat;
1399ca45077fSPaul Mullowney 
1400ca45077fSPaul Mullowney   PetscFunctionBegin;
140134d6c7a5SJose E. Roman   /* The line below is necessary due to the operations that modify the matrix on the CPU (axpy, scale, etc) */
140234d6c7a5SJose E. Roman   ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
14039ff858a8SKarl Rupp   matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1404aa372e3fSPaul Mullowney   if (!matstructT) {
1405bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEGenerateTransposeForMult(A);CHKERRQ(ierr);
1406aa372e3fSPaul Mullowney     matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1407bda325fcSPaul Mullowney   }
1408c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayRead(xx,&xarray);CHKERRQ(ierr);
1409c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDAGetArrayWrite(yy,&yarray);CHKERRQ(ierr);
1410f6ae8131SMark   if (yy->map->n) {
1411f6ae8131SMark     PetscInt                     n = yy->map->n;
1412f6ae8131SMark     cudaError_t                  err;
1413f6ae8131SMark     err = cudaMemset(yarray,0,n*sizeof(PetscScalar));CHKERRCUDA(err); /* hack to fix numerical errors from reading output vector yy, apparently */
1414f6ae8131SMark   }
1415aa372e3fSPaul Mullowney 
14167a052e47Shannah_mairs   ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1417aa372e3fSPaul Mullowney   if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
1418aa372e3fSPaul Mullowney     CsrMatrix *mat = (CsrMatrix*)matstructT->mat;
1419aa372e3fSPaul Mullowney     stat = cusparse_csr_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1420aa372e3fSPaul Mullowney                              mat->num_rows, mat->num_cols,
1421b06137fdSPaul Mullowney                              mat->num_entries, matstructT->alpha, matstructT->descr,
1422aa372e3fSPaul Mullowney                              mat->values->data().get(), mat->row_offsets->data().get(),
14237656d835SStefano Zampini                              mat->column_indices->data().get(), xarray, matstructT->beta_zero,
1424*57d48284SJunchao Zhang                              yarray);CHKERRCUSPARSE(stat);
1425aa372e3fSPaul Mullowney   } else {
1426aa372e3fSPaul Mullowney     cusparseHybMat_t hybMat = (cusparseHybMat_t)matstructT->mat;
1427aa372e3fSPaul Mullowney     stat = cusparse_hyb_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1428b06137fdSPaul Mullowney                              matstructT->alpha, matstructT->descr, hybMat,
14297656d835SStefano Zampini                              xarray, matstructT->beta_zero,
1430*57d48284SJunchao Zhang                              yarray);CHKERRCUSPARSE(stat);
1431ca45077fSPaul Mullowney   }
1432c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayRead(xx,&xarray);CHKERRQ(ierr);
1433c41cb2e2SAlejandro Lamas Daviña   ierr = VecCUDARestoreArrayWrite(yy,&yarray);CHKERRQ(ierr);
1434*57d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1435661c2d29Shannah_mairs   ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1436958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*a->nz - cusparsestruct->nonzerorow);CHKERRQ(ierr);
1437ca45077fSPaul Mullowney   PetscFunctionReturn(0);
1438ca45077fSPaul Mullowney }
1439ca45077fSPaul Mullowney 
1440aa372e3fSPaul Mullowney 
14416fa9248bSJed Brown static PetscErrorCode MatMultAdd_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy,Vec zz)
14429ae82921SPaul Mullowney {
14439ae82921SPaul Mullowney   Mat_SeqAIJ                   *a = (Mat_SeqAIJ*)A->data;
1444aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE           *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
14459ff858a8SKarl Rupp   Mat_SeqAIJCUSPARSEMultStruct *matstruct;
1446465f34aeSAlejandro Lamas Daviña   const PetscScalar            *xarray;
14477656d835SStefano Zampini   PetscScalar                  *zarray,*dptr,*beta;
1448b175d8bbSPaul Mullowney   PetscErrorCode               ierr;
1449*57d48284SJunchao Zhang   cudaError_t                  cerr;
1450aa372e3fSPaul Mullowney   cusparseStatus_t             stat;
1451c1fb3f03SStefano Zampini   PetscBool                    cmpr; /* if the matrix has been compressed (zero rows) */
14526e111a19SKarl Rupp 
14539ae82921SPaul Mullowney   PetscFunctionBegin;
145434d6c7a5SJose E. Roman   /* The line below is necessary due to the operations that modify the matrix on the CPU (axpy, scale, etc) */
145534d6c7a5SJose E. Roman   ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
14569ff858a8SKarl Rupp   matstruct = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->mat;
14579ae82921SPaul Mullowney   try {
1458c1fb3f03SStefano Zampini     cmpr = (PetscBool)(cusparsestruct->workVector->size() == (thrust::detail::vector_base<PetscScalar, thrust::device_malloc_allocator<PetscScalar> >::size_type)(A->rmap->n));
1459c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDAGetArrayRead(xx,&xarray);CHKERRQ(ierr);
1460c1fb3f03SStefano Zampini     if (yy && !cmpr) { /* MatMultAdd with noncompressed storage -> need uptodate zz vector */
1461f2d70e9dSBarry Smith       ierr = VecCUDAGetArray(zz,&zarray);CHKERRQ(ierr);
1462c1fb3f03SStefano Zampini     } else {
1463c1fb3f03SStefano Zampini       ierr = VecCUDAGetArrayWrite(zz,&zarray);CHKERRQ(ierr);
1464c1fb3f03SStefano Zampini     }
1465c1fb3f03SStefano Zampini     dptr = cmpr ? zarray : cusparsestruct->workVector->data().get();
14667656d835SStefano Zampini     beta = (yy == zz && dptr == zarray) ? matstruct->beta_one : matstruct->beta_zero;
14679ae82921SPaul Mullowney 
14687a052e47Shannah_mairs     ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
14697656d835SStefano Zampini     /* csr_spmv is multiply add */
1470aa372e3fSPaul Mullowney     if (cusparsestruct->format == MAT_CUSPARSE_CSR) {
1471b06137fdSPaul Mullowney       /* here we need to be careful to set the number of rows in the multiply to the
1472b06137fdSPaul Mullowney          number of compressed rows in the matrix ... which is equivalent to the
1473b06137fdSPaul Mullowney          size of the workVector */
14747656d835SStefano Zampini       CsrMatrix *mat = (CsrMatrix*)matstruct->mat;
1475aa372e3fSPaul Mullowney       stat = cusparse_csr_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1476a65300a6SPaul Mullowney                                mat->num_rows, mat->num_cols,
1477b06137fdSPaul Mullowney                                mat->num_entries, matstruct->alpha, matstruct->descr,
1478aa372e3fSPaul Mullowney                                mat->values->data().get(), mat->row_offsets->data().get(),
14797656d835SStefano Zampini                                mat->column_indices->data().get(), xarray, beta,
1480*57d48284SJunchao Zhang                                dptr);CHKERRCUSPARSE(stat);
1481aa372e3fSPaul Mullowney     } else {
1482a65300a6SPaul Mullowney       if (cusparsestruct->workVector->size()) {
1483301298b4SMark Adams         cusparseHybMat_t hybMat = (cusparseHybMat_t)matstruct->mat;
1484aa372e3fSPaul Mullowney         stat = cusparse_hyb_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1485b06137fdSPaul Mullowney                                  matstruct->alpha, matstruct->descr, hybMat,
14867656d835SStefano Zampini                                  xarray, beta,
1487*57d48284SJunchao Zhang                                  dptr);CHKERRCUSPARSE(stat);
1488a65300a6SPaul Mullowney       }
1489aa372e3fSPaul Mullowney     }
1490958c4211Shannah_mairs     ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1491aa372e3fSPaul Mullowney 
14927656d835SStefano Zampini     if (yy) {
14937656d835SStefano Zampini       if (dptr != zarray) {
14947656d835SStefano Zampini         ierr = VecCopy_SeqCUDA(yy,zz);CHKERRQ(ierr);
14957656d835SStefano Zampini       } else if (zz != yy) {
14967656d835SStefano Zampini         ierr = VecAXPY_SeqCUDA(zz,1.0,yy);CHKERRQ(ierr);
14977656d835SStefano Zampini       }
14987656d835SStefano Zampini     } else if (dptr != zarray) {
1499c1fb3f03SStefano Zampini       ierr = VecSet_SeqCUDA(zz,0);CHKERRQ(ierr);
15007656d835SStefano Zampini     }
1501aa372e3fSPaul Mullowney     /* scatter the data from the temporary into the full vector with a += operation */
15027a052e47Shannah_mairs     ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
15037656d835SStefano Zampini     if (dptr != zarray) {
15047656d835SStefano Zampini       thrust::device_ptr<PetscScalar> zptr;
15057656d835SStefano Zampini 
15067656d835SStefano Zampini       zptr = thrust::device_pointer_cast(zarray);
1507c41cb2e2SAlejandro Lamas Daviña       thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple(cusparsestruct->workVector->begin(), thrust::make_permutation_iterator(zptr, matstruct->cprowIndices->begin()))),
1508c41cb2e2SAlejandro Lamas Daviña                        thrust::make_zip_iterator(thrust::make_tuple(cusparsestruct->workVector->begin(), thrust::make_permutation_iterator(zptr, matstruct->cprowIndices->begin()))) + cusparsestruct->workVector->size(),
1509c41cb2e2SAlejandro Lamas Daviña                        VecCUDAPlusEquals());
15107656d835SStefano Zampini     }
1511958c4211Shannah_mairs     ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1512c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDARestoreArrayRead(xx,&xarray);CHKERRQ(ierr);
1513c1fb3f03SStefano Zampini     if (yy && !cmpr) {
1514f2d70e9dSBarry Smith       ierr = VecCUDARestoreArray(zz,&zarray);CHKERRQ(ierr);
1515c1fb3f03SStefano Zampini     } else {
1516c1fb3f03SStefano Zampini       ierr = VecCUDARestoreArrayWrite(zz,&zarray);CHKERRQ(ierr);
1517c1fb3f03SStefano Zampini     }
15189ae82921SPaul Mullowney   } catch(char *ex) {
15199ae82921SPaul Mullowney     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
15209ae82921SPaul Mullowney   }
1521*57d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr);
1522958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*a->nz);CHKERRQ(ierr);
15239ae82921SPaul Mullowney   PetscFunctionReturn(0);
15249ae82921SPaul Mullowney }
15259ae82921SPaul Mullowney 
15266fa9248bSJed Brown static PetscErrorCode MatMultTransposeAdd_SeqAIJCUSPARSE(Mat A,Vec xx,Vec yy,Vec zz)
1527ca45077fSPaul Mullowney {
1528ca45077fSPaul Mullowney   Mat_SeqAIJ                      *a = (Mat_SeqAIJ*)A->data;
1529aa372e3fSPaul Mullowney   Mat_SeqAIJCUSPARSE              *cusparsestruct = (Mat_SeqAIJCUSPARSE*)A->spptr;
15309ff858a8SKarl Rupp   Mat_SeqAIJCUSPARSEMultStruct    *matstructT;
1531465f34aeSAlejandro Lamas Daviña   const PetscScalar               *xarray;
1532a3fdcf43SKarl Rupp   PetscScalar                     *zarray,*dptr,*beta;
1533b175d8bbSPaul Mullowney   PetscErrorCode                  ierr;
1534*57d48284SJunchao Zhang   cudaError_t                     cerr;
1535aa372e3fSPaul Mullowney   cusparseStatus_t                stat;
15366e111a19SKarl Rupp 
1537ca45077fSPaul Mullowney   PetscFunctionBegin;
153834d6c7a5SJose E. Roman   /* The line below is necessary due to the operations that modify the matrix on the CPU (axpy, scale, etc) */
153934d6c7a5SJose E. Roman   ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
15409ff858a8SKarl Rupp   matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1541aa372e3fSPaul Mullowney   if (!matstructT) {
1542bda325fcSPaul Mullowney     ierr = MatSeqAIJCUSPARSEGenerateTransposeForMult(A);CHKERRQ(ierr);
1543aa372e3fSPaul Mullowney     matstructT = (Mat_SeqAIJCUSPARSEMultStruct*)cusparsestruct->matTranspose;
1544bda325fcSPaul Mullowney   }
1545aa372e3fSPaul Mullowney 
1546ca45077fSPaul Mullowney   try {
1547c41cb2e2SAlejandro Lamas Daviña     ierr = VecCopy_SeqCUDA(yy,zz);CHKERRQ(ierr);
1548c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDAGetArrayRead(xx,&xarray);CHKERRQ(ierr);
1549f2d70e9dSBarry Smith     ierr = VecCUDAGetArray(zz,&zarray);CHKERRQ(ierr);
1550a3fdcf43SKarl Rupp     dptr = cusparsestruct->workVector->size() == (thrust::detail::vector_base<PetscScalar, thrust::device_malloc_allocator<PetscScalar> >::size_type)(A->cmap->n) ? zarray : cusparsestruct->workVector->data().get();
1551a3fdcf43SKarl Rupp     beta = (yy == zz && dptr == zarray) ? matstructT->beta_one : matstructT->beta_zero;
1552ca45077fSPaul Mullowney 
15537a052e47Shannah_mairs     ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1554e057df02SPaul Mullowney     /* multiply add with matrix transpose */
1555aa372e3fSPaul Mullowney     if (cusparsestruct->format==MAT_CUSPARSE_CSR) {
1556aa372e3fSPaul Mullowney       CsrMatrix *mat = (CsrMatrix*)matstructT->mat;
1557b06137fdSPaul Mullowney       /* here we need to be careful to set the number of rows in the multiply to the
1558b06137fdSPaul Mullowney          number of compressed rows in the matrix ... which is equivalent to the
1559b06137fdSPaul Mullowney          size of the workVector */
1560aa372e3fSPaul Mullowney       stat = cusparse_csr_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1561a65300a6SPaul Mullowney                                mat->num_rows, mat->num_cols,
1562b06137fdSPaul Mullowney                                mat->num_entries, matstructT->alpha, matstructT->descr,
1563aa372e3fSPaul Mullowney                                mat->values->data().get(), mat->row_offsets->data().get(),
1564a3fdcf43SKarl Rupp                                mat->column_indices->data().get(), xarray, beta,
1565*57d48284SJunchao Zhang                                dptr);CHKERRCUSPARSE(stat);
1566aa372e3fSPaul Mullowney     } else {
1567aa372e3fSPaul Mullowney       cusparseHybMat_t hybMat = (cusparseHybMat_t)matstructT->mat;
1568a65300a6SPaul Mullowney       if (cusparsestruct->workVector->size()) {
1569aa372e3fSPaul Mullowney         stat = cusparse_hyb_spmv(cusparsestruct->handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
1570b06137fdSPaul Mullowney                                  matstructT->alpha, matstructT->descr, hybMat,
1571a3fdcf43SKarl Rupp                                  xarray, beta,
1572*57d48284SJunchao Zhang                                  dptr);CHKERRCUSPARSE(stat);
1573a65300a6SPaul Mullowney       }
1574aa372e3fSPaul Mullowney     }
1575a3fdcf43SKarl Rupp     ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1576a3fdcf43SKarl Rupp 
1577a3fdcf43SKarl Rupp     if (dptr != zarray) {
1578a3fdcf43SKarl Rupp       ierr = VecCopy_SeqCUDA(yy,zz);CHKERRQ(ierr);
1579a3fdcf43SKarl Rupp     } else if (zz != yy) {
1580a3fdcf43SKarl Rupp       ierr = VecAXPY_SeqCUDA(zz,1.0,yy);CHKERRQ(ierr);
1581a3fdcf43SKarl Rupp     }
1582a3fdcf43SKarl Rupp     /* scatter the data from the temporary into the full vector with a += operation */
1583a3fdcf43SKarl Rupp     ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
1584a3fdcf43SKarl Rupp     if (dptr != zarray) {
1585a3fdcf43SKarl Rupp       thrust::device_ptr<PetscScalar> zptr;
1586a3fdcf43SKarl Rupp 
1587a3fdcf43SKarl Rupp       zptr = thrust::device_pointer_cast(zarray);
1588aa372e3fSPaul Mullowney 
1589aa372e3fSPaul Mullowney       /* scatter the data from the temporary into the full vector with a += operation */
1590c41cb2e2SAlejandro Lamas Daviña       thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple(cusparsestruct->workVector->begin(), thrust::make_permutation_iterator(zptr, matstructT->cprowIndices->begin()))),
1591554b8892SKarl Rupp                        thrust::make_zip_iterator(thrust::make_tuple(cusparsestruct->workVector->begin(), thrust::make_permutation_iterator(zptr, matstructT->cprowIndices->begin()))) + A->cmap->n,
1592c41cb2e2SAlejandro Lamas Daviña                        VecCUDAPlusEquals());
1593a3fdcf43SKarl Rupp     }
1594a3fdcf43SKarl Rupp     ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
1595c41cb2e2SAlejandro Lamas Daviña     ierr = VecCUDARestoreArrayRead(xx,&xarray);CHKERRQ(ierr);
1596f2d70e9dSBarry Smith     ierr = VecCUDARestoreArray(zz,&zarray);CHKERRQ(ierr);
1597ca45077fSPaul Mullowney   } catch(char *ex) {
1598ca45077fSPaul Mullowney     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CUSPARSE error: %s", ex);
1599661c2d29Shannah_mairs   }
1600*57d48284SJunchao Zhang   cerr = WaitForGPU();CHKERRCUDA(cerr); /* is this needed? just for yy==0 in Mult */
1601958c4211Shannah_mairs   ierr = PetscLogGpuFlops(2.0*a->nz);CHKERRQ(ierr);
1602ca45077fSPaul Mullowney   PetscFunctionReturn(0);
1603ca45077fSPaul Mullowney }
1604ca45077fSPaul Mullowney 
16056fa9248bSJed Brown static PetscErrorCode MatAssemblyEnd_SeqAIJCUSPARSE(Mat A,MatAssemblyType mode)
16069ae82921SPaul Mullowney {
16079ae82921SPaul Mullowney   PetscErrorCode ierr;
16086e111a19SKarl Rupp 
16099ae82921SPaul Mullowney   PetscFunctionBegin;
16109ae82921SPaul Mullowney   ierr = MatAssemblyEnd_SeqAIJ(A,mode);CHKERRQ(ierr);
1611489de41dSStefano Zampini   if (mode == MAT_FLUSH_ASSEMBLY) PetscFunctionReturn(0);
1612bc3f50f2SPaul Mullowney   if (A->factortype == MAT_FACTOR_NONE) {
1613e057df02SPaul Mullowney     ierr = MatSeqAIJCUSPARSECopyToGPU(A);CHKERRQ(ierr);
1614bc3f50f2SPaul Mullowney   }
1615bbf3fe20SPaul Mullowney   A->ops->mult             = MatMult_SeqAIJCUSPARSE;
1616bbf3fe20SPaul Mullowney   A->ops->multadd          = MatMultAdd_SeqAIJCUSPARSE;
1617bbf3fe20SPaul Mullowney   A->ops->multtranspose    = MatMultTranspose_SeqAIJCUSPARSE;
1618bbf3fe20SPaul Mullowney   A->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJCUSPARSE;
16199ae82921SPaul Mullowney   PetscFunctionReturn(0);
16209ae82921SPaul Mullowney }
16219ae82921SPaul Mullowney 
16229ae82921SPaul Mullowney /* --------------------------------------------------------------------------------*/
1623e057df02SPaul Mullowney /*@
16249ae82921SPaul Mullowney    MatCreateSeqAIJCUSPARSE - Creates a sparse matrix in AIJ (compressed row) format
1625e057df02SPaul Mullowney    (the default parallel PETSc format). This matrix will ultimately pushed down
1626e057df02SPaul Mullowney    to NVidia GPUs and use the CUSPARSE library for calculations. For good matrix
1627e057df02SPaul Mullowney    assembly performance the user should preallocate the matrix storage by setting
1628e057df02SPaul Mullowney    the parameter nz (or the array nnz).  By setting these parameters accurately,
1629e057df02SPaul Mullowney    performance during matrix assembly can be increased by more than a factor of 50.
16309ae82921SPaul Mullowney 
1631d083f849SBarry Smith    Collective
16329ae82921SPaul Mullowney 
16339ae82921SPaul Mullowney    Input Parameters:
16349ae82921SPaul Mullowney +  comm - MPI communicator, set to PETSC_COMM_SELF
16359ae82921SPaul Mullowney .  m - number of rows
16369ae82921SPaul Mullowney .  n - number of columns
16379ae82921SPaul Mullowney .  nz - number of nonzeros per row (same for all rows)
16389ae82921SPaul Mullowney -  nnz - array containing the number of nonzeros in the various rows
16390298fd71SBarry Smith          (possibly different for each row) or NULL
16409ae82921SPaul Mullowney 
16419ae82921SPaul Mullowney    Output Parameter:
16429ae82921SPaul Mullowney .  A - the matrix
16439ae82921SPaul Mullowney 
16449ae82921SPaul Mullowney    It is recommended that one use the MatCreate(), MatSetType() and/or MatSetFromOptions(),
16459ae82921SPaul Mullowney    MatXXXXSetPreallocation() paradgm instead of this routine directly.
16469ae82921SPaul Mullowney    [MatXXXXSetPreallocation() is, for example, MatSeqAIJSetPreallocation]
16479ae82921SPaul Mullowney 
16489ae82921SPaul Mullowney    Notes:
16499ae82921SPaul Mullowney    If nnz is given then nz is ignored
16509ae82921SPaul Mullowney 
16519ae82921SPaul Mullowney    The AIJ format (also called the Yale sparse matrix format or
16529ae82921SPaul Mullowney    compressed row storage), is fully compatible with standard Fortran 77
16539ae82921SPaul Mullowney    storage.  That is, the stored row and column indices can begin at
16549ae82921SPaul Mullowney    either one (as in Fortran) or zero.  See the users' manual for details.
16559ae82921SPaul Mullowney 
16569ae82921SPaul Mullowney    Specify the preallocated storage with either nz or nnz (not both).
16570298fd71SBarry Smith    Set nz=PETSC_DEFAULT and nnz=NULL for PETSc to control dynamic memory
16589ae82921SPaul Mullowney    allocation.  For large problems you MUST preallocate memory or you
16599ae82921SPaul Mullowney    will get TERRIBLE performance, see the users' manual chapter on matrices.
16609ae82921SPaul Mullowney 
16619ae82921SPaul Mullowney    By default, this format uses inodes (identical nodes) when possible, to
16629ae82921SPaul Mullowney    improve numerical efficiency of matrix-vector products and solves. We
16639ae82921SPaul Mullowney    search for consecutive rows with the same nonzero structure, thereby
16649ae82921SPaul Mullowney    reusing matrix information to achieve increased efficiency.
16659ae82921SPaul Mullowney 
16669ae82921SPaul Mullowney    Level: intermediate
16679ae82921SPaul Mullowney 
1668e057df02SPaul Mullowney .seealso: MatCreate(), MatCreateAIJ(), MatSetValues(), MatSeqAIJSetColumnIndices(), MatCreateSeqAIJWithArrays(), MatCreateAIJ(), MATSEQAIJCUSPARSE, MATAIJCUSPARSE
16699ae82921SPaul Mullowney @*/
16709ae82921SPaul Mullowney PetscErrorCode  MatCreateSeqAIJCUSPARSE(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt nz,const PetscInt nnz[],Mat *A)
16719ae82921SPaul Mullowney {
16729ae82921SPaul Mullowney   PetscErrorCode ierr;
16739ae82921SPaul Mullowney 
16749ae82921SPaul Mullowney   PetscFunctionBegin;
16759ae82921SPaul Mullowney   ierr = MatCreate(comm,A);CHKERRQ(ierr);
16769ae82921SPaul Mullowney   ierr = MatSetSizes(*A,m,n,m,n);CHKERRQ(ierr);
16779ae82921SPaul Mullowney   ierr = MatSetType(*A,MATSEQAIJCUSPARSE);CHKERRQ(ierr);
16789ae82921SPaul Mullowney   ierr = MatSeqAIJSetPreallocation_SeqAIJ(*A,nz,(PetscInt*)nnz);CHKERRQ(ierr);
16799ae82921SPaul Mullowney   PetscFunctionReturn(0);
16809ae82921SPaul Mullowney }
16819ae82921SPaul Mullowney 
16826fa9248bSJed Brown static PetscErrorCode MatDestroy_SeqAIJCUSPARSE(Mat A)
16839ae82921SPaul Mullowney {
16849ae82921SPaul Mullowney   PetscErrorCode   ierr;
1685ab25e6cbSDominic Meiser 
16869ae82921SPaul Mullowney   PetscFunctionBegin;
16879ae82921SPaul Mullowney   if (A->factortype==MAT_FACTOR_NONE) {
1688c70f7ee4SJunchao Zhang     if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) {
1689470880abSPatrick Sanan       ierr = MatSeqAIJCUSPARSE_Destroy((Mat_SeqAIJCUSPARSE**)&A->spptr);CHKERRQ(ierr);
16909ae82921SPaul Mullowney     }
16919ae82921SPaul Mullowney   } else {
1692470880abSPatrick Sanan     ierr = MatSeqAIJCUSPARSETriFactors_Destroy((Mat_SeqAIJCUSPARSETriFactors**)&A->spptr);CHKERRQ(ierr);
1693aa372e3fSPaul Mullowney   }
16949ae82921SPaul Mullowney   ierr = MatDestroy_SeqAIJ(A);CHKERRQ(ierr);
16959ae82921SPaul Mullowney   PetscFunctionReturn(0);
16969ae82921SPaul Mullowney }
16979ae82921SPaul Mullowney 
16989ff858a8SKarl Rupp static PetscErrorCode MatDuplicate_SeqAIJCUSPARSE(Mat A,MatDuplicateOption cpvalues,Mat *B)
16999ff858a8SKarl Rupp {
17009ff858a8SKarl Rupp   PetscErrorCode ierr;
17019ff858a8SKarl Rupp   Mat C;
17029ff858a8SKarl Rupp   cusparseStatus_t stat;
17039ff858a8SKarl Rupp   cusparseHandle_t handle=0;
17049ff858a8SKarl Rupp 
17059ff858a8SKarl Rupp   PetscFunctionBegin;
17069ff858a8SKarl Rupp   ierr = MatDuplicate_SeqAIJ(A,cpvalues,B);CHKERRQ(ierr);
17079ff858a8SKarl Rupp   C    = *B;
170834136279SStefano Zampini   ierr = PetscFree(C->defaultvectype);CHKERRQ(ierr);
170934136279SStefano Zampini   ierr = PetscStrallocpy(VECCUDA,&C->defaultvectype);CHKERRQ(ierr);
171034136279SStefano Zampini 
17119ff858a8SKarl Rupp   /* inject CUSPARSE-specific stuff */
17129ff858a8SKarl Rupp   if (C->factortype==MAT_FACTOR_NONE) {
17139ff858a8SKarl Rupp     /* you cannot check the inode.use flag here since the matrix was just created.
17149ff858a8SKarl Rupp        now build a GPU matrix data structure */
17159ff858a8SKarl Rupp     C->spptr = new Mat_SeqAIJCUSPARSE;
17169ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->mat          = 0;
17179ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->matTranspose = 0;
17189ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->workVector   = 0;
17199ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->format       = MAT_CUSPARSE_CSR;
17209ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->stream       = 0;
1721*57d48284SJunchao Zhang     stat = cusparseCreate(&handle);CHKERRCUSPARSE(stat);
17229ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->handle       = handle;
17239ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSE*)C->spptr)->nonzerostate = 0;
17249ff858a8SKarl Rupp   } else {
17259ff858a8SKarl Rupp     /* NEXT, set the pointers to the triangular factors */
17269ff858a8SKarl Rupp     C->spptr = new Mat_SeqAIJCUSPARSETriFactors;
17279ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->loTriFactorPtr          = 0;
17289ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->upTriFactorPtr          = 0;
17299ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->loTriFactorPtrTranspose = 0;
17309ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->upTriFactorPtrTranspose = 0;
17319ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->rpermIndices            = 0;
17329ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->cpermIndices            = 0;
17339ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->workVector              = 0;
17349ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->handle                  = 0;
1735*57d48284SJunchao Zhang     stat = cusparseCreate(&handle);CHKERRCUSPARSE(stat);
17369ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->handle                  = handle;
17379ff858a8SKarl Rupp     ((Mat_SeqAIJCUSPARSETriFactors*)C->spptr)->nnz                     = 0;
17389ff858a8SKarl Rupp   }
17399ff858a8SKarl Rupp 
17409ff858a8SKarl Rupp   C->ops->assemblyend      = MatAssemblyEnd_SeqAIJCUSPARSE;
17419ff858a8SKarl Rupp   C->ops->destroy          = MatDestroy_SeqAIJCUSPARSE;
17429ff858a8SKarl Rupp   C->ops->setfromoptions   = MatSetFromOptions_SeqAIJCUSPARSE;
17439ff858a8SKarl Rupp   C->ops->mult             = MatMult_SeqAIJCUSPARSE;
17449ff858a8SKarl Rupp   C->ops->multadd          = MatMultAdd_SeqAIJCUSPARSE;
17459ff858a8SKarl Rupp   C->ops->multtranspose    = MatMultTranspose_SeqAIJCUSPARSE;
17469ff858a8SKarl Rupp   C->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJCUSPARSE;
17479ff858a8SKarl Rupp   C->ops->duplicate        = MatDuplicate_SeqAIJCUSPARSE;
17489ff858a8SKarl Rupp 
17499ff858a8SKarl Rupp   ierr = PetscObjectChangeTypeName((PetscObject)C,MATSEQAIJCUSPARSE);CHKERRQ(ierr);
17509ff858a8SKarl Rupp 
1751c70f7ee4SJunchao Zhang   C->offloadmask = PETSC_OFFLOAD_UNALLOCATED;
17529ff858a8SKarl Rupp 
17539ff858a8SKarl Rupp   ierr = PetscObjectComposeFunction((PetscObject)C, "MatCUSPARSESetFormat_C", MatCUSPARSESetFormat_SeqAIJCUSPARSE);CHKERRQ(ierr);
17549ff858a8SKarl Rupp   PetscFunctionReturn(0);
17559ff858a8SKarl Rupp }
17569ff858a8SKarl Rupp 
175702fe1965SBarry Smith PETSC_EXTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCUSPARSE(Mat B)
17589ae82921SPaul Mullowney {
17599ae82921SPaul Mullowney   PetscErrorCode ierr;
1760aa372e3fSPaul Mullowney   cusparseStatus_t stat;
1761aa372e3fSPaul Mullowney   cusparseHandle_t handle=0;
17629ae82921SPaul Mullowney 
17639ae82921SPaul Mullowney   PetscFunctionBegin;
176434136279SStefano Zampini   ierr = PetscFree(B->defaultvectype);CHKERRQ(ierr);
176534136279SStefano Zampini   ierr = PetscStrallocpy(VECCUDA,&B->defaultvectype);CHKERRQ(ierr);
176634136279SStefano Zampini 
17679ae82921SPaul Mullowney   if (B->factortype==MAT_FACTOR_NONE) {
1768e057df02SPaul Mullowney     /* you cannot check the inode.use flag here since the matrix was just created.
1769e057df02SPaul Mullowney        now build a GPU matrix data structure */
17709ae82921SPaul Mullowney     B->spptr = new Mat_SeqAIJCUSPARSE;
17719ae82921SPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->mat          = 0;
1772aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->matTranspose = 0;
1773aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->workVector   = 0;
1774e057df02SPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->format       = MAT_CUSPARSE_CSR;
1775aa372e3fSPaul Mullowney     ((Mat_SeqAIJCUSPARSE*)B->spptr)->stream       = 0;
1776*57d48284SJunchao 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;
1789*57d48284SJunchao 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;
18022205254eSKarl Rupp 
18039ae82921SPaul Mullowney   ierr = PetscObjectChangeTypeName((PetscObject)B,MATSEQAIJCUSPARSE);CHKERRQ(ierr);
18042205254eSKarl Rupp 
1805c70f7ee4SJunchao Zhang   B->offloadmask = PETSC_OFFLOAD_UNALLOCATED;
18062205254eSKarl Rupp 
1807bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B, "MatCUSPARSESetFormat_C", MatCUSPARSESetFormat_SeqAIJCUSPARSE);CHKERRQ(ierr);
18089ae82921SPaul Mullowney   PetscFunctionReturn(0);
18099ae82921SPaul Mullowney }
18109ae82921SPaul Mullowney 
181102fe1965SBarry Smith PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJCUSPARSE(Mat B)
181202fe1965SBarry Smith {
181302fe1965SBarry Smith   PetscErrorCode ierr;
181402fe1965SBarry Smith 
181502fe1965SBarry Smith   PetscFunctionBegin;
181602fe1965SBarry Smith   ierr = MatCreate_SeqAIJ(B);CHKERRQ(ierr);
1817489de41dSStefano Zampini   ierr = MatConvert_SeqAIJ_SeqAIJCUSPARSE(B);CHKERRQ(ierr);
181802fe1965SBarry Smith   PetscFunctionReturn(0);
181902fe1965SBarry Smith }
182002fe1965SBarry Smith 
18213ca39a21SBarry Smith /*MC
1822e057df02SPaul Mullowney    MATSEQAIJCUSPARSE - MATAIJCUSPARSE = "(seq)aijcusparse" - A matrix type to be used for sparse matrices.
1823e057df02SPaul Mullowney 
1824e057df02SPaul Mullowney    A matrix type type whose data resides on Nvidia GPUs. These matrices can be in either
18252692e278SPaul Mullowney    CSR, ELL, or Hybrid format. The ELL and HYB formats require CUDA 4.2 or later.
18262692e278SPaul Mullowney    All matrix calculations are performed on Nvidia GPUs using the CUSPARSE library.
1827e057df02SPaul Mullowney 
1828e057df02SPaul Mullowney    Options Database Keys:
1829e057df02SPaul Mullowney +  -mat_type aijcusparse - sets the matrix type to "seqaijcusparse" during a call to MatSetFromOptions()
1830aa372e3fSPaul 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).
1831a2b725a8SWilliam 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).
1832e057df02SPaul Mullowney 
1833e057df02SPaul Mullowney   Level: beginner
1834e057df02SPaul Mullowney 
18358468deeeSKarl Rupp .seealso: MatCreateSeqAIJCUSPARSE(), MATAIJCUSPARSE, MatCreateAIJCUSPARSE(), MatCUSPARSESetFormat(), MatCUSPARSEStorageFormat, MatCUSPARSEFormatOperation
1836e057df02SPaul Mullowney M*/
18377f756511SDominic Meiser 
183842c9c57cSBarry Smith PETSC_EXTERN PetscErrorCode MatGetFactor_seqaijcusparse_cusparse(Mat,MatFactorType,Mat*);
183942c9c57cSBarry Smith 
18400f39cd5aSBarry Smith 
18413ca39a21SBarry Smith PETSC_EXTERN PetscErrorCode MatSolverTypeRegister_CUSPARSE(void)
184242c9c57cSBarry Smith {
184342c9c57cSBarry Smith   PetscErrorCode ierr;
184442c9c57cSBarry Smith 
184542c9c57cSBarry Smith   PetscFunctionBegin;
18463ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_LU,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
18473ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_CHOLESKY,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
18483ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_ILU,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
18493ca39a21SBarry Smith   ierr = MatSolverTypeRegister(MATSOLVERCUSPARSE,MATSEQAIJCUSPARSE,MAT_FACTOR_ICC,MatGetFactor_seqaijcusparse_cusparse);CHKERRQ(ierr);
185042c9c57cSBarry Smith   PetscFunctionReturn(0);
185142c9c57cSBarry Smith }
185229b38603SBarry Smith 
185381e08676SBarry Smith 
1854470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSE_Destroy(Mat_SeqAIJCUSPARSE **cusparsestruct)
18557f756511SDominic Meiser {
18567f756511SDominic Meiser   cusparseStatus_t stat;
18577f756511SDominic Meiser   cusparseHandle_t handle;
18587f756511SDominic Meiser 
18597f756511SDominic Meiser   PetscFunctionBegin;
18607f756511SDominic Meiser   if (*cusparsestruct) {
1861470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*cusparsestruct)->mat,(*cusparsestruct)->format);
1862470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*cusparsestruct)->matTranspose,(*cusparsestruct)->format);
18637f756511SDominic Meiser     delete (*cusparsestruct)->workVector;
18647f756511SDominic Meiser     if (handle = (*cusparsestruct)->handle) {
1865*57d48284SJunchao Zhang       stat = cusparseDestroy(handle);CHKERRCUSPARSE(stat);
18667f756511SDominic Meiser     }
18677f756511SDominic Meiser     delete *cusparsestruct;
18687f756511SDominic Meiser     *cusparsestruct = 0;
18697f756511SDominic Meiser   }
18707f756511SDominic Meiser   PetscFunctionReturn(0);
18717f756511SDominic Meiser }
18727f756511SDominic Meiser 
18737f756511SDominic Meiser static PetscErrorCode CsrMatrix_Destroy(CsrMatrix **mat)
18747f756511SDominic Meiser {
18757f756511SDominic Meiser   PetscFunctionBegin;
18767f756511SDominic Meiser   if (*mat) {
18777f756511SDominic Meiser     delete (*mat)->values;
18787f756511SDominic Meiser     delete (*mat)->column_indices;
18797f756511SDominic Meiser     delete (*mat)->row_offsets;
18807f756511SDominic Meiser     delete *mat;
18817f756511SDominic Meiser     *mat = 0;
18827f756511SDominic Meiser   }
18837f756511SDominic Meiser   PetscFunctionReturn(0);
18847f756511SDominic Meiser }
18857f756511SDominic Meiser 
1886470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSEMultStruct_Destroy(Mat_SeqAIJCUSPARSETriFactorStruct **trifactor)
18877f756511SDominic Meiser {
18887f756511SDominic Meiser   cusparseStatus_t stat;
18897f756511SDominic Meiser   PetscErrorCode   ierr;
18907f756511SDominic Meiser 
18917f756511SDominic Meiser   PetscFunctionBegin;
18927f756511SDominic Meiser   if (*trifactor) {
1893*57d48284SJunchao Zhang     if ((*trifactor)->descr) { stat = cusparseDestroyMatDescr((*trifactor)->descr);CHKERRCUSPARSE(stat); }
1894*57d48284SJunchao Zhang     if ((*trifactor)->solveInfo) { stat = cusparseDestroySolveAnalysisInfo((*trifactor)->solveInfo);CHKERRCUSPARSE(stat); }
18957f756511SDominic Meiser     ierr = CsrMatrix_Destroy(&(*trifactor)->csrMat);CHKERRQ(ierr);
18967f756511SDominic Meiser     delete *trifactor;
18977f756511SDominic Meiser     *trifactor = 0;
18987f756511SDominic Meiser   }
18997f756511SDominic Meiser   PetscFunctionReturn(0);
19007f756511SDominic Meiser }
19017f756511SDominic Meiser 
1902470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSEMultStruct_Destroy(Mat_SeqAIJCUSPARSEMultStruct **matstruct,MatCUSPARSEStorageFormat format)
19037f756511SDominic Meiser {
19047f756511SDominic Meiser   CsrMatrix        *mat;
19057f756511SDominic Meiser   cusparseStatus_t stat;
19067f756511SDominic Meiser   cudaError_t      err;
19077f756511SDominic Meiser 
19087f756511SDominic Meiser   PetscFunctionBegin;
19097f756511SDominic Meiser   if (*matstruct) {
19107f756511SDominic Meiser     if ((*matstruct)->mat) {
19117f756511SDominic Meiser       if (format==MAT_CUSPARSE_ELL || format==MAT_CUSPARSE_HYB) {
19127f756511SDominic Meiser         cusparseHybMat_t hybMat = (cusparseHybMat_t)(*matstruct)->mat;
1913*57d48284SJunchao Zhang         stat = cusparseDestroyHybMat(hybMat);CHKERRCUSPARSE(stat);
19147f756511SDominic Meiser       } else {
19157f756511SDominic Meiser         mat = (CsrMatrix*)(*matstruct)->mat;
19167f756511SDominic Meiser         CsrMatrix_Destroy(&mat);
19177f756511SDominic Meiser       }
19187f756511SDominic Meiser     }
1919*57d48284SJunchao Zhang     if ((*matstruct)->descr) { stat = cusparseDestroyMatDescr((*matstruct)->descr);CHKERRCUSPARSE(stat); }
19207f756511SDominic Meiser     delete (*matstruct)->cprowIndices;
1921c41cb2e2SAlejandro Lamas Daviña     if ((*matstruct)->alpha)     { err=cudaFree((*matstruct)->alpha);CHKERRCUDA(err); }
19227656d835SStefano Zampini     if ((*matstruct)->beta_zero) { err=cudaFree((*matstruct)->beta_zero);CHKERRCUDA(err); }
19237656d835SStefano Zampini     if ((*matstruct)->beta_one)  { err=cudaFree((*matstruct)->beta_one);CHKERRCUDA(err); }
19247f756511SDominic Meiser     delete *matstruct;
19257f756511SDominic Meiser     *matstruct = 0;
19267f756511SDominic Meiser   }
19277f756511SDominic Meiser   PetscFunctionReturn(0);
19287f756511SDominic Meiser }
19297f756511SDominic Meiser 
1930470880abSPatrick Sanan static PetscErrorCode MatSeqAIJCUSPARSETriFactors_Destroy(Mat_SeqAIJCUSPARSETriFactors** trifactors)
19317f756511SDominic Meiser {
19327f756511SDominic Meiser   cusparseHandle_t handle;
19337f756511SDominic Meiser   cusparseStatus_t stat;
19347f756511SDominic Meiser 
19357f756511SDominic Meiser   PetscFunctionBegin;
19367f756511SDominic Meiser   if (*trifactors) {
1937470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->loTriFactorPtr);
1938470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->upTriFactorPtr);
1939470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->loTriFactorPtrTranspose);
1940470880abSPatrick Sanan     MatSeqAIJCUSPARSEMultStruct_Destroy(&(*trifactors)->upTriFactorPtrTranspose);
19417f756511SDominic Meiser     delete (*trifactors)->rpermIndices;
19427f756511SDominic Meiser     delete (*trifactors)->cpermIndices;
19437f756511SDominic Meiser     delete (*trifactors)->workVector;
19447f756511SDominic Meiser     if (handle = (*trifactors)->handle) {
1945*57d48284SJunchao Zhang       stat = cusparseDestroy(handle);CHKERRCUSPARSE(stat);
19467f756511SDominic Meiser     }
19477f756511SDominic Meiser     delete *trifactors;
19487f756511SDominic Meiser     *trifactors = 0;
19497f756511SDominic Meiser   }
19507f756511SDominic Meiser   PetscFunctionReturn(0);
19517f756511SDominic Meiser }
19527f756511SDominic Meiser 
1953