Whamcloud - gitweb
LU-9464 hsm: use OBD_ALLOC_LARGE() for hsm_scan_data array
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2016, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <obd_support.h>
43 #include <lustre_net.h>
44 #include <lustre_export.h>
45 #include <obd.h>
46 #include <lprocfs_status.h>
47 #include <lustre_log.h>
48 #include <lustre_kernelcomm.h>
49 #include "mdt_internal.h"
50
51 static struct lprocfs_vars lprocfs_mdt_hsm_vars[];
52
53 /**
54  * get obj and HSM attributes on a fid
55  * \param mti [IN] context
56  * \param fid [IN] object fid
57  * \param hsm [OUT] HSM meta data
58  * \retval obj or error (-ENOENT if not found)
59  */
60 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
61                                       const struct lu_fid *fid,
62                                       struct md_hsm *hsm)
63 {
64         struct md_attr          *ma;
65         struct mdt_object       *obj;
66         int                      rc;
67         ENTRY;
68
69         ma = &mti->mti_attr;
70         ma->ma_need = MA_HSM;
71         ma->ma_valid = 0;
72
73         /* find object by FID */
74         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
75         if (IS_ERR(obj))
76                 RETURN(obj);
77
78         if (!mdt_object_exists(obj)) {
79                 /* no more object */
80                 mdt_object_put(mti->mti_env, obj);
81                 RETURN(ERR_PTR(-ENOENT));
82         }
83
84         rc = mdt_attr_get_complex(mti, obj, ma);
85         if (rc) {
86                 mdt_object_put(mti->mti_env, obj);
87                 RETURN(ERR_PTR(rc));
88         }
89
90         if (ma->ma_valid & MA_HSM)
91                 *hsm = ma->ma_hsm;
92         else
93                 memset(hsm, 0, sizeof(*hsm));
94         ma->ma_valid = 0;
95         RETURN(obj);
96 }
97
98 void mdt_hsm_dump_hal(int level, const char *prefix,
99                       struct hsm_action_list *hal)
100 {
101         int                      i, sz;
102         struct hsm_action_item  *hai;
103         char                     buf[12];
104
105         CDEBUG(level, "%s: HAL header: version %X count %d compound %#llx"
106                       " archive_id %d flags %#llx\n",
107                prefix, hal->hal_version, hal->hal_count,
108                hal->hal_compound_id, hal->hal_archive_id, hal->hal_flags);
109
110         hai = hai_first(hal);
111         for (i = 0; i < hal->hal_count; i++) {
112                 sz = hai->hai_len - sizeof(*hai);
113                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
114                        " compound/cookie=%#llx/%#llx"
115                        " action=%s extent=%#llx-%#llx gid=%#llx"
116                        " datalen=%d data=[%s]\n",
117                        prefix, i,
118                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
119                        hal->hal_compound_id, hai->hai_cookie,
120                        hsm_copytool_action2name(hai->hai_action),
121                        hai->hai_extent.offset,
122                        hai->hai_extent.length,
123                        hai->hai_gid, sz,
124                        hai_dump_data_field(hai, buf, sizeof(buf)));
125                 hai = hai_next(hai);
126         }
127 }
128
129 /**
130  * data passed to llog_cat_process() callback
131  * to scan requests and take actions
132  */
133 struct hsm_scan_request {
134         int                      hal_sz;
135         int                      hal_used_sz;
136         struct hsm_action_list  *hal;
137 };
138
139 struct hsm_scan_data {
140         struct mdt_thread_info          *mti;
141         char                             fs_name[MTI_NAME_MAXLEN+1];
142         /* request to be send to agents */
143         int                              max_requests;  /** vector size */
144         int                              request_cnt;   /** used count */
145         struct hsm_scan_request         *request;
146 };
147
148 /**
149  *  llog_cat_process() callback, used to:
150  *  - find waiting request and start action
151  *  - purge canceled and done requests
152  * \param env [IN] environment
153  * \param llh [IN] llog handle
154  * \param hdr [IN] llog record
155  * \param data [IN/OUT] cb data = struct hsm_scan_data
156  * \retval 0 success
157  * \retval -ve failure
158  */
159 static int mdt_coordinator_cb(const struct lu_env *env,
160                               struct llog_handle *llh,
161                               struct llog_rec_hdr *hdr,
162                               void *data)
163 {
164         struct llog_agent_req_rec       *larr;
165         struct hsm_scan_data            *hsd;
166         struct hsm_action_item          *hai;
167         struct mdt_device               *mdt;
168         struct coordinator              *cdt;
169         int                              rc;
170         ENTRY;
171
172         hsd = data;
173         mdt = hsd->mti->mti_mdt;
174         cdt = &mdt->mdt_coordinator;
175
176         larr = (struct llog_agent_req_rec *)hdr;
177         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
178         switch (larr->arr_status) {
179         case ARS_WAITING: {
180                 int i;
181                 struct hsm_scan_request *request;
182
183                 /* Are agents full? */
184                 if (atomic_read(&cdt->cdt_request_count) >=
185                     cdt->cdt_max_requests)
186                         break;
187
188                 /* first search whether the request is found in the
189                  * list we have built. */
190                 request = NULL;
191                 for (i = 0; i < hsd->request_cnt; i++) {
192                         if (hsd->request[i].hal->hal_compound_id ==
193                             larr->arr_compound_id) {
194                                 request = &hsd->request[i];
195                                 break;
196                         }
197                 }
198
199                 if (!request) {
200                         struct hsm_action_list *hal;
201
202                         if (hsd->request_cnt == hsd->max_requests)
203                                 /* Unknown request and no more room
204                                  * for a new request. Continue to scan
205                                  * to find other entries for already
206                                  * existing requests.
207                                  */
208                                 RETURN(0);
209
210                         request = &hsd->request[hsd->request_cnt];
211
212                         /* allocates hai vector size just needs to be large
213                          * enough */
214                         request->hal_sz =
215                                 sizeof(*request->hal) +
216                                 cfs_size_round(MTI_NAME_MAXLEN+1) +
217                                 2 * cfs_size_round(larr->arr_hai.hai_len);
218                         OBD_ALLOC(hal, request->hal_sz);
219                         if (!hal)
220                                 RETURN(-ENOMEM);
221                         hal->hal_version = HAL_VERSION;
222                         strlcpy(hal->hal_fsname, hsd->fs_name,
223                                 MTI_NAME_MAXLEN + 1);
224                         hal->hal_compound_id = larr->arr_compound_id;
225                         hal->hal_archive_id = larr->arr_archive_id;
226                         hal->hal_flags = larr->arr_flags;
227                         hal->hal_count = 0;
228                         request->hal_used_sz = hal_size(hal);
229                         request->hal = hal;
230                         hsd->request_cnt++;
231                         hai = hai_first(hal);
232                 } else {
233                         /* request is known */
234                         /* we check if record archive num is the same as the
235                          * known request, if not we will serve it in multiple
236                          * time because we do not know if the agent can serve
237                          * multiple backend
238                          * a use case is a compound made of multiple restore
239                          * where the files are not archived in the same backend
240                          */
241                         if (larr->arr_archive_id !=
242                             request->hal->hal_archive_id)
243                                 RETURN(0);
244
245                         if (request->hal_sz <
246                             request->hal_used_sz +
247                             cfs_size_round(larr->arr_hai.hai_len)) {
248                                 /* Not enough room, need an extension */
249                                 void *hal_buffer;
250                                 int sz;
251
252                                 sz = 2 * request->hal_sz;
253                                 OBD_ALLOC(hal_buffer, sz);
254                                 if (!hal_buffer)
255                                         RETURN(-ENOMEM);
256                                 memcpy(hal_buffer, request->hal,
257                                        request->hal_used_sz);
258                                 OBD_FREE(request->hal,
259                                          request->hal_sz);
260                                 request->hal = hal_buffer;
261                                 request->hal_sz = sz;
262                         }
263                         hai = hai_first(request->hal);
264                         for (i = 0; i < request->hal->hal_count; i++)
265                                 hai = hai_next(hai);
266                 }
267                 memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
268                 hai->hai_cookie = larr->arr_hai.hai_cookie;
269                 hai->hai_gid = larr->arr_hai.hai_gid;
270
271                 request->hal_used_sz += cfs_size_round(hai->hai_len);
272                 request->hal->hal_count++;
273                 break;
274         }
275         case ARS_STARTED: {
276                 struct hsm_progress_kernel pgs;
277                 struct cdt_agent_req *car;
278                 cfs_time_t now = cfs_time_current_sec();
279                 cfs_time_t last;
280
281                 /* we search for a running request
282                  * error may happen if coordinator crashes or stopped
283                  * with running request
284                  */
285                 car = mdt_cdt_find_request(cdt, larr->arr_hai.hai_cookie);
286                 if (car == NULL) {
287                         last = larr->arr_req_change;
288                 } else {
289                         last = car->car_req_update;
290                         mdt_cdt_put_request(car);
291                 }
292
293                 /* test if request too long, if yes cancel it
294                  * the same way the copy tool acknowledge a cancel request */
295                 if (now <= last + cdt->cdt_active_req_timeout)
296                         RETURN(0);
297
298                 dump_llog_agent_req_rec("request timed out, start cleaning",
299                                         larr);
300                 /* a too old cancel request just needs to be removed
301                  * this can happen, if copy tool does not support
302                  * cancel for other requests, we have to remove the
303                  * running request and notify the copytool */
304                 pgs.hpk_fid = larr->arr_hai.hai_fid;
305                 pgs.hpk_cookie = larr->arr_hai.hai_cookie;
306                 pgs.hpk_extent = larr->arr_hai.hai_extent;
307                 pgs.hpk_flags = HP_FLAG_COMPLETED;
308                 pgs.hpk_errval = ENOSYS;
309                 pgs.hpk_data_version = 0;
310
311                 /* update request state, but do not record in llog, to
312                  * avoid deadlock on cdt_llog_lock */
313                 rc = mdt_hsm_update_request_state(hsd->mti, &pgs, 0);
314                 if (rc)
315                         CERROR("%s: cannot cleanup timed out request: "
316                                DFID" for cookie %#llx action=%s\n",
317                                mdt_obd_name(mdt),
318                                PFID(&pgs.hpk_fid), pgs.hpk_cookie,
319                                hsm_copytool_action2name(
320                                        larr->arr_hai.hai_action));
321
322                 if (rc == -ENOENT) {
323                         /* The request no longer exists, forget
324                          * about it, and do not send a cancel request
325                          * to the client, for which an error will be
326                          * sent back, leading to an endless cycle of
327                          * cancellation. */
328                         RETURN(LLOG_DEL_RECORD);
329                 }
330
331                 /* XXX A cancel request cannot be cancelled. */
332                 if (larr->arr_hai.hai_action == HSMA_CANCEL)
333                         RETURN(0);
334
335                 larr->arr_status = ARS_CANCELED;
336                 larr->arr_req_change = now;
337                 rc = llog_write(hsd->mti->mti_env, llh, hdr, hdr->lrh_index);
338                 if (rc < 0)
339                         CERROR("%s: cannot update agent log: rc = %d\n",
340                                mdt_obd_name(mdt), rc);
341                 break;
342         }
343         case ARS_FAILED:
344         case ARS_CANCELED:
345         case ARS_SUCCEED:
346                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
347                     cfs_time_current_sec())
348                         RETURN(LLOG_DEL_RECORD);
349                 break;
350         }
351         RETURN(0);
352 }
353
354 /**
355  * create /proc entries for coordinator
356  * \param mdt [IN]
357  * \retval 0 success
358  * \retval -ve failure
359  */
360 int hsm_cdt_procfs_init(struct mdt_device *mdt)
361 {
362         struct coordinator      *cdt = &mdt->mdt_coordinator;
363         int                      rc = 0;
364         ENTRY;
365
366         /* init /proc entries, failure is not critical */
367         cdt->cdt_proc_dir = lprocfs_register("hsm",
368                                              mdt2obd_dev(mdt)->obd_proc_entry,
369                                              lprocfs_mdt_hsm_vars, mdt);
370         if (IS_ERR(cdt->cdt_proc_dir)) {
371                 rc = PTR_ERR(cdt->cdt_proc_dir);
372                 CERROR("%s: Cannot create 'hsm' directory in mdt proc dir,"
373                        " rc=%d\n", mdt_obd_name(mdt), rc);
374                 cdt->cdt_proc_dir = NULL;
375                 RETURN(rc);
376         }
377
378         RETURN(0);
379 }
380
381 /**
382  * remove /proc entries for coordinator
383  * \param mdt [IN]
384  */
385 void  hsm_cdt_procfs_fini(struct mdt_device *mdt)
386 {
387         struct coordinator      *cdt = &mdt->mdt_coordinator;
388
389         LASSERT(cdt->cdt_state == CDT_STOPPED);
390         if (cdt->cdt_proc_dir != NULL)
391                 lprocfs_remove(&cdt->cdt_proc_dir);
392 }
393
394 /**
395  * get vector of hsm cdt /proc vars
396  * \param none
397  * \retval var vector
398  */
399 struct lprocfs_vars *hsm_cdt_get_proc_vars(void)
400 {
401         return lprocfs_mdt_hsm_vars;
402 }
403
404 /**
405  * coordinator thread
406  * \param data [IN] obd device
407  * \retval 0 success
408  * \retval -ve failure
409  */
410 static int mdt_coordinator(void *data)
411 {
412         struct mdt_thread_info  *mti = data;
413         struct mdt_device       *mdt = mti->mti_mdt;
414         struct coordinator      *cdt = &mdt->mdt_coordinator;
415         struct hsm_scan_data     hsd = { NULL };
416         int                      rc = 0;
417         int                      request_sz;
418         ENTRY;
419
420         cdt->cdt_flags = SVC_RUNNING;
421         wake_up(&cdt->cdt_waitq);
422
423         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
424                mdt_obd_name(mdt), current_pid());
425
426         /* we use a copy of cdt_max_requests in the cb, so if cdt_max_requests
427          * increases due to a change from /proc we do not overflow the
428          * hsd.request[] vector
429          */
430         hsd.max_requests = cdt->cdt_max_requests;
431         request_sz = hsd.max_requests * sizeof(*hsd.request);
432         OBD_ALLOC_LARGE(hsd.request, request_sz);
433         if (!hsd.request)
434                 GOTO(out, rc = -ENOMEM);
435
436         hsd.mti = mti;
437         obd_uuid2fsname(hsd.fs_name, mdt_obd_name(mdt), MTI_NAME_MAXLEN);
438
439         while (1) {
440                 struct l_wait_info lwi;
441                 int i;
442
443                 lwi = LWI_TIMEOUT(cfs_time_seconds(cdt->cdt_loop_period),
444                                   NULL, NULL);
445                 l_wait_event(cdt->cdt_waitq,
446                              cdt->cdt_flags & (SVC_STOPPING|SVC_EVENT),
447                              &lwi);
448
449                 CDEBUG(D_HSM, "coordinator resumes\n");
450
451                 if (cdt->cdt_flags & SVC_STOPPING ||
452                     cdt->cdt_state == CDT_STOPPING) {
453                         cdt->cdt_flags &= ~SVC_STOPPING;
454                         rc = 0;
455                         break;
456                 }
457
458                 /* wake up before timeout, new work arrives */
459                 if (cdt->cdt_flags & SVC_EVENT)
460                         cdt->cdt_flags &= ~SVC_EVENT;
461
462                 /* if coordinator is suspended continue to wait */
463                 if (cdt->cdt_state == CDT_DISABLE) {
464                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
465                         continue;
466                 }
467
468                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
469
470                 if (hsd.max_requests != cdt->cdt_max_requests) {
471                         /* cdt_max_requests has changed,
472                          * we need to allocate a new buffer
473                          */
474                         OBD_FREE_LARGE(hsd.request, request_sz);
475                         hsd.max_requests = cdt->cdt_max_requests;
476                         request_sz = hsd.max_requests * sizeof(*hsd.request);
477                         OBD_ALLOC_LARGE(hsd.request, request_sz);
478                         if (!hsd.request) {
479                                 rc = -ENOMEM;
480                                 break;
481                         }
482                 }
483
484                 hsd.request_cnt = 0;
485
486                 rc = cdt_llog_process(mti->mti_env, mdt,
487                                       mdt_coordinator_cb, &hsd);
488                 if (rc < 0)
489                         goto clean_cb_alloc;
490
491                 CDEBUG(D_HSM, "found %d requests to send\n", hsd.request_cnt);
492
493                 if (list_empty(&cdt->cdt_agents)) {
494                         CDEBUG(D_HSM, "no agent available, "
495                                       "coordinator sleeps\n");
496                         goto clean_cb_alloc;
497                 }
498
499                 /* here hsd contains a list of requests to be started */
500                 for (i = 0; i < hsd.request_cnt; i++) {
501                         struct hsm_scan_request *request = &hsd.request[i];
502                         struct hsm_action_list  *hal = request->hal;
503                         struct hsm_action_item  *hai;
504                         __u64                   *cookies;
505                         int                      sz, j;
506                         enum agent_req_status    status;
507
508                         /* still room for work ? */
509                         if (atomic_read(&cdt->cdt_request_count) >=
510                             cdt->cdt_max_requests)
511                                 break;
512
513                         rc = mdt_hsm_agent_send(mti, hal, 0);
514                         /* if failure, we suppose it is temporary
515                          * if the copy tool failed to do the request
516                          * it has to use hsm_progress
517                          */
518                         status = (rc ? ARS_WAITING : ARS_STARTED);
519
520                         /* set up cookie vector to set records status
521                          * after copy tools start or failed
522                          */
523                         sz = hal->hal_count * sizeof(__u64);
524                         OBD_ALLOC(cookies, sz);
525                         if (cookies == NULL)
526                                 continue;
527
528                         hai = hai_first(hal);
529                         for (j = 0; j < hal->hal_count; j++) {
530                                 cookies[j] = hai->hai_cookie;
531                                 hai = hai_next(hai);
532                         }
533
534                         rc = mdt_agent_record_update(mti->mti_env, mdt, cookies,
535                                                      hal->hal_count, status);
536                         if (rc)
537                                 CERROR("%s: mdt_agent_record_update() failed, "
538                                        "rc=%d, cannot update status to %s "
539                                        "for %d cookies\n",
540                                        mdt_obd_name(mdt), rc,
541                                        agent_req_status2name(status),
542                                        hal->hal_count);
543
544                         OBD_FREE(cookies, sz);
545                 }
546 clean_cb_alloc:
547                 /* free hal allocated by callback */
548                 for (i = 0; i < hsd.request_cnt; i++) {
549                         struct hsm_scan_request *request = &hsd.request[i];
550
551                         OBD_FREE(request->hal, request->hal_sz);
552                 }
553         }
554         EXIT;
555 out:
556         if (hsd.request)
557                 OBD_FREE_LARGE(hsd.request, request_sz);
558
559         if (cdt->cdt_state == CDT_STOPPING) {
560                 /* request comes from /proc path, so we need to clean cdt
561                  * struct */
562                  mdt_hsm_cdt_stop(mdt);
563                  mdt->mdt_opts.mo_coordinator = 0;
564         } else {
565                 /* request comes from a thread event, generated
566                  * by mdt_stop_coordinator(), we have to ack
567                  * and cdt cleaning will be done by event sender
568                  */
569                 cdt->cdt_flags = SVC_STOPPED;
570                 wake_up(&cdt->cdt_waitq);
571         }
572
573         if (rc != 0)
574                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
575                        mdt_obd_name(mdt), current_pid(), rc);
576         else
577                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
578                               " no error\n",
579                        mdt_obd_name(mdt), current_pid());
580
581         return rc;
582 }
583
584 /**
585  * lookup a restore handle by FID
586  * caller needs to hold cdt_restore_lock
587  * \param cdt [IN] coordinator
588  * \param fid [IN] FID
589  * \retval cdt_restore_handle found
590  * \retval NULL not found
591  */
592 struct cdt_restore_handle *mdt_hsm_restore_hdl_find(struct coordinator *cdt,
593                                                        const struct lu_fid *fid)
594 {
595         struct cdt_restore_handle       *crh;
596         ENTRY;
597
598         list_for_each_entry(crh, &cdt->cdt_restore_hdl, crh_list) {
599                 if (lu_fid_eq(&crh->crh_fid, fid))
600                         RETURN(crh);
601         }
602         RETURN(NULL);
603 }
604
605 /**
606  * data passed to llog_cat_process() callback
607  * to scan requests and take actions
608  */
609 struct hsm_restore_data {
610         struct mdt_thread_info  *hrd_mti;
611 };
612
613 /**
614  *  llog_cat_process() callback, used to:
615  *  - find restore request and allocate the restore handle
616  * \param env [IN] environment
617  * \param llh [IN] llog handle
618  * \param hdr [IN] llog record
619  * \param data [IN/OUT] cb data = struct hsm_restore_data
620  * \retval 0 success
621  * \retval -ve failure
622  */
623 static int hsm_restore_cb(const struct lu_env *env,
624                           struct llog_handle *llh,
625                           struct llog_rec_hdr *hdr, void *data)
626 {
627         struct llog_agent_req_rec       *larr;
628         struct hsm_restore_data         *hrd;
629         struct cdt_restore_handle       *crh;
630         struct hsm_action_item          *hai;
631         struct mdt_thread_info          *mti;
632         struct coordinator              *cdt;
633         struct mdt_object               *child;
634         int rc;
635         ENTRY;
636
637         hrd = data;
638         mti = hrd->hrd_mti;
639         cdt = &mti->mti_mdt->mdt_coordinator;
640
641         larr = (struct llog_agent_req_rec *)hdr;
642         hai = &larr->arr_hai;
643         if (hai->hai_cookie > cdt->cdt_last_cookie)
644                 /* update the cookie to avoid collision */
645                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
646
647         if (hai->hai_action != HSMA_RESTORE ||
648             agent_req_in_final_state(larr->arr_status))
649                 RETURN(0);
650
651         /* restore request not in a final state */
652
653         /* force replay of restore requests left in started state from previous
654          * CDT context, to be canceled later if finally found to be incompatible
655          * when being re-started */
656         if (larr->arr_status == ARS_STARTED) {
657                 larr->arr_status = ARS_WAITING;
658                 larr->arr_req_change = cfs_time_current_sec();
659                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
660                 if (rc != 0)
661                         GOTO(out, rc);
662         }
663
664         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
665         if (crh == NULL)
666                 RETURN(-ENOMEM);
667
668         crh->crh_fid = hai->hai_fid;
669         /* in V1 all file is restored
670         crh->extent.start = hai->hai_extent.offset;
671         crh->extent.end = hai->hai_extent.offset + hai->hai_extent.length;
672         */
673         crh->crh_extent.start = 0;
674         crh->crh_extent.end = hai->hai_extent.length;
675         /* get the layout lock */
676         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
677         child = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
678                                      MDS_INODELOCK_LAYOUT);
679         if (IS_ERR(child))
680                 GOTO(out, rc = PTR_ERR(child));
681
682         rc = 0;
683         /* we choose to not keep a reference
684          * on the object during the restore time which can be very long */
685         mdt_object_put(mti->mti_env, child);
686
687         mutex_lock(&cdt->cdt_restore_lock);
688         list_add_tail(&crh->crh_list, &cdt->cdt_restore_hdl);
689         mutex_unlock(&cdt->cdt_restore_lock);
690
691 out:
692         RETURN(rc);
693 }
694
695 /**
696  * restore coordinator state at startup
697  * the goal is to take a layout lock for each registered restore request
698  * \param mti [IN] context
699  */
700 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
701 {
702         struct hsm_restore_data  hrd;
703         int                      rc;
704         ENTRY;
705
706         hrd.hrd_mti = mti;
707
708         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
709                               hsm_restore_cb, &hrd);
710
711         RETURN(rc);
712 }
713
714 static int hsm_init_ucred(struct lu_ucred *uc)
715 {
716         ENTRY;
717
718         uc->uc_valid = UCRED_OLD;
719         uc->uc_o_uid = 0;
720         uc->uc_o_gid = 0;
721         uc->uc_o_fsuid = 0;
722         uc->uc_o_fsgid = 0;
723         uc->uc_uid = 0;
724         uc->uc_gid = 0;
725         uc->uc_fsuid = 0;
726         uc->uc_fsgid = 0;
727         uc->uc_suppgids[0] = -1;
728         uc->uc_suppgids[1] = -1;
729         uc->uc_cap = CFS_CAP_FS_MASK;
730         uc->uc_umask = 0777;
731         uc->uc_ginfo = NULL;
732         uc->uc_identity = NULL;
733
734         RETURN(0);
735 }
736
737 /**
738  * wake up coordinator thread
739  * \param mdt [IN] device
740  * \retval 0 success
741  * \retval -ve failure
742  */
743 int mdt_hsm_cdt_wakeup(struct mdt_device *mdt)
744 {
745         struct coordinator      *cdt = &mdt->mdt_coordinator;
746         ENTRY;
747
748         if (cdt->cdt_state == CDT_STOPPED)
749                 RETURN(-ESRCH);
750
751         /* wake up coordinator */
752         cdt->cdt_flags = SVC_EVENT;
753         wake_up(&cdt->cdt_waitq);
754
755         RETURN(0);
756 }
757
758 /**
759  * initialize coordinator struct
760  * \param mdt [IN] device
761  * \retval 0 success
762  * \retval -ve failure
763  */
764 int mdt_hsm_cdt_init(struct mdt_device *mdt)
765 {
766         struct coordinator      *cdt = &mdt->mdt_coordinator;
767         struct mdt_thread_info  *cdt_mti = NULL;
768         int                      rc;
769         ENTRY;
770
771         cdt->cdt_state = CDT_STOPPED;
772
773         init_waitqueue_head(&cdt->cdt_waitq);
774         mutex_init(&cdt->cdt_llog_lock);
775         init_rwsem(&cdt->cdt_agent_lock);
776         init_rwsem(&cdt->cdt_request_lock);
777         mutex_init(&cdt->cdt_restore_lock);
778
779         INIT_LIST_HEAD(&cdt->cdt_request_list);
780         INIT_LIST_HEAD(&cdt->cdt_agents);
781         INIT_LIST_HEAD(&cdt->cdt_restore_hdl);
782
783         cdt->cdt_request_cookie_hash = cfs_hash_create("REQUEST_COOKIE_HASH",
784                                                        CFS_HASH_BITS_MIN,
785                                                        CFS_HASH_BITS_MAX,
786                                                        CFS_HASH_BKT_BITS,
787                                                        0 /* extra bytes */,
788                                                        CFS_HASH_MIN_THETA,
789                                                        CFS_HASH_MAX_THETA,
790                                                 &cdt_request_cookie_hash_ops,
791                                                        CFS_HASH_DEFAULT);
792         if (cdt->cdt_request_cookie_hash == NULL)
793                 RETURN(-ENOMEM);
794
795         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
796         if (rc < 0)
797                 GOTO(out_request_cookie_hash, rc);
798
799         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
800         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
801         if (rc < 0)
802                 GOTO(out_env, rc);
803
804         lu_context_enter(&cdt->cdt_session);
805         cdt->cdt_env.le_ses = &cdt->cdt_session;
806
807         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
808         LASSERT(cdt_mti != NULL);
809
810         cdt_mti->mti_env = &cdt->cdt_env;
811         cdt_mti->mti_mdt = mdt;
812
813         hsm_init_ucred(mdt_ucred(cdt_mti));
814
815         /* default values for /proc tunnables
816          * can be override by MGS conf */
817         cdt->cdt_default_archive_id = 1;
818         cdt->cdt_grace_delay = 60;
819         cdt->cdt_loop_period = 10;
820         cdt->cdt_max_requests = 3;
821         cdt->cdt_policy = CDT_DEFAULT_POLICY;
822         cdt->cdt_active_req_timeout = 3600;
823
824         RETURN(0);
825
826 out_env:
827         lu_env_fini(&cdt->cdt_env);
828 out_request_cookie_hash:
829         cfs_hash_putref(cdt->cdt_request_cookie_hash);
830         cdt->cdt_request_cookie_hash = NULL;
831
832         return rc;
833 }
834
835 /**
836  * free a coordinator thread
837  * \param mdt [IN] device
838  */
839 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
840 {
841         struct coordinator *cdt = &mdt->mdt_coordinator;
842         ENTRY;
843
844         lu_context_exit(cdt->cdt_env.le_ses);
845         lu_context_fini(cdt->cdt_env.le_ses);
846
847         lu_env_fini(&cdt->cdt_env);
848
849         cfs_hash_putref(cdt->cdt_request_cookie_hash);
850         cdt->cdt_request_cookie_hash = NULL;
851
852         RETURN(0);
853 }
854
855 /**
856  * start a coordinator thread
857  * \param mdt [IN] device
858  * \retval 0 success
859  * \retval -ve failure
860  */
861 static int mdt_hsm_cdt_start(struct mdt_device *mdt)
862 {
863         struct coordinator      *cdt = &mdt->mdt_coordinator;
864         int                      rc;
865         void                    *ptr;
866         struct mdt_thread_info  *cdt_mti;
867         struct task_struct      *task;
868         ENTRY;
869
870         /* functions defined but not yet used
871          * this avoid compilation warning
872          */
873         ptr = dump_requests;
874
875         if (cdt->cdt_state != CDT_STOPPED) {
876                 CERROR("%s: Coordinator already started\n",
877                        mdt_obd_name(mdt));
878                 RETURN(-EALREADY);
879         }
880
881         CLASSERT(1 << (CDT_POLICY_SHIFT_COUNT - 1) == CDT_POLICY_LAST);
882         cdt->cdt_policy = CDT_DEFAULT_POLICY;
883
884         cdt->cdt_state = CDT_INIT;
885
886         atomic_set(&cdt->cdt_compound_id, cfs_time_current_sec());
887         /* just need to be larger than previous one */
888         /* cdt_last_cookie is protected by cdt_llog_lock */
889         cdt->cdt_last_cookie = cfs_time_current_sec();
890         atomic_set(&cdt->cdt_request_count, 0);
891         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
892         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
893         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
894
895         /* to avoid deadlock when start is made through /proc
896          * /proc entries are created by the coordinator thread */
897
898         /* set up list of started restore requests */
899         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
900         rc = mdt_hsm_pending_restore(cdt_mti);
901         if (rc)
902                 CERROR("%s: cannot take the layout locks needed"
903                        " for registered restore: %d\n",
904                        mdt_obd_name(mdt), rc);
905
906         if (mdt->mdt_bottom->dd_rdonly)
907                 RETURN(0);
908
909         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
910         if (IS_ERR(task)) {
911                 rc = PTR_ERR(task);
912                 cdt->cdt_state = CDT_STOPPED;
913                 CERROR("%s: error starting coordinator thread: %d\n",
914                        mdt_obd_name(mdt), rc);
915                 RETURN(rc);
916         } else {
917                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
918                        mdt_obd_name(mdt));
919                 rc = 0;
920         }
921
922         wait_event(cdt->cdt_waitq,
923                        (cdt->cdt_flags & SVC_RUNNING));
924
925         cdt->cdt_state = CDT_RUNNING;
926         mdt->mdt_opts.mo_coordinator = 1;
927         RETURN(0);
928 }
929
930 /**
931  * stop a coordinator thread
932  * \param mdt [IN] device
933  */
934 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
935 {
936         struct coordinator              *cdt = &mdt->mdt_coordinator;
937         struct cdt_agent_req            *car, *tmp1;
938         struct hsm_agent                *ha, *tmp2;
939         struct cdt_restore_handle       *crh, *tmp3;
940         struct mdt_thread_info          *cdt_mti;
941         ENTRY;
942
943         if (cdt->cdt_state == CDT_STOPPED) {
944                 CERROR("%s: Coordinator already stopped\n",
945                        mdt_obd_name(mdt));
946                 RETURN(-EALREADY);
947         }
948
949         if (cdt->cdt_state != CDT_STOPPING) {
950                 /* stop coordinator thread before cleaning */
951                 cdt->cdt_flags = SVC_STOPPING;
952                 wake_up(&cdt->cdt_waitq);
953                 wait_event(cdt->cdt_waitq,
954                            cdt->cdt_flags & SVC_STOPPED);
955         }
956         cdt->cdt_state = CDT_STOPPED;
957
958         /* start cleaning */
959         down_write(&cdt->cdt_request_lock);
960         list_for_each_entry_safe(car, tmp1, &cdt->cdt_request_list,
961                                  car_request_list) {
962                 cfs_hash_del(cdt->cdt_request_cookie_hash,
963                              &car->car_hai->hai_cookie,
964                              &car->car_cookie_hash);
965                 list_del(&car->car_request_list);
966                 mdt_cdt_put_request(car);
967         }
968         up_write(&cdt->cdt_request_lock);
969
970         down_write(&cdt->cdt_agent_lock);
971         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
972                 list_del(&ha->ha_list);
973                 OBD_FREE_PTR(ha);
974         }
975         up_write(&cdt->cdt_agent_lock);
976
977         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
978         mutex_lock(&cdt->cdt_restore_lock);
979         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_hdl, crh_list) {
980                 struct mdt_object       *child;
981
982                 /* give back layout lock */
983                 child = mdt_object_find(&cdt->cdt_env, mdt, &crh->crh_fid);
984                 if (!IS_ERR(child))
985                         mdt_object_unlock_put(cdt_mti, child, &crh->crh_lh, 1);
986
987                 list_del(&crh->crh_list);
988
989                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
990         }
991         mutex_unlock(&cdt->cdt_restore_lock);
992
993         mdt->mdt_opts.mo_coordinator = 0;
994
995         RETURN(0);
996 }
997
998 static int mdt_hsm_set_exists(struct mdt_thread_info *mti,
999                               const struct lu_fid *fid,
1000                               u32 archive_id)
1001 {
1002         struct mdt_object *obj;
1003         struct md_hsm mh;
1004         int rc;
1005
1006         obj = mdt_hsm_get_md_hsm(mti, fid, &mh);
1007         if (IS_ERR(obj))
1008                 GOTO(out, rc = PTR_ERR(obj));
1009
1010         if (mh.mh_flags & HS_EXISTS &&
1011             mh.mh_arch_id == archive_id)
1012                 GOTO(out_obj, rc = 0);
1013
1014         mh.mh_flags |= HS_EXISTS;
1015         mh.mh_arch_id = archive_id;
1016         rc = mdt_hsm_attr_set(mti, obj, &mh);
1017
1018 out_obj:
1019         mdt_object_put(mti->mti_env, obj);
1020 out:
1021         return rc;
1022 }
1023
1024 /**
1025  * register all requests from an hal in the memory list
1026  * \param mti [IN] context
1027  * \param hal [IN] request
1028  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1029  *  which is running the CT
1030  * \retval 0 success
1031  * \retval -ve failure
1032  */
1033 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1034                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1035 {
1036         struct mdt_device       *mdt = mti->mti_mdt;
1037         struct coordinator      *cdt = &mdt->mdt_coordinator;
1038         struct hsm_action_item  *hai;
1039         int                      rc = 0, i;
1040         ENTRY;
1041
1042         /* register request in memory list */
1043         hai = hai_first(hal);
1044         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1045                 struct cdt_agent_req *car;
1046
1047                 /* in case of a cancel request, we first mark the ondisk
1048                  * record of the request we want to stop as canceled
1049                  * this does not change the cancel record
1050                  * it will be done when updating the request status
1051                  */
1052                 if (hai->hai_action == HSMA_CANCEL) {
1053                         rc = mdt_agent_record_update(mti->mti_env, mti->mti_mdt,
1054                                                      &hai->hai_cookie,
1055                                                      1, ARS_CANCELED);
1056                         if (rc) {
1057                                 CERROR("%s: mdt_agent_record_update() failed, "
1058                                        "rc=%d, cannot update status to %s "
1059                                        "for cookie %#llx\n",
1060                                        mdt_obd_name(mdt), rc,
1061                                        agent_req_status2name(ARS_CANCELED),
1062                                        hai->hai_cookie);
1063                                 GOTO(out, rc);
1064                         }
1065
1066                         /* find the running request to set it canceled */
1067                         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
1068                         if (car != NULL) {
1069                                 car->car_canceled = 1;
1070                                 /* uuid has to be changed to the one running the
1071                                 * request to cancel */
1072                                 *uuid = car->car_uuid;
1073                                 mdt_cdt_put_request(car);
1074                         }
1075                         /* no need to memorize cancel request
1076                          * this also avoid a deadlock when we receive
1077                          * a purge all requests command
1078                          */
1079                         continue;
1080                 }
1081
1082                 if (hai->hai_action == HSMA_ARCHIVE) {
1083                         rc = mdt_hsm_set_exists(mti, &hai->hai_fid,
1084                                                 hal->hal_archive_id);
1085                         if (rc == -ENOENT)
1086                                 continue;
1087                         else if (rc < 0)
1088                                 GOTO(out, rc);
1089                 }
1090
1091                 car = mdt_cdt_alloc_request(hal->hal_compound_id,
1092                                             hal->hal_archive_id, hal->hal_flags,
1093                                             uuid, hai);
1094                 if (IS_ERR(car))
1095                         GOTO(out, rc = PTR_ERR(car));
1096
1097                 rc = mdt_cdt_add_request(cdt, car);
1098                 if (rc != 0)
1099                         mdt_cdt_free_request(car);
1100         }
1101 out:
1102         RETURN(rc);
1103 }
1104
1105 /**
1106  * swap layouts between 2 fids
1107  * \param mti [IN] context
1108  * \param obj [IN]
1109  * \param dfid [IN]
1110  * \param mh_common [IN] MD HSM
1111  */
1112 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1113                             struct mdt_object *obj, const struct lu_fid *dfid,
1114                             struct md_hsm *mh_common)
1115 {
1116         struct mdt_object       *dobj;
1117         struct mdt_lock_handle  *dlh;
1118         int                      rc;
1119         ENTRY;
1120
1121         if (!mdt_object_exists(obj))
1122                 GOTO(out, rc = -ENOENT);
1123
1124         /* we already have layout lock on obj so take only
1125          * on dfid */
1126         dlh = &mti->mti_lh[MDT_LH_OLD];
1127         mdt_lock_reg_init(dlh, LCK_EX);
1128         dobj = mdt_object_find_lock(mti, dfid, dlh, MDS_INODELOCK_LAYOUT);
1129         if (IS_ERR(dobj))
1130                 GOTO(out, rc = PTR_ERR(dobj));
1131
1132         /* if copy tool closes the volatile before sending the final
1133          * progress through llapi_hsm_copy_end(), all the objects
1134          * are removed and mdd_swap_layout LBUG */
1135         if (!mdt_object_exists(dobj)) {
1136                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1137                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1138                 GOTO(out_dobj, rc = -ENOENT);
1139         }
1140         /* Since we only handle restores here, unconditionally use
1141          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1142          * be preserved in case of failure during swap_layout and not
1143          * leave a file in an intermediate but incoherent state.
1144          * But need to setup HSM xattr of data FID before, reuse
1145          * mti and mh presets for FID in hsm_cdt_request_completed(),
1146          * only need to clear RELEASED and DIRTY.
1147          */
1148         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1149         rc = mdt_hsm_attr_set(mti, dobj, mh_common);
1150         if (rc == 0)
1151                 rc = mo_swap_layouts(mti->mti_env,
1152                                      mdt_object_child(obj),
1153                                      mdt_object_child(dobj),
1154                                      SWAP_LAYOUTS_MDS_HSM);
1155
1156 out_dobj:
1157         mdt_object_unlock_put(mti, dobj, dlh, 1);
1158 out:
1159         RETURN(rc);
1160 }
1161
1162 /**
1163  * update status of a completed request
1164  * \param mti [IN] context
1165  * \param pgs [IN] progress of the copy tool
1166  * \param update_record [IN] update llog record
1167  * \retval 0 success
1168  * \retval -ve failure
1169  */
1170 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1171                                      struct hsm_progress_kernel *pgs,
1172                                      const struct cdt_agent_req *car,
1173                                      enum agent_req_status *status)
1174 {
1175         const struct lu_env     *env = mti->mti_env;
1176         struct mdt_device       *mdt = mti->mti_mdt;
1177         struct coordinator      *cdt = &mdt->mdt_coordinator;
1178         struct mdt_object       *obj = NULL;
1179         int                      cl_flags = 0, rc = 0;
1180         struct md_hsm            mh;
1181         bool                     is_mh_changed;
1182         bool                     need_changelog = true;
1183         ENTRY;
1184
1185         /* default is to retry */
1186         *status = ARS_WAITING;
1187
1188         /* find object by FID, mdt_hsm_get_md_hsm() returns obj or err
1189          * if error/removed continue anyway to get correct reporting done */
1190         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1191         /* we will update MD HSM only if needed */
1192         is_mh_changed = false;
1193
1194         /* no need to change mh->mh_arch_id
1195          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1196          */
1197         if (pgs->hpk_errval != 0) {
1198                 switch (pgs->hpk_errval) {
1199                 case ENOSYS:
1200                         /* the copy tool does not support cancel
1201                          * so the cancel request is failed
1202                          * As we cannot distinguish a cancel progress
1203                          * from another action progress (they have the
1204                          * same cookie), we suppose here the CT returns
1205                          * ENOSYS only if does not support cancel
1206                          */
1207                         /* this can also happen when cdt calls it to
1208                          * for a timed out request */
1209                         *status = ARS_FAILED;
1210                         /* to have a cancel event in changelog */
1211                         pgs->hpk_errval = ECANCELED;
1212                         break;
1213                 case ECANCELED:
1214                         /* the request record has already been set to
1215                          * ARS_CANCELED, this set the cancel request
1216                          * to ARS_SUCCEED */
1217                         *status = ARS_SUCCEED;
1218                         break;
1219                 default:
1220                         /* retry only if current policy or requested, and
1221                          * object is not on error/removed */
1222                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1223                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ||
1224                                    IS_ERR(obj)) ? ARS_FAILED : ARS_WAITING;
1225                         break;
1226                 }
1227
1228                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1229                         CERROR("%s: Request %#llx on "DFID
1230                                " failed, error code %d too large\n",
1231                                mdt_obd_name(mdt),
1232                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1233                                pgs->hpk_errval);
1234                         hsm_set_cl_error(&cl_flags,
1235                                          CLF_HSM_ERROVERFLOW);
1236                         rc = -EINVAL;
1237                 } else {
1238                         hsm_set_cl_error(&cl_flags, pgs->hpk_errval);
1239                 }
1240
1241                 switch (car->car_hai->hai_action) {
1242                 case HSMA_ARCHIVE:
1243                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1244                         break;
1245                 case HSMA_RESTORE:
1246                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1247                         break;
1248                 case HSMA_REMOVE:
1249                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1250                         break;
1251                 case HSMA_CANCEL:
1252                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1253                         CERROR("%s: Failed request %#llx on "DFID
1254                                " cannot be a CANCEL\n",
1255                                mdt_obd_name(mdt),
1256                                pgs->hpk_cookie,
1257                                PFID(&pgs->hpk_fid));
1258                         break;
1259                 default:
1260                         CERROR("%s: Failed request %#llx on "DFID
1261                                " %d is an unknown action\n",
1262                                mdt_obd_name(mdt),
1263                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1264                                car->car_hai->hai_action);
1265                         rc = -EINVAL;
1266                         break;
1267                 }
1268         } else {
1269                 *status = ARS_SUCCEED;
1270                 switch (car->car_hai->hai_action) {
1271                 case HSMA_ARCHIVE:
1272                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1273                         /* set ARCHIVE keep EXIST and clear LOST and
1274                          * DIRTY */
1275                         mh.mh_arch_ver = pgs->hpk_data_version;
1276                         mh.mh_flags |= HS_ARCHIVED;
1277                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1278                         is_mh_changed = true;
1279                         break;
1280                 case HSMA_RESTORE:
1281                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1282
1283                         /* do not clear RELEASED and DIRTY here
1284                          * this will occur in hsm_swap_layouts()
1285                          */
1286
1287                         /* Restoring has changed the file version on
1288                          * disk. */
1289                         mh.mh_arch_ver = pgs->hpk_data_version;
1290                         is_mh_changed = true;
1291                         break;
1292                 case HSMA_REMOVE:
1293                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1294                         /* clear ARCHIVED EXISTS and LOST */
1295                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1296                         is_mh_changed = true;
1297                         break;
1298                 case HSMA_CANCEL:
1299                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1300                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1301                                mdt_obd_name(mdt),
1302                                pgs->hpk_cookie,
1303                                PFID(&pgs->hpk_fid));
1304                         break;
1305                 default:
1306                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1307                                mdt_obd_name(mdt),
1308                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1309                                car->car_hai->hai_action);
1310                         rc = -EINVAL;
1311                         break;
1312                 }
1313         }
1314
1315         /* rc != 0 means error when analysing action, it may come from
1316          * a crasy CT no need to manage DIRTY
1317          */
1318         if (rc == 0)
1319                 hsm_set_cl_flags(&cl_flags,
1320                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1321
1322         /* unlock is done later, after layout lock management */
1323         if (is_mh_changed && !IS_ERR(obj))
1324                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1325
1326         /* we give back layout lock only if restore was successful or
1327          * if no retry will be attempted and if object is still alive,
1328          * in other cases we just unlock the object */
1329         if (car->car_hai->hai_action == HSMA_RESTORE) {
1330                 struct cdt_restore_handle       *crh;
1331
1332                 /* restore in data FID done, we swap the layouts
1333                  * only if restore is successful */
1334                 if (pgs->hpk_errval == 0 && !IS_ERR(obj)) {
1335                         rc = hsm_swap_layouts(mti, obj, &car->car_hai->hai_dfid,
1336                                               &mh);
1337                         if (rc) {
1338                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1339                                         *status = ARS_FAILED;
1340                                 pgs->hpk_errval = -rc;
1341                         }
1342                 }
1343                 /* we have to retry, so keep layout lock */
1344                 if (*status == ARS_WAITING)
1345                         GOTO(out, rc);
1346
1347                 /* restore special case, need to create ChangeLog record
1348                  * before to give back layout lock to avoid concurrent
1349                  * file updater to post out of order ChangeLog */
1350                 mo_changelog(env, CL_HSM, cl_flags, mdt->mdt_child,
1351                              &car->car_hai->hai_fid);
1352                 need_changelog = false;
1353
1354                 /* give back layout lock */
1355                 mutex_lock(&cdt->cdt_restore_lock);
1356                 crh = mdt_hsm_restore_hdl_find(cdt, &car->car_hai->hai_fid);
1357                 if (crh != NULL)
1358                         list_del(&crh->crh_list);
1359                 mutex_unlock(&cdt->cdt_restore_lock);
1360                 /* Just give back layout lock, we keep the reference
1361                  * which is given back later with the lock for HSM
1362                  * flags.
1363                  * XXX obj may be invalid so we do not pass it. */
1364                 if (crh != NULL)
1365                         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
1366
1367                 if (crh != NULL)
1368                         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
1369         }
1370
1371         GOTO(out, rc);
1372
1373 out:
1374         /* always add a ChangeLog record */
1375         if (need_changelog)
1376                 mo_changelog(env, CL_HSM, cl_flags, mdt->mdt_child,
1377                              &car->car_hai->hai_fid);
1378
1379         if (!IS_ERR(obj))
1380                 mdt_object_put(mti->mti_env, obj);
1381
1382         RETURN(rc);
1383 }
1384
1385 /**
1386  * update status of a request
1387  * \param mti [IN] context
1388  * \param pgs [IN] progress of the copy tool
1389  * \param update_record [IN] update llog record
1390  * \retval 0 success
1391  * \retval -ve failure
1392  */
1393 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1394                                  struct hsm_progress_kernel *pgs,
1395                                  const int update_record)
1396 {
1397         struct mdt_device       *mdt = mti->mti_mdt;
1398         struct coordinator      *cdt = &mdt->mdt_coordinator;
1399         struct cdt_agent_req    *car;
1400         int                      rc = 0;
1401         ENTRY;
1402
1403         /* no coordinator started, so we cannot serve requests */
1404         if (cdt->cdt_state == CDT_STOPPED)
1405                 RETURN(-EAGAIN);
1406
1407         /* first do sanity checks */
1408         car = mdt_cdt_update_request(cdt, pgs);
1409         if (IS_ERR(car)) {
1410                 CERROR("%s: Cannot find running request for cookie %#llx"
1411                        " on fid="DFID"\n",
1412                        mdt_obd_name(mdt),
1413                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1414
1415                 RETURN(PTR_ERR(car));
1416         }
1417
1418         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1419                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1420                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1421                       hsm_copytool_action2name(car->car_hai->hai_action),
1422                       pgs->hpk_flags, pgs->hpk_errval,
1423                       PFID(&car->car_hai->hai_fid),
1424                       PFID(&car->car_hai->hai_dfid));
1425
1426         /* progress is done on FID or data FID depending of the action and
1427          * of the copy progress */
1428         /* for restore progress is used to send back the data FID to cdt */
1429         if (car->car_hai->hai_action == HSMA_RESTORE &&
1430             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1431                 car->car_hai->hai_dfid = pgs->hpk_fid;
1432
1433         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1434              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1435             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1436              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1437                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1438                        " does not match request FID "DFID" nor data FID "
1439                        DFID"\n",
1440                        mdt_obd_name(mdt),
1441                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1442                        PFID(&car->car_hai->hai_fid),
1443                        PFID(&car->car_hai->hai_dfid));
1444                 GOTO(out, rc = -EINVAL);
1445         }
1446
1447         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1448                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1449                        " is not coherent (err=%d and not completed"
1450                        " (flags=%d))\n",
1451                        mdt_obd_name(mdt),
1452                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1453                        hsm_copytool_action2name(car->car_hai->hai_action),
1454                        pgs->hpk_errval, pgs->hpk_flags);
1455                 GOTO(out, rc = -EINVAL);
1456         }
1457
1458         /* now progress is valid */
1459
1460         /* we use a root like ucred */
1461         hsm_init_ucred(mdt_ucred(mti));
1462
1463         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1464                 enum agent_req_status    status;
1465
1466                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1467
1468                 CDEBUG(D_HSM, "%s record: fid="DFID" cookie=%#llx action=%s "
1469                               "status=%s\n",
1470                        update_record ? "Updating" : "Not updating",
1471                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1472                        hsm_copytool_action2name(car->car_hai->hai_action),
1473                        agent_req_status2name(status));
1474
1475                 /* update record first (LU-9075) */
1476                 if (update_record) {
1477                         int rc1;
1478
1479                         rc1 = mdt_agent_record_update(mti->mti_env, mdt,
1480                                                      &pgs->hpk_cookie, 1,
1481                                                      status);
1482                         if (rc1)
1483                                 CERROR("%s: mdt_agent_record_update() failed,"
1484                                        " rc=%d, cannot update status to %s"
1485                                        " for cookie %#llx\n",
1486                                        mdt_obd_name(mdt), rc1,
1487                                        agent_req_status2name(status),
1488                                        pgs->hpk_cookie);
1489                         rc = (rc != 0 ? rc : rc1);
1490                 }
1491
1492                 /* then remove request from memory list (LU-9075) */
1493                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1494
1495                 /* ct has completed a request, so a slot is available, wakeup
1496                  * cdt to find new work */
1497                 mdt_hsm_cdt_wakeup(mdt);
1498         } else {
1499                 /* if copytool send a progress on a canceled request
1500                  * we inform copytool it should stop
1501                  */
1502                 if (car->car_canceled == 1)
1503                         rc = -ECANCELED;
1504         }
1505         GOTO(out, rc);
1506
1507 out:
1508         /* remove ref got from mdt_cdt_update_request() */
1509         mdt_cdt_put_request(car);
1510
1511         return rc;
1512 }
1513
1514
1515 /**
1516  * data passed to llog_cat_process() callback
1517  * to cancel requests
1518  */
1519 struct hsm_cancel_all_data {
1520         struct mdt_device       *mdt;
1521 };
1522
1523 /**
1524  *  llog_cat_process() callback, used to:
1525  *  - purge all requests
1526  * \param env [IN] environment
1527  * \param llh [IN] llog handle
1528  * \param hdr [IN] llog record
1529  * \param data [IN] cb data = struct hsm_cancel_all_data
1530  * \retval 0 success
1531  * \retval -ve failure
1532  */
1533 static int mdt_cancel_all_cb(const struct lu_env *env,
1534                              struct llog_handle *llh,
1535                              struct llog_rec_hdr *hdr, void *data)
1536 {
1537         struct llog_agent_req_rec       *larr;
1538         struct hsm_cancel_all_data      *hcad;
1539         int                              rc = 0;
1540         ENTRY;
1541
1542         larr = (struct llog_agent_req_rec *)hdr;
1543         hcad = data;
1544         if (larr->arr_status == ARS_WAITING ||
1545             larr->arr_status == ARS_STARTED) {
1546                 larr->arr_status = ARS_CANCELED;
1547                 larr->arr_req_change = cfs_time_current_sec();
1548                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
1549         }
1550
1551         RETURN(rc);
1552 }
1553
1554 /**
1555  * cancel all actions
1556  * \param obd [IN] MDT device
1557  */
1558 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1559 {
1560         struct lu_env                    env;
1561         struct lu_context                session;
1562         struct mdt_thread_info          *mti;
1563         struct coordinator              *cdt = &mdt->mdt_coordinator;
1564         struct cdt_agent_req            *car;
1565         struct hsm_action_list          *hal = NULL;
1566         struct hsm_action_item          *hai;
1567         struct hsm_cancel_all_data       hcad;
1568         int                              hal_sz = 0, hal_len, rc;
1569         enum cdt_states                  save_state;
1570         ENTRY;
1571
1572         rc = lu_env_init(&env, LCT_MD_THREAD);
1573         if (rc < 0)
1574                 RETURN(rc);
1575
1576         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1577         rc = lu_context_init(&session, LCT_SERVER_SESSION);
1578         if (rc < 0)
1579                 GOTO(out_env, rc);
1580
1581         lu_context_enter(&session);
1582         env.le_ses = &session;
1583
1584         mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
1585         LASSERT(mti != NULL);
1586
1587         mti->mti_env = &env;
1588         mti->mti_mdt = mdt;
1589
1590         hsm_init_ucred(mdt_ucred(mti));
1591
1592         /* disable coordinator */
1593         save_state = cdt->cdt_state;
1594         cdt->cdt_state = CDT_DISABLE;
1595
1596         /* send cancel to all running requests */
1597         down_read(&cdt->cdt_request_lock);
1598         list_for_each_entry(car, &cdt->cdt_request_list, car_request_list) {
1599                 mdt_cdt_get_request(car);
1600                 /* request is not yet removed from list, it will be done
1601                  * when copytool will return progress
1602                  */
1603
1604                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1605                         mdt_cdt_put_request(car);
1606                         continue;
1607                 }
1608
1609                 /* needed size */
1610                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1611                           cfs_size_round(car->car_hai->hai_len);
1612
1613                 if (hal_len > hal_sz && hal_sz > 0) {
1614                         /* not enough room, free old buffer */
1615                         OBD_FREE(hal, hal_sz);
1616                         hal = NULL;
1617                 }
1618
1619                 /* empty buffer, allocate one */
1620                 if (hal == NULL) {
1621                         hal_sz = hal_len;
1622                         OBD_ALLOC(hal, hal_sz);
1623                         if (hal == NULL) {
1624                                 mdt_cdt_put_request(car);
1625                                 up_read(&cdt->cdt_request_lock);
1626                                 GOTO(out_cdt_state, rc = -ENOMEM);
1627                         }
1628                 }
1629
1630                 hal->hal_version = HAL_VERSION;
1631                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1632                                 MTI_NAME_MAXLEN);
1633                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1634                 hal->hal_compound_id = car->car_compound_id;
1635                 hal->hal_archive_id = car->car_archive_id;
1636                 hal->hal_flags = car->car_flags;
1637                 hal->hal_count = 0;
1638
1639                 hai = hai_first(hal);
1640                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1641                 hai->hai_action = HSMA_CANCEL;
1642                 hal->hal_count = 1;
1643
1644                 /* it is possible to safely call mdt_hsm_agent_send()
1645                  * (ie without a deadlock on cdt_request_lock), because the
1646                  * write lock is taken only if we are not in purge mode
1647                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1648                  *   nor mdt_cdt_remove_request())
1649                  */
1650                 /* no conflict with cdt thread because cdt is disable and we
1651                  * have the request lock */
1652                 mdt_hsm_agent_send(mti, hal, 1);
1653
1654                 mdt_cdt_put_request(car);
1655         }
1656         up_read(&cdt->cdt_request_lock);
1657
1658         if (hal != NULL)
1659                 OBD_FREE(hal, hal_sz);
1660
1661         /* cancel all on-disk records */
1662         hcad.mdt = mdt;
1663
1664         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
1665                               mdt_cancel_all_cb, &hcad);
1666 out_cdt_state:
1667         /* enable coordinator */
1668         cdt->cdt_state = save_state;
1669         lu_context_exit(&session);
1670         lu_context_fini(&session);
1671 out_env:
1672         lu_env_fini(&env);
1673
1674         RETURN(rc);
1675 }
1676
1677 /**
1678  * check if a request is compatible with file status
1679  * \param hai [IN] request description
1680  * \param archive_id [IN] request archive id
1681  * \param rq_flags [IN] request flags
1682  * \param hsm [IN] file HSM metadata
1683  * \retval boolean
1684  */
1685 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1686                               u32 archive_id, u64 rq_flags,
1687                               const struct md_hsm *hsm)
1688 {
1689         int      is_compat = false;
1690         int      hsm_flags;
1691         ENTRY;
1692
1693         hsm_flags = hsm->mh_flags;
1694         switch (hai->hai_action) {
1695         case HSMA_ARCHIVE:
1696                 if (!(hsm_flags & HS_NOARCHIVE) &&
1697                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1698                         is_compat = true;
1699
1700                 if (hsm_flags & HS_EXISTS &&
1701                     archive_id != 0 &&
1702                     archive_id != hsm->mh_arch_id)
1703                         is_compat = false;
1704
1705                 break;
1706         case HSMA_RESTORE:
1707                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1708                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1709                         is_compat = true;
1710                 break;
1711         case HSMA_REMOVE:
1712                 if (!(hsm_flags & HS_RELEASED) &&
1713                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1714                         is_compat = true;
1715                 break;
1716         case HSMA_CANCEL:
1717                 is_compat = true;
1718                 break;
1719         }
1720         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
1721                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
1722                       PFID(&hai->hai_fid),
1723                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1724                       hai->hai_extent.offset, hai->hai_extent.length,
1725                       hsm->mh_flags,
1726                       (is_compat ? "compatible" : "uncompatible"));
1727
1728         RETURN(is_compat);
1729 }
1730
1731 /*
1732  * /proc interface used to get/set HSM behaviour (cdt->cdt_policy)
1733  */
1734 static const struct {
1735         __u64            bit;
1736         char            *name;
1737         char            *nickname;
1738 } hsm_policy_names[] = {
1739         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1740         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1741         { 0 },
1742 };
1743
1744 /**
1745  * convert a policy name to a bit
1746  * \param name [IN] policy name
1747  * \retval 0 unknown
1748  * \retval   policy bit
1749  */
1750 static __u64 hsm_policy_str2bit(const char *name)
1751 {
1752         int      i;
1753
1754         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1755                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1756                     strcmp(hsm_policy_names[i].name, name) == 0)
1757                         return hsm_policy_names[i].bit;
1758         return 0;
1759 }
1760
1761 /**
1762  * convert a policy bit field to a string
1763  * \param mask [IN] policy bit field
1764  * \param hexa [IN] print mask before bit names
1765  * \param buffer [OUT] string
1766  * \param count [IN] size of buffer
1767  */
1768 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
1769                                 const bool hexa)
1770 {
1771         int      i, j;
1772         __u64    bit;
1773         ENTRY;
1774
1775         if (hexa)
1776                 seq_printf(m, "(%#llx) ", mask);
1777
1778         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1779                 bit = (1ULL << i);
1780
1781                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1782                         if (hsm_policy_names[j].bit == bit)
1783                                 break;
1784                 }
1785                 if (bit & mask)
1786                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
1787                 else
1788                         seq_printf(m, "%s ", hsm_policy_names[j].name);
1789         }
1790         /* remove last ' ' */
1791         m->count--;
1792         seq_putc(m, '\n');
1793 }
1794
1795 /* methods to read/write HSM policy flags */
1796 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
1797 {
1798         struct mdt_device       *mdt = m->private;
1799         struct coordinator      *cdt = &mdt->mdt_coordinator;
1800         ENTRY;
1801
1802         hsm_policy_bit2str(m, cdt->cdt_policy, false);
1803         RETURN(0);
1804 }
1805
1806 static ssize_t
1807 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
1808                          size_t count, loff_t *off)
1809 {
1810         struct seq_file         *m = file->private_data;
1811         struct mdt_device       *mdt = m->private;
1812         struct coordinator      *cdt = &mdt->mdt_coordinator;
1813         char                    *start, *token, sign;
1814         char                    *buf;
1815         __u64                    policy;
1816         __u64                    add_mask, remove_mask, set_mask;
1817         int                      rc;
1818         ENTRY;
1819
1820         if (count + 1 > PAGE_SIZE)
1821                 RETURN(-EINVAL);
1822
1823         OBD_ALLOC(buf, count + 1);
1824         if (buf == NULL)
1825                 RETURN(-ENOMEM);
1826
1827         if (copy_from_user(buf, buffer, count))
1828                 GOTO(out, rc = -EFAULT);
1829
1830         buf[count] = '\0';
1831
1832         start = buf;
1833         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
1834                start);
1835
1836         add_mask = remove_mask = set_mask = 0;
1837         do {
1838                 token = strsep(&start, "\n ");
1839                 sign = *token;
1840
1841                 if (sign == '\0')
1842                         continue;
1843
1844                 if (sign == '-' || sign == '+')
1845                         token++;
1846
1847                 policy = hsm_policy_str2bit(token);
1848                 if (policy == 0) {
1849                         CWARN("%s: '%s' is unknown, "
1850                               "supported policies are:\n", mdt_obd_name(mdt),
1851                               token);
1852                         hsm_policy_bit2str(m, 0, false);
1853                         GOTO(out, rc = -EINVAL);
1854                 }
1855                 switch (sign) {
1856                 case '-':
1857                         remove_mask |= policy;
1858                         break;
1859                 case '+':
1860                         add_mask |= policy;
1861                         break;
1862                 default:
1863                         set_mask |= policy;
1864                         break;
1865                 }
1866
1867         } while (start != NULL);
1868
1869         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
1870                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
1871
1872         /* if no sign in all string, it is a clear and set
1873          * if some sign found, all unsigned are converted
1874          * to add
1875          * P1 P2 = set to P1 and P2
1876          * P1 -P2 = add P1 clear P2 same as +P1 -P2
1877          */
1878         if (remove_mask == 0 && add_mask == 0) {
1879                 cdt->cdt_policy = set_mask;
1880         } else {
1881                 cdt->cdt_policy |= set_mask | add_mask;
1882                 cdt->cdt_policy &= ~remove_mask;
1883         }
1884
1885         GOTO(out, rc = count);
1886
1887 out:
1888         OBD_FREE(buf, count + 1);
1889         RETURN(rc);
1890 }
1891 LPROC_SEQ_FOPS(mdt_hsm_policy);
1892
1893 #define GENERATE_PROC_METHOD(VAR)                                       \
1894 static int mdt_hsm_##VAR##_seq_show(struct seq_file *m, void *data)     \
1895 {                                                                       \
1896         struct mdt_device       *mdt = m->private;                      \
1897         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1898         ENTRY;                                                          \
1899                                                                         \
1900         seq_printf(m, "%llu\n", (__u64)cdt->VAR);                       \
1901         RETURN(0);                                                      \
1902 }                                                                       \
1903 static ssize_t                                                          \
1904 mdt_hsm_##VAR##_seq_write(struct file *file, const char __user *buffer, \
1905                           size_t count, loff_t *off)                    \
1906                                                                         \
1907 {                                                                       \
1908         struct seq_file         *m = file->private_data;                \
1909         struct mdt_device       *mdt = m->private;                      \
1910         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1911         __s64                    val;                                   \
1912         int                      rc;                                    \
1913         ENTRY;                                                          \
1914                                                                         \
1915         rc = lprocfs_str_to_s64(buffer, count, &val);                   \
1916         if (rc)                                                         \
1917                 RETURN(rc);                                             \
1918         if (val > 0 && val < INT_MAX) {                                 \
1919                 cdt->VAR = val;                                         \
1920                 RETURN(count);                                          \
1921         }                                                               \
1922         RETURN(-EINVAL);                                                \
1923 }                                                                       \
1924
1925 GENERATE_PROC_METHOD(cdt_loop_period)
1926 GENERATE_PROC_METHOD(cdt_grace_delay)
1927 GENERATE_PROC_METHOD(cdt_active_req_timeout)
1928 GENERATE_PROC_METHOD(cdt_max_requests)
1929 GENERATE_PROC_METHOD(cdt_default_archive_id)
1930
1931 /*
1932  * procfs write method for MDT/hsm_control
1933  * proc entry is in mdt directory so data is mdt obd_device pointer
1934  */
1935 #define CDT_ENABLE_CMD   "enabled"
1936 #define CDT_STOP_CMD     "shutdown"
1937 #define CDT_DISABLE_CMD  "disabled"
1938 #define CDT_PURGE_CMD    "purge"
1939 #define CDT_HELP_CMD     "help"
1940 #define CDT_MAX_CMD_LEN  10
1941
1942 ssize_t
1943 mdt_hsm_cdt_control_seq_write(struct file *file, const char __user *buffer,
1944                               size_t count, loff_t *off)
1945 {
1946         struct seq_file         *m = file->private_data;
1947         struct obd_device       *obd = m->private;
1948         struct mdt_device       *mdt = mdt_dev(obd->obd_lu_dev);
1949         struct coordinator      *cdt = &(mdt->mdt_coordinator);
1950         int                      rc, usage = 0;
1951         char                     kernbuf[CDT_MAX_CMD_LEN];
1952         ENTRY;
1953
1954         if (count == 0 || count >= sizeof(kernbuf))
1955                 RETURN(-EINVAL);
1956
1957         if (copy_from_user(kernbuf, buffer, count))
1958                 RETURN(-EFAULT);
1959         kernbuf[count] = 0;
1960
1961         if (kernbuf[count - 1] == '\n')
1962                 kernbuf[count - 1] = 0;
1963
1964         rc = 0;
1965         if (strcmp(kernbuf, CDT_ENABLE_CMD) == 0) {
1966                 if (cdt->cdt_state == CDT_DISABLE) {
1967                         cdt->cdt_state = CDT_RUNNING;
1968                         mdt_hsm_cdt_wakeup(mdt);
1969                 } else {
1970                         rc = mdt_hsm_cdt_start(mdt);
1971                 }
1972         } else if (strcmp(kernbuf, CDT_STOP_CMD) == 0) {
1973                 if ((cdt->cdt_state == CDT_STOPPING) ||
1974                     (cdt->cdt_state == CDT_STOPPED)) {
1975                         CERROR("%s: Coordinator already stopped\n",
1976                                mdt_obd_name(mdt));
1977                         rc = -EALREADY;
1978                 } else {
1979                         cdt->cdt_state = CDT_STOPPING;
1980                         mdt_hsm_cdt_wakeup(mdt);
1981                 }
1982         } else if (strcmp(kernbuf, CDT_DISABLE_CMD) == 0) {
1983                 if ((cdt->cdt_state == CDT_STOPPING) ||
1984                     (cdt->cdt_state == CDT_STOPPED)) {
1985                         CERROR("%s: Coordinator is stopped\n",
1986                                mdt_obd_name(mdt));
1987                         rc = -EINVAL;
1988                 } else {
1989                         cdt->cdt_state = CDT_DISABLE;
1990                 }
1991         } else if (strcmp(kernbuf, CDT_PURGE_CMD) == 0) {
1992                 rc = hsm_cancel_all_actions(mdt);
1993         } else if (strcmp(kernbuf, CDT_HELP_CMD) == 0) {
1994                 usage = 1;
1995         } else {
1996                 usage = 1;
1997                 rc = -EINVAL;
1998         }
1999
2000         if (usage == 1)
2001                 CERROR("%s: Valid coordinator control commands are: "
2002                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2003                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2004                        CDT_PURGE_CMD, CDT_HELP_CMD);
2005
2006         if (rc)
2007                 RETURN(rc);
2008
2009         RETURN(count);
2010 }
2011
2012 int mdt_hsm_cdt_control_seq_show(struct seq_file *m, void *data)
2013 {
2014         struct obd_device       *obd = m->private;
2015         struct coordinator      *cdt;
2016         ENTRY;
2017
2018         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2019
2020         if (cdt->cdt_state == CDT_INIT)
2021                 seq_printf(m, "init\n");
2022         else if (cdt->cdt_state == CDT_RUNNING)
2023                 seq_printf(m, "enabled\n");
2024         else if (cdt->cdt_state == CDT_STOPPING)
2025                 seq_printf(m, "stopping\n");
2026         else if (cdt->cdt_state == CDT_STOPPED)
2027                 seq_printf(m, "stopped\n");
2028         else if (cdt->cdt_state == CDT_DISABLE)
2029                 seq_printf(m, "disabled\n");
2030         else
2031                 seq_printf(m, "unknown\n");
2032
2033         RETURN(0);
2034 }
2035
2036 static int
2037 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
2038 {
2039         bool first = true;
2040         int i;
2041         ENTRY;
2042
2043         for (i = 0; i < 8 * sizeof(mask); i++) {
2044                 if (mask & (1UL << i)) {
2045                         seq_printf(m, "%s%s", first ? "" : " ",
2046                                    hsm_copytool_action2name(i));
2047                         first = false;
2048                 }
2049         }
2050         seq_putc(m, '\n');
2051
2052         RETURN(0);
2053 }
2054
2055 static int
2056 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2057 {
2058         struct mdt_device *mdt = m->private;
2059         struct coordinator *cdt = &mdt->mdt_coordinator;
2060
2061         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2062 }
2063
2064 static int
2065 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2066 {
2067         struct mdt_device *mdt = m->private;
2068         struct coordinator *cdt = &mdt->mdt_coordinator;
2069
2070         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2071 }
2072
2073 static int
2074 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2075 {
2076         struct mdt_device *mdt = m->private;
2077         struct coordinator *cdt = &mdt->mdt_coordinator;
2078
2079         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2080 }
2081
2082 static inline enum hsm_copytool_action
2083 hsm_copytool_name2action(const char *name)
2084 {
2085         if (strcasecmp(name, "NOOP") == 0)
2086                 return HSMA_NONE;
2087         else if (strcasecmp(name, "ARCHIVE") == 0)
2088                 return HSMA_ARCHIVE;
2089         else if (strcasecmp(name, "RESTORE") == 0)
2090                 return HSMA_RESTORE;
2091         else if (strcasecmp(name, "REMOVE") == 0)
2092                 return HSMA_REMOVE;
2093         else if (strcasecmp(name, "CANCEL") == 0)
2094                 return HSMA_CANCEL;
2095         else
2096                 return -1;
2097 }
2098
2099 static ssize_t
2100 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2101                             size_t user_count, __u64 *mask)
2102 {
2103         char *buf, *pos, *name;
2104         size_t buf_size;
2105         __u64 new_mask = 0;
2106         int rc;
2107         ENTRY;
2108
2109         if (!(user_count < 4096))
2110                 RETURN(-ENOMEM);
2111
2112         buf_size = user_count + 1;
2113
2114         OBD_ALLOC(buf, buf_size);
2115         if (buf == NULL)
2116                 RETURN(-ENOMEM);
2117
2118         if (copy_from_user(buf, user_buf, buf_size - 1))
2119                 GOTO(out, rc = -EFAULT);
2120
2121         buf[buf_size - 1] = '\0';
2122
2123         pos = buf;
2124         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2125                 int action;
2126
2127                 if (*name == '\0')
2128                         continue;
2129
2130                 action = hsm_copytool_name2action(name);
2131                 if (action < 0)
2132                         GOTO(out, rc = -EINVAL);
2133
2134                 new_mask |= (1UL << action);
2135         }
2136
2137         *mask = new_mask;
2138         rc = user_count;
2139 out:
2140         OBD_FREE(buf, buf_size);
2141
2142         RETURN(rc);
2143 }
2144
2145 static ssize_t
2146 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2147                                         size_t count, loff_t *off)
2148 {
2149         struct seq_file         *m = file->private_data;
2150         struct mdt_device       *mdt = m->private;
2151         struct coordinator *cdt = &mdt->mdt_coordinator;
2152
2153         return mdt_write_hsm_request_mask(file, buf, count,
2154                                            &cdt->cdt_user_request_mask);
2155 }
2156
2157 static ssize_t
2158 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2159                                         size_t count, loff_t *off)
2160 {
2161         struct seq_file         *m = file->private_data;
2162         struct mdt_device       *mdt = m->private;
2163         struct coordinator      *cdt = &mdt->mdt_coordinator;
2164
2165         return mdt_write_hsm_request_mask(file, buf, count,
2166                                            &cdt->cdt_group_request_mask);
2167 }
2168
2169 static ssize_t
2170 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2171                                         size_t count, loff_t *off)
2172 {
2173         struct seq_file         *m = file->private_data;
2174         struct mdt_device       *mdt = m->private;
2175         struct coordinator      *cdt = &mdt->mdt_coordinator;
2176
2177         return mdt_write_hsm_request_mask(file, buf, count,
2178                                            &cdt->cdt_other_request_mask);
2179 }
2180
2181 LPROC_SEQ_FOPS(mdt_hsm_cdt_loop_period);
2182 LPROC_SEQ_FOPS(mdt_hsm_cdt_grace_delay);
2183 LPROC_SEQ_FOPS(mdt_hsm_cdt_active_req_timeout);
2184 LPROC_SEQ_FOPS(mdt_hsm_cdt_max_requests);
2185 LPROC_SEQ_FOPS(mdt_hsm_cdt_default_archive_id);
2186 LPROC_SEQ_FOPS(mdt_hsm_user_request_mask);
2187 LPROC_SEQ_FOPS(mdt_hsm_group_request_mask);
2188 LPROC_SEQ_FOPS(mdt_hsm_other_request_mask);
2189
2190 static struct lprocfs_vars lprocfs_mdt_hsm_vars[] = {
2191         { .name =       "agents",
2192           .fops =       &mdt_hsm_agent_fops                     },
2193         { .name =       "actions",
2194           .fops =       &mdt_hsm_actions_fops,
2195           .proc_mode =  0444                                    },
2196         { .name =       "default_archive_id",
2197           .fops =       &mdt_hsm_cdt_default_archive_id_fops    },
2198         { .name =       "grace_delay",
2199           .fops =       &mdt_hsm_cdt_grace_delay_fops           },
2200         { .name =       "loop_period",
2201           .fops =       &mdt_hsm_cdt_loop_period_fops           },
2202         { .name =       "max_requests",
2203           .fops =       &mdt_hsm_cdt_max_requests_fops          },
2204         { .name =       "policy",
2205           .fops =       &mdt_hsm_policy_fops                    },
2206         { .name =       "active_request_timeout",
2207           .fops =       &mdt_hsm_cdt_active_req_timeout_fops    },
2208         { .name =       "active_requests",
2209           .fops =       &mdt_hsm_active_requests_fops           },
2210         { .name =       "user_request_mask",
2211           .fops =       &mdt_hsm_user_request_mask_fops,        },
2212         { .name =       "group_request_mask",
2213           .fops =       &mdt_hsm_group_request_mask_fops,       },
2214         { .name =       "other_request_mask",
2215           .fops =       &mdt_hsm_other_request_mask_fops,       },
2216         { 0 }
2217 };