Whamcloud - gitweb
LU-10212 test: ESTALE read
[fs/lustre-release.git] / lustre / utils / liblustreapi_hsm.c
1 /*
2  * LGPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * (C) Copyright 2012 Commissariat a l'energie atomique et aux energies
7  *     alternatives
8  *
9  * Copyright (c) 2013, 2016, Intel Corporation.
10  *
11  * All rights reserved. This program and the accompanying materials
12  * are made available under the terms of the GNU Lesser General Public License
13  * (LGPL) version 2.1 or (at your discretion) any later version.
14  * (LGPL) version 2.1 accompanies this distribution, and is available at
15  * http://www.gnu.org/licenses/lgpl-2.1.html
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20  * Lesser General Public License for more details.
21  *
22  * LGPL HEADER END
23  */
24 /*
25  * lustre/utils/liblustreapi_hsm.c
26  *
27  * lustreapi library for hsm calls
28  *
29  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
30  * Author: JC Lafoucriere <jacques-charles.lafoucriere@cea.fr>
31  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
32  * Author: Henri Doreau <henri.doreau@cea.fr>
33  */
34
35 #include <fcntl.h>
36 #include <stdlib.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <stddef.h>
40 #include <sys/ioctl.h>
41 #include <unistd.h>
42 #include <malloc.h>
43 #include <errno.h>
44 #include <dirent.h>
45 #include <stdarg.h>
46 #include <sys/stat.h>
47 #include <sys/time.h>
48 #include <sys/types.h>
49 #include <time.h>
50 #include <utime.h>
51 #include <sys/syscall.h>
52 #include <fnmatch.h>
53 #include <signal.h>
54 #ifdef HAVE_LINUX_UNISTD_H
55 #include <linux/unistd.h>
56 #else
57 #include <unistd.h>
58 #endif
59
60 #include <lnet/lnetctl.h>
61 #include <lustre/lustre_idl.h>
62 #include <lustre/lustreapi.h>
63 #include "lustreapi_internal.h"
64
65 #define OPEN_BY_FID_PATH dot_lustre_name"/fid"
66
67 /****** HSM Copytool API ********/
68 #define CT_PRIV_MAGIC 0xC0BE2001
69 struct hsm_copytool_private {
70         int                      magic;
71         char                    *mnt;
72         struct kuc_hdr          *kuch;
73         int                      mnt_fd;
74         int                      open_by_fid_fd;
75         struct lustre_kernelcomm kuc;
76         __u32                    archives;
77 };
78
79 #define CP_PRIV_MAGIC 0x19880429
80 struct hsm_copyaction_private {
81         __u32                                    magic;
82         __u32                                    source_fd;
83         __s32                                    data_fd;
84         const struct hsm_copytool_private       *ct_priv;
85         struct hsm_copy                          copy;
86         lstat_t                                  stat;
87 };
88
89 enum ct_progress_type {
90         CT_START        = 0,
91         CT_RUNNING      = 50,
92         CT_FINISH       = 100,
93         CT_CANCEL       = 150,
94         CT_ERROR        = 175
95 };
96
97 enum ct_event {
98         CT_REGISTER             = 1,
99         CT_UNREGISTER           = 2,
100         CT_ARCHIVE_START        = HSMA_ARCHIVE,
101         CT_ARCHIVE_RUNNING      = HSMA_ARCHIVE + CT_RUNNING,
102         CT_ARCHIVE_FINISH       = HSMA_ARCHIVE + CT_FINISH,
103         CT_ARCHIVE_CANCEL       = HSMA_ARCHIVE + CT_CANCEL,
104         CT_ARCHIVE_ERROR        = HSMA_ARCHIVE + CT_ERROR,
105         CT_RESTORE_START        = HSMA_RESTORE,
106         CT_RESTORE_RUNNING      = HSMA_RESTORE + CT_RUNNING,
107         CT_RESTORE_FINISH       = HSMA_RESTORE + CT_FINISH,
108         CT_RESTORE_CANCEL       = HSMA_RESTORE + CT_CANCEL,
109         CT_RESTORE_ERROR        = HSMA_RESTORE + CT_ERROR,
110         CT_REMOVE_START         = HSMA_REMOVE,
111         CT_REMOVE_RUNNING       = HSMA_REMOVE + CT_RUNNING,
112         CT_REMOVE_FINISH        = HSMA_REMOVE + CT_FINISH,
113         CT_REMOVE_CANCEL        = HSMA_REMOVE + CT_CANCEL,
114         CT_REMOVE_ERROR         = HSMA_REMOVE + CT_ERROR,
115         CT_EVENT_MAX
116 };
117
118 /* initialized in llapi_hsm_register_event_fifo() */
119 static int llapi_hsm_event_fd = -1;
120 static bool created_hsm_event_fifo;
121
122 static inline const char *llapi_hsm_ct_ev2str(int type)
123 {
124         switch (type) {
125         case CT_REGISTER:
126                 return "REGISTER";
127         case CT_UNREGISTER:
128                 return "UNREGISTER";
129         case CT_ARCHIVE_START:
130                 return "ARCHIVE_START";
131         case CT_ARCHIVE_RUNNING:
132                 return "ARCHIVE_RUNNING";
133         case CT_ARCHIVE_FINISH:
134                 return "ARCHIVE_FINISH";
135         case CT_ARCHIVE_CANCEL:
136                 return "ARCHIVE_CANCEL";
137         case CT_ARCHIVE_ERROR:
138                 return "ARCHIVE_ERROR";
139         case CT_RESTORE_START:
140                 return "RESTORE_START";
141         case CT_RESTORE_RUNNING:
142                 return "RESTORE_RUNNING";
143         case CT_RESTORE_FINISH:
144                 return "RESTORE_FINISH";
145         case CT_RESTORE_CANCEL:
146                 return "RESTORE_CANCEL";
147         case CT_RESTORE_ERROR:
148                 return "RESTORE_ERROR";
149         case CT_REMOVE_START:
150                 return "REMOVE_START";
151         case CT_REMOVE_RUNNING:
152                 return "REMOVE_RUNNING";
153         case CT_REMOVE_FINISH:
154                 return "REMOVE_FINISH";
155         case CT_REMOVE_CANCEL:
156                 return "REMOVE_CANCEL";
157         case CT_REMOVE_ERROR:
158                 return "REMOVE_ERROR";
159         default:
160                 llapi_err_noerrno(LLAPI_MSG_ERROR,
161                                   "Unknown event type: %d", type);
162                 return NULL;
163         }
164 }
165
166 /**
167  * Writes a JSON event to the monitor FIFO. Noop if no FIFO has been
168  * registered.
169  *
170  * \param event              A list of llapi_json_items comprising a
171  *                           single JSON-formatted event.
172  *
173  * \retval 0 on success.
174  * \retval -errno on error.
175  */
176 static int llapi_hsm_write_json_event(struct llapi_json_item_list **event)
177 {
178         int                             rc;
179         char                            time_string[40];
180         char                            json_buf[PIPE_BUF];
181         FILE                            *buf_file;
182         time_t                          event_time = time(0);
183         struct tm                       time_components;
184         struct llapi_json_item_list     *json_items;
185
186         /* Noop unless the event fd was initialized */
187         if (llapi_hsm_event_fd < 0)
188                 return 0;
189
190         if (event == NULL || *event == NULL)
191                 return -EINVAL;
192
193         json_items = *event;
194
195         localtime_r(&event_time, &time_components);
196
197         if (strftime(time_string, sizeof(time_string), "%Y-%m-%d %T %z",
198                      &time_components) == 0) {
199                 rc = -EINVAL;
200                 llapi_error(LLAPI_MSG_ERROR, rc, "strftime() failed");
201                 return rc;
202         }
203
204         rc = llapi_json_add_item(&json_items, "event_time", LLAPI_JSON_STRING,
205                                  time_string);
206         if (rc < 0) {
207                 llapi_error(LLAPI_MSG_ERROR, -rc, "error in "
208                             "llapi_json_add_item()");
209                 return rc;
210         }
211
212         buf_file = fmemopen(json_buf, sizeof(json_buf), "w");
213         if (buf_file == NULL)
214                 return -errno;
215
216         rc = llapi_json_write_list(event, buf_file);
217         if (rc < 0) {
218                 fclose(buf_file);
219                 return rc;
220         }
221
222         fclose(buf_file);
223
224         if (write(llapi_hsm_event_fd, json_buf, strlen(json_buf)) < 0) {
225                 /* Ignore write failures due to missing reader. */
226                 if (errno != EPIPE)
227                         return -errno;
228         }
229
230         return 0;
231 }
232
233 /**
234  * Hook for llapi_hsm_copytool_register and llapi_hsm_copytool_unregister
235  * to generate JSON events suitable for consumption by a copytool
236  * monitoring process.
237  *
238  * \param priv               Opaque private control structure.
239  * \param event_type         The type of event (register or unregister).
240  *
241  * \retval 0 on success.
242  * \retval -errno on error.
243  */
244 static int llapi_hsm_log_ct_registration(struct hsm_copytool_private **priv,
245                                          __u32 event_type)
246 {
247         int                             rc;
248         char                            agent_uuid[UUID_MAX];
249         struct hsm_copytool_private     *ct;
250         struct llapi_json_item_list     *json_items;
251
252         /* Noop unless the event fd was initialized */
253         if (llapi_hsm_event_fd < 0)
254                 return 0;
255
256         if (priv == NULL || *priv == NULL)
257                 return -EINVAL;
258
259         ct = *priv;
260         if (ct->magic != CT_PRIV_MAGIC)
261                 return -EINVAL;
262
263         if (event_type != CT_REGISTER && event_type != CT_UNREGISTER)
264                 return -EINVAL;
265
266         rc = llapi_json_init_list(&json_items);
267         if (rc < 0)
268                 goto err;
269
270         rc = llapi_get_agent_uuid(ct->mnt, agent_uuid, sizeof(agent_uuid));
271         if (rc < 0)
272                 goto err;
273         llapi_chomp_string(agent_uuid);
274
275         rc = llapi_json_add_item(&json_items, "uuid", LLAPI_JSON_STRING,
276                                  agent_uuid);
277         if (rc < 0)
278                 goto err;
279
280         rc = llapi_json_add_item(&json_items, "mount_point", LLAPI_JSON_STRING,
281                                  ct->mnt);
282         if (rc < 0)
283                 goto err;
284
285         rc = llapi_json_add_item(&json_items, "archive", LLAPI_JSON_INTEGER,
286                                  &ct->archives);
287         if (rc < 0)
288                 goto err;
289
290         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
291                                  (char *)llapi_hsm_ct_ev2str(event_type));
292         if (rc < 0)
293                 goto err;
294
295         rc = llapi_hsm_write_json_event(&json_items);
296         if (rc < 0)
297                 goto err;
298
299         goto out_free;
300
301 err:
302         llapi_error(LLAPI_MSG_ERROR, rc, "error in "
303                     "llapi_hsm_log_ct_registration()");
304
305 out_free:
306         if (json_items != NULL)
307                 llapi_json_destroy_list(&json_items);
308
309         return rc;
310 }
311
312 /**
313  * Given a copytool progress update, construct a JSON event suitable for
314  * consumption by a copytool monitoring process.
315  *
316  * Examples of various events generated here and written by
317  * llapi_hsm_write_json_event:
318  *
319  * Copytool registration and deregistration:
320  * {"event_time": "2014-02-26 14:58:01 -0500", "event_type": "REGISTER",
321  *  "archive": 0, "mount_point": "/mnt/lustre",
322  *  "uuid": "80379a60-1f8a-743f-daf2-307cde793ec2"}
323  * {"event_time": "2014-02-26 14:58:01 -0500", "event_type": "UNREGISTER",
324  *  "archive": 0, "mount_point": "/mnt/lustre",
325  *  "uuid": "80379a60-1f8a-743f-daf2-307cde793ec2"}
326  *
327  * An archive action, start to completion:
328  * {"event_time": "2014-02-26 14:50:13 -0500", "event_type": "ARCHIVE_START",
329  *  "total_bytes": 0, "lustre_path": "d71.sanity-hsm/f71.sanity-hsm",
330  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
331  * {"event_time": "2014-02-26 14:50:18 -0500", "event_type": "ARCHIVE_RUNNING",
332  *  "current_bytes": 5242880, "total_bytes": 39000000,
333  *  "lustre_path": "d71.sanity-hsm/f71.sanity-hsm",
334  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
335  * {"event_time": "2014-02-26 14:50:50 -0500", "event_type": "ARCHIVE_FINISH",
336  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
337  *
338  * A log message:
339  * {"event_time": "2014-02-26 14:50:13 -0500", "event_type": "LOGGED_MESSAGE",
340  *  "level": "INFO",
341  *  "message": "lhsmtool_posix[42]: copytool fs=lustre archive#=2 item_count=1"}
342  *
343  * \param hcp                Opaque action handle returned by
344  *                           llapi_hsm_action_start.
345  * \param hai                The hsm_action_item describing the request.
346  * \param progress_type      The ct_progress_type describing the update.
347  * \param total              The total expected bytes for the request.
348  * \param current            The current copied byte count for the request.
349  *
350  * \retval 0 on success.
351  * \retval -errno on error.
352  */
353 static int llapi_hsm_log_ct_progress(struct hsm_copyaction_private **phcp,
354                                      const struct hsm_action_item *hai,
355                                      __u32 progress_type,
356                                      __u64 total, __u64 current)
357 {
358         int                             rc;
359         int                             linkno = 0;
360         long long                       recno = -1;
361         char                            lustre_path[PATH_MAX];
362         char                            strfid[FID_NOBRACE_LEN + 1];
363         struct hsm_copyaction_private   *hcp;
364         struct llapi_json_item_list     *json_items;
365
366         /* Noop unless the event fd was initialized */
367         if (llapi_hsm_event_fd < 0)
368                 return 0;
369
370         if (phcp == NULL || *phcp == NULL)
371                 return -EINVAL;
372
373         hcp = *phcp;
374
375         rc = llapi_json_init_list(&json_items);
376         if (rc < 0)
377                 goto err;
378
379         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(&hai->hai_dfid));
380         rc = llapi_json_add_item(&json_items, "data_fid",
381                                  LLAPI_JSON_STRING, strfid);
382         if (rc < 0)
383                 goto err;
384
385         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(&hai->hai_fid));
386         rc = llapi_json_add_item(&json_items, "source_fid",
387                                  LLAPI_JSON_STRING, strfid);
388         if (rc < 0)
389                 goto err;
390
391         if (hcp->copy.hc_errval == ECANCELED) {
392                 progress_type = CT_CANCEL;
393                 goto cancel;
394         }
395
396         if (hcp->copy.hc_errval != 0) {
397                 progress_type = CT_ERROR;
398
399                 rc = llapi_json_add_item(&json_items, "errno",
400                                          LLAPI_JSON_INTEGER,
401                                          &hcp->copy.hc_errval);
402                 if (rc < 0)
403                         goto err;
404
405                 rc = llapi_json_add_item(&json_items, "error",
406                                          LLAPI_JSON_STRING,
407                                          strerror(hcp->copy.hc_errval));
408                 if (rc < 0)
409                         goto err;
410
411                 goto cancel;
412         }
413
414         /* lustre_path isn't available after a restore completes */
415         /* total_bytes isn't available after a restore or archive completes */
416         if (progress_type != CT_FINISH) {
417                 rc = llapi_fid2path(hcp->ct_priv->mnt, strfid, lustre_path,
418                                     sizeof(lustre_path), &recno, &linkno);
419                 if (rc < 0)
420                         goto err;
421
422                 rc = llapi_json_add_item(&json_items, "lustre_path",
423                                          LLAPI_JSON_STRING, lustre_path);
424                 if (rc < 0)
425                         goto err;
426
427                 rc = llapi_json_add_item(&json_items, "total_bytes",
428                                          LLAPI_JSON_BIGNUM, &total);
429                 if (rc < 0)
430                         goto err;
431         }
432
433         if (progress_type == CT_RUNNING) {
434                 rc = llapi_json_add_item(&json_items, "current_bytes",
435                                          LLAPI_JSON_BIGNUM, &current);
436                 if (rc < 0)
437                         goto err;
438         }
439
440 cancel:
441         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
442                                  (char *)llapi_hsm_ct_ev2str(hai->hai_action +
443                                                              progress_type));
444         if (rc < 0)
445                 goto err;
446
447         rc = llapi_hsm_write_json_event(&json_items);
448         if (rc < 0)
449                 goto err;
450
451         goto out_free;
452
453 err:
454         llapi_error(LLAPI_MSG_ERROR, rc, "error in "
455                     "llapi_hsm_log_ct_progress()");
456
457 out_free:
458         if (json_items != NULL)
459                 llapi_json_destroy_list(&json_items);
460
461         return rc;
462 }
463
464 /**
465  * Given a path to a FIFO, create a filehandle for nonblocking writes to it.
466  * Intended to be used for copytool monitoring processes that read an
467  * event stream from the FIFO. Events written in the absence of a reader
468  * are lost.
469  *
470  * \param path               Path to monitor FIFO.
471  *
472  * \retval 0 on success.
473  * \retval -errno on error.
474  */
475 int llapi_hsm_register_event_fifo(const char *path)
476 {
477         int read_fd;
478         struct stat statbuf;
479         struct sigaction ignore_action;
480         int rc;
481
482         /* Create the FIFO if necessary. */
483         if ((mkfifo(path, 0644) < 0) && (errno != EEXIST)) {
484                 llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed", path);
485                 return -errno;
486         }
487         if (errno == EEXIST) {
488                 if (stat(path, &statbuf) < 0) {
489                         llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed",
490                                     path);
491                         return -errno;
492                 }
493                 if (!S_ISFIFO(statbuf.st_mode) ||
494                     ((statbuf.st_mode & 0777) != 0644)) {
495                         llapi_error(LLAPI_MSG_ERROR, errno, "%s exists but is "
496                                     "not a pipe or has a wrong mode", path);
497                         return -errno;
498                 }
499         } else {
500                 created_hsm_event_fifo = true;
501         }
502
503         /* Open the FIFO for read so that the subsequent open for write
504          * doesn't immediately fail. */
505         read_fd = open(path, O_RDONLY | O_NONBLOCK);
506         if (read_fd < 0) {
507                 llapi_error(LLAPI_MSG_ERROR, errno,
508                             "cannot open(%s) for read", path);
509                 return -errno;
510         }
511
512         /* Open the FIFO for writes, but don't block on waiting
513          * for a reader. */
514         llapi_hsm_event_fd = open(path, O_WRONLY | O_NONBLOCK);
515         rc = -errno;
516
517         /* Now close the reader. An external monitoring process can
518          * now open the FIFO for reads. If no reader comes along the
519          * events are lost. NOTE: Only one reader at a time! */
520         close(read_fd);
521
522         if (llapi_hsm_event_fd < 0) {
523                 llapi_error(LLAPI_MSG_ERROR, -rc,
524                             "cannot open(%s) for write", path);
525                 return rc;
526         }
527
528         /* Ignore SIGPIPEs -- can occur if the reader goes away. */
529         memset(&ignore_action, 0, sizeof(ignore_action));
530         ignore_action.sa_handler = SIG_IGN;
531         sigemptyset(&ignore_action.sa_mask);
532         sigaction(SIGPIPE, &ignore_action, NULL);
533
534         return 0;
535 }
536
537 /**
538  * Given a path to a FIFO, close its filehandle and delete the FIFO.
539  *
540  * \param path               Path to monitor FIFO.
541  *
542  * \retval 0 on success.
543  * \retval -errno on error.
544  */
545 int llapi_hsm_unregister_event_fifo(const char *path)
546 {
547         /* Noop unless the event fd was initialized */
548         if (llapi_hsm_event_fd < 0)
549                 return 0;
550
551         if (close(llapi_hsm_event_fd) < 0)
552                 return -errno;
553
554         if (created_hsm_event_fifo) {
555                 unlink(path);
556                 created_hsm_event_fifo = false;
557         }
558
559         llapi_hsm_event_fd = -1;
560
561         return 0;
562 }
563
564 /**
565  * Custom logging callback to be used when a monitoring FIFO has been
566  * registered. Formats log entries as JSON events suitable for
567  * consumption by a copytool monitoring process.
568  *
569  * \param level              The message loglevel.
570  * \param _rc                The returncode associated with the message.
571  * \param fmt                The message format string.
572  * \param args               Arguments to be formatted by the format string.
573  *
574  * \retval None.
575  */
576 void llapi_hsm_log_error(enum llapi_message_level level, int _rc,
577                          const char *fmt, va_list args)
578 {
579         int                             rc;
580         int                             msg_len;
581         int                             real_level;
582         char                            *msg = NULL;
583         va_list                         args2;
584         struct llapi_json_item_list     *json_items;
585
586         /* Noop unless the event fd was initialized */
587         if (llapi_hsm_event_fd < 0)
588                 return;
589
590         rc = llapi_json_init_list(&json_items);
591         if (rc < 0)
592                 goto err;
593
594         if ((level & LLAPI_MSG_NO_ERRNO) == 0) {
595                 rc = llapi_json_add_item(&json_items, "errno",
596                                          LLAPI_JSON_INTEGER,
597                                          &_rc);
598                 if (rc < 0)
599                         goto err;
600
601                 rc = llapi_json_add_item(&json_items, "error",
602                                          LLAPI_JSON_STRING,
603                                          strerror(abs(_rc)));
604                 if (rc < 0)
605                         goto err;
606         }
607
608         va_copy(args2, args);
609         msg_len = vsnprintf(NULL, 0, fmt, args2) + 1;
610         va_end(args2);
611         if (msg_len >= 0) {
612                 msg = (char *) alloca(msg_len);
613                 if (msg == NULL) {
614                         rc = -ENOMEM;
615                         goto err;
616                 }
617
618                 rc = vsnprintf(msg, msg_len, fmt, args);
619                 if (rc < 0)
620                         goto err;
621
622                 rc = llapi_json_add_item(&json_items, "message",
623                                          LLAPI_JSON_STRING,
624                                          msg);
625                 if (rc < 0)
626                         goto err;
627         } else {
628                 rc = llapi_json_add_item(&json_items, "message",
629                                          LLAPI_JSON_STRING,
630                                          "INTERNAL ERROR: message failed");
631                 if (rc < 0)
632                         goto err;
633         }
634
635         real_level = level & LLAPI_MSG_NO_ERRNO;
636         real_level = real_level > 0 ? level - LLAPI_MSG_NO_ERRNO : level;
637
638         rc = llapi_json_add_item(&json_items, "level", LLAPI_JSON_STRING,
639                                  (void *)llapi_msg_level2str(real_level));
640         if (rc < 0)
641                 goto err;
642
643         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
644                                  "LOGGED_MESSAGE");
645         if (rc < 0)
646                 goto err;
647
648         rc = llapi_hsm_write_json_event(&json_items);
649         if (rc < 0)
650                 goto err;
651
652         goto out_free;
653
654 err:
655         /* Write directly to stderr to avoid llapi_error, which now
656          * emits JSON event messages. */
657         fprintf(stderr, "\nFATAL ERROR IN llapi_hsm_log_error(): rc %d,", rc);
658
659 out_free:
660         if (json_items != NULL)
661                 llapi_json_destroy_list(&json_items);
662
663         return;
664 }
665
666 /** Register a copytool
667  * \param[out] priv             Opaque private control structure
668  * \param mnt                   Lustre filesystem mount point
669  * \param archive_count         Number of valid archive IDs in \a archives
670  * \param archives              Which archive numbers this copytool is
671  *                              responsible for
672  * \param rfd_flags             flags applied to read fd of pipe
673  *                              (e.g. O_NONBLOCK)
674  *
675  * \retval 0 on success.
676  * \retval -errno on error.
677  */
678 int llapi_hsm_copytool_register(struct hsm_copytool_private **priv,
679                                 const char *mnt, int archive_count,
680                                 int *archives, int rfd_flags)
681 {
682         struct hsm_copytool_private     *ct;
683         int                              rc;
684
685         if (archive_count > 0 && archives == NULL) {
686                 llapi_err_noerrno(LLAPI_MSG_ERROR,
687                                   "NULL archive numbers");
688                 return -EINVAL;
689         }
690
691         if (archive_count > LL_HSM_MAX_ARCHIVE) {
692                 llapi_err_noerrno(LLAPI_MSG_ERROR, "%d requested when maximum "
693                                   "of %zu archives supported", archive_count,
694                                   LL_HSM_MAX_ARCHIVE);
695                 return -EINVAL;
696         }
697
698         ct = calloc(1, sizeof(*ct));
699         if (ct == NULL)
700                 return -ENOMEM;
701
702         ct->magic = CT_PRIV_MAGIC;
703         ct->mnt_fd = -1;
704         ct->open_by_fid_fd = -1;
705         ct->kuc.lk_rfd = LK_NOFD;
706         ct->kuc.lk_wfd = LK_NOFD;
707
708         ct->mnt = strdup(mnt);
709         if (ct->mnt == NULL) {
710                 rc = -ENOMEM;
711                 goto out_err;
712         }
713
714         ct->kuch = malloc(HAL_MAXSIZE + sizeof(*ct->kuch));
715         if (ct->kuch == NULL) {
716                 rc = -ENOMEM;
717                 goto out_err;
718         }
719
720         ct->mnt_fd = open(ct->mnt, O_RDONLY);
721         if (ct->mnt_fd < 0) {
722                 rc = -errno;
723                 goto out_err;
724         }
725
726         ct->open_by_fid_fd = openat(ct->mnt_fd, OPEN_BY_FID_PATH, O_RDONLY);
727         if (ct->open_by_fid_fd < 0) {
728                 rc = -errno;
729                 goto out_err;
730         }
731
732         /* no archives specified means "match all". */
733         ct->archives = 0;
734         for (rc = 0; rc < archive_count; rc++) {
735                 if ((archives[rc] > LL_HSM_MAX_ARCHIVE) || (archives[rc] < 0)) {
736                         llapi_err_noerrno(LLAPI_MSG_ERROR, "%d requested when "
737                                           "archive id [0 - %zu] is supported",
738                                           archives[rc], LL_HSM_MAX_ARCHIVE);
739                         rc = -EINVAL;
740                         goto out_err;
741                 }
742                 /* in the list we have an all archive wildcard
743                  * so move to all archives mode
744                  */
745                 if (archives[rc] == 0) {
746                         ct->archives = 0;
747                         archive_count = 0;
748                         break;
749                 }
750                 ct->archives |= (1 << (archives[rc] - 1));
751         }
752
753         rc = libcfs_ukuc_start(&ct->kuc, KUC_GRP_HSM, rfd_flags);
754         if (rc < 0)
755                 goto out_err;
756
757         /* Storing archive(s) in lk_data; see mdc_ioc_hsm_ct_start */
758         ct->kuc.lk_data = ct->archives;
759         rc = ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, &ct->kuc);
760         if (rc < 0) {
761                 rc = -errno;
762                 llapi_error(LLAPI_MSG_ERROR, rc,
763                             "cannot start copytool on '%s'", mnt);
764                 goto out_kuc;
765         }
766
767         llapi_hsm_log_ct_registration(&ct, CT_REGISTER);
768
769         /* Only the kernel reference keeps the write side open */
770         close(ct->kuc.lk_wfd);
771         ct->kuc.lk_wfd = LK_NOFD;
772         *priv = ct;
773
774         return 0;
775
776 out_kuc:
777         /* cleanup the kuc channel */
778         libcfs_ukuc_stop(&ct->kuc);
779
780 out_err:
781         if (!(ct->mnt_fd < 0))
782                 close(ct->mnt_fd);
783
784         if (!(ct->open_by_fid_fd < 0))
785                 close(ct->open_by_fid_fd);
786
787         free(ct->mnt);
788
789         free(ct->kuch);
790
791         free(ct);
792
793         return rc;
794 }
795
796 /** Deregister a copytool
797  * Note: under Linux, until llapi_hsm_copytool_unregister is called
798  * (or the program is killed), the libcfs module will be referenced
799  * and unremovable, even after Lustre services stop.
800  */
801 int llapi_hsm_copytool_unregister(struct hsm_copytool_private **priv)
802 {
803         struct hsm_copytool_private *ct;
804
805         if (priv == NULL || *priv == NULL)
806                 return -EINVAL;
807
808         ct = *priv;
809         if (ct->magic != CT_PRIV_MAGIC)
810                 return -EINVAL;
811
812         /* Close the read side of the KUC pipe. This should be done
813          * before unregistering to avoid deadlock: a ldlm_cb thread
814          * enters libcfs_kkuc_group_put() acquires kg_sem and blocks
815          * in pipe_write() due to full pipe; then we attempt to
816          * unregister and block on kg_sem. */
817         libcfs_ukuc_stop(&ct->kuc);
818
819         /* Tell the kernel to stop sending us messages */
820         ct->kuc.lk_flags = LK_FLG_STOP;
821         ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, &ct->kuc);
822
823         llapi_hsm_log_ct_registration(&ct, CT_UNREGISTER);
824
825         close(ct->open_by_fid_fd);
826         close(ct->mnt_fd);
827         free(ct->mnt);
828         free(ct->kuch);
829         free(ct);
830         *priv = NULL;
831
832         return 0;
833 }
834
835 /** Returns a file descriptor to poll/select on.
836  * \param ct Opaque private control structure
837  * \retval -EINVAL on error
838  * \retval the file descriptor for reading HSM events from the kernel
839  */
840 int llapi_hsm_copytool_get_fd(struct hsm_copytool_private *ct)
841 {
842         if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
843                 return -EINVAL;
844
845         return libcfs_ukuc_get_rfd(&ct->kuc);
846 }
847
848 /** Wait for the next hsm_action_list
849  * \param ct Opaque private control structure
850  * \param halh Action list handle, will be allocated here
851  * \param msgsize Number of bytes in the message, will be set here
852  * \return 0 valid message received; halh and msgsize are set
853  *         <0 error code
854  * Note: The application must not call llapi_hsm_copytool_recv until it has
855  * cleared the data in ct->kuch from the previous call.
856  */
857 int llapi_hsm_copytool_recv(struct hsm_copytool_private *ct,
858                             struct hsm_action_list **halh, int *msgsize)
859 {
860         struct kuc_hdr          *kuch;
861         struct hsm_action_list  *hal;
862         int                      rc = 0;
863
864         if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
865                 return -EINVAL;
866
867         if (halh == NULL || msgsize == NULL)
868                 return -EINVAL;
869
870         kuch = ct->kuch;
871
872 repeat:
873         rc = libcfs_ukuc_msg_get(&ct->kuc, (char *)kuch,
874                                  HAL_MAXSIZE + sizeof(*kuch),
875                                  KUC_TRANSPORT_HSM);
876         if (rc < 0)
877                 goto out_err;
878
879         /* Handle generic messages */
880         if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
881             kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
882                 rc = -ESHUTDOWN;
883                 goto out_err;
884         }
885
886         if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
887             kuch->kuc_msgtype != HMT_ACTION_LIST) {
888                 llapi_err_noerrno(LLAPI_MSG_ERROR,
889                                   "Unknown HSM message type %d:%d\n",
890                                   kuch->kuc_transport, kuch->kuc_msgtype);
891                 rc = -EPROTO;
892                 goto out_err;
893         }
894
895         if (kuch->kuc_msglen < sizeof(*kuch) + sizeof(*hal)) {
896                 llapi_err_noerrno(LLAPI_MSG_ERROR, "Short HSM message %d",
897                                   kuch->kuc_msglen);
898                 rc = -EPROTO;
899                 goto out_err;
900         }
901
902         /* Our message is a hsm_action_list. Use pointer math to skip
903         * kuch_hdr and point directly to the message payload.
904         */
905         hal = (struct hsm_action_list *)(kuch + 1);
906
907         /* Check that we have registered for this archive #
908          * if 0 registered, we serve any archive */
909         if (ct->archives &&
910             ((1 << (hal->hal_archive_id - 1)) & ct->archives) == 0) {
911                 llapi_err_noerrno(LLAPI_MSG_INFO,
912                                   "This copytool does not service archive #%d,"
913                                   " ignoring this request."
914                                   " Mask of served archive is 0x%.8X",
915                                   hal->hal_archive_id, ct->archives);
916
917                 goto repeat;
918         }
919
920         *halh = hal;
921         *msgsize = kuch->kuc_msglen - sizeof(*kuch);
922         return 0;
923
924 out_err:
925         *halh = NULL;
926         *msgsize = 0;
927         return rc;
928 }
929
930 /** Get parent path from mount point and fid.
931  *
932  * \param mnt        Filesystem root path.
933  * \param fid        Object FID.
934  * \param parent     Destination buffer.
935  * \param parent_len Destination buffer size.
936  * \return 0 on success.
937  */
938 static int fid_parent(const char *mnt, const lustre_fid *fid, char *parent,
939                       size_t parent_len)
940 {
941         int              rc;
942         int              linkno = 0;
943         long long        recno = -1;
944         char             file[PATH_MAX];
945         char             strfid[FID_NOBRACE_LEN + 1];
946         char            *ptr;
947
948         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(fid));
949
950         rc = llapi_fid2path(mnt, strfid, file, sizeof(file),
951                             &recno, &linkno);
952         if (rc < 0)
953                 return rc;
954
955         /* fid2path returns a relative path */
956         rc = snprintf(parent, parent_len, "%s/%s", mnt, file);
957         if (rc >= parent_len)
958                 return -ENAMETOOLONG;
959
960         /* remove file name */
961         ptr = strrchr(parent, '/');
962         if (ptr == NULL || ptr == parent) {
963                 rc = -EINVAL;
964         } else {
965                 *ptr = '\0';
966                 rc = 0;
967         }
968
969         return rc;
970 }
971
972 static int ct_open_by_fid(const struct hsm_copytool_private *ct,
973                           const struct lu_fid *fid, int open_flags)
974 {
975         char fid_name[FID_NOBRACE_LEN + 1];
976         int fd;
977
978         snprintf(fid_name, sizeof(fid_name), DFID_NOBRACE, PFID(fid));
979
980         fd = openat(ct->open_by_fid_fd, fid_name, open_flags);
981         return fd < 0 ? -errno : fd;
982 }
983
984 /**
985  * Get metadata attributes of file by FID.
986  *
987  * Use the IOC_MDC_GETFILEINFO ioctl (to send a MDS_GETATTR_NAME RPC)
988  * to get the attributes of the file identified by \a fid. This
989  * returns only the attributes stored on the MDT and avoids taking
990  * layout locks or accessing OST objects. It also bypasses the inode
991  * cache. Attributes are returned in \a st.
992  */
993 static int ct_md_getattr(const struct hsm_copytool_private *ct,
994                          const struct lu_fid *fid,
995                          lstat_t *st)
996 {
997         struct lov_user_mds_data *lmd;
998         size_t lmd_size;
999         int rc;
1000
1001         lmd_size = sizeof(lmd->lmd_st) +
1002                 lov_user_md_size(LOV_MAX_STRIPE_COUNT, LOV_USER_MAGIC_V3);
1003
1004         if (lmd_size < sizeof(lmd->lmd_st) + XATTR_SIZE_MAX)
1005                 lmd_size = sizeof(lmd->lmd_st) + XATTR_SIZE_MAX;
1006
1007         if (lmd_size < FID_NOBRACE_LEN + 1)
1008                 lmd_size = FID_NOBRACE_LEN + 1;
1009
1010         lmd = malloc(lmd_size);
1011         if (lmd == NULL)
1012                 return -ENOMEM;
1013
1014         snprintf((char *)lmd, lmd_size, DFID_NOBRACE, PFID(fid));
1015
1016         rc = ioctl(ct->open_by_fid_fd, IOC_MDC_GETFILEINFO, lmd);
1017         if (rc != 0) {
1018                 rc = -errno;
1019                 llapi_error(LLAPI_MSG_ERROR, rc,
1020                             "cannot get metadata attributes of "DFID" in '%s'",
1021                             PFID(fid), ct->mnt);
1022                 goto out;
1023         }
1024
1025         *st = lmd->lmd_st;
1026 out:
1027         free(lmd);
1028
1029         return rc;
1030 }
1031
1032 /** Create the destination volatile file for a restore operation.
1033  *
1034  * \param hcp        Private copyaction handle.
1035  * \param mdt_index  MDT index where to create the volatile file.
1036  * \param flags      Volatile file creation flags.
1037  * \return 0 on success.
1038  */
1039 static int create_restore_volatile(struct hsm_copyaction_private *hcp,
1040                                    int mdt_index, int open_flags)
1041 {
1042         int                      rc;
1043         int                      fd;
1044         char                     parent[PATH_MAX + 1];
1045         const char              *mnt = hcp->ct_priv->mnt;
1046         struct hsm_action_item  *hai = &hcp->copy.hc_hai;
1047
1048         rc = fid_parent(mnt, &hai->hai_fid, parent, sizeof(parent));
1049         if (rc < 0) {
1050                 /* fid_parent() failed, try to keep on going */
1051                 llapi_error(LLAPI_MSG_ERROR, rc,
1052                             "cannot get parent path to restore "DFID" "
1053                             "using '%s'", PFID(&hai->hai_fid), mnt);
1054                 snprintf(parent, sizeof(parent), "%s", mnt);
1055         }
1056
1057         fd = llapi_create_volatile_idx(parent, mdt_index, open_flags);
1058         if (fd < 0)
1059                 return fd;
1060
1061         rc = fchown(fd, hcp->stat.st_uid, hcp->stat.st_gid);
1062         if (rc < 0)
1063                 goto err_cleanup;
1064
1065         rc = llapi_fd2fid(fd, &hai->hai_dfid);
1066         if (rc < 0)
1067                 goto err_cleanup;
1068
1069         hcp->data_fd = fd;
1070
1071         return 0;
1072
1073 err_cleanup:
1074         hcp->data_fd = -1;
1075         close(fd);
1076
1077         return rc;
1078 }
1079
1080 /** Start processing an HSM action.
1081  * Should be called by copytools just before starting handling a request.
1082  * It could be skipped if copytool only want to directly report an error,
1083  * \see llapi_hsm_action_end().
1084  *
1085  * \param hcp                Opaque action handle to be passed to
1086  *                           llapi_hsm_action_progress and llapi_hsm_action_end.
1087  * \param ct                 Copytool handle acquired at registration.
1088  * \param hai                The hsm_action_item describing the request.
1089  * \param restore_mdt_index  On restore: MDT index where to create the volatile
1090  *                           file. Use -1 for default.
1091  * \param restore_open_flags On restore: volatile file creation mode. Use
1092  *                           O_LOV_DELAY_CREATE to manually set the LOVEA
1093  *                           afterwards.
1094  * \param is_error           Whether this call is just to report an error.
1095  *
1096  * \return 0 on success.
1097  */
1098 int llapi_hsm_action_begin(struct hsm_copyaction_private **phcp,
1099                            const struct hsm_copytool_private *ct,
1100                            const struct hsm_action_item *hai,
1101                            int restore_mdt_index, int restore_open_flags,
1102                            bool is_error)
1103 {
1104         struct hsm_copyaction_private *hcp;
1105         int fd;
1106         int rc;
1107
1108         hcp = calloc(1, sizeof(*hcp));
1109         if (hcp == NULL)
1110                 return -ENOMEM;
1111
1112         hcp->source_fd = -1;
1113         hcp->data_fd = -1;
1114         hcp->ct_priv = ct;
1115         hcp->copy.hc_hai = *hai;
1116         hcp->copy.hc_hai.hai_len = sizeof(*hai);
1117
1118         if (is_error)
1119                 goto ok_out;
1120
1121         if (hai->hai_action == HSMA_ARCHIVE) {
1122                 fd = ct_open_by_fid(hcp->ct_priv, &hai->hai_dfid,
1123                                 O_RDONLY | O_NOATIME | O_NOFOLLOW | O_NONBLOCK);
1124                 if (fd < 0) {
1125                         rc = fd;
1126                         goto err_out;
1127                 }
1128
1129                 hcp->source_fd = fd;
1130         } else if (hai->hai_action == HSMA_RESTORE) {
1131                 rc = ct_md_getattr(hcp->ct_priv, &hai->hai_fid, &hcp->stat);
1132                 if (rc < 0)
1133                         goto err_out;
1134
1135                 rc = create_restore_volatile(hcp, restore_mdt_index,
1136                                              restore_open_flags);
1137                 if (rc < 0)
1138                         goto err_out;
1139         } else if (hai->hai_action == HSMA_REMOVE) {
1140                 /* Since remove is atomic there is no need to send an
1141                  * initial MDS_HSM_PROGRESS RPC. */
1142                 goto out_log;
1143         }
1144
1145         rc = ioctl(ct->mnt_fd, LL_IOC_HSM_COPY_START, &hcp->copy);
1146         if (rc < 0) {
1147                 rc = -errno;
1148                 goto err_out;
1149         }
1150
1151 out_log:
1152         llapi_hsm_log_ct_progress(&hcp, hai, CT_START, 0, 0);
1153
1154 ok_out:
1155         hcp->magic = CP_PRIV_MAGIC;
1156         *phcp = hcp;
1157         return 0;
1158
1159 err_out:
1160         if (!(hcp->source_fd < 0))
1161                 close(hcp->source_fd);
1162
1163         if (!(hcp->data_fd < 0))
1164                 close(hcp->data_fd);
1165
1166         free(hcp);
1167
1168         return rc;
1169 }
1170
1171 /** Terminate an HSM action processing.
1172  * Should be called by copytools just having finished handling the request.
1173  * \param hdl[in,out]  Handle returned by llapi_hsm_action_start.
1174  * \param he[in]       The final range of copied data (for copy actions).
1175  * \param errval[in]   The status code of the operation.
1176  * \param flags[in]    The flags about the termination status (HP_FLAG_RETRY if
1177  *                     the error is retryable).
1178  *
1179  * \return 0 on success.
1180  */
1181 int llapi_hsm_action_end(struct hsm_copyaction_private **phcp,
1182                          const struct hsm_extent *he, int hp_flags, int errval)
1183 {
1184         struct hsm_copyaction_private   *hcp;
1185         struct hsm_action_item          *hai;
1186         int                              rc;
1187
1188         if (phcp == NULL || *phcp == NULL || he == NULL)
1189                 return -EINVAL;
1190
1191         hcp = *phcp;
1192
1193         if (hcp->magic != CP_PRIV_MAGIC)
1194                 return -EINVAL;
1195
1196         hai = &hcp->copy.hc_hai;
1197
1198         if (hai->hai_action == HSMA_RESTORE && errval == 0) {
1199                 struct ll_futimes_3 lfu = {
1200                         .lfu_atime_sec = hcp->stat.st_atim.tv_sec,
1201                         .lfu_atime_nsec = hcp->stat.st_atim.tv_nsec,
1202                         .lfu_mtime_sec = hcp->stat.st_mtim.tv_sec,
1203                         .lfu_mtime_nsec = hcp->stat.st_mtim.tv_nsec,
1204                         .lfu_ctime_sec = hcp->stat.st_ctim.tv_sec,
1205                         .lfu_ctime_nsec = hcp->stat.st_ctim.tv_nsec,
1206                 };
1207
1208                 rc = fsync(hcp->data_fd);
1209                 if (rc < 0) {
1210                         errval = -errno;
1211                         goto end;
1212                 }
1213
1214                 /* Set {a,m,c}time of volatile file to that of original. */
1215                 rc = ioctl(hcp->data_fd, LL_IOC_FUTIMES_3, &lfu);
1216                 if (rc < 0) {
1217                         errval = -errno;
1218                         goto end;
1219                 }
1220         }
1221
1222 end:
1223         /* In some cases, like restore, 2 FIDs are used.
1224          * Set the right FID to use here. */
1225         if (hai->hai_action == HSMA_ARCHIVE || hai->hai_action == HSMA_RESTORE)
1226                 hai->hai_fid = hai->hai_dfid;
1227
1228         /* Fill the last missing data that will be needed by
1229          * kernel to send a hsm_progress. */
1230         hcp->copy.hc_flags  = hp_flags;
1231         hcp->copy.hc_errval = abs(errval);
1232
1233         hcp->copy.hc_hai.hai_extent = *he;
1234
1235         rc = ioctl(hcp->ct_priv->mnt_fd, LL_IOC_HSM_COPY_END, &hcp->copy);
1236         if (rc) {
1237                 rc = -errno;
1238                 goto err_cleanup;
1239         }
1240
1241         llapi_hsm_log_ct_progress(&hcp, hai, CT_FINISH, 0, 0);
1242
1243 err_cleanup:
1244         if (!(hcp->source_fd < 0))
1245                 close(hcp->source_fd);
1246
1247         if (!(hcp->data_fd < 0))
1248                 close(hcp->data_fd);
1249
1250         free(hcp);
1251         *phcp = NULL;
1252
1253         return rc;
1254 }
1255
1256 /** Notify a progress in processing an HSM action.
1257  * \param hdl[in,out]   handle returned by llapi_hsm_action_start.
1258  * \param he[in]        the range of copied data (for copy actions).
1259  * \param total[in]     the expected total of copied data (for copy actions).
1260  * \param hp_flags[in]  HSM progress flags.
1261  * \return 0 on success.
1262  */
1263 int llapi_hsm_action_progress(struct hsm_copyaction_private *hcp,
1264                               const struct hsm_extent *he, __u64 total,
1265                               int hp_flags)
1266 {
1267         int                      rc;
1268         struct hsm_progress      hp;
1269         struct hsm_action_item  *hai;
1270
1271         if (hcp == NULL || he == NULL)
1272                 return -EINVAL;
1273
1274         if (hcp->magic != CP_PRIV_MAGIC)
1275                 return -EINVAL;
1276
1277         hai = &hcp->copy.hc_hai;
1278
1279         memset(&hp, 0, sizeof(hp));
1280
1281         hp.hp_cookie = hai->hai_cookie;
1282         hp.hp_flags  = hp_flags;
1283
1284         /* Progress is made on the data fid */
1285         hp.hp_fid = hai->hai_dfid;
1286         hp.hp_extent = *he;
1287
1288         rc = ioctl(hcp->ct_priv->mnt_fd, LL_IOC_HSM_PROGRESS, &hp);
1289         if (rc < 0)
1290                 rc = -errno;
1291
1292         llapi_hsm_log_ct_progress(&hcp, hai, CT_RUNNING, total, he->length);
1293
1294         return rc;
1295 }
1296
1297 /** Get the fid of object to be used for copying data.
1298  * @return error code if the action is not a copy operation.
1299  */
1300 int llapi_hsm_action_get_dfid(const struct hsm_copyaction_private *hcp,
1301                               lustre_fid *fid)
1302 {
1303         const struct hsm_action_item    *hai = &hcp->copy.hc_hai;
1304
1305         if (hcp->magic != CP_PRIV_MAGIC)
1306                 return -EINVAL;
1307
1308         if (hai->hai_action != HSMA_RESTORE && hai->hai_action != HSMA_ARCHIVE)
1309                 return -EINVAL;
1310
1311         *fid = hai->hai_dfid;
1312
1313         return 0;
1314 }
1315
1316 /**
1317  * Get a file descriptor to be used for copying data. It's up to the
1318  * caller to close the FDs obtained from this function.
1319  *
1320  * @retval a file descriptor on success.
1321  * @retval a negative error code on failure.
1322  */
1323 int llapi_hsm_action_get_fd(const struct hsm_copyaction_private *hcp)
1324 {
1325         const struct hsm_action_item    *hai = &hcp->copy.hc_hai;
1326         int fd;
1327
1328         if (hcp->magic != CP_PRIV_MAGIC)
1329                 return -EINVAL;
1330
1331         if (hai->hai_action == HSMA_ARCHIVE) {
1332                 fd = dup(hcp->source_fd);
1333                 return fd < 0 ? -errno : fd;
1334         } else if (hai->hai_action == HSMA_RESTORE) {
1335                 fd = dup(hcp->data_fd);
1336                 return fd < 0 ? -errno : fd;
1337         } else {
1338                 return -EINVAL;
1339         }
1340 }
1341
1342 /**
1343  * Import an existing hsm-archived file into Lustre.
1344  *
1345  * Caller must access file by (returned) newfid value from now on.
1346  *
1347  * \param dst      path to Lustre destination (e.g. /mnt/lustre/my/file).
1348  * \param archive  archive number.
1349  * \param st       struct stat buffer containing file ownership, perm, etc.
1350  * \param stripe_* Striping options.  Currently ignored, since the restore
1351  *                 operation will set the striping.  In V2, this striping might
1352  *                 be used.
1353  * \param newfid[out] Filled with new Lustre fid.
1354  */
1355 int llapi_hsm_import(const char *dst, int archive, const struct stat *st,
1356                      unsigned long long stripe_size, int stripe_offset,
1357                      int stripe_count, int stripe_pattern, char *pool_name,
1358                      lustre_fid *newfid)
1359 {
1360         struct hsm_user_import   hui;
1361         int                      fd;
1362         int                      rc = 0;
1363
1364         if (stripe_pattern == 0)
1365                 stripe_pattern = LOV_PATTERN_RAID0;
1366
1367         /* Create a non-striped file */
1368         fd = llapi_file_open_pool(dst, O_CREAT | O_WRONLY, st->st_mode,
1369                                   stripe_size, stripe_offset, stripe_count,
1370                                   stripe_pattern | LOV_PATTERN_F_RELEASED,
1371                                   pool_name);
1372         if (fd < 0) {
1373                 llapi_error(LLAPI_MSG_ERROR, fd,
1374                             "cannot create '%s' for import", dst);
1375                 return fd;
1376         }
1377
1378         /* Get the new fid in Lustre. Caller needs to use this fid
1379            from now on. */
1380         rc = llapi_fd2fid(fd, newfid);
1381         if (rc != 0) {
1382                 llapi_error(LLAPI_MSG_ERROR, rc,
1383                             "cannot get fid of '%s' for import", dst);
1384                 goto out_unlink;
1385         }
1386
1387         hui.hui_uid = st->st_uid;
1388         hui.hui_gid = st->st_gid;
1389         hui.hui_mode = st->st_mode;
1390         hui.hui_size = st->st_size;
1391         hui.hui_archive_id = archive;
1392         hui.hui_atime = st->st_atime;
1393         hui.hui_atime_ns = st->st_atim.tv_nsec;
1394         hui.hui_mtime = st->st_mtime;
1395         hui.hui_mtime_ns = st->st_mtim.tv_nsec;
1396         rc = ioctl(fd, LL_IOC_HSM_IMPORT, &hui);
1397         if (rc != 0) {
1398                 rc = -errno;
1399                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot import '%s'", dst);
1400                 goto out_unlink;
1401         }
1402
1403 out_unlink:
1404         if (fd >= 0)
1405                 close(fd);
1406         if (rc)
1407                 unlink(dst);
1408         return rc;
1409 }
1410
1411 /**
1412  * Return the current HSM states and HSM requests related to file pointed by \a
1413  * path.
1414  *
1415  * \param hus  Should be allocated by caller. Will be filled with current file
1416  *             states.
1417  *
1418  * \retval 0 on success.
1419  * \retval -errno on error.
1420  */
1421 int llapi_hsm_state_get_fd(int fd, struct hsm_user_state *hus)
1422 {
1423         int rc;
1424
1425         rc = ioctl(fd, LL_IOC_HSM_STATE_GET, hus);
1426         /* If error, save errno value */
1427         rc = rc ? -errno : 0;
1428
1429         return rc;
1430 }
1431
1432 /**
1433  * Return the current HSM states and HSM requests related to file pointed by \a
1434  * path.
1435  *
1436  * see llapi_hsm_state_get_fd() for args use and return
1437  */
1438 int llapi_hsm_state_get(const char *path, struct hsm_user_state *hus)
1439 {
1440         int fd;
1441         int rc;
1442
1443         fd = open(path, O_RDONLY | O_NONBLOCK);
1444         if (fd < 0)
1445                 return -errno;
1446
1447         rc = llapi_hsm_state_get_fd(fd, hus);
1448
1449         close(fd);
1450         return rc;
1451 }
1452
1453 /**
1454  * Set HSM states of file pointed by \a fd
1455  *
1456  * Using the provided bitmasks, the current HSM states for this file will be
1457  * changed. \a archive_id could be used to change the archive number also. Set
1458  * it to 0 if you do not want to change it.
1459  *
1460  * \param setmask      Bitmask for flag to be set.
1461  * \param clearmask    Bitmask for flag to be cleared.
1462  * \param archive_id  Archive number identifier to use. 0 means no change.
1463  *
1464  * \retval 0 on success.
1465  * \retval -errno on error.
1466  */
1467 int llapi_hsm_state_set_fd(int fd, __u64 setmask, __u64 clearmask,
1468                            __u32 archive_id)
1469 {
1470         struct hsm_state_set     hss;
1471         int                      rc;
1472
1473         hss.hss_valid = HSS_SETMASK|HSS_CLEARMASK;
1474         hss.hss_setmask = setmask;
1475         hss.hss_clearmask = clearmask;
1476         /* Change archive_id if provided. We can only change
1477          * to set something different than 0. */
1478         if (archive_id > 0) {
1479                 hss.hss_valid |= HSS_ARCHIVE_ID;
1480                 hss.hss_archive_id = archive_id;
1481         }
1482         rc = ioctl(fd, LL_IOC_HSM_STATE_SET, &hss);
1483         /* If error, save errno value */
1484         rc = rc ? -errno : 0;
1485
1486         return rc;
1487 }
1488
1489 /**
1490  * Set HSM states of file pointed by \a path.
1491  *
1492  * see llapi_hsm_state_set_fd() for args use and return
1493  */
1494 int llapi_hsm_state_set(const char *path, __u64 setmask, __u64 clearmask,
1495                         __u32 archive_id)
1496 {
1497         int fd;
1498         int rc;
1499
1500         fd = open(path, O_WRONLY | O_LOV_DELAY_CREATE | O_NONBLOCK);
1501         if (fd < 0)
1502                 return -errno;
1503
1504         rc = llapi_hsm_state_set_fd(fd, setmask, clearmask, archive_id);
1505
1506         close(fd);
1507         return rc;
1508 }
1509
1510 /**
1511  * Return the current HSM request related to file pointed by \a path.
1512  *
1513  * \param hca  Should be allocated by caller. Will be filled with current file
1514  *             actions.
1515  *
1516  * \retval 0 on success.
1517  * \retval -errno on error.
1518  */
1519 int llapi_hsm_current_action(const char *path, struct hsm_current_action *hca)
1520 {
1521         int fd;
1522         int rc;
1523
1524         fd = open(path, O_RDONLY | O_NONBLOCK);
1525         if (fd < 0)
1526                 return -errno;
1527
1528         rc = ioctl(fd, LL_IOC_HSM_ACTION, hca);
1529         /* If error, save errno value */
1530         rc = rc ? -errno : 0;
1531
1532         close(fd);
1533         return rc;
1534 }
1535
1536 /**
1537  * Allocate a hsm_user_request with the specified carateristics.
1538  * This structure should be freed with free().
1539  *
1540  * \return an allocated structure on success, NULL otherwise.
1541  */
1542 struct hsm_user_request *llapi_hsm_user_request_alloc(int itemcount,
1543                                                       int data_len)
1544 {
1545         int len = 0;
1546
1547         len += sizeof(struct hsm_user_request);
1548         len += sizeof(struct hsm_user_item) * itemcount;
1549         len += data_len;
1550
1551         return (struct hsm_user_request *)malloc(len);
1552 }
1553
1554 /**
1555  * Send a HSM request to Lustre, described in \param request.
1556  *
1557  * \param path    Fullpath to the file to operate on.
1558  * \param request The request, allocated with llapi_hsm_user_request_alloc().
1559  *
1560  * \return 0 on success, an error code otherwise.
1561  */
1562 int llapi_hsm_request(const char *path, const struct hsm_user_request *request)
1563 {
1564         int rc;
1565         int fd;
1566
1567         rc = get_root_path(WANT_FD, NULL, &fd, (char *)path, -1);
1568         if (rc)
1569                 return rc;
1570
1571         rc = ioctl(fd, LL_IOC_HSM_REQUEST, request);
1572         /* If error, save errno value */
1573         rc = rc ? -errno : 0;
1574
1575         close(fd);
1576         return rc;
1577 }
1578